sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def output(self, response, accepts): """ Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = self.get_graph(response) if graph is not None: ...
Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling
entailment
def decorate(self, view): """ Wraps a view function to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified """ from functools import wraps @wraps(view) def decorated(*args, **kwargs): response = view...
Wraps a view function to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified
entailment
def ecc(self, n): r""" Calculate eccentricity harmonic `\varepsilon_n`. :param int n: Eccentricity order. """ ny, nx = self._profile.shape xmax, ymax = self._xymax xcm, ycm = self._cm # create (X, Y) grids relative to CM Y, X = np.mgrid[ymax:-ym...
r""" Calculate eccentricity harmonic `\varepsilon_n`. :param int n: Eccentricity order.
entailment
def get(self, var, default=None): """Return a value from configuration. Safe version which always returns a default value if the value is not found. """ try: return self.__get(var) except (KeyError, IndexError): return default
Return a value from configuration. Safe version which always returns a default value if the value is not found.
entailment
def insert(self, var, value, index=None): """Insert at the index. If the index is not provided appends to the end of the list. """ current = self.__get(var) if not isinstance(current, list): raise KeyError("%s: is not a list" % var) if index is None: ...
Insert at the index. If the index is not provided appends to the end of the list.
entailment
def keys(self): """Return a merged set of top level keys from all configurations.""" s = set() for config in self.__configs: s |= config.keys() return s
Return a merged set of top level keys from all configurations.
entailment
def close(self): """Close the stream.""" self.flush() self.stream.close() logging.StreamHandler.close(self)
Close the stream.
entailment
def emit(self, record): """Emit a record. Output the record to the file, catering for rollover as described in doRollover(). """ try: if self.shouldRollover(record): self.doRollover() FileHandler.emit(self, record) except (Keyboard...
Emit a record. Output the record to the file, catering for rollover as described in doRollover().
entailment
def doRollover(self): """Do a rollover, as described in __init__().""" self.stream.close() try: if self.backupCount > 0: tmp_location = "%s.0" % self.baseFilename os.rename(self.baseFilename, tmp_location) for i in range(self.backupCoun...
Do a rollover, as described in __init__().
entailment
def shouldRollover(self, record): """Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. """ if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) self...
Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have.
entailment
def split(s, posix=True): """Split the string s using shell-like syntax. Args: s (str): String to split posix (bool): Use posix split Returns: list of str: List of string parts """ if isinstance(s, six.binary_type): s = s.decode("utf-8") return shlex.split(s, po...
Split the string s using shell-like syntax. Args: s (str): String to split posix (bool): Use posix split Returns: list of str: List of string parts
entailment
def search(path, matcher="*", dirs=False, files=True): """Recursive search function. Args: path (str): Path to search recursively matcher (str or callable): String pattern to search for or function that returns True/False for a file argument dirs (bool): if True returns dire...
Recursive search function. Args: path (str): Path to search recursively matcher (str or callable): String pattern to search for or function that returns True/False for a file argument dirs (bool): if True returns directories that match the pattern files(bool): if True re...
entailment
def chdir(directory): """Change the current working directory. Args: directory (str): Directory to go to. """ directory = os.path.abspath(directory) logger.info("chdir -> %s" % directory) try: if not os.path.isdir(directory): logger.error( "chdir -> %...
Change the current working directory. Args: directory (str): Directory to go to.
entailment
def goto(directory, create=False): """Context object for changing directory. Args: directory (str): Directory to go to. create (bool): Create directory if it doesn't exists. Usage:: >>> with goto(directory) as ok: ... if not ok: ... print 'Error' ...
Context object for changing directory. Args: directory (str): Directory to go to. create (bool): Create directory if it doesn't exists. Usage:: >>> with goto(directory) as ok: ... if not ok: ... print 'Error' ... else: ... print ...
entailment
def mkdir(path, mode=0o755, delete=False): """Make a directory. Create a leaf directory and all intermediate ones. Works like ``mkdir``, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. Args: path (str): Directory t...
Make a directory. Create a leaf directory and all intermediate ones. Works like ``mkdir``, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. Args: path (str): Directory to create mode (int): Directory mode ...
entailment
def __copyfile(source, destination): """Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation...
Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise.
entailment
def __copyfile2(source, destination): """Copy data and all stat info ("cp -p source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the o...
Copy data and all stat info ("cp -p source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise.
entailment
def __copytree(source, destination, symlinks=False): """Copy a directory tree recursively using copy2(). The destination directory must not already exist. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the ...
Copy a directory tree recursively using copy2(). The destination directory must not already exist. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are c...
entailment
def copy(source, destination): """Copy file or directory. Args: source (str): Source file or directory destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise. """ if os.path.isdir(source): ...
Copy file or directory. Args: source (str): Source file or directory destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise.
entailment
def gcopy(pattern, destination): """Copy all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise. """ for item ...
Copy all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise.
entailment
def move(source, destination): """Move a file or directory (recursively) to another location. If the destination is on our current file system, then simply use rename. Otherwise, copy source to the destination and then remove source. Args: source (str): Source file or directory (file or di...
Move a file or directory (recursively) to another location. If the destination is on our current file system, then simply use rename. Otherwise, copy source to the destination and then remove source. Args: source (str): Source file or directory (file or directory to move). destination ...
entailment
def gmove(pattern, destination): """Move all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise. """ for item ...
Move all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise.
entailment
def __rmfile(path): """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. """ logger.info("rmfile: %s" % path) try: os.remove(path) return True except Exception as ...
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.
entailment
def __rmtree(path): """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. """ logger.info("rmtree: %s" % path) try: shutil.rmtree(path) retur...
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.
entailment
def remove(path): """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. """ if os.path.isdir(path): return __rmtree(path) else: return __rmfil...
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.
entailment
def gremove(pattern): """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. """ for item in glob.glob(pattern): if not remove(item): return False re...
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.
entailment
def read(path, encoding="utf-8"): """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 """ try: with io.open(path, encoding=encoding) as f: ...
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
entailment
def touch(path, content="", encoding="utf-8", overwrite=False): """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....
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...
entailment
def get_object(path="", obj=None): """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. ...
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...
entailment
def load_subclasses(klass, modules=None): """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 ...
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...
entailment
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 = traceback.format_tb(sys.exc_info()[2]) ...
Return full formatted traceback as a string.
entailment
def load(self, *modules): """Load one or more modules. Args: modules: Either a string full path to a module or an actual module object. """ for module in modules: if isinstance(module, six.string_types): try: mo...
Load one or more modules. Args: modules: Either a string full path to a module or an actual module object.
entailment
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]
Calculate the product filter.
entailment
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
Build base url.
entailment
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 self.direction_id: s...
Fetch data from rmv.de.
entailment
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=lambda k: k.real_depart...
Return travel data.
entailment
def _station(self) -> str: """Extract station name.""" return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval)
Extract station name.
entailment
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())
Extract current time.
entailment
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("-------------") pr...
Pretty print travel times.
entailment
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): """ :param variable_path: a delimiter-separated path to a nested value :para...
: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...
entailment
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 Exception("Invalid file reading mode") with open(path, encoding=encoding, mode=mo...
Process a text file's content. If the file name ends with .gz, read it as gzip file
entailment
def read_file(path, encoding='utf-8', *args, **kwargs): ''' 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. ''' if 'mode' in kwargs and kwargs['mode'] == 'r...
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.
entailment
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: mode = 'wt' if not path: raise ValueError("Output path is i...
Write content to a file. If the path ends with .gz, gzip will be used.
entailment
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_stream.read(1024)) input_stream.seek(0) if 'quoting' ...
Read CSV content as a table (list of lists) from an input stream
entailment
def read_csv_iter(path, fieldnames=None, sniff=True, mode='rt', encoding='utf-8', *args, **kwargs): ''' 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 inst...
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.
entailment
def read_csv(path, fieldnames=None, sniff=True, encoding='utf-8', *args, **kwargs): ''' 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 sni...
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.
entailment
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_MINIMAL if 'lineterminator' not in kwargs: kw...
Write rows data to a CSV file (with or without fieldnames)
entailment
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_name, rows, fieldnames=header, *args, **kwargs)
Write rows data to a CSV file (with or without header)
entailment
def make_msgid(idstring=None, utc=False): """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. """ if utc: timesta...
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.
entailment
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 " "(got %r for header %r)" % (val, name) ) ...
Forbid multi-line headers, to prevent header injection.
entailment
def send_mail( subject, sender, to, message, html_message=None, cc=None, bcc=None, attachments=None, host=None, port=None, auth_user=None, auth_password=None, use_tls=False, fail_silently=False, ): """Send a single email to a recipient list. ...
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.
entailment
def send_mass_mail( datatuple, fail_silently=False, auth_user=None, auth_password=None ): """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_...
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. ...
entailment
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.connection: # Nothing to do if the connection is already open. return False try: # I...
Ensure we have a connection to the email server. Returns whether or not a new connection was required (True or False).
entailment
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 # sometimes. self.connection.cl...
Close the connection to the email server.
entailment
def send_messages(self, messages): """Send one or more EmailMessage objects. Returns: int: Number of email messages sent. """ if not messages: return new_conn_created = self.open() if not self.connection: # We failed silentl...
Send one or more EmailMessage objects. Returns: int: Number of email messages sent.
entailment
def _send(self, message): """Send an email. Helper method that does the actual sending. """ if not message.recipients(): return False try: self.connection.sendmail( message.sender, message.recipients(), ...
Send an email. Helper method that does the actual sending.
entailment
def attach(self, filename=None, content=None, mimetype=None): """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...
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.
entailment
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)
Attache a file from the filesystem.
entailment
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 None: mimetype = DEFAULT_ATTACHMENT_MIME_TYPE ...
Convert the filename, content, mimetype triple to attachment.
entailment
def attach_alternative(self, content, mimetype=None): """Attach an alternative content representation.""" self.attach(content=content, mimetype=mimetype)
Attach an alternative content representation.
entailment
def setup_logging(verbose=False, logger=None): """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. """ if not verbose: logging.getLogger('requests').set...
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.
entailment
def with_log(func): """Automatically adds a named logger to a function upon function call. :param func: Function to decorate. :return: Decorated function. :rtype: function """ @functools.wraps(func) def wrapper(*args, **kwargs): """Inject `log` argument into wrapped function. ...
Automatically adds a named logger to a function upon function call. :param func: Function to decorate. :return: Decorated function. :rtype: function
entailment
def get_arguments(argv=None, environ=None): """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 """ name = 'a...
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
entailment
def query_api(endpoint, log): """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() decor...
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...
entailment
def validate(config, log): """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. """ if config['always_job_dirs'] and config['no_job_...
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.
entailment
def query_build_version(config, log): """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...
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...
entailment
def query_job_ids(build_version, config, log): """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_ver...
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...
entailment
def query_artifacts(job_ids, log): """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 """...
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
entailment
def artifacts_urls(config, jobs_artifacts, log): """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_l...
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...
entailment
def get_urls(config, log): """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 """ ...
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
entailment
def download_file(config, local_path, url, expected_size, chunk_size, log): """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 ...
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 ...
entailment
def mangle_coverage(local_path, log): """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. """ # Read the file, or return if not a .cove...
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.
entailment
def main(config, log): """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. """ validate(config) paths_and_urls = get_urls(config) if not paths_and_urls: log.w...
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.
entailment
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 config['raise']: rai...
Entry-point from setuptools.
entailment
def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]: """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. ...
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.
entailment
def _safe_get(mapping, key, default=None): """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 ...
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...
entailment
def strip_callables(row): """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 ...
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...
entailment
def build(self, columns): """Build the style and fields. Parameters ---------- columns : list of str Column names. """ self.columns = columns default = dict(elements.default("default_"), **_safe_get(self.init_style, "default_", ...
Build the style and fields. Parameters ---------- columns : list of str Column names.
entailment
def _compose(self, name, attributes): """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. Ret...
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 ...
entailment
def _set_widths(self, row, proc_group): """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...
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...
entailment
def _proc_group(self, style, adopt=True): """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 th...
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. ...
entailment
def render(self, row, style=None, adopt=True): """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`...
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...
entailment
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 = { "bootstrap_servers": self.get_brokers(), "security_protocol": 'SSL', "s...
Sets up the basic config from the variables passed in all of these are from what Heroku gives you.
entailment
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.hostname, parsedUrl.port) for parsedUrl in [urlparse(url) for url in self.kafka_url.split(',')]]
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format that kafka-python expects.
entailment
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 SSL cert files
entailment
def create_temp_file(self, suffix, content): """ Creates file, because environment variables are by default escaped it encodes and then decodes them before write so \n etc. work correctly. """ temp = tempfile.NamedTemporaryFile(suffix=suffix) temp.write(content.encode('l...
Creates file, because environment variables are by default escaped it encodes and then decodes them before write so \n etc. work correctly.
entailment
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): return [self.topic_prefix + topic for top...
Adds the topic_prefix to topic(s) supplied
entailment
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)
Appends the prefix to the topic before sendingf
entailment
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): """ Inherited method should take all specified arguments. :param variable_p...
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...
entailment
def coerce(val: t.Any, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None) -> t.Any: """ Casts a type of ``val`` to ``coerce_type`` with ``coercer``. If ``coerce_type`` is bool and no ``coercer`` specified it uses :func:`~django_...
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 ...
entailment
def client(self): """ 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 """ if self._client is not None: return self._client ...
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
entailment
def _splice(value, n): """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. Ret...
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...
entailment
def write_uwsgi_ini_cfg(fp: t.IO, cfg: dict): """ 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...
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...
entailment
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): """ :param variable_path: a delimiter-separated path to a nested value :para...
: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...
entailment
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_table_size(header_table) header_chunk = itunessd[0:header_size] header_dic = chunk_to_dic(header_chunk, header...
:param itunessd: the whole iTunesSD bytes data :return: translate to tree object, see doc of dics_to_itunessd
entailment
def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes): """ :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 "...
: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
entailment
def add(self, kind, key, *values): """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 ke...
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...
entailment
def _format(self, _, result): """Wrap format call as a two-argument processor function. """ return self._fmt.format(six.text_type(result))
Wrap format call as a two-argument processor function.
entailment
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", result, function) try: retur...
Return a processor for a style's "transform" function.
entailment
def by_key(self, style_key, style_value): """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 boolea...
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...
entailment