INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Draw an image.
def draw_image(image, x1, y1, x2 = None, y2 = None): '''Draw an image. The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they are calculated to render the image at its native resoultion. Note that images can be flipped and scal...
Draw a rectangular region of an image.
def draw_image_region(image, x1, y1, x2, y2, ix1, iy1, ix2, iy2): '''Draw a rectangular region of an image. The part of the image contained by the rectangle in texel-space by the coordinates ``(ix1, iy1)`` to ``(ix2, iy2)`` is drawn at coordinates ``(x1, y1)`` to ``(x2, y2)``. All co...
Total frame size.
def size(self): """Total frame size.""" header_size = 27 # Initial header size for datum in self.packets: quot, rem = divmod(len(datum), 255) header_size += quot + 1 if not self.complete and rem == 0: # Packet contains a multiple of 255 bytes and is n...
Replace old_pages with new_pages within fileobj.
def replace(cls, fileobj, old_pages, new_pages): """Replace old_pages with new_pages within fileobj. old_pages must have come from reading fileobj originally. new_pages are assumed to have the 'same' data as old_pages, and so the serial and sequence numbers will be copied, as will ...
Find the last page of the stream serial.
def find_last(fileobj, serial): """Find the last page of the stream 'serial'. If the file is not multiplexed this function is fast. If it is, it must read the whole the stream. This finds the last page in the actual file object, or the last page in the stream (with eos set), wh...
Load file information from a filename.
def load(self, filename): """Load file information from a filename.""" self.filename = filename fileobj = open(filename, "rb") try: try: self.info = self._Info(fileobj) self.tags = self._Tags(fileobj, self.info) self.info._post...
Remove tags from a file.
def delete(self, filename=None): """Remove tags from a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename self.tags.clear() fileobj = open(filename, "rb+") try: try: ...
Write tag data into the Theora comment packet/ page.
def _inject(self, fileobj): """Write tag data into the Theora comment packet/page.""" fileobj.seek(0) page = OggPage(fileobj) while not page.packets[0].startswith(b"\x81theora"): page = OggPage(fileobj) old_pages = [page] while not (old_pages[-1].complete or...
Parses the API responses for the: py: meth: route53. connection. Route53Connection. create_hosted_zone method.
def created_hosted_zone_parser(root, connection): """ Parses the API responses for the :py:meth:`route53.connection.Route53Connection.create_hosted_zone` method. :param lxml.etree._Element root: The root node of the etree parsed response from the API. :param Route53Connection connection: Th...
set current section during parsing
def set_section( self, section_name ): """set current section during parsing""" if not self.sections.has_key( section_name ): section = DocSection( section_name ) self.sections[section_name] = section self.section = section else: se...
add a new markup section
def add_markup( self ): """add a new markup section""" if self.markup and self.markup_lines: # get rid of last line of markup if it's empty marks = self.markup_lines if len( marks ) > 0 and not string.strip( marks[-1] ): self.markup_lines = marks[:-1...
process a block content and return a list of DocMarkup objects corresponding to it
def process_content( self, content ): """process a block content and return a list of DocMarkup objects corresponding to it""" markup = None markup_lines = [] first = 1 for line in content: found = None for t in re_markup_tags: ...
return the DocMarkup corresponding to a given tag in a block
def get_markup( self, tag_name ): """return the DocMarkup corresponding to a given tag in a block""" for m in self.markups: if m.tag == string.lower( tag_name ): return m return None
Forms an XML string that we ll send to Route53 in order to create a new hosted zone.
def create_hosted_zone_writer(connection, name, caller_reference, comment): """ Forms an XML string that we'll send to Route53 in order to create a new hosted zone. :param Route53Connection connection: The connection instance used to query the API. :param str name: The name of the hosted zo...
Lock a file object safely.
def lock(fileobj): """Lock a file object 'safely'. That means a failure to lock because the platform doesn't support fcntl or filesystem locks is not considered a failure. This call does block. Returns whether or not the lock was successful, or raises an exception in more extreme circumstances...
Insert size bytes of empty space starting at offset.
def insert_bytes(fobj, size, offset, BUFFER_SIZE=2**16): """Insert size bytes of empty space starting at offset. fobj must be an open file object, open rb+ or equivalent. Mutagen tries to use mmap to resize the file, but falls back to a significantly slower method if mmap fails. """ assert 0 <...
Delete size bytes of empty space starting at offset.
def delete_bytes(fobj, size, offset, BUFFER_SIZE=2**16): """Delete size bytes of empty space starting at offset. fobj must be an open file object, open rb+ or equivalent. Mutagen tries to use mmap to resize the file, but falls back to a significantly slower method if mmap fails. """ locked = F...
Convert a basestring to a valid UTF - 8 str.
def utf8(data): """Convert a basestring to a valid UTF-8 str.""" if isinstance(data, bytes): return data.decode("utf-8", "replace").encode("utf-8") elif isinstance(data, text_type): return data.encode("utf-8") else: raise TypeError("only unicode/bytes types can be converted to U...
Adds a change to this change set.
def add_change(self, action, record_set): """ Adds a change to this change set. :param str action: Must be one of either 'CREATE' or 'DELETE'. :param resource_record_set.ResourceRecordSet record_set: The ResourceRecordSet object that was created or deleted. """ ...
Parses a ChangeInfo tag. Seen in CreateHostedZone DeleteHostedZone and ChangeResourceRecordSetsRequest.
def parse_change_info(e_change_info): """ Parses a ChangeInfo tag. Seen in CreateHostedZone, DeleteHostedZone, and ChangeResourceRecordSetsRequest. :param lxml.etree._Element e_change_info: A ChangeInfo element. :rtype: dict :returns: A dict representation of the change info. """ if e_...
Get a path to the given filename to load as a resource. All non - absolute filenames passed to: class: Image: class: Font: class: Sound etc are transformed through this function.
def get_resource_path(filename): '''Get a path to the given filename to load as a resource. All non-absolute filenames passed to :class:`Image`, :class:`Font`, :class:`Sound`, etc are transformed through this function. :param str filename: a relative path to a resource file :return str: an absolute pa...
Retrieves a: class: Glyph that renders the given character.
def get_glyph(self, char): '''Retrieves a :class:`Glyph` that renders the given character. :param char: the character (a string) ''' try: return self._glyphs[char] except KeyError: glyph = self._font_file.get_glyph(self._size, self._content_scale, char, s...
Calculates the width of the given string in this font.
def measure_string(self, str): '''Calculates the width of the given string in this font. :param str: the string to measure :return float: width of the string, in pixels ''' style = bacon.text.Style(self) run = bacon.text.GlyphRun(style, str) glyph_layout = bacon....
Determines whether this record set has been modified since the last retrieval or save.
def is_modified(self): """ Determines whether this record set has been modified since the last retrieval or save. :rtype: bool :returns: ``True` if the record set has been modified, and ``False`` if not. """ for key, val in self._initial_vals.items()...
Deletes this record set.
def delete(self): """ Deletes this record set. """ cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id) cset.add_change('DELETE', self) return self.connection._change_resource_record_sets(cset)
Saves any changes to this record set.
def save(self): """ Saves any changes to this record set. """ cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id) # Record sets can't actually be modified. You have to delete the # existing one and create a new one. Since this happens within a singl...
Remove tags from a file.
def delete(filename, delete_v1=True, delete_v2=True): """Remove tags from a file. Keyword arguments: * delete_v1 -- delete any ID3v1 tag * delete_v2 -- delete any ID3v2 tag """ f = open(filename, 'rb+') if delete_v1: try: f.seek(-128, 2) except IOError: ...
Parse an ID3v1 tag returning a list of ID3v2. 4 frames.
def ParseID3v1(data): """Parse an ID3v1 tag, returning a list of ID3v2.4 frames.""" try: data = data[data.index(b'TAG'):] except ValueError: return None if 128 < len(data) or len(data) < 124: return None # Issue #69 - Previous versions of Mutagen, when encountering # ou...
Return an ID3v1. 1 tag string from a dict of ID3v2. 4 frames.
def MakeID3v1(id3): """Return an ID3v1.1 tag string from a dict of ID3v2.4 frames.""" v1 = {} for v2id, name in {"TIT2": "title", "TPE1": "artist", "TALB": "album"}.items(): if v2id in id3: text = id3[v2id].text[0].encode('latin1', 'replace')[:30] else: ...
Read a certain number of bytes from the source file.
def __fullread(self, size): """ Read a certain number of bytes from the source file. """ try: if size < 0: raise ValueError('Requested bytes (%s) less than zero' % size) if size > self.__filesize: raise EOFError('Requested %#x of %#x (%s)' % ( ...
Load tags from a filename.
def load(self, filename, known_frames=None, translate=True, v2_version=4): """Load tags from a filename. Keyword arguments: * filename -- filename to load tag data from * known_frames -- dict mapping frame IDs to Frame objects * translate -- Update all tags to ID3v2.3/4 interna...
Return all frames with a given name ( the list may be empty ).
def getall(self, key): """Return all frames with a given name (the list may be empty). This is best explained by examples:: id3.getall('TIT2') == [id3['TIT2']] id3.getall('TTTT') == [] id3.getall('TXXX') == [TXXX(desc='woo', text='bar'), ...
Delete all tags of a given kind ; see getall.
def delall(self, key): """Delete all tags of a given kind; see getall.""" if key in self: del(self[key]) else: key = key + ":" for k in self.keys(): if k.startswith(key): del(self[k])
Deprecated ; use the add method.
def loaded_frame(self, tag): """Deprecated; use the add method.""" # turn 2.2 into 2.3/2.4 tags if len(type(tag).__name__) == 3: tag = type(tag).__base__(tag) self[tag.HashKey] = tag
Save changes to a file.
def save(self, filename=None, v1=1, v2_version=4, v23_sep='/'): """Save changes to a file. If no filename is given, the one most recently loaded is used. Keyword arguments: v1 -- if 0, ID3v1 tags will be removed if 1, ID3v1 tags will be updated but not added ...
Remove tags from a file.
def delete(self, filename=None, delete_v1=True, delete_v2=True): """Remove tags from a file. If no filename is given, the one most recently loaded is used. Keyword arguments: * delete_v1 -- delete any ID3v1 tag * delete_v2 -- delete any ID3v2 tag """ if filenam...
Updates done by both v23 and v24 update
def __update_common(self): """Updates done by both v23 and v24 update""" if "TCON" in self: # Get rid of "(xx)Foobr" format. self["TCON"].genres = self["TCON"].genres if self.version < self._V23: # ID3v2.2 PIC frames are slightly different. pics ...
Convert older tags into an ID3v2. 4 tag.
def update_to_v24(self): """Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag. """ self.__update_...
Convert older ( and newer ) tags into an ID3v2. 3 tag.
def update_to_v23(self): """Convert older (and newer) tags into an ID3v2.3 tag. This updates incompatible ID3v2 frames to ID3v2.3 ones. If you intend to save tags as ID3v2.3, you must call this function at some point. If you want to to go off spec and include some v2.4 frames ...
Load stream and tag information from a file.
def load(self, filename, ID3=None, **kwargs): """Load stream and tag information from a file. A custom tag reader may be used in instead of the default mutagen.id3.ID3 object, e.g. an EasyID3 reader. """ if ID3 is None: ID3 = self.ID3 else: # If ...
Release all resources associated with the sound.
def unload(self): '''Release all resources associated with the sound.''' if self._handle != -1: lib.UnloadSound(self._handle) self._handle = -1
Play the sound as a one - shot.
def play(self, gain=None, pan=None, pitch=None): '''Play the sound as a `one-shot`. The sound will be played to completion. If the sound is played more than once at a time, it will mix with all previous instances of itself. If you need more control over the playback of sounds, see :cl...
Set the loop points within the sound.
def set_loop_points(self, start_sample=-1, end_sample=0): '''Set the loop points within the sound. The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to the entire sound duration. :note: There is currently no API for converting ...
Parses the API responses for the: py: meth: route53. connection. Route53Connection. list_hosted_zones method.
def list_hosted_zones_parser(root, connection): """ Parses the API responses for the :py:meth:`route53.connection.Route53Connection.list_hosted_zones` method. :param lxml.etree._Element root: The root node of the etree parsed response from the API. :param Route53Connection connection: The c...
return the list of glyph names and their unicode values
def adobe_glyph_values(): """return the list of glyph names and their unicode values""" lines = string.split( adobe_glyph_list, '\n' ) glyphs = [] values = [] for line in lines: if line: fields = string.split( line, ';' ) # print fields[1] + ' - ' + fields[0] subfields = string.split( f...
filter alist by taking _out_ all glyph names that are in filter
def filter_glyph_names( alist, filter ): """filter `alist' by taking _out_ all glyph names that are in `filter'""" count = 0 extras = [] for name in alist: try: filtered_index = filter.index( name ) except: extras.append( name ) return extras
dump a given encoding
def dump_encoding( file, encoding_name, encoding_list ): """dump a given encoding""" write = file.write write( " /* the following are indices into the SID name table */\n" ) write( " static const unsigned short " + encoding_name + "[" + repr( len( encoding_list ) ) + "] =\n" ) write( " {\n" ) ...
dumps a given encoding
def dump_array( the_array, write, array_name ): """dumps a given encoding""" write( " static const unsigned char " + array_name + "[" + repr( len( the_array ) ) + "L] =\n" ) write( " {\n" ) line = "" comma = " " col = 0 for value in the_array: line += comma line += "%3d" % ord...
main program body
def main(): """main program body""" if len( sys.argv ) != 2: print __doc__ % sys.argv[0] sys.exit( 1 ) file = open( sys.argv[1], "w\n" ) write = file.write count_sid = len( sid_standard_names ) # `mac_extras' contains the list of glyph names in the Macintosh standard # encoding which are not ...
checks that a given file exists
def file_exists( pathname ): """checks that a given file exists""" result = 1 try: file = open( pathname, "r" ) file.close() except: result = None sys.stderr.write( pathname + " couldn't be accessed\n" ) return result
builds a list of input files from command - line arguments
def make_file_list( args = None ): """builds a list of input files from command-line arguments""" file_list = [] # sys.stderr.write( repr( sys.argv[1 :] ) + '\n' ) if not args: args = sys.argv[1 :] for pathname in args: if string.find( pathname, '*' ) >= 0: newpath = g...
This a common parser that allows the passing of any valid HostedZone tag. It will spit out the appropriate HostedZone object for the tag.
def parse_hosted_zone(e_zone, connection): """ This a common parser that allows the passing of any valid HostedZone tag. It will spit out the appropriate HostedZone object for the tag. :param lxml.etree._Element e_zone: The root node of the etree parsed response from the API. :param Route53...
Parses a DelegationSet tag. These often accompany HostedZone tags in responses like CreateHostedZone and GetHostedZone.
def parse_delegation_set(zone, e_delegation_set): """ Parses a DelegationSet tag. These often accompany HostedZone tags in responses like CreateHostedZone and GetHostedZone. :param HostedZone zone: An existing HostedZone instance to populate. :param lxml.etree._Element e_delegation_set: A Delegatio...
Render metadata block as a byte string.
def writeblocks(blocks): """Render metadata block as a byte string.""" data = [] codes = [[block.code, block.write()] for block in blocks] codes[-1][0] |= 128 for code, datum in codes: byte = chr_(code) if len(datum) > 2**24: raise error("b...
Consolidate FLAC padding metadata blocks.
def group_padding(blocks): """Consolidate FLAC padding metadata blocks. The overall size of the rendered blocks does not change, so this adds several bytes of padding for each merged block. """ paddings = [b for b in blocks if isinstance(b, Padding)] for p in paddings: ...
Remove Vorbis comments from a file.
def delete(self, filename=None): """Remove Vorbis comments from a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename for s in list(self.metadata_blocks): if isinstance(s, VCFLACDict): ...
Load file information from a filename.
def load(self, filename): """Load file information from a filename.""" self.metadata_blocks = [] self.tags = None self.cuesheet = None self.seektable = None self.filename = filename fileobj = StrictFileObject(open(filename, "rb")) try: self.__...
Save metadata blocks to a file.
def save(self, filename=None, deleteid3=False): """Save metadata blocks to a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename f = open(filename, 'rb+') try: # Ensure we've got...
Parses an Alias tag beneath a ResourceRecordSet spitting out the two values found within. This is specific to A records that are set to Alias.
def parse_rrset_alias(e_alias): """ Parses an Alias tag beneath a ResourceRecordSet, spitting out the two values found within. This is specific to A records that are set to Alias. :param lxml.etree._Element e_alias: An Alias tag beneath a ResourceRecordSet. :rtype: tuple :returns: A tuple in th...
Used to parse the various Values from the ResourceRecords tags on most rrset types.
def parse_rrset_record_values(e_resource_records): """ Used to parse the various Values from the ResourceRecords tags on most rrset types. :param lxml.etree._Element e_resource_records: A ResourceRecords tag beneath a ResourceRecordSet. :rtype: list :returns: A list of resource record s...
This a parser that allows the passing of any valid ResourceRecordSet tag. It will spit out the appropriate ResourceRecordSet object for the tag.
def parse_rrset(e_rrset, connection, zone_id): """ This a parser that allows the passing of any valid ResourceRecordSet tag. It will spit out the appropriate ResourceRecordSet object for the tag. :param lxml.etree._Element e_rrset: The root node of the etree parsed response from the API. :p...
Parses the API responses for the: py: meth: route53. connection. Route53Connection. list_resource_record_sets_by_zone_id method.
def list_resource_record_sets_by_zone_id_parser(e_root, connection, zone_id): """ Parses the API responses for the :py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id` method. :param lxml.etree._Element e_root: The root node of the etree parsed response from ...
: rtype: list: returns: A list of nameserver strings for this hosted zone.
def nameservers(self): """ :rtype: list :returns: A list of nameserver strings for this hosted zone. """ # If this HostedZone was instantiated by ListHostedZones, the nameservers # attribute didn't get populated. If the user requests it, we'll # lazy load by quer...
Deletes this hosted zone. After this method is ran you won t be able to add records or do anything else with the zone. You d need to re - create it as zones are read - only after creation.
def delete(self, force=False): """ Deletes this hosted zone. After this method is ran, you won't be able to add records, or do anything else with the zone. You'd need to re-create it, as zones are read-only after creation. :keyword bool force: If ``True``, delete the ...
Convenience method for creating ResourceRecordSets. Most of the calls are basically the same this saves on repetition.
def _add_record(self, record_set_class, name, values, ttl=60, weight=None, region=None,set_identifier=None, alias_hosted_zone_id=None, alias_dns_name=None): """ Convenience method for creating ResourceRecordSets. Most of the calls are basically the same, t...
Creates and returns an A record attached to this hosted zone.
def create_a_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None, alias_hosted_zone_id=None, alias_dns_name=None): """ Creates and returns an A record attached to this hosted zone. :param str name: The fully qualified name o...
Creates an AAAA record attached to this hosted zone.
def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates an AAAA record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings...
Creates a CNAME record attached to this hosted zone.
def create_cname_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates a CNAME record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value str...
Creates a MX record attached to this hosted zone.
def create_mx_record(self, name, values, ttl=60): """ Creates a MX record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (i...
Creates a NS record attached to this hosted zone.
def create_ns_record(self, name, values, ttl=60): """ Creates a NS record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (i...
Creates a PTR record attached to this hosted zone.
def create_ptr_record(self, name, values, ttl=60): """ Creates a PTR record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
Creates a SPF record attached to this hosted zone.
def create_spf_record(self, name, values, ttl=60): """ Creates a SPF record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
Creates a SRV record attached to this hosted zone.
def create_srv_record(self, name, values, ttl=60): """ Creates a SRV record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
Creates a TXT record attached to this hosted zone.
def create_txt_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates a TXT record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings ...
Register a user - defined text frame key.
def RegisterTXXXKey(cls, key, desc): """Register a user-defined text frame key. Some ID3 tags are stored in TXXX frames, which allow a freeform 'description' which acts as a subkey, e.g. TXXX:BARCODE.:: EasyID3.RegisterTXXXKey('barcode', 'BARCODE'). """ fram...
In the case of deletions we pull the change values for the XML request from the ResourceRecordSet. _initial_vals dict since we want the original values. For creations we pull from the attributes on ResourceRecordSet.
def get_change_values(change): """ In the case of deletions, we pull the change values for the XML request from the ResourceRecordSet._initial_vals dict, since we want the original values. For creations, we pull from the attributes on ResourceRecordSet. Since we're dealing with attributes vs. dict ...
Creates an XML element for the change.
def write_change(change): """ Creates an XML element for the change. :param tuple change: A change tuple from a ChangeSet. Comes in the form of ``(action, rrset)``. :rtype: lxml.etree._Element :returns: A fully baked Change tag. """ action, rrset = change change_vals = get_cha...
Forms an XML string that we ll send to Route53 in order to change record sets.
def change_resource_record_set_writer(connection, change_set, comment=None): """ Forms an XML string that we'll send to Route53 in order to change record sets. :param Route53Connection connection: The connection instance used to query the API. :param change_set.ChangeSet change_set: The Cha...
Initiate log file.
def init_logs(): """Initiate log file.""" start_time = dt.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M') logname = os.path.join(os.path.expanduser("~") + "/nanoGUI_" + start_time + ".log") handlers = [logging.FileHandler(logname)] logging.basicConfig( format='%(asctime)s %(message)s', ...
Check if text Entry is valid ( number ).
def validate_integer(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): """Check if text Entry is valid (number). I have no idea what all these arguments are doing here but took this from https://stackoverflow.com/ques...
Gets an item by its alias.
def alias_item(self, alias): """Gets an item by its alias.""" ident = self.alias[alias] return self.items[ident]
Freezes dict into tuple.
def freeze_dict(dict_): """Freezes ``dict`` into ``tuple``. A typical usage is packing ``dict`` into hashable. e.g.:: >>> freeze_dict({'a': 1, 'b': 2}) (('a', 1), ('b', 2)) """ pairs = dict_.items() key_getter = operator.itemgetter(0) return tuple(sorted(pairs, key=key_get...
Joins the map structure into HTML attributes.
def join_html_attrs(attrs): """Joins the map structure into HTML attributes. The return value is a 2-tuple ``(template, ordered_values)``. It should be passed into :class:`markupsafe.Markup` to prevent XSS attacked. e.g.:: >>> join_html_attrs({'href': '/', 'data-active': 'true'}) ('da...
Initializes an app to work with this extension.
def init_app(self, app): """Initializes an app to work with this extension. The app-context signals will be subscribed and the template context will be initialized. :param app: the :class:`flask.Flask` app instance. """ # connects app-level signals appcontext_pu...
Calls the initializers of all bound navigation bars.
def initialize_bars(self, sender=None, **kwargs): """Calls the initializers of all bound navigation bars.""" for bar in self.bars.values(): for initializer in bar.initializers: initializer(self)
Binds a navigation bar into this extension instance.
def bind_bar(self, sender=None, **kwargs): """Binds a navigation bar into this extension instance.""" bar = kwargs.pop('bar') self.bars[bar.name] = bar
The arguments which will be passed to url_for.
def args(self): """The arguments which will be passed to ``url_for``. :type: :class:`dict` """ if self._args is None: return {} if callable(self._args): return dict(self._args()) return dict(self._args)
The final url of this navigation item.
def url(self): """The final url of this navigation item. By default, the value is generated by the :attr:`self.endpoint` and :attr:`self.args`. .. note:: The :attr:`url` property require the app context without a provided config value :const:`SERVER_NAME`, becaus...
True if current request has same endpoint with the item.
def is_current(self): """``True`` if current request has same endpoint with the item. The property should be used in a bound request context, or the :class:`RuntimeError` may be raised. """ if not self.is_internal: return False # always false for external url ...
Set lang
def lang(self, language): """Set lang""" if isinstance(language, str): self._lang = [language] elif isinstance(language, collections.Iterable): self._lang = list(language) if any(lang not in self._supported_langs for lang in self._lang): raise BadArgu...
Set config_path
def config_path(self, value): """Set config_path""" self._config_path = value or '' if not isinstance(self._config_path, str): raise BadArgumentError("config_path must be string: {}".format( self._config_path))
Set dictionary
def dictionary(self, value): """Set dictionary""" self._dictionary = value or {} if not isinstance(self._dictionary, dict): raise BadArgumentError("dictionary must be dict: {}".format( self._dictionary))
current spelling settings: return: api options as number
def api_options(self): """ current spelling settings :return: api options as number """ options = 0 if self._ignore_uppercase: options |= 1 if self._ignore_digits: options |= 2 if self._ignore_urls: options |= 4 ...
Does basic Metric option validation.
def validate(metric_class): """ Does basic Metric option validation. """ if not hasattr(metric_class, 'label'): raise ImproperlyConfigured("No 'label' attribute found for metric %s." % metric_class.__name__) if not hasattr(metric_class, 'widget'): raise ImproperlyConfigured("No...
Fetches a statistics based on the given class name. Does a look - up in the gadgets registered statistics to find the specified one.
def get_statistic_by_name(stat_name): """ Fetches a statistics based on the given class name. Does a look-up in the gadgets' registered statistics to find the specified one. """ if stat_name == 'ALL': return get_statistic_models() for stat in get_statistic_models(): if stat.__n...
Calculates all of the metrics associated with the registered gadgets.
def calculate_statistics(stat, frequencies): """ Calculates all of the metrics associated with the registered gadgets. """ stats = ensure_list(stat) frequencies = ensure_list(frequencies) for stat in stats: for f in frequencies: print "Calculating %s (%s)..." % (stat.__name_...
Resets the specified statistic s data ( deletes it ) for the given frequency/ ies.
def reset_statistics(stat, frequencies, reset_cumulative, recalculate=False): """ Resets the specified statistic's data (deletes it) for the given frequency/ies. """ stats = ensure_list(stat) frequencies = ensure_list(frequencies) for s in stats: for f in frequencies: i...
Auto - discover INSTALLED_APPS gadgets. py modules and fail silently when not present. This forces an import on them to register any gadgets they may want.
def autodiscover(): """ Auto-discover INSTALLED_APPS gadgets.py modules and fail silently when not present. This forces an import on them to register any gadgets they may want. """ from django.conf import settings from django.utils.importlib import import_module from django.utils.module_...
Returns a CSV dump of all of the specified metric s counts and cumulative counts.
def csv_dump(request, uid): """ Returns a CSV dump of all of the specified metric's counts and cumulative counts. """ metric = Metric.objects.get(uid=uid) frequency = request.GET.get('frequency', settings.STATISTIC_FREQUENCY_DAILY) response = HttpResponse(mimetype='text/csv') response[...
Runs the calculator for this type of statistic.
def calculate(cls, frequency=settings.STATISTIC_FREQUENCY_DAILY, verbose=settings.STATISTIC_CALCULATION_VERBOSE): """ Runs the calculator for this type of statistic. """ if verbose: print _("Calculating statistics for %(class)s...") % {'class': cls.get_label()} start...