INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Add other item to this document. It will create additional links according to the item type. :Args: - item: item we want to add defined as instance of EpubItem
def add_item(self, item): """ Add other item to this document. It will create additional links according to the item type. :Args: - item: item we want to add defined as instance of EpubItem """ if item.get_type() == ebooklib.ITEM_STYLE: self.add_link(href=i...
Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2) or 'bytes' (Python 3). :Returns: Returns content of this document.
def get_body_content(self): """ Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2) or 'bytes' (Python 3). :Returns: Returns content of this document. """ try: html_tree = parse_html_string(self.content)...
Returns content for this document as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3). :Args: - default: Default value for the content if it is not defined. :Returns: Returns content of this document.
def get_content(self, default=None): """ Returns content for this document as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3). :Args: - default: Default value for the content if it is not defined. :Returns: Returns content of this...
Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3). :Returns: Returns content of this document.
def get_content(self): """ Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3). :Returns: Returns content of this document. """ self.content = self.book.get_template('cover') tree = parse_string(super(...
Initialises all needed variables to default values
def reset(self): "Initialises all needed variables to default values" self.metadata = {} self.items = [] self.spine = [] self.guide = [] self.pages = [] self.toc = [] self.bindings = [] self.IDENTIFIER_ID = 'id' self.FOLDER_NAME = 'EPUB' ...
Sets unique id for this epub :Args: - uid: Value of unique identifier for this book
def set_identifier(self, uid): """ Sets unique id for this epub :Args: - uid: Value of unique identifier for this book """ self.uid = uid self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
Set title. You can set multiple titles. :Args: - title: Title value
def set_title(self, title): """ Set title. You can set multiple titles. :Args: - title: Title value """ self.title = title self.add_metadata('DC', 'title', self.title)
Set cover and create cover document if needed. :Args: - file_name: file name of the cover page - content: Content for the cover image - create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
def set_cover(self, file_name, content, create_page=True): """ Set cover and create cover document if needed. :Args: - file_name: file name of the cover page - content: Content for the cover image - create_page: Should cover page be defined. Defined as bool value (...
Add author for this document
def add_author(self, author, file_as=None, role=None, uid='creator'): "Add author for this document" self.add_metadata('DC', 'creator', author, {'id': uid}) if file_as: self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid, ...
Add metadata
def add_metadata(self, namespace, name, value, others=None): "Add metadata" if namespace in NAMESPACES: namespace = NAMESPACES[namespace] if namespace not in self.metadata: self.metadata[namespace] = {} if name not in self.metadata[namespace]: self....
Retrieve metadata
def get_metadata(self, namespace, name): "Retrieve metadata" if namespace in NAMESPACES: namespace = NAMESPACES[namespace] return self.metadata[namespace].get(name, [])
Add additional item to the book. If not defined, media type and chapter id will be defined for the item. :Args: - item: Item instance
def add_item(self, item): """ Add additional item to the book. If not defined, media type and chapter id will be defined for the item. :Args: - item: Item instance """ if item.media_type == '': (has_guessed, media_type) = guess_type(item.get_name()....
Returns item for defined UID. >>> book.get_item_with_id('image_001') :Args: - uid: UID for the item :Returns: Returns item object. Returns None if nothing was found.
def get_item_with_id(self, uid): """ Returns item for defined UID. >>> book.get_item_with_id('image_001') :Args: - uid: UID for the item :Returns: Returns item object. Returns None if nothing was found. """ for item in self.get_items(): ...
Returns item for defined HREF. >>> book.get_item_with_href('EPUB/document.xhtml') :Args: - href: HREF for the item we are searching for :Returns: Returns item object. Returns None if nothing was found.
def get_item_with_href(self, href): """ Returns item for defined HREF. >>> book.get_item_with_href('EPUB/document.xhtml') :Args: - href: HREF for the item we are searching for :Returns: Returns item object. Returns None if nothing was found. """ ...
Returns all items of specified type. >>> book.get_items_of_type(epub.ITEM_IMAGE) :Args: - item_type: Type for items we are searching for :Returns: Returns found items as tuple.
def get_items_of_type(self, item_type): """ Returns all items of specified type. >>> book.get_items_of_type(epub.ITEM_IMAGE) :Args: - item_type: Type for items we are searching for :Returns: Returns found items as tuple. """ return (item for...
Returns all items of specified media type. :Args: - media_type: Media type for items we are searching for :Returns: Returns found items as tuple.
def get_items_of_media_type(self, media_type): """ Returns all items of specified media type. :Args: - media_type: Media type for items we are searching for :Returns: Returns found items as tuple. """ return (item for item in self.items if item.media...
Run ftfy as a command-line utility.
def main(): """ Run ftfy as a command-line utility. """ import argparse parser = argparse.ArgumentParser( description="ftfy (fixes text for you), version %s" % __version__ ) parser.add_argument('filename', default='-', nargs='?', help='The file whose Unicode ...
Performs a single step of re-decoding text that's been decoded incorrectly. Returns the decoded text, plus a "plan" for how to reproduce what it did.
def fix_one_step_and_explain(text): """ Performs a single step of re-decoding text that's been decoded incorrectly. Returns the decoded text, plus a "plan" for how to reproduce what it did. """ if isinstance(text, bytes): raise UnicodeError(BYTES_ERROR_TEXT) if len(text) == 0: r...
Re-decodes text that has been decoded incorrectly, and also return a "plan" indicating all the steps required to fix it. The resulting plan could be used with :func:`ftfy.fixes.apply_plan` to fix additional strings that are broken in the same way.
def fix_encoding_and_explain(text): """ Re-decodes text that has been decoded incorrectly, and also return a "plan" indicating all the steps required to fix it. The resulting plan could be used with :func:`ftfy.fixes.apply_plan` to fix additional strings that are broken in the same way. """ ...
Apply a plan for fixing the encoding of text. The plan is a list of tuples of the form (operation, encoding, cost): - `operation` is 'encode' if it turns a string into bytes, 'decode' if it turns bytes into a string, and 'transcode' if it keeps the type the same. - `encoding` is the name of the enco...
def apply_plan(text, plan): """ Apply a plan for fixing the encoding of text. The plan is a list of tuples of the form (operation, encoding, cost): - `operation` is 'encode' if it turns a string into bytes, 'decode' if it turns bytes into a string, and 'transcode' if it keeps the type the same. ...
Replace one matched HTML entity with the character it represents, if possible.
def _unescape_fixup(match): """ Replace one matched HTML entity with the character it represents, if possible. """ text = match.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": codept = int(text[3:-1], 16) else...
Convert a surrogate pair to the single codepoint it represents. This implements the formula described at: http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
def convert_surrogate_pair(match): """ Convert a surrogate pair to the single codepoint it represents. This implements the formula described at: http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates """ pair = match.group(0) codept = 0x10000 + (ord(pair[0]) - 0xd800) * ...
Replace 16-bit surrogate codepoints with the characters they represent (when properly paired), or with \ufffd otherwise. >>> high_surrogate = chr(0xd83d) >>> low_surrogate = chr(0xdca9) >>> print(fix_surrogates(high_surrogate + low_surrogate)) 💩 >>> print(fix_surrogates(low...
def fix_surrogates(text): """ Replace 16-bit surrogate codepoints with the characters they represent (when properly paired), or with \ufffd otherwise. >>> high_surrogate = chr(0xd83d) >>> low_surrogate = chr(0xdca9) >>> print(fix_surrogates(high_surrogate + low_surrogate)) �...
Some mojibake has been additionally altered by a process that said "hmm, byte A0, that's basically a space!" and replaced it with an ASCII space. When the A0 is part of a sequence that we intend to decode as UTF-8, changing byte A0 to 20 would make it fail to decode. This process finds sequences that w...
def restore_byte_a0(byts): """ Some mojibake has been additionally altered by a process that said "hmm, byte A0, that's basically a space!" and replaced it with an ASCII space. When the A0 is part of a sequence that we intend to decode as UTF-8, changing byte A0 to 20 would make it fail to decode. ...
Fix particular characters that seem to be found in the wild encoded in UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be consistently applied. One form of inconsistency we need to deal with is that some character might be from the Latin-1 C1 control character set, while others a...
def fix_partial_utf8_punct_in_1252(text): """ Fix particular characters that seem to be found in the wild encoded in UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be consistently applied. One form of inconsistency we need to deal with is that some character might be fro...
Return `text` left-justified in a Unicode string whose display width, in a monospaced terminal, should be at least `width` character cells. The rest of the string will be padded with `fillchar`, which must be a width-1 character. "Left" here means toward the beginning of the string, which may actually ...
def display_ljust(text, width, fillchar=' '): """ Return `text` left-justified in a Unicode string whose display width, in a monospaced terminal, should be at least `width` character cells. The rest of the string will be padded with `fillchar`, which must be a width-1 character. "Left" here mea...
Return `text` centered in a Unicode string whose display width, in a monospaced terminal, should be at least `width` character cells. The rest of the string will be padded with `fillchar`, which must be a width-1 character. >>> lines = ['Table flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し'] >>> for line in lines:...
def display_center(text, width, fillchar=' '): """ Return `text` centered in a Unicode string whose display width, in a monospaced terminal, should be at least `width` character cells. The rest of the string will be padded with `fillchar`, which must be a width-1 character. >>> lines = ['Table ...
Take a codec name, and return a 'sloppy' version of that codec that can encode and decode the unassigned bytes in that encoding. Single-byte encodings in the standard library are defined using some boilerplate classes surrounding the functions that do the actual work, `codecs.charmap_decode` and `charm...
def make_sloppy_codec(encoding): """ Take a codec name, and return a 'sloppy' version of that codec that can encode and decode the unassigned bytes in that encoding. Single-byte encodings in the standard library are defined using some boilerplate classes surrounding the functions that do the actual...
Creates a list of regexes that match 'weird' character sequences. The more matches there are, the weirder the text is.
def _make_weirdness_regex(): """ Creates a list of regexes that match 'weird' character sequences. The more matches there are, the weirder the text is. """ groups = [] # Match diacritical marks, except when they modify a non-cased letter or # another mark. # # You wouldn't put a dia...
Build the compressed data file 'char_classes.dat' and write it to the current directory. If you run this, run it in Python 3.7.0 or later. It will run in earlier versions, but you won't get the Unicode 11 standard, leading to inconsistent behavior. Pre-releases of Python 3.7 won't work (Unicode 11 wasn...
def make_char_data_file(do_it_anyway=False): """ Build the compressed data file 'char_classes.dat' and write it to the current directory. If you run this, run it in Python 3.7.0 or later. It will run in earlier versions, but you won't get the Unicode 11 standard, leading to inconsistent behavio...
Decode bytes that may be arriving in a stream, following the Codecs API. `input` is the incoming sequence of bytes. `errors` tells us how to handle errors, though we delegate all error-handling cases to the real UTF-8 decoder to ensure correct behavior. `final` indicates whether ...
def _buffer_decode(self, input, errors, final): """ Decode bytes that may be arriving in a stream, following the Codecs API. `input` is the incoming sequence of bytes. `errors` tells us how to handle errors, though we delegate all error-handling cases to the real UTF-8 d...
Register our "bad codecs" with Python's codecs API. This involves adding a search function that takes in an encoding name, and returns a codec for that encoding if it knows one, or None if it doesn't. The encodings this will match are: - Encodings of the form 'sloppy-windows-NNNN' or 'sloppy-iso-8859-...
def search_function(encoding): """ Register our "bad codecs" with Python's codecs API. This involves adding a search function that takes in an encoding name, and returns a codec for that encoding if it knows one, or None if it doesn't. The encodings this will match are: - Encodings of the form...
There are three possibilities for each decoding step: - Decode as much real UTF-8 as possible. - Decode a six-byte CESU-8 sequence at the current position. - Decode a Java-style null at the current position. This method figures out which step is appropriate, and does it.
def _buffer_decode_step(self, input, errors, final): """ There are three possibilities for each decoding step: - Decode as much real UTF-8 as possible. - Decode a six-byte CESU-8 sequence at the current position. - Decode a Java-style null at the current position. This ...
When we have improperly encoded surrogates, we can still see the bits that they were meant to represent. The surrogates were meant to encode a 20-bit number, to which we add 0x10000 to get a codepoint. That 20-bit number now appears in this form: 11101101 1010abcd 10efghij 11...
def _buffer_decode_surrogates(sup, input, errors, final): """ When we have improperly encoded surrogates, we can still see the bits that they were meant to represent. The surrogates were meant to encode a 20-bit number, to which we add 0x10000 to get a codepoint. That 20-bit num...
r""" Given Unicode text as input, fix inconsistencies and glitches in it, such as mojibake. Let's start with some examples: >>> print(fix_text('ünicode')) ünicode >>> print(fix_text('Broken text… it’s flubberific!', ... normalization='NFKC')) ...
def fix_text(text, *, fix_entities='auto', remove_terminal_escapes=True, fix_encoding=True, fix_latin_ligatures=True, fix_character_width=True, uncurl_quotes=True, fix_line_breaks=True, fix_surrogates=Tr...
Fix text that is found in a file. If the file is being read as Unicode text, use that. If it's being read as bytes, then we hope an encoding was supplied. If not, unfortunately, we have to guess what encoding it is. We'll try a few common encodings, but we make no promises. See the `guess_bytes` functi...
def fix_file(input_file, encoding=None, *, fix_entities='auto', remove_terminal_escapes=True, fix_encoding=True, fix_latin_ligatures=True, fix_character_width=True, uncurl_quotes=True, fix_line_breaks=Tr...
Apply fixes to text in a single chunk. This could be a line of text within a larger run of `fix_text`, or it could be a larger amount of text that you are certain is in a consistent encoding. See `fix_text` for a description of the parameters.
def fix_text_segment(text, *, fix_entities='auto', remove_terminal_escapes=True, fix_encoding=True, fix_latin_ligatures=True, fix_character_width=True, uncurl_quotes=True, ...
NOTE: Using `guess_bytes` is not the recommended way of using ftfy. ftfy is not designed to be an encoding detector. In the unfortunate situation that you have some bytes in an unknown encoding, ftfy can guess a reasonable strategy for decoding them, by trying a few common encodings that can be disting...
def guess_bytes(bstring): """ NOTE: Using `guess_bytes` is not the recommended way of using ftfy. ftfy is not designed to be an encoding detector. In the unfortunate situation that you have some bytes in an unknown encoding, ftfy can guess a reasonable strategy for decoding them, by trying a fe...
A utility method that's useful for debugging mysterious Unicode. It breaks down a string, showing you for each codepoint its number in hexadecimal, its glyph, its category in the Unicode standard, and its name in the Unicode standard. >>> explain_unicode('(╯°□°)╯︵ ┻━┻') U+0028 ( [Ps...
def explain_unicode(text): """ A utility method that's useful for debugging mysterious Unicode. It breaks down a string, showing you for each codepoint its number in hexadecimal, its glyph, its category in the Unicode standard, and its name in the Unicode standard. >>> explain_unicode('(╯°...
ENCODING_REGEXES contain reasonably fast ways to detect if we could represent a given string in a given encoding. The simplest one is the 'ascii' detector, which of course just determines if all characters are between U+0000 and U+007F.
def _build_regexes(): """ ENCODING_REGEXES contain reasonably fast ways to detect if we could represent a given string in a given encoding. The simplest one is the 'ascii' detector, which of course just determines if all characters are between U+0000 and U+007F. """ # Define a regex that mat...
Build a translate mapping that strips likely-unintended control characters. See :func:`ftfy.fixes.remove_control_chars` for a description of these codepoint ranges and why they should be removed.
def _build_control_char_mapping(): """ Build a translate mapping that strips likely-unintended control characters. See :func:`ftfy.fixes.remove_control_chars` for a description of these codepoint ranges and why they should be removed. """ control_chars = {} for i in itertools.chain( ...
Build a translate mapping that replaces halfwidth and fullwidth forms with their standard-width forms.
def _build_width_map(): """ Build a translate mapping that replaces halfwidth and fullwidth forms with their standard-width forms. """ # Though it's not listed as a fullwidth character, we'll want to convert # U+3000 IDEOGRAPHIC SPACE to U+20 SPACE on the same principle, so start # with that...
Set the accuracy mode for VML operations. The `mode` parameter can take the values: - 'high': high accuracy mode (HA), <1 least significant bit - 'low': low accuracy mode (LA), typically 1-2 least significant bits - 'fast': enhanced performance mode (EP) - None: mode settings are ignored This ...
def set_vml_accuracy_mode(mode): """ Set the accuracy mode for VML operations. The `mode` parameter can take the values: - 'high': high accuracy mode (HA), <1 least significant bit - 'low': low accuracy mode (LA), typically 1-2 least significant bits - 'fast': enhanced performance mode (EP) ...
Detects the environment variable 'NUMEXPR_MAX_THREADS' to set the threadpool size, and if necessary the slightly redundant 'NUMEXPR_NUM_THREADS' or 'OMP_NUM_THREADS' env vars to set the initial number of threads used by the virtual machine.
def _init_num_threads(): """ Detects the environment variable 'NUMEXPR_MAX_THREADS' to set the threadpool size, and if necessary the slightly redundant 'NUMEXPR_NUM_THREADS' or 'OMP_NUM_THREADS' env vars to set the initial number of threads used by the virtual machine. """ # Any platform-...
Detects the number of cores on a system. Cribbed from pp.
def detect_number_of_cores(): """ Detects the number of cores on a system. Cribbed from pp. """ # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: # Linux & Unix: ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if i...
DEPRECATED: use `_init_num_threads` instead. If this is modified, please update the note in: https://github.com/pydata/numexpr/wiki/Numexpr-Users-Guide
def detect_number_of_threads(): """ DEPRECATED: use `_init_num_threads` instead. If this is modified, please update the note in: https://github.com/pydata/numexpr/wiki/Numexpr-Users-Guide """ log.warning('Deprecated, use `init_num_threads` instead.') try: nthreads = int(os.environ.get('N...
Very stupid "chunk vectorizer" which keeps memory use down. This version requires all inputs to have the same number of elements, although it shouldn't be that hard to implement simple broadcasting.
def chunkify(chunksize): """ Very stupid "chunk vectorizer" which keeps memory use down. This version requires all inputs to have the same number of elements, although it shouldn't be that hard to implement simple broadcasting. """ def chunkifier(func): def wrap(*args): ...
Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number.
def expressionToAST(ex): """Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number. """ return ASTNode(ex.astType, ex.astKind, ex.value, [expressionToAST(c) fo...
Generate all possible signatures derived by upcasting the given signature.
def sigPerms(s): """Generate all possible signatures derived by upcasting the given signature. """ codes = 'bilfdc' if not s: yield '' elif s[0] in codes: start = codes.index(s[0]) for x in codes[start:]: for y in sigPerms(s[1:]): yield x + y ...
Assign appropiate types to each node in the AST. Will convert opcodes and functions to appropiate upcast version, and add "cast" ops if needed.
def typeCompileAst(ast): """Assign appropiate types to each node in the AST. Will convert opcodes and functions to appropiate upcast version, and add "cast" ops if needed. """ children = list(ast.children) if ast.astType == 'op': retsig = ast.typecode() basesig = ''.join(x.typec...
Given a string, convert it to a tree of ExpressionNode's.
def stringToExpression(s, types, context): """Given a string, convert it to a tree of ExpressionNode's. """ old_ctx = expressions._context.get_current_context() try: expressions._context.set_new_context(context) # first compile to a code object to determine the names if context.g...
Derive the input order of the variables in an expression.
def getInputOrder(ast, input_order=None): """Derive the input order of the variables in an expression. """ variables = {} for a in ast.allOf('variable'): variables[a.value] = a variable_names = set(variables.keys()) if input_order: if variable_names != set(input_order): ...
RAM: implemented magic method __lt__ for ASTNode to fix issues #88 and #209. The following test code works now, as does the test suite. import numexpr as ne a = 1 + 3j; b = 5.0 ne.evaluate( 'a*2 + 15j - b' )
def getConstants(ast): ''' RAM: implemented magic method __lt__ for ASTNode to fix issues #88 and #209. The following test code works now, as does the test suite. import numexpr as ne a = 1 + 3j; b = 5.0 ne.evaluate( 'a*2 + 15j - b' ) ''' constants_order = sorted( ast.allOf('constant') )...
Assign new registers to each of the leaf nodes.
def assignLeafRegisters(inodes, registerMaker): """Assign new registers to each of the leaf nodes. """ leafRegisters = {} for node in inodes: key = node.key() if key in leafRegisters: node.reg = leafRegisters[key] else: node.reg = leafRegisters[key] = regi...
Assign temporary registers to each of the branch nodes.
def assignBranchRegisters(inodes, registerMaker): """Assign temporary registers to each of the branch nodes. """ for node in inodes: node.reg = registerMaker(node, temporary=True)
Common subexpression elimination.
def collapseDuplicateSubtrees(ast): """Common subexpression elimination. """ seen = {} aliases = [] for a in ast.allOf('op'): if a in seen: target = seen[a] a.astType = 'alias' a.value = target a.children = () aliases.append(a) ...
Attempt to minimize the number of temporaries needed, by reusing old ones.
def optimizeTemporariesAllocation(ast): """Attempt to minimize the number of temporaries needed, by reusing old ones. """ nodes = [n for n in ast.postorderWalk() if n.reg.temporary] users_of = dict((n.reg, set()) for n in nodes) node_regs = dict((n, set(c.reg for c in n.children if c.reg.tempor...
Given an order of nodes, assign register numbers.
def setOrderedRegisterNumbers(order, start): """Given an order of nodes, assign register numbers. """ for i, node in enumerate(order): node.reg.n = start + i return start + len(order)
Assign register numbers for temporary registers, keeping track of aliases and handling immediate operands.
def setRegisterNumbersForTemporaries(ast, start): """Assign register numbers for temporary registers, keeping track of aliases and handling immediate operands. """ seen = 0 signature = '' aliases = [] for node in ast.postorderWalk(): if node.astType == 'alias': aliases.ap...
Convert an AST to a three address form. Three address form is (op, reg1, reg2, reg3), where reg1 is the destination of the result of the instruction. I suppose this should be called three register form, but three address form is found in compiler theory.
def convertASTtoThreeAddrForm(ast): """Convert an AST to a three address form. Three address form is (op, reg1, reg2, reg3), where reg1 is the destination of the result of the instruction. I suppose this should be called three register form, but three address form is found in compiler theory. ...
Given a three address form of the program, compile it a string that the VM understands.
def compileThreeAddrForm(program): """Given a three address form of the program, compile it a string that the VM understands. """ def nToChr(reg): if reg is None: return b'\xff' elif reg.n < 0: raise ValueError("negative value for register number %s" % reg.n) ...
Compile the expression to an intermediate form.
def precompile(ex, signature=(), context={}): """Compile the expression to an intermediate form. """ types = dict(signature) input_order = [name for (name, type_) in signature] if isinstance(ex, (str, unicode)): ex = stringToExpression(ex, types, context) # the AST is like the expressi...
Compile an expression built using E.<variable> variables to a function. ex can also be specified as a string "2*a+3*b". The order of the input variables and their types can be specified using the signature parameter, which is a list of (name, type) pairs. Returns a `NumExpr` object containing the com...
def NumExpr(ex, signature=(), **kwargs): """ Compile an expression built using E.<variable> variables to a function. ex can also be specified as a string "2*a+3*b". The order of the input variables and their types can be specified using the signature parameter, which is a list of (name, type) pair...
Given a NumExpr object, return a list which is the program disassembled.
def disassemble(nex): """ Given a NumExpr object, return a list which is the program disassembled. """ rev_opcodes = {} for op in interpreter.opcodes: rev_opcodes[interpreter.opcodes[op]] = op r_constants = 1 + len(nex.signature) r_temps = r_constants + len(nex.constants) def ge...
Get the arguments based on the names.
def getArguments(names, local_dict=None, global_dict=None): """Get the arguments based on the names.""" call_frame = sys._getframe(2) clear_local_dict = False if local_dict is None: local_dict = call_frame.f_locals clear_local_dict = True try: frame_globals = call_frame.f_gl...
Evaluate a simple array expression element-wise, using the new iterator. ex is a string forming an expression, like "2*a+3*b". The values for "a" and "b" will by default be taken from the calling function's frame (through use of sys._getframe()). Alternatively, they can be specifed using the 'local_dic...
def evaluate(ex, local_dict=None, global_dict=None, out=None, order='K', casting='safe', **kwargs): """Evaluate a simple array expression element-wise, using the new iterator. ex is a string forming an expression, like "2*a+3*b". The values for "a" and "b" will by default be taken from the cal...
Re-evaluate the previous executed array expression without any check. This is meant for accelerating loops that are re-evaluating the same expression repeatedly without changing anything else than the operands. If unsure, use evaluate() which is safer. Parameters ---------- local_dict : dicti...
def re_evaluate(local_dict=None): """Re-evaluate the previous executed array expression without any check. This is meant for accelerating loops that are re-evaluating the same expression repeatedly without changing anything else than the operands. If unsure, use evaluate() which is safer. Paramete...
Compute the polynomial.
def compute(): """Compute the polynomial.""" if what == "numpy": y = eval(expr) else: y = ne.evaluate(expr) return len(y)
Returns the row principal coordinates.
def row_coordinates(self, X): """Returns the row principal coordinates.""" utils.validation.check_is_fitted(self, 's_') # Check input if self.check_input: utils.check_array(X, dtype=[str, np.number]) # Prepare input X = self._prepare_input(X) return...
Returns the row contributions towards each principal component.
def row_contributions(self, X): """Returns the row contributions towards each principal component.""" utils.validation.check_is_fitted(self, 's_') # Check input if self.check_input: utils.check_array(X, dtype=[str, np.number]) # Prepare input X = self._prepa...
Returns the row coordinates for each group.
def partial_row_coordinates(self, X): """Returns the row coordinates for each group.""" utils.validation.check_is_fitted(self, 's_') # Check input if self.check_input: utils.check_array(X, dtype=[str, np.number]) # Prepare input X = self._prepare_input(X) ...
Returns the column correlations.
def column_correlations(self, X): """Returns the column correlations.""" utils.validation.check_is_fitted(self, 's_') X_global = self._build_X_global(X) row_pc = self._row_coordinates_from_global(X_global) return pd.DataFrame({ component: { feature: ...
Plot the row principal coordinates.
def plot_partial_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, color_labels=None, **kwargs): """Plot the row principal coordinates.""" utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax = plt.sub...
Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data.
def transform(self, X): """Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data. """ ...
The eigenvalues associated with each principal component.
def eigenvalues_(self): """The eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist()
The percentage of explained inertia per principal component.
def explained_inertia_(self): """The percentage of explained inertia per principal component.""" utils.validation.check_is_fitted(self, 'total_inertia_') return [eig / self.total_inertia_ for eig in self.eigenvalues_]
The row principal coordinates.
def row_coordinates(self, X): """The row principal coordinates.""" utils.validation.check_is_fitted(self, 'V_') _, row_names, _, _ = util.make_labels_and_names(X) if isinstance(X, pd.SparseDataFrame): X = X.to_coo().astype(float) elif isinstance(X, pd.DataFrame): ...
The column principal coordinates.
def column_coordinates(self, X): """The column principal coordinates.""" utils.validation.check_is_fitted(self, 'V_') _, _, _, col_names = util.make_labels_and_names(X) if isinstance(X, pd.SparseDataFrame): X = X.to_coo() elif isinstance(X, pd.DataFrame): ...
Plot the principal coordinates.
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, show_row_labels=True, show_col_labels=True, **kwargs): """Plot the principal coordinates.""" utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax =...
Computes the row principal coordinates of a dataset.
def transform(self, X): """Computes the row principal coordinates of a dataset.""" utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X, dtype=[str, np.number]) return self.row_coordinates(X)
Plot row and column principal coordinates. Args: ax (matplotlib.Axis): A fresh one will be created and returned if not provided. figsize ((float, float)): The desired figure size if `ax` is not provided. x_component (int): Number of the component used for the x-axis. ...
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, show_row_points=True, row_points_size=10, show_row_labels=False, show_column_points=True, column_points_size=30, show_column_label...
Computes an SVD with k components.
def compute_svd(X, n_components, n_iter, random_state, engine): """Computes an SVD with k components.""" # Determine what SVD engine to use if engine == 'auto': engine = 'sklearn' # Compute the SVD if engine == 'fbpca': if FBPCA_INSTALLED: U, s, V = fbpca.pca(X, k=n_com...
Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors.
def row_coordinates(self, X): """Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors. """ utils.validation.check_is_fitted(self, 's_') # Extract index index = X.index if isinstance(X, pd.DataFrame...
Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue.
def row_standard_coordinates(self, X): """Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue. """ utils.validation.check_is_fitted(self, 's_') return self.row_coordinates...
Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue associated to each principal component.
def row_contributions(self, X): """Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue a...
Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated by squaring each row projection coordinat...
def row_cosine_similarities(self, X): """Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated ...
Returns the column correlations with each principal component.
def column_correlations(self, X): """Returns the column correlations with each principal component.""" utils.validation.check_is_fitted(self, 's_') # Convert numpy array to pandas DataFrame if isinstance(X, np.ndarray): X = pd.DataFrame(X) row_pc = self.row_coordina...
Plot the row principal coordinates.
def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): """Plot the row principal coordinates.""" utils.valida...
Construct ellipse coordinates from two arrays of numbers. Args: X (1D array_like) Y (1D array_like) Returns: float: The mean of `X`. float: The mean of `Y`. float: The width of the ellipse. float: The height of the ellipse. float: The angle of orientatio...
def build_ellipse(X, Y): """Construct ellipse coordinates from two arrays of numbers. Args: X (1D array_like) Y (1D array_like) Returns: float: The mean of `X`. float: The mean of `Y`. float: The width of the ellipse. float: The height of the ellipse. ...
set the start time. when start time is set, drop down list will start from start time and duration will be displayed in brackets
def set_start_time(self, start_time): """ set the start time. when start time is set, drop down list will start from start time and duration will be displayed in brackets """ start_time = start_time or dt.time() if isinstance(start_time, dt.time): # ensure that we...
extract time from a time_re match.
def extract_time(match): """extract time from a time_re match.""" hour = int(match.group('hour')) minute = int(match.group('minute')) return dt.time(hour, minute)
tries to extract fact fields from the string the optional arguments in the syntax makes us actually try parsing values and fallback to next phase start -> [end] -> activity[@category] -> tags Returns dict for the fact and achieved phase TODO - While we are now bit cooler and go...
def parse_fact(text, phase=None, res=None, date=None): """tries to extract fact fields from the string the optional arguments in the syntax makes us actually try parsing values and fallback to next phase start -> [end] -> activity[@category] -> tags Returns dict for the fact and ach...
Return a toplevel logger. This should be used only in the toplevel file. Files deeper in the hierarchy should use ``logger = logging.getLogger(__name__)``, in order to considered as children of the toplevel logger. Beware that without a setLevel() somewhere, the default value (warning) will be...
def default_logger(name): """Return a toplevel logger. This should be used only in the toplevel file. Files deeper in the hierarchy should use ``logger = logging.getLogger(__name__)``, in order to considered as children of the toplevel logger. Beware that without a setLevel() somewhere, th...
Duration (datetime.timedelta).
def delta(self): """Duration (datetime.timedelta).""" end_time = self.end_time if self.end_time else dt.datetime.now() return end_time - self.start_time
calculate the actual dimensions after rotation
def _with_rotation(self, w, h): """calculate the actual dimensions after rotation""" res_w = abs(w * math.cos(self.rotation) + h * math.sin(self.rotation)) res_h = abs(h * math.cos(self.rotation) + w * math.sin(self.rotation)) return res_w, res_h
request the element to re-check it's child sprite sizes
def queue_resize(self): """request the element to re-check it's child sprite sizes""" self._children_resize_queued = True parent = getattr(self, "parent", None) if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"): parent.queue_resize()
returns size required by the widget
def get_min_size(self): """returns size required by the widget""" if self.visible == False: return 0, 0 else: return ((self.min_width or 0) + self.horizontal_padding + self.margin_left + self.margin_right, (self.min_height or 0) + self.vertical_padding...
insert widget in the sprites list at the given index. by default will prepend.
def insert(self, index = 0, *widgets): """insert widget in the sprites list at the given index. by default will prepend.""" for widget in widgets: self._add(widget, index) index +=1 # as we are moving forwards self._sort()
insert this widget into the targets parent before the target
def insert_before(self, target): """insert this widget into the targets parent before the target""" if not target.parent: return target.parent.insert(target.parent.sprites.index(target), self)
insert this widget into the targets parent container after the target
def insert_after(self, target): """insert this widget into the targets parent container after the target""" if not target.parent: return target.parent.insert(target.parent.sprites.index(target) + 1, self)