repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
xolox/python-rotate-backups
rotate_backups/__init__.py
Location.match
python
def match(self, location): if self.ssh_alias != location.ssh_alias: # Never match locations on other systems. return False elif self.have_wildcards: # Match filename patterns using fnmatch(). return fnmatch.fnmatch(location.directory, self.directory) ...
Check if the given location "matches". :param location: The :class:`Location` object to try to match. :returns: :data:`True` if the two locations are on the same system and the :attr:`directory` can be matched as a filename pattern or a literal match on the normalize...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L773-L792
null
class Location(PropertyManager): """:class:`Location` objects represent a root directory containing backups.""" @required_property def context(self): """An execution context created using :mod:`executor.contexts`.""" @required_property def directory(self): """The pathname of a dir...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment._swap
python
def _swap(self): '''Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed''' self.ref_start, self.qry_start = self.qry_start, self.ref_start self.ref_end, self.qry_end = self.qry_end, self.ref_end self.hit...
Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L52-L58
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.qry_coords
python
def qry_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence''' return pyfastaq.intervals.Interval(min(self.qry_start, self.qry_end), max(self.qry_start, self.qry_end))
Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L61-L63
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.ref_coords
python
def ref_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence''' return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end))
Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L66-L68
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.on_same_strand
python
def on_same_strand(self): '''Returns true iff the direction of the alignment is the same in the reference and the query''' return (self.ref_start < self.ref_end) == (self.qry_start < self.qry_end)
Returns true iff the direction of the alignment is the same in the reference and the query
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L71-L73
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.is_self_hit
python
def is_self_hit(self): '''Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity''' return self.ref_name == self.qry_name \ and self.ref_start == self.qry_start \ and self.ref_end == self.qry_end \ ...
Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L76-L81
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.reverse_query
python
def reverse_query(self): '''Changes the coordinates as if the query sequence has been reverse complemented''' self.qry_start = self.qry_length - self.qry_start - 1 self.qry_end = self.qry_length - self.qry_end - 1
Changes the coordinates as if the query sequence has been reverse complemented
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L84-L87
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.reverse_reference
python
def reverse_reference(self): '''Changes the coordinates as if the reference sequence has been reverse complemented''' self.ref_start = self.ref_length - self.ref_start - 1 self.ref_end = self.ref_length - self.ref_end - 1
Changes the coordinates as if the reference sequence has been reverse complemented
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L90-L93
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.to_msp_crunch
python
def to_msp_crunch(self): '''Returns the alignment as a line in MSPcrunch format. The columns are space-separated and are: 1. score 2. percent identity 3. match start in the query sequence 4. match end in the query sequence 5. query sequence name ...
Returns the alignment as a line in MSPcrunch format. The columns are space-separated and are: 1. score 2. percent identity 3. match start in the query sequence 4. match end in the query sequence 5. query sequence name 6. subject sequence start ...
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L113-L136
null
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/alignment.py
Alignment.qry_coords_from_ref_coord
python
def qry_coords_from_ref_coord(self, ref_coord, variant_list): '''Given a reference position and a list of variants ([variant.Variant]), works out the position in the query sequence, accounting for indels. Returns a tuple: (position, True|False), where second element is whether o...
Given a reference position and a list of variants ([variant.Variant]), works out the position in the query sequence, accounting for indels. Returns a tuple: (position, True|False), where second element is whether or not the ref_coord lies in an indel. If it is, then returns t...
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/alignment.py#L147-L181
[ "def ref_coords(self):\n '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence'''\n return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end))\n" ]
class Alignment: def __init__(self, line): '''Constructs Alignment object from a line of show-coords -dTlro''' # nucmer: # [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [LEN R] [LEN Q] [FRM] [TAGS] #1162 25768 24536 4 24607 24533 99.32 640851 24536 1 -1 ...
sanger-pathogens/pymummer
pymummer/nucmer.py
Runner._nucmer_command
python
def _nucmer_command(self, ref, qry, outprefix): '''Construct the nucmer command''' if self.use_promer: command = 'promer' else: command = 'nucmer' command += ' -p ' + outprefix if self.breaklen is not None: command += ' -b ' + str(self.breakl...
Construct the nucmer command
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/nucmer.py#L53-L83
null
class Runner: '''Handy reference for all the arguments needed for nucmer, delta-filter, show-coords, show-snps''' def __init__( self, ref, query, outfile, min_id=None, min_length=None, breaklen=None, coords_header=True, diagdiff=None, diagfactor=None, ...
sanger-pathogens/pymummer
pymummer/nucmer.py
Runner._delta_filter_command
python
def _delta_filter_command(self, infile, outfile): '''Construct delta-filter command''' command = 'delta-filter' if self.min_id is not None: command += ' -i ' + str(self.min_id) if self.min_length is not None: command += ' -l ' + str(self.min_length) ret...
Construct delta-filter command
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/nucmer.py#L86-L96
null
class Runner: '''Handy reference for all the arguments needed for nucmer, delta-filter, show-coords, show-snps''' def __init__( self, ref, query, outfile, min_id=None, min_length=None, breaklen=None, coords_header=True, diagdiff=None, diagfactor=None, ...
sanger-pathogens/pymummer
pymummer/nucmer.py
Runner._show_coords_command
python
def _show_coords_command(self, infile, outfile): '''Construct show-coords command''' command = 'show-coords -dTlro' if not self.coords_header: command += ' -H' return command + ' ' + infile + ' > ' + outfile
Construct show-coords command
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/nucmer.py#L99-L106
null
class Runner: '''Handy reference for all the arguments needed for nucmer, delta-filter, show-coords, show-snps''' def __init__( self, ref, query, outfile, min_id=None, min_length=None, breaklen=None, coords_header=True, diagdiff=None, diagfactor=None, ...
sanger-pathogens/pymummer
pymummer/nucmer.py
Runner._write_script
python
def _write_script(self, script_name, ref, qry, outfile): '''Write commands into a bash script''' f = pyfastaq.utils.open_file_write(script_name) print(self._nucmer_command(ref, qry, 'p'), file=f) print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f) print(self._s...
Write commands into a bash script
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/nucmer.py#L118-L126
[ "def _nucmer_command(self, ref, qry, outprefix):\n '''Construct the nucmer command'''\n if self.use_promer:\n command = 'promer'\n else:\n command = 'nucmer'\n\n command += ' -p ' + outprefix\n\n if self.breaklen is not None:\n command += ' -b ' + str(self.breaklen)\n\n if sel...
class Runner: '''Handy reference for all the arguments needed for nucmer, delta-filter, show-coords, show-snps''' def __init__( self, ref, query, outfile, min_id=None, min_length=None, breaklen=None, coords_header=True, diagdiff=None, diagfactor=None, ...
sanger-pathogens/pymummer
pymummer/nucmer.py
Runner.run
python
def run(self): ''' Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory ''' qry = os.path.abspath(self.qry) ref = os.path.abspath(self.ref) outfile = os.path.abspath(self.outf...
Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/nucmer.py#L129-L146
[ "def _write_script(self, script_name, ref, qry, outfile):\n '''Write commands into a bash script'''\n f = pyfastaq.utils.open_file_write(script_name)\n print(self._nucmer_command(ref, qry, 'p'), file=f)\n print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f)\n print(self._show_coords...
class Runner: '''Handy reference for all the arguments needed for nucmer, delta-filter, show-coords, show-snps''' def __init__( self, ref, query, outfile, min_id=None, min_length=None, breaklen=None, coords_header=True, diagdiff=None, diagfactor=None, ...
sanger-pathogens/pymummer
pymummer/variant.py
Variant.update_indel
python
def update_indel(self, nucmer_snp): '''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False''' new_v...
Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/variant.py#L62-L84
null
class Variant: def __init__(self, snp): '''Create a Variant object from a pymummer.snp.Snp object''' if snp.ref_base == '.': self.var_type = INS self.qry_base = snp.qry_base self.ref_base = '.' elif snp.qry_base == '.': self.var_type = DEL ...
sanger-pathogens/pymummer
pymummer/coords_file.py
reader
python
def reader(fname): '''Helper function to open the results file (coords file) and create alignment objects with the values in it''' f = pyfastaq.utils.open_file_read(fname) for line in f: if line.startswith('[') or (not '\t' in line): continue yield alignment.Alignment(line) ...
Helper function to open the results file (coords file) and create alignment objects with the values in it
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/coords_file.py#L6-L16
null
import pyfastaq from pymummer import alignment class Error (Exception): pass def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None): '''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely). ACT ignores sequence names in the crunch file, and just looks at th...
sanger-pathogens/pymummer
pymummer/coords_file.py
convert_to_msp_crunch
python
def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None): '''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely). ACT ignores sequence names in the crunch file, and just looks at the numbers. To make a compatible file, the coords all must be shifted appro...
Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely). ACT ignores sequence names in the crunch file, and just looks at the numbers. To make a compatible file, the coords all must be shifted appropriately, which can be done by providing both the ref_fai and qry_fai op...
train
https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/coords_file.py#L19-L47
[ "def reader(fname):\n '''Helper function to open the results file (coords file) and create alignment objects with the values in it'''\n f = pyfastaq.utils.open_file_read(fname)\n\n for line in f:\n if line.startswith('[') or (not '\\t' in line):\n continue\n\n yield alignment.Align...
import pyfastaq from pymummer import alignment class Error (Exception): pass def reader(fname): '''Helper function to open the results file (coords file) and create alignment objects with the values in it''' f = pyfastaq.utils.open_file_read(fname) for line in f: if line.startswith('[') or (not '...
xolox/python-qpass
setup.py
get_requirements
python
def get_requirements(*args): 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.isspace(): requirements.add(re.sub(r'\s+', '', li...
Get requirements from pip requirement files.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/setup.py#L44-L54
[ "def get_contents(*args):\n \"\"\"Get the contents of a file relative to the source distribution directory.\"\"\"\n with codecs.open(get_absolute_path(*args), 'r', 'UTF-8') as handle:\n return handle.read()\n" ]
#!/usr/bin/env python # Setup script for the `qpass' package. # # Author: Peter Odding <peter@peterodding.com> # Last Change: April 26, 2018 # URL: https://github.com/xolox/python-qpass """ Setup script for the ``qpass`` package. **python setup.py install** Install from the working directory into the current Pytho...
xolox/python-qpass
qpass/__init__.py
create_fuzzy_pattern
python
def create_fuzzy_pattern(pattern): return re.compile(".*".join(map(re.escape, pattern)), re.IGNORECASE)
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 the resulting expression into a case insens...
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L431-L442
null
# qpass: Frontend for pass (the standard unix password manager). # # Author: Peter Odding <peter@peterodding.com> # Last Change: December 3, 2018 # URL: https://github.com/xolox/python-qpass """ Frontend for pass_, the standard unix password manager. .. _pass: https://www.passwordstore.org/ """ # Standard library mo...
xolox/python-qpass
qpass/__init__.py
AbstractPasswordStore.filtered_entries
python
def filtered_entries(self): return [ e for e in self.entries if not any(fnmatch.fnmatch(e.name.lower(), p.lower()) for p in self.exclude_list) ]
A list of :class:`PasswordEntry` objects that don't match the exclude list.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L104-L108
null
class AbstractPasswordStore(PropertyManager): """ Abstract Python API to query passwords managed by pass_. This abstract base class has two concrete subclasses: - The :class:`QuickPass` class manages multiple password stores as one. - The :class:`PasswordStore` class manages a single password sto...
xolox/python-qpass
qpass/__init__.py
AbstractPasswordStore.fuzzy_search
python
def fuzzy_search(self, *filters): matches = [] logger.verbose( "Performing fuzzy search on %s (%s) ..", pluralize(len(filters), "pattern"), concatenate(map(repr, filters)) ) patterns = list(map(create_fuzzy_pattern, filters)) for entry in self.filtered_entries: ...
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).
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L110-L130
null
class AbstractPasswordStore(PropertyManager): """ Abstract Python API to query passwords managed by pass_. This abstract base class has two concrete subclasses: - The :class:`QuickPass` class manages multiple password stores as one. - The :class:`PasswordStore` class manages a single password sto...
xolox/python-qpass
qpass/__init__.py
AbstractPasswordStore.select_entry
python
def select_entry(self, *arguments): matches = self.smart_search(*arguments) if len(matches) > 1: logger.info("More than one match, prompting for choice ..") labels = [entry.name for entry in matches] return matches[labels.index(prompt_for_choice(labels))] else...
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`).
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L132-L147
null
class AbstractPasswordStore(PropertyManager): """ Abstract Python API to query passwords managed by pass_. This abstract base class has two concrete subclasses: - The :class:`QuickPass` class manages multiple password stores as one. - The :class:`PasswordStore` class manages a single password sto...
xolox/python-qpass
qpass/__init__.py
AbstractPasswordStore.simple_search
python
def simple_search(self, *keywords): matches = [] keywords = [kw.lower() for kw in keywords] logger.verbose( "Performing simple search on %s (%s) ..", pluralize(len(keywords), "keyword"), concatenate(map(repr, keywords)), ) for entry in self.fil...
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 are returned.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L149-L175
null
class AbstractPasswordStore(PropertyManager): """ Abstract Python API to query passwords managed by pass_. This abstract base class has two concrete subclasses: - The :class:`QuickPass` class manages multiple password stores as one. - The :class:`PasswordStore` class manages a single password sto...
xolox/python-qpass
qpass/__init__.py
AbstractPasswordStore.smart_search
python
def smart_search(self, *arguments): matches = self.simple_search(*arguments) if not matches: logger.verbose("Falling back from substring search to fuzzy search ..") matches = self.fuzzy_search(*arguments) if not matches: if len(self.filtered_entries) > 0: ...
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: - :exc:`.NoMatchingPasswordError` when no matching pas...
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L177-L204
null
class AbstractPasswordStore(PropertyManager): """ Abstract Python API to query passwords managed by pass_. This abstract base class has two concrete subclasses: - The :class:`QuickPass` class manages multiple password stores as one. - The :class:`PasswordStore` class manages a single password sto...
xolox/python-qpass
qpass/__init__.py
QuickPass.entries
python
def entries(self): passwords = [] for store in self.stores: passwords.extend(store.entries) return natsort(passwords, key=lambda e: e.name)
A list of :class:`PasswordEntry` objects.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L219-L224
null
class QuickPass(AbstractPasswordStore): """ Python API to query multiple password stores as if they are one. :see also: The :class:`PasswordStore` class to query a single password store. """ repr_properties = ["stores"] """The properties included in the output of :func:`repr()`.""" @cach...
xolox/python-qpass
qpass/__init__.py
PasswordStore.context
python
def context(self): # Make sure the directory exists. self.ensure_directory_exists() # Prepare the environment variables. environment = {DIRECTORY_VARIABLE: self.directory} try: # Try to enable the GPG agent in headless sessions. environment.update(get_gpg_...
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 the value of :attr:`directory...
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L244-L272
null
class PasswordStore(AbstractPasswordStore): """ Python API to query a single password store. :see also: The :class:`QuickPass` class to query multiple password stores. """ repr_properties = ["directory", "entries"] """The properties included in the output of :func:`repr()`.""" @mutable_p...
xolox/python-qpass
qpass/__init__.py
PasswordStore.directory
python
def directory(self, value): # 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_property(self, "entries")
Normalize the value of :attr:`directory` when it's set.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L292-L298
null
class PasswordStore(AbstractPasswordStore): """ Python API to query a single password store. :see also: The :class:`QuickPass` class to query multiple password stores. """ repr_properties = ["directory", "entries"] """The properties included in the output of :func:`repr()`.""" @mutable_p...
xolox/python-qpass
qpass/__init__.py
PasswordStore.entries
python
def entries(self): 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, "\0"): basename, extension = os.path.splitext(...
A list of :class:`PasswordEntry` objects.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L301-L314
null
class PasswordStore(AbstractPasswordStore): """ Python API to query a single password store. :see also: The :class:`QuickPass` class to query multiple password stores. """ repr_properties = ["directory", "entries"] """The properties included in the output of :func:`repr()`.""" @mutable_p...
xolox/python-qpass
qpass/__init__.py
PasswordStore.ensure_directory_exists
python
def ensure_directory_exists(self): if not os.path.isdir(self.directory): msg = "The password storage directory doesn't exist! (%s)" raise MissingPasswordStoreError(msg % self.directory)
Make sure :attr:`directory` exists. :raises: :exc:`.MissingPasswordStoreError` when the password storage directory doesn't exist.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L316-L325
null
class PasswordStore(AbstractPasswordStore): """ Python API to query a single password store. :see also: The :class:`QuickPass` class to query multiple password stores. """ repr_properties = ["directory", "entries"] """The properties included in the output of :func:`repr()`.""" @mutable_p...
xolox/python-qpass
qpass/__init__.py
PasswordEntry.format_text
python
def format_text(self, include_password=True, use_colors=None, padding=True, filters=()): # Determine whether we can use ANSI escape sequences. if use_colors is None: use_colors = terminal_supports_colors() # Extract the password (first line) from the entry. lines = self.text....
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 password from the formatted text. :param use_colors: :data:`True` to use ANS...
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L362-L428
null
class PasswordEntry(PropertyManager): """:class:`PasswordEntry` objects bind the name of a password to the store that contains the password.""" repr_properties = ["name"] """The properties included in the output of :func:`repr()`.""" @property def context(self): """The :attr:`~PasswordSto...
xolox/python-qpass
qpass/cli.py
main
python
def main(): # 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_clipboard_supported()) verbosity = 0 # Parse the command li...
Command line interface for the ``qpass`` program.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/cli.py#L101-L160
[ "def is_clipboard_supported():\n \"\"\"\n Check whether the clipboard is supported.\n\n :returns: :data:`True` if the clipboard is supported, :data:`False` otherwise.\n \"\"\"\n return platform.system().lower() == \"darwin\" or bool(os.environ.get(\"DISPLAY\"))\n", "def edit_matching_entry(program,...
# qpass: Frontend for pass (the standard unix password manager). # # Author: Peter Odding <peter@peterodding.com> # Last Change: December 3, 2018 # URL: https://github.com/xolox/python-qpass """ Usage: qpass [OPTIONS] KEYWORD.. Search your password store for the given keywords or patterns and copy the password of the...
xolox/python-qpass
qpass/cli.py
edit_matching_entry
python
def edit_matching_entry(program, arguments): entry = program.select_entry(*arguments) entry.context.execute("pass", "edit", entry.name)
Edit the matching entry.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/cli.py#L163-L166
null
# qpass: Frontend for pass (the standard unix password manager). # # Author: Peter Odding <peter@peterodding.com> # Last Change: December 3, 2018 # URL: https://github.com/xolox/python-qpass """ Usage: qpass [OPTIONS] KEYWORD.. Search your password store for the given keywords or patterns and copy the password of the...
xolox/python-qpass
qpass/cli.py
list_matching_entries
python
def list_matching_entries(program, arguments): output("\n".join(entry.name for entry in program.smart_search(*arguments)))
List the entries matching the given keywords/patterns.
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/cli.py#L169-L171
null
# qpass: Frontend for pass (the standard unix password manager). # # Author: Peter Odding <peter@peterodding.com> # Last Change: December 3, 2018 # URL: https://github.com/xolox/python-qpass """ Usage: qpass [OPTIONS] KEYWORD.. Search your password store for the given keywords or patterns and copy the password of the...
xolox/python-qpass
qpass/cli.py
show_matching_entry
python
def show_matching_entry(program, arguments, use_clipboard=True, quiet=False, filters=()): entry = program.select_entry(*arguments) if not quiet: formatted_entry = entry.format_text(include_password=not use_clipboard, filters=filters) if formatted_entry and not formatted_entry.isspace(): ...
Show the matching entry on the terminal (and copy the password to the clipboard).
train
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/cli.py#L174-L182
null
# qpass: Frontend for pass (the standard unix password manager). # # Author: Peter Odding <peter@peterodding.com> # Last Change: December 3, 2018 # URL: https://github.com/xolox/python-qpass """ Usage: qpass [OPTIONS] KEYWORD.. Search your password store for the given keywords or patterns and copy the password of the...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
init_interface
python
def init_interface(): sys.stdout = LoggerWriter(LOGGER.debug) sys.stderr = LoggerWriter(LOGGER.error) warnings.simplefilter('error', UserWarning) try: load_dotenv(join(expanduser("~") + '/.polyglot/.env')) except (UserWarning) as err: LOGGER.warning('File does not exist: {}.'.format(...
Grab the ~/.polyglot/.env file for variables If you are running Polyglot v2 on this same machine then it should already exist. If not create it.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L76-L112
null
#!/usr/bin/env python """ Python Interface for UDI Polyglot v2 NodeServers by Einstein.42 (James Milne) milne.james@gmail.com """ from copy import deepcopy from dotenv import load_dotenv import json import ssl import logging import logging.handlers import __main__ as main import markdown2 import os from os.path import...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._connect
python
def _connect(self, mqttc, userdata, flags, rc): if rc == 0: self.connected = True results = [] LOGGER.info("MQTT Connected with result code " + str(rc) + " (Success)") # result, mid = self._mqttc.subscribe(self.topicInput) results.append((self.topicInp...
The callback for when the client receives a CONNACK response from the server. Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed. :param mqttc: The client instance for this callback :param userdata: The private userdata for ...
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L207-L239
null
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._message
python
def _message(self, mqttc, userdata, msg): try: inputCmds = ['query', 'command', 'result', 'status', 'shortPoll', 'longPoll', 'delete'] parsed_msg = json.loads(msg.payload.decode('utf-8')) if 'node' in parsed_msg: if parsed_msg['node'] != 'polyglot': ...
The callback for when a PUBLISH message is received from the server. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param msg: Dictionary of MQTT received...
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L241-L272
null
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._disconnect
python
def _disconnect(self, mqttc, userdata, rc): self.connected = False if rc != 0: LOGGER.info("MQTT Unexpected disconnection. Trying reconnect.") try: self._mqttc.reconnect() except Exception as ex: template = "An exception of type {0} occ...
The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anything else is unclean
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L274-L292
null
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._startMqtt
python
def _startMqtt(self): LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port)) try: # self._mqttc.connect_async(str(self._server), int(self._port), 10) self._mqttc.connect_async('{}'.format(self._server), int(self._port), 10) self._mqttc.loop_foreve...
The client start method. Starts the thread for the MQTT Client and publishes the connected message.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L313-L326
null
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.stop
python
def stop(self): # self.loop.call_soon_threadsafe(self.loop.stop) # self.loop.stop() # self._longPoll.cancel() # self._shortPoll.cancel() if self.connected: LOGGER.info('Disconnecting from MQTT... {}:{}'.format(self._server, self._port)) self._mqttc.publish...
The client stop method. If the client is currently connected stop the thread and disconnect. Publish the disconnected message if clean shutdown.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L328-L347
null
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.send
python
def send(self, message): if not isinstance(message, dict) and self.connected: warnings.warn('payload not a dictionary') return False try: message['node'] = self.profileNum self._mqttc.publish(self.topicInput, json.dumps(message), retain=False) exce...
Formatted Message to send to Polyglot. Connection messages are sent automatically from this module so this method is used to send commands to/from Polyglot and formats it for consumption
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L349-L361
null
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.addNode
python
def addNode(self, node): LOGGER.info('Adding node {}({})'.format(node.name, node.address)) message = { 'addnode': { 'nodes': [{ 'address': node.address, 'name': node.name, 'node_def_id': node.id, ...
Add a node to the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L363-L382
[ "def send(self, message):\n \"\"\"\n Formatted Message to send to Polyglot. Connection messages are sent automatically from this module\n so this method is used to send commands to/from Polyglot and formats it for consumption\n \"\"\"\n if not isinstance(message, dict) and self.connected:\n wa...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.saveCustomData
python
def saveCustomData(self, data): LOGGER.info('Sending customData to Polyglot.') message = { 'customdata': data } self.send(message)
Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L384-L392
[ "def send(self, message):\n \"\"\"\n Formatted Message to send to Polyglot. Connection messages are sent automatically from this module\n so this method is used to send commands to/from Polyglot and formats it for consumption\n \"\"\"\n if not isinstance(message, dict) and self.connected:\n wa...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.saveCustomParams
python
def saveCustomParams(self, data): LOGGER.info('Sending customParams to Polyglot.') message = { 'customparams': data } self.send(message)
Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L394-L402
[ "def send(self, message):\n \"\"\"\n Formatted Message to send to Polyglot. Connection messages are sent automatically from this module\n so this method is used to send commands to/from Polyglot and formats it for consumption\n \"\"\"\n if not isinstance(message, dict) and self.connected:\n wa...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.addNotice
python
def addNotice(self, data): LOGGER.info('Sending addnotice to Polyglot: {}'.format(data)) message = { 'addnotice': data } self.send(message)
Add custom notice to front-end for this NodeServers :param data: String of characters to add as a notification in the front-end.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L404-L412
[ "def send(self, message):\n \"\"\"\n Formatted Message to send to Polyglot. Connection messages are sent automatically from this module\n so this method is used to send commands to/from Polyglot and formats it for consumption\n \"\"\"\n if not isinstance(message, dict) and self.connected:\n wa...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.removeNotice
python
def removeNotice(self, data): LOGGER.info('Sending removenotice to Polyglot for index {}'.format(data)) message = { 'removenotice': data } self.send(message)
Add custom notice to front-end for this NodeServers :param data: Index of notices list to remove.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L414-L422
[ "def send(self, message):\n \"\"\"\n Formatted Message to send to Polyglot. Connection messages are sent automatically from this module\n so this method is used to send commands to/from Polyglot and formats it for consumption\n \"\"\"\n if not isinstance(message, dict) and self.connected:\n wa...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.delNode
python
def delNode(self, address): LOGGER.info('Removing node {}'.format(address)) message = { 'removenode': { 'address': address } } self.send(message)
Delete a node from the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L439-L451
[ "def send(self, message):\n \"\"\"\n Formatted Message to send to Polyglot. Connection messages are sent automatically from this module\n so this method is used to send commands to/from Polyglot and formats it for consumption\n \"\"\"\n if not isinstance(message, dict) and self.connected:\n wa...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.getNode
python
def getNode(self, address): try: for node in self.config['nodes']: if node['address'] == address: return node return False except KeyError: LOGGER.error('Usually means we have not received the config yet.', exc_info=True) ...
Get Node by Address of existing nodes.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L453-L464
null
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.inConfig
python
def inConfig(self, config): self.config = config self.isyVersion = config['isyVersion'] try: for watcher in self.__configObservers: watcher(config) self.send_custom_config_docs() except KeyError as e: LOGGER.error('KeyError in gotConf...
Save incoming config received from Polyglot to Interface.config and then do any functions that are waiting on the config to be received.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L466-L480
[ "def send_custom_config_docs(self):\n data = ''\n if not self.custom_params_docs_file_sent:\n data = self.get_md_file_data(Interface.CUSTOM_CONFIG_DOCS_FILE_NAME)\n else:\n data = self.config.get('customParamsDoc', '')\n\n # send if we're sending new file or there are updates\n if (not ...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.save_typed_params
python
def save_typed_params(self, data): LOGGER.info('Sending typed parameters to Polyglot.') if type(data) is not list: data = [ data ] message = { 'typedparams': data } self.send(message)
Send custom parameters descriptions to Polyglot to be used in front end UI configuration screen Accepts list of objects with the followin properties name - used as a key when data is sent from UI title - displayed in UI defaultValue - optionanl type - opti...
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L519-L542
[ "def send(self, message):\n \"\"\"\n Formatted Message to send to Polyglot. Connection messages are sent automatically from this module\n so this method is used to send commands to/from Polyglot and formats it for consumption\n \"\"\"\n if not isinstance(message, dict) and self.connected:\n wa...
class Interface(object): CUSTOM_CONFIG_DOCS_FILE_NAME = 'POLYGLOT_CONFIG.md' """ Polyglot Interface Class :param envVar: The Name of the variable from ~/.polyglot/.env that has this NodeServer's profile number """ # pylint: disable=too-many-instance-attributes # pylint: disable=unused-arg...
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Controller.delNode
python
def delNode(self, address): if address in self.nodes: del self.nodes[address] self.poly.delNode(address)
Just send it along if requested, should be able to delete the node even if it isn't in our config anywhere. Usually used for normalization.
train
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L844-L851
null
class Controller(Node): """ Controller Class for controller management. Superclass of Node """ __exists = False def __init__(self, poly, name='Controller'): if self.__exists: warnings.warn('Only one Controller is allowed.') return try: self.contro...
daskos/mentor
mentor/utils.py
remote_exception
python
def remote_exception(exc, tb): if type(exc) in exceptions: typ = exceptions[type(exc)] return typ(exc, tb) else: try: typ = type(exc.__class__.__name__, (RemoteException, type(exc)), {'exception_type': type(exc)}) exce...
Metaclass that wraps exception type in RemoteException
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/utils.py#L61-L74
null
from __future__ import absolute_import, division, print_function import signal from contextlib import contextmanager class TimeoutError(Exception): pass @contextmanager def timeout(seconds): def signal_handler(signum, frame): raise TimeoutError("Timed out!") if seconds > 0: signal.sign...
daskos/mentor
mentor/binpack.py
ff
python
def ff(items, targets): bins = [(target, []) for target in targets] skip = [] for item in items: for target, content in bins: if item <= (target - sum(content)): content.append(item) break else: skip.append(item) return bins, skip
First-Fit This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. Complexity O(n^2)
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/binpack.py#L22-L40
null
from __future__ import absolute_import, division, print_function import operator def weight(items, **kwargs): if not len(kwargs): raise ValueError('Missing attribute for weighting items!') scaled = [] for attr, weight in kwargs.items(): values = [float(getattr(item, attr)) for item in ite...
daskos/mentor
mentor/binpack.py
ffd
python
def ffd(items, targets, **kwargs): sizes = zip(items, weight(items, **kwargs)) sizes = sorted(sizes, key=operator.itemgetter(1), reverse=True) items = map(operator.itemgetter(0), sizes) return ff(items, targets)
First-Fit Decreasing This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. This algorithm differs only from Next-Fit Decreasing in having a 'sort'; that is, the items are pre-sorted (largest to smallest). Complexity O(n^2)
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/binpack.py#L43-L58
[ "def weight(items, **kwargs):\n if not len(kwargs):\n raise ValueError('Missing attribute for weighting items!')\n scaled = []\n for attr, weight in kwargs.items():\n values = [float(getattr(item, attr)) for item in items]\n try:\n s = sum(values)\n scaled.append(...
from __future__ import absolute_import, division, print_function import operator def weight(items, **kwargs): if not len(kwargs): raise ValueError('Missing attribute for weighting items!') scaled = [] for attr, weight in kwargs.items(): values = [float(getattr(item, attr)) for item in ite...
daskos/mentor
mentor/binpack.py
mr
python
def mr(items, targets, **kwargs): bins = [(target, []) for target in targets] skip = [] for item in items: capacities = [target - sum(content) for target, content in bins] weighted = weight(capacities, **kwargs) (target, content), capacity, _ = max(zip(bins, capacities, weighted), ...
Max-Rest Complexity O(n^2)
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/binpack.py#L61-L79
[ "def weight(items, **kwargs):\n if not len(kwargs):\n raise ValueError('Missing attribute for weighting items!')\n scaled = []\n for attr, weight in kwargs.items():\n values = [float(getattr(item, attr)) for item in items]\n try:\n s = sum(values)\n scaled.append(...
from __future__ import absolute_import, division, print_function import operator def weight(items, **kwargs): if not len(kwargs): raise ValueError('Missing attribute for weighting items!') scaled = [] for attr, weight in kwargs.items(): values = [float(getattr(item, attr)) for item in ite...
daskos/mentor
mentor/binpack.py
bf
python
def bf(items, targets, **kwargs): bins = [(target, []) for target in targets] skip = [] for item in items: containers = [] capacities = [] for target, content in bins: capacity = target - sum(content) if item <= capacity: containers.append(con...
Best-Fit Complexity O(n^2)
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/binpack.py#L90-L113
[ "def weight(items, **kwargs):\n if not len(kwargs):\n raise ValueError('Missing attribute for weighting items!')\n scaled = []\n for attr, weight in kwargs.items():\n values = [float(getattr(item, attr)) for item in items]\n try:\n s = sum(values)\n scaled.append(...
from __future__ import absolute_import, division, print_function import operator def weight(items, **kwargs): if not len(kwargs): raise ValueError('Missing attribute for weighting items!') scaled = [] for attr, weight in kwargs.items(): values = [float(getattr(item, attr)) for item in ite...
daskos/mentor
mentor/binpack.py
bfd
python
def bfd(items, targets, **kwargs): sizes = zip(items, weight(items, **kwargs)) sizes = sorted(sizes, key=operator.itemgetter(1), reverse=True) items = map(operator.itemgetter(0), sizes) return bf(items, targets, **kwargs)
Best-Fit Decreasing Complexity O(n^2)
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/binpack.py#L116-L124
[ "def weight(items, **kwargs):\n if not len(kwargs):\n raise ValueError('Missing attribute for weighting items!')\n scaled = []\n for attr, weight in kwargs.items():\n values = [float(getattr(item, attr)) for item in items]\n try:\n s = sum(values)\n scaled.append(...
from __future__ import absolute_import, division, print_function import operator def weight(items, **kwargs): if not len(kwargs): raise ValueError('Missing attribute for weighting items!') scaled = [] for attr, weight in kwargs.items(): values = [float(getattr(item, attr)) for item in ite...
daskos/mentor
mentor/proxies/executor.py
ExecutorDriverProxy.update
python
def update(self, status): logging.info('Executor sends status update {} for task {}'.format( status.state, status.task_id)) return self.driver.sendStatusUpdate(encode(status))
Sends a status update to the framework scheduler. Retrying as necessary until an acknowledgement has been received or the executor is terminated (in which case, a TASK_LOST status update will be sent). See Scheduler.statusUpdate for more information about status update acknowled...
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/executor.py#L108-L119
null
class ExecutorDriverProxy(object): def __init__(self, driver): self.driver = driver def start(self): """Starts the executor driver. This needs to be called before any other driver calls are made. """ logging.info('Driver started') return self.driver.start() ...
daskos/mentor
mentor/proxies/executor.py
ExecutorDriverProxy.message
python
def message(self, data): logging.info('Driver sends framework message {}'.format(data)) return self.driver.sendFrameworkMessage(data)
Sends a message to the framework scheduler. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion.
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/executor.py#L121-L128
null
class ExecutorDriverProxy(object): def __init__(self, driver): self.driver = driver def start(self): """Starts the executor driver. This needs to be called before any other driver calls are made. """ logging.info('Driver started') return self.driver.start() ...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.stop
python
def stop(self, failover=False): logging.info('Stops Scheduler Driver') return self.driver.stop(failover)
Stops the scheduler driver. If the 'failover' flag is set to False then it is expected that this framework will never reconnect to Mesos and all of its executors and tasks can be terminated. Otherwise, all executors and tasks will remain running (for some framework specific failover ti...
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L86-L97
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.request
python
def request(self, requests): logging.info('Request resources from Mesos') return self.driver.requestResources(map(encode, requests))
Requests resources from Mesos. (see mesos.proto for a description of Request and how, for example, to request resources from specific slaves.) Any resources available are offered to the framework via Scheduler.resourceOffers callback, asynchronously.
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L121-L131
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.launch
python
def launch(self, offer_id, tasks, filters=Filters()): logging.info('Launches tasks {}'.format(tasks)) return self.driver.launchTasks(encode(offer_id), map(encode, tasks), encode(filters))
Launches the given set of tasks. Any resources remaining (i.e., not used by the tasks or their executors) will be considered declined. The specified filters are applied on all unused resources (see mesos.proto for a description of Filters). Available resources are aggregated whe...
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L133-L150
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.kill
python
def kill(self, task_id): logging.info('Kills task {}'.format(task_id)) return self.driver.killTask(encode(task_id))
Kills the specified task. Note that attempting to kill a task is currently not reliable. If, for example, a scheduler fails over while it was attempting to kill a task it will need to retry in the future. Likewise, if unregistered / disconnected, the request will be dropped (the...
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L152-L162
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.reconcile
python
def reconcile(self, statuses): logging.info('Reconciles task statuses {}'.format(statuses)) return self.driver.reconcileTasks(map(encode, statuses))
Allows the framework to query the status for non-terminal tasks. This causes the master to send back the latest task status for each task in 'statuses', if possible. Tasks that are no longer known will result in a TASK_LOST update. If statuses is empty, then the master will send the lat...
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L164-L173
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.decline
python
def decline(self, offer_id, filters=Filters()): logging.info('Declines offer {}'.format(offer_id)) return self.driver.declineOffer(encode(offer_id), encode(filters))
Declines an offer in its entirety and applies the specified filters on the resources (see mesos.proto for a description of Filters). Note that this can be done at any time, it is not necessary to do this within the Scheduler::resourceOffers callback.
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L175-L185
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.accept
python
def accept(self, offer_ids, operations, filters=Filters()): logging.info('Accepts offers {}'.format(offer_ids)) return self.driver.acceptOffers(map(encode, offer_ids), map(encode, operations), encode(filters))
Accepts the given offers and performs a sequence of operations on those accepted offers. See Offer.Operation in mesos.proto for the set of available operations. Available resources are aggregated when multiple offers are provided. Note that all offers must belong to the same slave. ...
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L187-L201
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.acknowledge
python
def acknowledge(self, status): logging.info('Acknowledges status update {}'.format(status)) return self.driver.acknowledgeStatusUpdate(encode(status))
Acknowledges the status update. This should only be called once the status update is processed durably by the scheduler. Not that explicit acknowledgements must be requested via the constructor argument, otherwise a call to this method will cause the driver to crash.
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L221-L232
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
daskos/mentor
mentor/proxies/scheduler.py
SchedulerDriverProxy.message
python
def message(self, executor_id, slave_id, message): logging.info('Sends message `{}` to executor `{}` on slave `{}`'.format( message, executor_id, slave_id)) return self.driver.sendFrameworkMessage(encode(executor_id), encode(slave_id),...
Sends a message from the framework to one of its executors. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion.
train
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L234-L244
null
class SchedulerDriverProxy(object): """Proxy Interface for Mesos scheduler drivers.""" def __init__(self, driver): self.driver = driver def start(self): """Starts the scheduler driver. This needs to be called before any other driver calls are made. """ logging.info...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.query
python
async def query(self, path, method='get', **params): if method in ('get', 'post', 'patch', 'delete', 'put'): full_path = self.host + path if method == 'get': resp = await self.aio_sess.get(full_path, params=params) elif method == 'post': resp =...
Do a query to the System API :param path: url to the API :param method: the kind of query to do :param params: a dict with all the necessary things to query the API :return json data
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L60-L91
null
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.handle_json_response
python
async def handle_json_response(responses): json_data = {} if responses.status != 200: err_msg = HttpProcessingError(code=responses.status, message=await responses.json()) logging.error("Wallabag: aiohttp error {err_msg}".format( ...
get the json data response :param responses: the json response :return the json data without 'root' node
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L94-L115
null
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.__get_attr
python
def __get_attr(what, type_attr, value_attr, **kwargs): if what in kwargs: value = int(kwargs[what]) if type_attr == 'int' else kwargs[what] if value in value_attr: return value
get the value of a parm :param what: string parm :param type_attr: type of parm :param value_attr: :param kwargs: :return: value of the parm
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L118-L130
null
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.get_entries
python
async def get_entries(self, **kwargs): # default values params = dict({'access_token': self.token, 'sort': 'created', 'order': 'desc', 'page': 1, 'perPage': 30, 'tags': '', ...
GET /api/entries.{_format} Retrieve all entries. It could be filtered by many options. :param kwargs: can contain one of the following filters archive: '0' or '1', default '0' filter by archived status. starred: '0' or '1', default '0' filter by starred status. sor...
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L133-L177
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.post_entries
python
async def post_entries(self, url, title='', tags='', starred=0, archive=0, content='', language='', published_at='', authors='', public=1, original_url=''): params = {'access_token': self.token, 'url': url, 'title': title, 'tags': tags, 'starred': starred, 'archive':...
POST /api/entries.{_format} Create an entry :param url: the url of the note to store :param title: Optional, we'll get the title from the page. :param tags: tag1,tag2,tag3 a comma-separated list of tags. :param starred entry already starred :param archive entry already ...
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L179-L206
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.get_entry
python
async def get_entry(self, entry): params = {'access_token': self.token} url = '/api/entries/{entry}.{ext}'.format(entry=entry, ext=self.format) return await self.query(url, "get", **params)
GET /api/entries/{entry}.{_format} Retrieve a single entry :param entry: \w+ an integer The Entry ID :return data related to the ext
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L208-L220
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.patch_entries
python
async def patch_entries(self, entry, **kwargs): # default values params = {'access_token': self.token, 'title': '', 'tags': []} if 'title' in kwargs: params['title'] = kwargs['title'] if 'tags' in kwargs and isinstance(kwargs['tags'], list...
PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags tag1,tag2,tag3 archive: '0' or '1', default '0' archive...
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L236-L276
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.delete_entries
python
async def delete_entries(self, entry): params = {'Authorization': 'Bearer {}'.format(self.token)} path = '/api/entries/{entry}.{ext}'.format( entry=entry, ext=self.format) return await self.query(path, "delete", **params)
DELETE /api/entries/{entry}.{_format} Delete permanently an entry :param entry: \w+ an integer The Entry ID :return result
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L308-L321
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.entries_exists
python
async def entries_exists(self, url, urls=''): params = {'access_token': self.token, 'url': url, 'urls': urls} path = '/api/entries/exists.{ext}'.format(ext=self.format) return await self.query(path, "get", **params)
GET /api/entries/exists.{_format} Check if an entry exist by url. :param url string true An url Url to check if it exists :param urls string false An array of urls (?urls[]=http...&urls[]=http...) Urls (as an array) to check if it exists :return result
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L323-L341
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.post_entry_tags
python
async def post_entry_tags(self, entry, tags): params = {'access_token': self.token, 'tags': []} if len(tags) > 0 and isinstance(tags, list): params['tags'] = ', '.join(tags) path = '/api/entries/{entry}/tags.{ext}'.format( entry=entry, ext=self.format) return awai...
POST /api/entries/{entry}/tags.{_format} Add one or more tags to an entry :param entry: \w+ an integer The Entry ID :param tags: list of tags (urlencoded) :return result
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L359-L374
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.delete_entry_tag
python
async def delete_entry_tag(self, entry, tag): params = {'access_token': self.token} url = '/api/entries/{entry}/tags/{tag}.{ext}'.format( entry=entry, tag=tag, ext=self.format) return await self.query(url, "delete", **params)
DELETE /api/entries/{entry}/tags/{tag}.{_format} Permanently remove one tag for an entry :param entry: \w+ an integer The Entry ID :param tag: string The Tag :return data related to the ext
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L376-L389
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.get_tags
python
async def get_tags(self): params = {'access_token': self.token} path = '/api/tags.{ext}'.format(ext=self.format) return await self.query(path, "get", **params)
GET /api/tags.{_format} Retrieve all tags :return data related to the ext
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L391-L401
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.delete_tag
python
async def delete_tag(self, tag): path = '/api/tags/{tag}.{ext}'.format(tag=tag, ext=self.format) params = {'access_token': self.token} return await self.query(path, "delete", **params)
DELETE /api/tags/{tag}.{_format} Permanently remove one tag from every entry :param tag: string The Tag :return data related to the ext
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L403-L414
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.put_annotations
python
async def put_annotations(self, annotation): params = {'access_token': self.token} url = '/api/annotations/{annotation}.{ext}'.format( annotation=annotation, ext=self.format) return await self.query(url, "put", **params)
PUT /api/annotations/{annotation}.{_format} Updates an annotation. :param annotation \w+ string The annotation ID Will returns annotation for this entry :return data related to the ext
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L462-L476
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.post_annotations
python
async def post_annotations(self, entry, **kwargs): params = dict({'access_token': self.token, 'ranges': [], 'quote': '', 'text': ''}) if 'ranges' in kwargs: params['ranges'] = kwargs['ranges'] if 'quote' in kwargs: ...
POST /api/annotations/{entry}.{_format} Creates a new annotation. :param entry \w+ integer The entry ID :return
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L494-L517
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.version
python
async def version(self): params = {'access_token': self.token} url = '/api/version.{ext}'.format(ext=self.format) return await self.query(url, "get", **params)
GET /api/version.{_format} Retrieve version number :return data related to the ext
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L521-L531
[ "async def query(self, path, method='get', **params):\n \"\"\"\n Do a query to the System API\n\n :param path: url to the API\n :param method: the kind of query to do\n :param params: a dict with all the\n necessary things to query the API\n :return json data\n \"\"\"\n if method in ('get...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
push-things/wallabag_api
wallabag_api/wallabag.py
Wallabag.get_token
python
async def get_token(cls, host, **params): params['grant_type'] = "password" path = "/oauth/v2/token" async with aiohttp.ClientSession() as sess: async with sess.post(host + path, data=params) as resp: data = await cls.handle_json_response(resp) return ...
POST /oauth/v2/token Get a new token :param host: host of the service :param params: will contain : params = {"grant_type": "password", "client_id": "a string", "client_secret": "a string", "username": "a login", ...
train
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L534-L556
[ "async def handle_json_response(responses):\n \"\"\"\n get the json data response\n :param responses: the json response\n :return the json data without 'root' node\n \"\"\"\n json_data = {}\n if responses.status != 200:\n err_msg = HttpProcessingError(code=responses.status,\n ...
class Wallabag(object): """ Python Class 'Wallabag' to deal with Wallabag REST API This class is able to handle any data from your Wallabag account """ EXTENTIONS = ('xml', 'json', 'txt', 'csv', 'pdf', 'epub', 'mobi', 'html') host = '' token = '' client_id = '' client_secret ...
drslump/pyshould
pyshould/expectation.py
Expectation.reset
python
def reset(self): self.expr = [] self.matcher = None self.last_matcher = None self.description = None
Resets the state of the expression
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L44-L49
null
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation.clone
python
def clone(self): from copy import copy clone = copy(self) clone.expr = copy(self.expr) clone.factory = False return clone
Clone this expression
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L51-L57
null
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation.resolve
python
def resolve(self, value=None): # If we still have an uninitialized matcher init it now if self.matcher: self._init_matcher() # Evaluate the current set of matchers forming the expression matcher = self.evaluate() try: value = self._transform(value) ...
Resolve the current expression against the supplied value
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L81-L100
[ "def reset(self):\n \"\"\" Resets the state of the expression \"\"\"\n self.expr = []\n self.matcher = None\n self.last_matcher = None\n self.description = None\n", "def _assertion(self, matcher, value):\n \"\"\" Perform the actual assertion for the given matcher and value. Override\n thi...
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation._assertion
python
def _assertion(self, matcher, value): # To support the syntax `any_of(subject) | should ...` we check if the # value to check is an Expectation object and if it is we use the descriptor # protocol to bind the value's assertion logic to this expectation. if isinstance(value, Expectation):...
Perform the actual assertion for the given matcher and value. Override this method to apply a special configuration when performing the assertion. If the assertion fails it should raise an AssertionError.
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L102-L114
null
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation._transform
python
def _transform(self, value): if self.transform: try: value = self.transform(value) except: import sys exc_type, exc_obj, exc_tb = sys.exc_info() raise AssertionError('Error applying transformation <{0}>: {2}: {3}'.format( ...
Applies any defined transformation to the given value
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L116-L128
null
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation.evaluate
python
def evaluate(self): # Apply Shunting Yard algorithm to convert the infix expression # into Reverse Polish Notation. Since we have a very limited # set of operators and binding rules, the implementation becomes # really simple. The expression is formed of hamcrest matcher instances ...
Converts the current expression into a single matcher, applying coordination operators to operands according to their binding rules
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L130-L186
null
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation._find_matcher
python
def _find_matcher(self, alias): matcher = lookup(alias) if not matcher: msg = 'Matcher "%s" not found' % alias # Try to find similarly named matchers to help the user similar = suggest(alias, max=3, cutoff=0.5) if len(similar) > 1: last = ...
Finds a matcher based on the given alias or raises an error if no matcher could be found.
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L188-L206
[ "def lookup(alias):\n \"\"\" Tries to find a matcher callable associated to the given alias. If\n an exact match does not exists it will try normalizing it and even\n removing underscores to find one.\n \"\"\"\n\n if alias in matchers:\n return matchers[alias]\n else:\n norm ...
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation._init_matcher
python
def _init_matcher(self, *args, **kwargs): # If subject-less expectation are provided as arguments convert them # to plain Hamcrest matchers in order to allow complex compositions fn = lambda x: x.evaluate() if isinstance(x, Expectation) else x args = [fn(x) for x in args] kwargs...
Executes the current matcher appending it to the expression
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L208-L220
null
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/expectation.py
Expectation.described_as
python
def described_as(self, description, *args): if len(args): description = description.format(*args) self.description = description return self
Specify a custom message for the matcher
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L222-L227
null
class Expectation(object): """ Represents an expectation allowing to configure it with matchers and finally resolving it. """ _contexts = [] def __init__(self, value=None, deferred=False, description=None, factory=False, def_op=OPERATOR.AND, def_matcher='equal'): self....
drslump/pyshould
pyshould/matchers.py
register
python
def register(matcher, *aliases): docstr = matcher.__doc__ if matcher.__doc__ is not None else '' helpmatchers[matcher] = docstr.strip() for alias in aliases: matchers[alias] = matcher # Map a normalized version of the alias norm = normalize(alias) normalized[norm] = alias ...
Register a matcher associated to one or more aliases. Each alias given is also normalized.
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/matchers.py#L54-L68
[ "def normalize(alias):\n \"\"\" Normalizes an alias by removing adverbs defined in IGNORED_WORDS\n \"\"\"\n # Convert from CamelCase to snake_case\n alias = re.sub(r'([a-z])([A-Z])', r'\\1_\\2', alias)\n # Ignore words\n words = alias.lower().split('_')\n words = filter(lambda w: w not in IGNOR...
""" Defines the registry of matchers and the standard set of matchers """ import re from datetime import datetime, date import hamcrest as hc from difflib import get_close_matches from hamcrest.core.base_matcher import BaseMatcher from hamcrest.library.collection.isdict_containingentries import IsDictContainingEntries...
drslump/pyshould
pyshould/matchers.py
unregister
python
def unregister(matcher): # If it's a string handle it like an alias if isinstance(matcher, text_types) and matcher in matchers: matcher = matchers[matcher] # Find all aliases associated to the matcher aliases = [k for k, v in matchers.iteritems() if v == matcher] for alias in aliases: ...
Unregister a matcher (or alias) from the registry
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/matchers.py#L71-L91
null
""" Defines the registry of matchers and the standard set of matchers """ import re from datetime import datetime, date import hamcrest as hc from difflib import get_close_matches from hamcrest.core.base_matcher import BaseMatcher from hamcrest.library.collection.isdict_containingentries import IsDictContainingEntries...
drslump/pyshould
pyshould/matchers.py
normalize
python
def normalize(alias): # Convert from CamelCase to snake_case alias = re.sub(r'([a-z])([A-Z])', r'\1_\2', alias) # Ignore words words = alias.lower().split('_') words = filter(lambda w: w not in IGNORED_WORDS, words) return '_'.join(words)
Normalizes an alias by removing adverbs defined in IGNORED_WORDS
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/matchers.py#L94-L102
null
""" Defines the registry of matchers and the standard set of matchers """ import re from datetime import datetime, date import hamcrest as hc from difflib import get_close_matches from hamcrest.core.base_matcher import BaseMatcher from hamcrest.library.collection.isdict_containingentries import IsDictContainingEntries...
drslump/pyshould
pyshould/matchers.py
lookup
python
def lookup(alias): if alias in matchers: return matchers[alias] else: norm = normalize(alias) if norm in normalized: alias = normalized[norm] return matchers[alias] # Check without snake case if -1 != alias.find('_'): norm = normalize(alias).repl...
Tries to find a matcher callable associated to the given alias. If an exact match does not exists it will try normalizing it and even removing underscores to find one.
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/matchers.py#L105-L124
[ "def normalize(alias):\n \"\"\" Normalizes an alias by removing adverbs defined in IGNORED_WORDS\n \"\"\"\n # Convert from CamelCase to snake_case\n alias = re.sub(r'([a-z])([A-Z])', r'\\1_\\2', alias)\n # Ignore words\n words = alias.lower().split('_')\n words = filter(lambda w: w not in IGNOR...
""" Defines the registry of matchers and the standard set of matchers """ import re from datetime import datetime, date import hamcrest as hc from difflib import get_close_matches from hamcrest.core.base_matcher import BaseMatcher from hamcrest.library.collection.isdict_containingentries import IsDictContainingEntries...
drslump/pyshould
pyshould/matchers.py
suggest
python
def suggest(alias, max=3, cutoff=0.5): aliases = matchers.keys() similar = get_close_matches(alias, aliases, n=max, cutoff=cutoff) return similar
Suggest a list of aliases which are similar enough
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/matchers.py#L127-L134
null
""" Defines the registry of matchers and the standard set of matchers """ import re from datetime import datetime, date import hamcrest as hc from difflib import get_close_matches from hamcrest.core.base_matcher import BaseMatcher from hamcrest.library.collection.isdict_containingentries import IsDictContainingEntries...