text
stringlengths
81
112k
Delete a file. Args: path (str): Path to the file that needs to be deleted. Returns: bool: True if the operation is successful, False otherwise. def __rmfile(path): """Delete a file. Args: path (str): Path to the file that needs to be deleted. Returns: bool: True...
Recursively delete a directory tree. Args: path (str): Path to the directory that needs to be deleted. Returns: bool: True if the operation is successful, False otherwise. def __rmtree(path): """Recursively delete a directory tree. Args: path (str): Path to the directory that...
Delete a file or directory. Args: path (str): Path to the file or directory that needs to be deleted. Returns: bool: True if the operation is successful, False otherwise. def remove(path): """Delete a file or directory. Args: path (str): Path to the file or directory that nee...
Remove all file found by glob.glob(pattern). Args: pattern (str): Pattern of files to remove Returns: bool: True if the operation is successful, False otherwise. def gremove(pattern): """Remove all file found by glob.glob(pattern). Args: pattern (str): Pattern of files to remo...
Read the content of the file. Args: path (str): Path to the file encoding (str): File encoding. Default: utf-8 Returns: str: File content or empty string if there was an error def read(path, encoding="utf-8"): """Read the content of the file. Args: path (str): Path to...
Create a file at the given path if it does not already exists. Args: path (str): Path to the file. content (str): Optional content that will be written in the file. encoding (str): Encoding in which to write the content. Default: ``utf-8`` overwrite (bool): Overwrite the...
Return an object from a dot path. Path can either be a full path, in which case the `get_object` function will try to import the modules in the path and follow it to the final object. Or it can be a path relative to the object passed in as the second argument. Args: path (str): Full or rel...
Load recursively all all subclasses from a module. Args: klass (str or list of str): Class whose subclasses we want to load. modules: List of additional modules or module names that should be recursively imported in order to find all the subclasses of the desired class. Defa...
Return full formatted traceback as a string. def get_exception(): """Return full formatted traceback as a string.""" trace = "" exception = "" exc_list = traceback.format_exception_only( sys.exc_info()[0], sys.exc_info()[1] ) for entry in exc_list: exception += entry tb_list...
Load one or more modules. Args: modules: Either a string full path to a module or an actual module object. def load(self, *modules): """Load one or more modules. Args: modules: Either a string full path to a module or an actual module ob...
Calculate the product filter. def _product_filter(products) -> str: """Calculate the product filter.""" _filter = 0 for product in {PRODUCTS[p] for p in products}: _filter += product return format(_filter, "b")[::-1]
Build base url. def _base_url() -> str: """Build base url.""" _lang: str = "d" _type: str = "n" _with_suggestions: str = "?" return BASE_URI + STBOARD_PATH + _lang + _type + _with_suggestions
Fetch data from rmv.de. async def get_departures( self, station_id: str, direction_id: Optional[str] = None, max_journeys: int = 20, products: Optional[List[str]] = None, ) -> Dict[str, Any]: """Fetch data from rmv.de.""" self.station_id: str = station_id ...
Return travel data. def data(self) -> Dict[str, Any]: """Return travel data.""" data: Dict[str, Any] = {} data["station"] = self.station data["stationId"] = self.station_id data["filter"] = self.products_filter journeys = [] for j in sorted(self.journeys, key=la...
Extract station name. def _station(self) -> str: """Extract station name.""" return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval)
Extract current time. def current_time(self) -> datetime: """Extract current time.""" _date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d") _time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M") return datetime.combine(_date.date(), _time.time...
Pretty print travel times. def output(self) -> None: """Pretty print travel times.""" print("%s - %s" % (self.station, self.now)) print(self.products_filter) for j in sorted(self.journeys, key=lambda k: k.real_departure)[ : self.max_journeys ]: print("--...
:param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type casting with specified callback :param kwargs: additional a...
Process a text file's content. If the file name ends with .gz, read it as gzip file def process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs): ''' Process a text file's content. If the file name ends with .gz, read it as gzip file ''' if mode not in ('rU', 'rt', 'rb', 'r'): raise ...
Read text file content. If the file name ends with .gz, read it as gzip file. If mode argument is provided as 'rb', content will be read as byte stream. By default, content is read as string. def read_file(path, encoding='utf-8', *args, **kwargs): ''' Read text file content. If the file name ends with .gz,...
Write content to a file. If the path ends with .gz, gzip will be used. def write_file(path, content, mode=None, encoding='utf-8'): ''' Write content to a file. If the path ends with .gz, gzip will be used. ''' if not mode: if isinstance(content, bytes): mode = 'wb' else: ...
Read CSV content as a table (list of lists) from an input stream def iter_csv_stream(input_stream, fieldnames=None, sniff=False, *args, **kwargs): ''' Read CSV content as a table (list of lists) from an input stream ''' if 'dialect' not in kwargs and sniff: kwargs['dialect'] = csv.Sniffer().sniff(input...
Iterate through CSV rows in a file. By default, csv.reader() will be used any output will be a list of lists. If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead. CSV sniffing (dialect detection) is enabled by default, set sniff=False to switch it off. def read...
Read CSV rows as table from a file. By default, csv.reader() will be used any output will be a list of lists. If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead. CSV sniffing (dialect detection) is enabled by default, set sniff=False to switch it off. def read...
Write rows data to a CSV file (with or without fieldnames) def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs): ''' Write rows data to a CSV file (with or without fieldnames) ''' if not quoting: quoting = csv.QUOTE_MINIM...
Write rows data to a CSV file (with or without header) def write(file_name, rows, header=None, *args, **kwargs): ''' Write rows data to a CSV file (with or without header) ''' warnings.warn("chirptext.io.CSV is deprecated and will be removed in near future.", DeprecationWarning) write_csv(file_...
Return a string suitable for RFC 2822 compliant Message-ID. E.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. def make_msgid(idstring=None, utc=False): """Return a string suitable for RFC 2822...
Forbid multi-line headers, to prevent header injection. def forbid_multi_line_headers(name, val): """Forbid multi-line headers, to prevent header injection.""" val = smart_text(val) if "\n" in val or "\r" in val: raise BadHeaderError( "Header values can't contain newlines " ...
Send a single email to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. def send_mail( subject, sender,...
Send multiple emails to multiple recipients. Given a datatuple of (subject, message, sender, recipient_list), sends each message to each recipient list. Returns the number of e-mails sent. If auth_user and auth_password are set, they're used to log in. Note: The API for this method is frozen. ...
Ensure we have a connection to the email server. Returns whether or not a new connection was required (True or False). def open(self): """Ensure we have a connection to the email server. Returns whether or not a new connection was required (True or False). """ if self.c...
Close the connection to the email server. def close(self): """Close the connection to the email server.""" try: try: self.connection.quit() except socket.sslerror: # This happens when calling quit() on a TLS connection # som...
Send one or more EmailMessage objects. Returns: int: Number of email messages sent. def send_messages(self, messages): """Send one or more EmailMessage objects. Returns: int: Number of email messages sent. """ if not messages: re...
Send an email. Helper method that does the actual sending. def _send(self, message): """Send an email. Helper method that does the actual sending. """ if not message.recipients(): return False try: self.connection.sendmail( ...
Attache a file with the given filename and content. The filename can be omitted (useful for multipart/alternative messages) and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments. ...
Attache a file from the filesystem. def attach_file(self, path, mimetype=None): """Attache a file from the filesystem.""" filename = os.path.basename(path) content = open(path, "rb").read() self.attach(filename, content, mimetype)
Convert the filename, content, mimetype triple to attachment. def _create_attachment(self, filename, content, mimetype=None): """Convert the filename, content, mimetype triple to attachment.""" if mimetype is None: mimetype, _ = mimetypes.guess_type(filename) if mimetype is ...
Attach an alternative content representation. def attach_alternative(self, content, mimetype=None): """Attach an alternative content representation.""" self.attach(content=content, mimetype=mimetype)
Setup console logging. Info and below go to stdout, others go to stderr. :param bool verbose: Print debug statements. :param str logger: Which logger to set handlers to. Used for testing. def setup_logging(verbose=False, logger=None): """Setup console logging. Info and below go to stdout, others go to std...
Automatically adds a named logger to a function upon function call. :param func: Function to decorate. :return: Decorated function. :rtype: function def with_log(func): """Automatically adds a named logger to a function upon function call. :param func: Function to decorate. :return: Decorat...
Get command line arguments or values from environment variables. :param list argv: Command line argument list to process. For testing. :param dict environ: Environment variables. For testing. :return: Parsed options. :rtype: dict def get_arguments(argv=None, environ=None): """Get command line arg...
Query the AppVeyor API. :raise HandledError: On non HTTP200 responses or invalid JSON response. :param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts'). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: Parsed JSON respo...
Validate config values. :raise HandledError: On invalid config values. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. def validate(config, log): """Validate config values. :raise HandledError: On invali...
Find the build version we're looking for. AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query, only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status update. Returns None if the job isn't q...
Get one or more job IDs and their status associated with a build version. Filters jobs by name if --job-name is specified. :raise HandledError: On invalid JSON data or bad job name. :param str build_version: AppVeyor build version from query_build_version(). :param dict config: Dictionary from get_ar...
Query API again for artifacts. :param iter job_ids: List of AppVeyor jobIDs. :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: List of tuples: (job ID, artifact file name, artifact file size). :rtype: list def query_artifacts(job_ids, log): """Query ...
Determine destination file paths for job artifacts. :param dict config: Dictionary from get_arguments(). :param iter jobs_artifacts: List of job artifacts from query_artifacts(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: Destination file paths (ke...
Wait for AppVeyor job to finish and get all artifacts' URLs. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: Paths and URLs from artifacts_urls. :rtype: dict def get_urls(config, log): """Wait fo...
Download a file. :param dict config: Dictionary from get_arguments(). :param str local_path: Destination path to save file to. :param str url: URL of the file to download. :param int expected_size: Expected file size in bytes. :param int chunk_size: Number of bytes to read in memory before writing ...
Edit .coverage file substituting Windows file paths to Linux paths. :param str local_path: Destination path to save file to. :param logging.Logger log: Logger for this function. Populated by with_log() decorator. def mangle_coverage(local_path, log): """Edit .coverage file substituting Windows file paths ...
Main function. Runs the program. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. def main(config, log): """Main function. Runs the program. :param dict config: Dictionary from get_arguments(). :param logg...
Entry-point from setuptools. def entry_point(): """Entry-point from setuptools.""" signal.signal(signal.SIGINT, lambda *_: getattr(os, '_exit')(0)) # Properly handle Control+C config = get_arguments() setup_logging(config['verbose']) try: main(config) except HandledError: if co...
Consume the receive buffer and return the messages. If there are new messages added to the queue while this funciton is being processed, they will not be returned. This ensures that this terminates in a timely manner. def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]: """Con...
Helper for accessing style values. It exists to avoid checking whether `mapping` is indeed a mapping before trying to get a key. In the context of style dicts, this eliminates "is this a mapping" checks in two common situations: 1) a style argument is None, and 2) a style key's value (e.g., width) can...
Extract callable values from `row`. Replace the callable values with the initial value (if specified) or an empty string. Parameters ---------- row : mapping A data row. The keys are either a single column name or a tuple of column names. The values ta...
Build the style and fields. Parameters ---------- columns : list of str Column names. def build(self, columns): """Build the style and fields. Parameters ---------- columns : list of str Column names. """ self.columns = c...
Construct a style taking `attributes` from the column styles. Parameters ---------- name : str Name of main style (e.g., "header_"). attributes : set of str Adopt these elements from the column styles. Returns ------- The composite style ...
Update auto-width Fields based on `row`. Parameters ---------- row : dict proc_group : {'default', 'override'} Whether to consider 'default' or 'override' key for pre- and post-format processors. Returns ------- True if any widths require...
Return whether group is "default" or "override". In the case of "override", the self.fields pre-format and post-format processors will be set under the "override" key. Parameters ---------- style : dict A style that follows the schema defined in pyout.elements. ...
Render fields with values from `row`. Parameters ---------- row : dict A normalized row. style : dict, optional A style that follows the schema defined in pyout.elements. If None, `self.style` is used. adopt : bool, optional Merge...
Sets up the basic config from the variables passed in all of these are from what Heroku gives you. def get_config(self): """ Sets up the basic config from the variables passed in all of these are from what Heroku gives you. """ self.create_ssl_certs() config = {...
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format that kafka-python expects. def get_brokers(self): """ Parses the KAKFA_URL and returns a list of hostname:port pairs in the format that kafka-python expects. """ return ['{}:{}'.format(parsedUrl...
Creates SSL cert files def create_ssl_certs(self): """ Creates SSL cert files """ for key, file in self.ssl.items(): file["file"] = self.create_temp_file(file["suffix"], file["content"])
Creates file, because environment variables are by default escaped it encodes and then decodes them before write so \n etc. work correctly. def create_temp_file(self, suffix, content): """ Creates file, because environment variables are by default escaped it encodes and then decodes th...
Adds the topic_prefix to topic(s) supplied def prefix_topic(self, topics): """ Adds the topic_prefix to topic(s) supplied """ if not self.topic_prefix or not topics: return topics if not isinstance(topics, str) and isinstance(topics, collections.Iterable): ...
Appends the prefix to the topic before sendingf def send(self, topic, *args, **kwargs): """ Appends the prefix to the topic before sendingf """ prefix_topic = self.heroku_kafka.prefix_topic(topic) return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)
Inherited method should take all specified arguments. :param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type cast...
Casts a type of ``val`` to ``coerce_type`` with ``coercer``. If ``coerce_type`` is bool and no ``coercer`` specified it uses :func:`~django_docker_helpers.utils.coerce_str_to_bool` by default. :param val: a value of any type :param coerce_type: any type :param coercer: provide ...
Helper property to lazy initialize and cache client. Runs :meth:`~django_docker_helpers.config.backends.base.BaseParser.get_client`. :return: an instance of backend-specific client def client(self): """ Helper property to lazy initialize and cache client. Runs :meth:`~django_do...
Splice `value` at its center, retaining a total of `n` characters. Parameters ---------- value : str n : int The total length of the returned ends will not be greater than this value. Characters will be dropped from the center to reach this limit. Returns ------- A tuple o...
Writes into IO stream the uwsgi.ini file content (actually it does smth strange, just look below). uWSGI configs are likely to break INI (YAML, etc) specification (double key definition) so it writes `cfg` object (dict) in "uWSGI Style". >>> import sys >>> cfg = { ... 'static-map': [ ... '/sta...
:param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type casting with specified callback :param kwargs: additional a...
:param itunessd: the whole iTunesSD bytes data :return: translate to tree object, see doc of dics_to_itunessd def itunessd_to_dics(itunessd): """ :param itunessd: the whole iTunesSD bytes data :return: translate to tree object, see doc of dics_to_itunessd """ # header header_size = get_tabl...
:param header_dic: dic of header_table :param tracks_dics: list of all track_table's dics :param playlists_dics_and_indexes: list of all playlists and all their track's indexes :return: the whole iTunesSD bytes data def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes): """ :par...
Add processor functions. Any previous list of processors for `kind` and `key` will be overwritten. Parameters ---------- kind : {"pre", "post"} key : str A registered key. Add the functions (in order) to this key's list of processors. *v...
Wrap format call as a two-argument processor function. def _format(self, _, result): """Wrap format call as a two-argument processor function. """ return self._fmt.format(six.text_type(result))
Return a processor for a style's "transform" function. def transform(function): """Return a processor for a style's "transform" function. """ def transform_fn(_, result): if isinstance(result, Nothing): return result lgr.debug("Transforming %r with %r", ...
Return a processor for a "simple" style value. Parameters ---------- style_key : str A style key. style_value : bool or str A "simple" style value that is either a style attribute (str) and a boolean flag indicating to use the style attribute named by...
Return a processor that extracts the style from `mapping`. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with a "lookup" key whose value is a "mapping" style value that maps a field value to either a style attribut...
Return a processor for a "re_lookup" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with a "re_lookup" style value that consists of a sequence of items where each item should have the form `(regexp, ...
Return a processor for an "interval" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with an "interval" key whose value consists of a sequence of tuples where each tuple should have the form `(start, ...
Yield post-format processors based on `column_style`. Parameters ---------- column_style : dict A style where the top-level keys correspond to style attributes such as "bold" or "color". Returns ------- A generator object. def post_from_style(se...
Return `result` without flanking whitespace. def split_flanks(self, _, result): """Return `result` without flanking whitespace. """ if not result.strip(): self.left, self.right = "", "" return result match = self.flank_re.match(result) assert match, "Thi...
Prepend terminal code for `key` to `value`. Parameters ---------- style_attr : str A style attribute (e.g., "bold" or "blue"). value : str The value to render. Returns ------- The code for `key` (e.g., "\x1b[1m" for bold) plus the ...
A Terminal-specific reset to StyleProcessors.post_from_style. def post_from_style(self, column_style): """A Terminal-specific reset to StyleProcessors.post_from_style. """ for proc in super(TermProcessors, self).post_from_style(column_style): if proc.__name__ == "join_flanks": ...
See signal def connect(self, cback): "See signal" return self.signal.connect(cback, subscribers=self.subscribers, instance=self.instance)
See signal def disconnect(self, cback): "See signal" return self.signal.disconnect(cback, subscribers=self.subscribers, instance=self.instance)
Get per-instance subscribers from the signal. def get_subscribers(self): """Get per-instance subscribers from the signal. """ data = self.signal.instance_subscribers if self.instance not in data: data[self.instance] = MethodAwareWeakList() return data[self.instance]
See signal def notify(self, *args, **kwargs): "See signal" loop = kwargs.pop('loop', self.loop) return self.signal.prepare_notification( subscribers=self.subscribers, instance=self.instance, loop=loop).run(*args, **kwargs)
Like notify allows to pass more options to the underlying `Signal.prepare_notification()` method. The allowed options are: notify_external : bool a flag indicating if the notification should also include the registered `~.external.ExternalSignaller` in the notification. It'...
Add a function or a method as an handler of this signal. Any handler added can be a coroutine. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wrapper def connect(self, cback, subscribers=None, instance=None): ...
Remove a previously added function or method from the set of the signal's handlers. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wrapper def disconnect(self, cback, subscribers=None, instance=None): """Re...
If 'external_signaller' is defined, calls it's publish method to notify external event systems. This is for internal usage only, but it's doumented because it's part of the interface with external notification systems. def ext_publish(self, instance, loop, *args, **kwargs): """If 'exte...
Sets up a and configures an `~.utils.Executor`:class: instance. def prepare_notification(self, *, subscribers=None, instance=None, loop=None, notify_external=True): """Sets up a and configures an `~.utils.Executor`:class: instance.""" # merge callbacks added to the class le...
Configure logging module. Args: filename (str): Specifies a filename to log to. filemode (str): Specifies the mode to open the log file. Values: ``'a'``, ``'w'``. *Default:* ``a``. datefmt (str): Use the specified date/time format. fmt (str): Format string for the file h...
Determine what changes are required. args: existing_users (Users): List of discovered users proposed_users (Users): List of proposed users purge_undefined (bool): Remove discovered users that have not been defined in proposed users list protected_users (list): List of users' names t...
Create, Modify or Delete, depending on plan item. def execute_plan(plan=None): """Create, Modify or Delete, depending on plan item.""" execution_result = list() for task in plan: action = task['action'] if action == 'delete': command = generate_delete_user_command(username=task....
Reads a value of ``variable_path`` from environment. If ``coerce_type`` is ``bool`` and no ``coercer`` specified, ``coerces`` forced to be :func:`~django_docker_helpers.utils.coerce_str_to_bool` :param variable_path: a delimiter-separated path to a nested value :param default: default ...
Unzip a zip archive into destination directory. It unzips either the whole archive or specific file(s) from the archive. Usage: >>> output = os.path.join(os.getcwd(), 'output') >>> # Archive can be an instance of a ZipFile class >>> archive = zipfile.ZipFile('test.zip', 'r') >>...
Recursively zip a directory. Args: archive (zipfile.ZipFile or str): ZipFile object add to or path to the output zip archive. items (str or list of str): Single item or list of items (files and directories) to be added to zipfile. mode (str): w for create new and wri...