INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Normalize any unicode characters to ascii equivalent https:// docs. python. org/ 2/ library/ unicodedata. html#unicodedata. normalize
def normalize_unicode(text): """ Normalize any unicode characters to ascii equivalent https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize """ if isinstance(text, six.text_type): return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf8') else:...
Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character.
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True): """ Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character. """ if ngrams is None: ngrams = 1 ...
attempt to build using CMake > = 3
def cmake_setup(): """ attempt to build using CMake >= 3 """ cmake_exe = shutil.which('cmake') if not cmake_exe: raise FileNotFoundError('CMake not available') wopts = ['-G', 'MinGW Makefiles', '-DCMAKE_SH="CMAKE_SH-NOTFOUND'] if os.name == 'nt' else [] subprocess.check_call([cmake...
attempt to build with Meson + Ninja
def meson_setup(): """ attempt to build with Meson + Ninja """ meson_exe = shutil.which('meson') ninja_exe = shutil.which('ninja') if not meson_exe or not ninja_exe: raise FileNotFoundError('Meson or Ninja not available') if not (BINDIR / 'build.ninja').is_file(): subproces...
Adds an occurrence of the term in the specified document.
def add_term_occurrence(self, term, document): """ Adds an occurrence of the term in the specified document. """ if document not in self._documents: self._documents[document] = 0 if term not in self._terms: if self._freeze: return ...
Gets the frequency of the specified term in the entire corpus added to the HashedIndex.
def get_total_term_frequency(self, term): """ Gets the frequency of the specified term in the entire corpus added to the HashedIndex. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) return sum(self._terms[term].values())
Returns the frequency of the term specified in the document.
def get_term_frequency(self, term, document, normalized=False): """ Returns the frequency of the term specified in the document. """ if document not in self._documents: raise IndexError(DOCUMENT_DOES_NOT_EXIST) if term not in self._terms: raise IndexError...
Returns the number of documents the specified term appears in.
def get_document_frequency(self, term): """ Returns the number of documents the specified term appears in. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) else: return len(self._terms[term])
Returns the number of terms found within the specified document.
def get_document_length(self, document): """ Returns the number of terms found within the specified document. """ if document in self._documents: return self._documents[document] else: raise IndexError(DOCUMENT_DOES_NOT_EXIST)
Returns all documents related to the specified term in the form of a Counter object.
def get_documents(self, term): """ Returns all documents related to the specified term in the form of a Counter object. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) else: return self._terms[term]
Returns the Term - Frequency Inverse - Document - Frequency value for the given term in the specified document. If normalized is True term frequency will be divided by the document length.
def get_tfidf(self, term, document, normalized=False): """ Returns the Term-Frequency Inverse-Document-Frequency value for the given term in the specified document. If normalized is True, term frequency will be divided by the document length. """ tf = self.get_term_freque...
Returns a representation of the specified document as a feature vector weighted according the mode specified ( by default tf - dif ).
def generate_document_vector(self, doc, mode='tfidf'): """ Returns a representation of the specified document as a feature vector weighted according the mode specified (by default tf-dif). A custom weighting function can also be passed which receives the hashedindex instance, th...
Returns a feature matrix in the form of a list of lists which represents the terms and documents in this Inverted Index using the tf - idf weighting by default. The term counts in each document can alternatively be used by specifying scheme = count.
def generate_feature_matrix(self, mode='tfidf'): """ Returns a feature matrix in the form of a list of lists which represents the terms and documents in this Inverted Index using the tf-idf weighting by default. The term counts in each document can alternatively be used by specif...
Returns the first occurrence of an instance of type klass in the given list or None if no such instance is present.
def find_class_in_list(klass, lst): """ Returns the first occurrence of an instance of type `klass` in the given list, or None if no such instance is present. """ filtered = list(filter(lambda x: x.__class__ == klass, lst)) if filtered: return filtered[0] return None
Returns a tuple containing an entry corresponding to each of the requested class types where the entry is either the first object instance of that type or None of no such instances are available. Example Usage: find_classes_in_list ( [ Address Response ] [ <classes. Response... > <classes. Amount... > <classes. Address...
def find_classes_in_list(klasses, lst): """ Returns a tuple containing an entry corresponding to each of the requested class types, where the entry is either the first object instance of that type or None of no such instances are available. Example Usage: find_classes_in_list( ...
Converts a dictionary of name and value pairs into a PARMLIST string value acceptable to the Payflow Pro API.
def _build_parmlist(self, parameters): """ Converts a dictionary of name and value pairs into a PARMLIST string value acceptable to the Payflow Pro API. """ args = [] for key, value in parameters.items(): if not value is None: # We always us...
Parses a PARMLIST string into a dictionary of name and value pairs. The parsing is complicated by the following: - parameter keynames may or may not include a length specification - delimiter characters ( = & ) may appear inside parameter values provided the parameter has an explicit length. For example the following p...
def _parse_parmlist(self, parmlist): """ Parses a PARMLIST string into a dictionary of name and value pairs. The parsing is complicated by the following: - parameter keynames may or may not include a length specification - delimiter characters (=, &) may a...
Send a http request to the given * url * try to decode the reply assuming it s JSON in UTF - 8 and return the result
def request(self, url): """ Send a http request to the given *url*, try to decode the reply assuming it's JSON in UTF-8, and return the result :returns: Decoded result, or None in case of an error :rtype: mixed """ self.logger.debug('url:\n' + url) try: ...
Issue a geocoding query for * address * to the Nominatim instance and return the decoded results
def query(self, address, acceptlanguage=None, limit=20, countrycodes=None): """ Issue a geocoding query for *address* to the Nominatim instance and return the decoded results :param address: a query string with an address or presumed parts of an add...
Issue a reverse geocoding query for a place given by * lat * and * lon * or by * osm_id * and * osm_type * to the Nominatim instance and return the decoded results
def query(self, lat=None, lon=None, osm_id=None, osm_type=None, acceptlanguage='', zoom=18): """ Issue a reverse geocoding query for a place given by *lat* and *lon*, or by *osm_id* and *osm_type* to the Nominatim instance and return the decoded results :param lat:...
Define a grid using the specifications of a given model.
def from_model(cls, model_name, **kwargs): """ Define a grid using the specifications of a given model. Parameters ---------- model_name : string Name the model (see :func:`get_supported_models` for available model names). Supports multiple fo...
Set - up a user - defined grid using specifications of a reference grid model.
def copy_from_model(cls, model_name, reference, **kwargs): """ Set-up a user-defined grid using specifications of a reference grid model. Parameters ---------- model_name : string name of the user-defined grid model. reference : string or :class:`CTMG...
Compute scalars or coordinates associated to the vertical layers.
def get_layers(self, Psurf=1013.25, Ptop=0.01, **kwargs): """ Compute scalars or coordinates associated to the vertical layers. Parameters ---------- grid_spec : CTMGrid object CTMGrid containing the information necessary to re-construct grid levels for a...
Calculate longitude - latitude grid for a specified resolution and configuration/ ordering.
def get_lonlat(self): """ Calculate longitude-latitude grid for a specified resolution and configuration / ordering. Parameters ---------- rlon, rlat : float Resolution (in degrees) of longitude and latitude grids. halfpolar : bool (default=True) ...
existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir wins!
def _get_template_dirs(): """existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir wins!""" return filter(lambda x: os.path.exists(x), [ # user dir os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'), ...
try to get a license from the classifiers
def _license_from_classifiers(data): """try to get a license from the classifiers""" classifiers = data.get('classifiers', []) found_license = None for c in classifiers: if c.startswith("License :: OSI Approved :: "): found_license = c.replace("License :: OSI Approved :: ", "") r...
try to get SDPX license
def _normalize_license(data): """try to get SDPX license""" license = data.get('license', None) if not license: # try to get license from classifiers license = _license_from_classifiers(data) if license: if license in SDPX_LICENSES.keys(): data['license'] = SDPX_LICEN...
Wrap an IPython s Prompt class
def wrap_prompts_class(Klass): """ Wrap an IPython's Prompt class This is needed in order for Prompt to inject the correct escape sequences at the right positions for shell integrations. """ try: from prompt_toolkit.token import ZeroWidthEscape except ImportError: return K...
A generator which yields a list of all valid keys starting at the given start offset. If start is None we will start from the root of the tree.
def get_all_keys(self, start=None): """ A generator which yields a list of all valid keys starting at the given `start` offset. If `start` is `None`, we will start from the root of the tree. """ s = self.stream if not start: start = HEADER_SIZE + self...
Replace the * placeholder in a format string ( fmt ) so that struct. calcsize ( fmt ) is equal to the given size using the format following the placeholder.
def _replace_star(fmt, size): """ Replace the `*` placeholder in a format string (fmt), so that struct.calcsize(fmt) is equal to the given `size` using the format following the placeholder. Raises `ValueError` if number of `*` is larger than 1. If no `*` in `fmt`, returns `fmt` without checking...
Read pre - or suffix of line at current position with given format fmt ( default i ).
def _fix(self, fmt='i'): """ Read pre- or suffix of line at current position with given format `fmt` (default 'i'). """ fmt = self.endian + fmt fix = self.read(struct.calcsize(fmt)) if fix: return struct.unpack(fmt, fix)[0] else: ra...
Return next unformatted line. If format is given unpack content otherwise return byte string.
def readline(self, fmt=None): """ Return next unformatted "line". If format is given, unpack content, otherwise return byte string. """ prefix_size = self._fix() if fmt is None: content = self.read(prefix_size) else: fmt = self.endian + fm...
Skip the next line and returns position and size of line. Raises IOError if pre - and suffix of line do not match.
def skipline(self): """ Skip the next line and returns position and size of line. Raises IOError if pre- and suffix of line do not match. """ position = self.tell() prefix = self._fix() self.seek(prefix, 1) # skip content suffix = self._fix() if ...
Write line ( list of objects ) with given fmt to file. The line will be chained if object is iterable ( except for basestrings ).
def writeline(self, fmt, *args): """ Write `line` (list of objects) with given `fmt` to file. The `line` will be chained if object is iterable (except for basestrings). """ fmt = self.endian + fmt size = struct.calcsize(fmt) fix = struct.pack(self.endian ...
Write lines with given format.
def writelines(self, lines, fmt): """ Write `lines` with given `format`. """ if isinstance(fmt, basestring): fmt = [fmt] * len(lines) for f, line in zip(fmt, lines): self.writeline(f, line, self.endian)
Read while the most significant bit is set then put the 7 least significant bits of all read bytes together to create a number.
def read_varint(stream): """Read while the most significant bit is set, then put the 7 least significant bits of all read bytes together to create a number. """ value = 0 while True: byte = ord(stream.read(1)) if not byte & 0b10000000: return value << 7 | byte va...
Open a GEOS - Chem BPCH file output as an xarray Dataset.
def open_bpchdataset(filename, fields=[], categories=[], tracerinfo_file='tracerinfo.dat', diaginfo_file='diaginfo.dat', endian=">", decode_cf=True, memmap=True, dask=True, return_store=False): """ Open a GEOS-Chem BPCH file output ...
Open multiple bpch files as a single dataset.
def open_mfbpchdataset(paths, concat_dim='time', compat='no_conflicts', preprocess=None, lock=None, **kwargs): """ Open multiple bpch files as a single dataset. You must have dask installed for this to work, as this greatly simplifies issues relating to multi-file I/O. Also, ple...
Write your forwards methods here.
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for entry in orm['multilingual_news.NewsEntry'].objects.all(): self.migrate_placeholder( orm, entry, 'excerpt', 'multilin...
Return a bytes string that displays image given by bytes b in the terminal
def image_bytes(b, filename=None, inline=1, width='auto', height='auto', preserve_aspect_ratio=None): """ Return a bytes string that displays image given by bytes b in the terminal If filename=None, the filename defaults to "Unnamed file" width and height are strings, following the format ...
Display the image given by the bytes b in the terminal.
def display_image_bytes(b, filename=None, inline=1, width='auto', height='auto', preserve_aspect_ratio=None): """ Display the image given by the bytes b in the terminal. If filename=None the filename defaults to "Unnamed file". width and height are strings, following the format N: N chara...
Display an image in the terminal.
def display_image_file(fn, width='auto', height='auto', preserve_aspect_ratio=None): """ Display an image in the terminal. A newline is not printed. width and height are strings, following the format N: N character cells. Npx: N pixels. N%: N percent of the session's width o...
Get requirements from pip requirement files.
def get_requirements(*args): """Get requirements from pip requirement files.""" requirements = set() contents = get_contents(*args) for line in contents.splitlines(): # Strip comments. line = re.sub(r'^#.*|\s#.*', '', line) # Ignore empty lines if line and not line.isspac...
Gets a list of all known bank holidays optionally filtered by division and/ or year: param division: see division constants ; defaults to common holidays: param year: defaults to all available years: return: list of dicts with titles dates etc
def get_holidays(self, division=None, year=None): """ Gets a list of all known bank holidays, optionally filtered by division and/or year :param division: see division constants; defaults to common holidays :param year: defaults to all available years :return: list of dicts with ...
Returns the next known bank holiday: param division: see division constants ; defaults to common holidays: param date: search starting from this date ; defaults to today: return: dict
def get_next_holiday(self, division=None, date=None): """ Returns the next known bank holiday :param division: see division constants; defaults to common holidays :param date: search starting from this date; defaults to today :return: dict """ date = date or datet...
True if the date is a known bank holiday: param date: the date to check: param division: see division constants ; defaults to common holidays: return: bool
def is_holiday(self, date, division=None): """ True if the date is a known bank holiday :param date: the date to check :param division: see division constants; defaults to common holidays :return: bool """ return date in (holiday['date'] for holiday in self.get_ho...
Returns the next work day skipping weekends and bank holidays: param division: see division constants ; defaults to common holidays: param date: search starting from this date ; defaults to today: return: datetime. date ; NB: get_next_holiday returns a dict
def get_next_work_day(self, division=None, date=None): """ Returns the next work day, skipping weekends and bank holidays :param division: see division constants; defaults to common holidays :param date: search starting from this date; defaults to today :return: datetime.date; NB...
True if the date is not a weekend or a known bank holiday: param date: the date to check: param division: see division constants ; defaults to common holidays: return: bool
def is_work_day(self, date, division=None): """ True if the date is not a weekend or a known bank holiday :param date: the date to check :param division: see division constants; defaults to common holidays :return: bool """ return date.weekday() not in self.weeken...
Generator which yields a set of ( rx ry ) tuples which describe all regions for which the world has tile data
def get_all_regions_with_tiles(self): """ Generator which yields a set of (rx, ry) tuples which describe all regions for which the world has tile data """ for key in self.get_all_keys(): (layer, rx, ry) = struct.unpack('>BHH', key) if layer == 1: ...
Returns the coordinates of the given entity UUID inside this world or None if the UUID is not found.
def get_entity_uuid_coords(self, uuid): """ Returns the coordinates of the given entity UUID inside this world, or `None` if the UUID is not found. """ if uuid in self._entity_to_region_map: coords = self._entity_to_region_map[uuid] entities = self.get_ent...
A dict whose keys are the UUIDs ( or just IDs in some cases ) of entities and whose values are the ( rx ry ) coordinates in which that entity can be found. This can be used to easily locate particular entities inside the world.
def _entity_to_region_map(self): """ A dict whose keys are the UUIDs (or just IDs, in some cases) of entities, and whose values are the `(rx, ry)` coordinates in which that entity can be found. This can be used to easily locate particular entities inside the world. """ ...
Convert a string into a fuzzy regular expression pattern.
def create_fuzzy_pattern(pattern): """ Convert a string into a fuzzy regular expression pattern. :param pattern: The input pattern (a string). :returns: A compiled regular expression object. This function works by adding ``.*`` between each of the characters in the input pattern and compiling ...
A list of: class: PasswordEntry objects that don t match the exclude list.
def filtered_entries(self): """A list of :class:`PasswordEntry` objects that don't match the exclude list.""" return [ e for e in self.entries if not any(fnmatch.fnmatch(e.name.lower(), p.lower()) for p in self.exclude_list) ]
Perform a fuzzy search that matches the given characters in the given order.
def fuzzy_search(self, *filters): """ Perform a "fuzzy" search that matches the given characters in the given order. :param filters: The pattern(s) to search for. :returns: The matched password names (a list of strings). """ matches = [] logger.verbose( ...
Select a password from the available choices.
def select_entry(self, *arguments): """ Select a password from the available choices. :param arguments: Refer to :func:`smart_search()`. :returns: The name of a password (a string) or :data:`None` (when no password matched the given `arguments`). """ ma...
Perform a simple search for case insensitive substring matches.
def simple_search(self, *keywords): """ Perform a simple search for case insensitive substring matches. :param keywords: The string(s) to search for. :returns: The matched password names (a generator of strings). Only passwords whose names matches *all* of the given keywords a...
Perform a smart search on the given keywords or patterns.
def smart_search(self, *arguments): """ Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :returns: The matched password names (a list of strings). :raises: The following exceptions can be raised: ...
A list of: class: PasswordEntry objects.
def entries(self): """A list of :class:`PasswordEntry` objects.""" passwords = [] for store in self.stores: passwords.extend(store.entries) return natsort(passwords, key=lambda e: e.name)
An execution context created using: mod: executor. contexts.
def context(self): """ An execution context created using :mod:`executor.contexts`. The value of :attr:`context` defaults to a :class:`~executor.contexts.LocalContext` object with the following characteristics: - The working directory of the execution context is set to ...
Normalize the value of: attr: directory when it s set.
def directory(self, value): """Normalize the value of :attr:`directory` when it's set.""" # Normalize the value of `directory'. set_property(self, "directory", parse_path(value)) # Clear the computed values of `context' and `entries'. clear_property(self, "context") clear...
A list of: class: PasswordEntry objects.
def entries(self): """A list of :class:`PasswordEntry` objects.""" timer = Timer() passwords = [] logger.info("Scanning %s ..", format_path(self.directory)) listing = self.context.capture("find", "-type", "f", "-name", "*.gpg", "-print0") for filename in split(listing, "\...
Make sure: attr: directory exists.
def ensure_directory_exists(self): """ Make sure :attr:`directory` exists. :raises: :exc:`.MissingPasswordStoreError` when the password storage directory doesn't exist. """ if not os.path.isdir(self.directory): msg = "The password storage directory d...
Format: attr: text for viewing on a terminal.
def format_text(self, include_password=True, use_colors=None, padding=True, filters=()): """ Format :attr:`text` for viewing on a terminal. :param include_password: :data:`True` to include the password in the formatted text, :data:`False` to exclude the ...
Read an output s diaginfo. dat file and parse into a DataFrame for use in selecting and parsing categories.
def get_diaginfo(diaginfo_file): """ Read an output's diaginfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- diaginfo_file : str Path to diaginfo.dat Returns ------- DataFrame containing the category information. ...
Read an output s tracerinfo. dat file and parse into a DataFrame for use in selecting and parsing categories.
def get_tracerinfo(tracerinfo_file): """ Read an output's tracerinfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- tracerinfo_file : str Path to tracerinfo.dat Returns ------- DataFrame containing the tracer informati...
Read a chunk of data from a bpch output file.
def read_from_bpch(filename, file_position, shape, dtype, endian, use_mmap=False): """ Read a chunk of data from a bpch output file. Parameters ---------- filename : str Path to file on disk containing the data file_position : int Position (bytes) where desired d...
Helper function to load the data referenced by this bundle.
def _read(self): """ Helper function to load the data referenced by this bundle. """ if self._dask: d = da.from_delayed( delayed(read_from_bpch, )( self.filename, self.file_position, self.shape, self.dtype, self.endian, use_mmap=self._m...
Close this bpch file.
def close(self): """ Close this bpch file. """ if not self.fp.closed: for v in list(self.var_data): del self.var_data[v] self.fp.close()
Read the main metadata packaged within a bpch file indicating the output filetype and its title.
def _read_metadata(self): """ Read the main metadata packaged within a bpch file, indicating the output filetype and its title. """ filetype = self.fp.readline().strip() filetitle = self.fp.readline().strip() # Decode to UTF string, if possible try: ...
Process the header information ( data model/ grid spec )
def _read_header(self): """ Process the header information (data model / grid spec) """ self._header_pos = self.fp.tell() line = self.fp.readline('20sffii') modelname, res0, res1, halfpolar, center180 = line self._attributes.update({ "modelname": str(modelname, 'utf...
Iterate over the block of this bpch file and return handlers in the form of BPCHDataBundle s for access to the data contained therein.
def _read_var_data(self): """ Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data contained therein. """ var_bundles = OrderedDict() var_attrs = OrderedDict() n_vars = 0 while self.fp.tel...
Broadcast 1 - d array arr to ndim dimensions on the first axis ( axis = 0 ) or on the last axis ( axis = 1 ).
def broadcast_1d_array(arr, ndim, axis=1): """ Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid. """ ext_arr = arr ...
Return the current timestamp in machine local time.
def get_timestamp(time=True, date=True, fmt=None): """ Return the current timestamp in machine local time. Parameters: ----------- time, date : Boolean Flag to include the time or date components, respectively, in the output. fmt : str, optional If passed, will override the ...
This is a temporary hot - fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the scale_factor and units attributes we encode with the data we ingest converts the hydrocarbon and chemical attribute to a binary integer instead of a boolean and removes the units attribute from...
def fix_attr_encoding(ds): """ This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scale_factor' and 'units' attributes we encode with the data we ingest, converts the 'hydrocarbon' and 'chemical' attribute to a binary integer ins...
Shell sequence to be run after the command output.
def after_output(command_status): """ Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. """ if command_status not in range(256): raise ValueError("command_status must be an integer in the range 0-255") sys.stdout.write(AFTER_OUTPUT.f...
Write your forwards methods here.
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for entry_title in orm.NewsEntryTitle.objects.all(): entry = NewsEntry.objects.get(pk=entry_title.entry.pk) entry.translate(e...
Get equivalent units that are compatible with the udunits2 library ( thus CF - compliant ).
def get_cfcompliant_units(units, prefix='', suffix=''): """ Get equivalent units that are compatible with the udunits2 library (thus CF-compliant). Parameters ---------- units : string A string representation of the units. prefix : string Will be added at the beginning of th...
Replace characters ( e. g.: $ = - ) of a variable name which may cause problems when using with ( CF - ) netCDF based packages.
def get_valid_varname(varname): """ Replace characters (e.g., ':', '$', '=', '-') of a variable name, which may cause problems when using with (CF-)netCDF based packages. Parameters ---------- varname : string variable name. Notes ----- Characters replacement is based on th...
Given a Variable constructed from GEOS - Chem output enforce CF - compliant metadata and formatting.
def enforce_cf_variable(var, mask_and_scale=True): """ Given a Variable constructed from GEOS-Chem output, enforce CF-compliant metadata and formatting. Until a bug with lazily-loaded data and masking/scaling is resolved in xarray, you have the option to manually mask and scale the data here. Para...
Returns all entries which publication date has been hit or which have no date and which language matches the current language.
def published(self, check_language=True, language=None, kwargs=None, exclude_kwargs=None): """ Returns all entries, which publication date has been hit or which have no date and which language matches the current language. """ if check_language: qs ...
Returns recently published new entries.
def recent(self, check_language=True, language=None, limit=3, exclude=None, kwargs=None, category=None): """ Returns recently published new entries. """ if category: if not kwargs: kwargs = {} kwargs['categories__in'] = [category] ...
Returns the meta description for the given entry.
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 16...
DEPRECATED: Template tag to render a placeholder from an NewsEntry object
def render_news_placeholder(context, obj, name=False, truncate=False): # pragma: nocover # NOQA """ DEPRECATED: Template tag to render a placeholder from an NewsEntry object We don't need this any more because we don't have a placeholders M2M field on the model any more. Just use the default ``render...
Check if the requirement is satisfied by the marker.
def _requirement_filter_by_marker(req): # type: (pkg_resources.Requirement) -> bool """Check if the requirement is satisfied by the marker. This function checks for a given Requirement whether its environment marker is satisfied on the current platform. Currently only the python version and system ...
Find lowest required version.
def _requirement_find_lowest_possible(req): # type: (pkg_resources.Requirement) -> List[str] """Find lowest required version. Given a single Requirement, this function calculates the lowest required version to satisfy it. If the requirement excludes a specific version, then this version will not be...
Cleanup a list of requirement strings ( e. g. from requirements. txt ) to only contain entries valid for this platform and with the lowest required version only.
def _requirements_sanitize(req_list): # type: (List[str]) -> List[str] """ Cleanup a list of requirement strings (e.g. from requirements.txt) to only contain entries valid for this platform and with the lowest required version only. Example ------- >>> from sys import version_info ...
Return a coroutine function.
def _ensure_coroutine_function(func): """Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine! """ if asyncio.iscoroutinefunction(func): return func else: @asyncio.coroutine def coroutine_funct...
Return a string uniquely identifying the event.
def location(self): """Return a string uniquely identifying the event. This string can be used to find the event in the event store UI (cf. id attribute, which is the UUID that at time of writing doesn't let you easily find the event). """ if self._location is None: ...
Return first event matching predicate or None if none exists.
async def find_backwards(self, stream_name, predicate, predicate_label='predicate'): """Return first event matching predicate, or None if none exists. Note: 'backwards', both here and in Event Store, means 'towards the event emitted furthest in the past'. """ logger = self._logg...
Command line interface for the qpass program.
def main(): """Command line interface for the ``qpass`` program.""" # Initialize logging to the terminal. coloredlogs.install() # Prepare for command line argument parsing. action = show_matching_entry program_opts = dict(exclude_list=[]) show_opts = dict(filters=[], use_clipboard=is_clipboa...
Edit the matching entry.
def edit_matching_entry(program, arguments): """Edit the matching entry.""" entry = program.select_entry(*arguments) entry.context.execute("pass", "edit", entry.name)
List the entries matching the given keywords/ patterns.
def list_matching_entries(program, arguments): """List the entries matching the given keywords/patterns.""" output("\n".join(entry.name for entry in program.smart_search(*arguments)))
Show the matching entry on the terminal ( and copy the password to the clipboard ).
def show_matching_entry(program, arguments, use_clipboard=True, quiet=False, filters=()): """Show the matching entry on the terminal (and copy the password to the clipboard).""" entry = program.select_entry(*arguments) if not quiet: formatted_entry = entry.format_text(include_password=not use_clipbo...
Parses a set of Payflow Pro response parameter name and value pairs into a list of PayflowProObjects and returns a tuple containing the object list and a dictionary containing any unconsumed data. The first item in the object list will always be the Response object and the RecurringPayments object ( if any ) will be la...
def parse_parameters(payflowpro_response_data): """ Parses a set of Payflow Pro response parameter name and value pairs into a list of PayflowProObjects, and returns a tuple containing the object list and a dictionary containing any unconsumed data. The first item in the object list will alwa...
Convert items stored in canvas to SVG document. If items is None then all items are convered.
def convert(document, canvas, items=None, tounicode=None): """ Convert 'items' stored in 'canvas' to SVG 'document'. If 'items' is None, then all items are convered. tounicode is a function that get text and returns it's unicode representation. It should be used when national characters are used on canvas. Ret...
Create default SVG document
def SVGdocument(): "Create default SVG document" import xml.dom.minidom implementation = xml.dom.minidom.getDOMImplementation() doctype = implementation.createDocumentType( "svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" ) document= implementation.createDocument(None, "sv...
polyline with 2 vertices using <line > tag
def segment_to_line(document, coords): "polyline with 2 vertices using <line> tag" return setattribs( document.createElement('line'), x1 = coords[0], y1 = coords[1], x2 = coords[2], y2 = coords[3], )
polyline with more then 2 vertices
def polyline(document, coords): "polyline with more then 2 vertices" points = [] for i in range(0, len(coords), 2): points.append("%s,%s" % (coords[i], coords[i+1])) return setattribs( document.createElement('polyline'), points = ' '.join(points), )
smoothed polyline
def smoothline(document, coords): "smoothed polyline" element = document.createElement('path') path = [] points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] def pt(points): x0, y0 = points[0] x1, y1 = points[1] p0 = (2*x0-x1, 2*y0-y1) x0, y0 = points[-1] x1, y1 = points[-2] ...
cubic bezier polyline
def cubic_bezier(document, coords): "cubic bezier polyline" element = document.createElement('path') points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] path = ["M%s %s" %points[0]] for n in xrange(1, len(points), 3): A, B, C = points[n:n+3] path.append("C%s,%s %s,%s %s,%s" % (A[0], A[1]...