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
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
_get_submodules
python
def _get_submodules(app, module): if inspect.ismodule(module): if hasattr(module, '__path__'): p = module.__path__ else: return [] elif isinstance(module, str): p = module else: raise TypeError("Only Module or String accepted. %s given." % type(module)...
Get all submodules for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of module names and boolean whether its a package :rtype: list :raises: TypeEr...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L221-L244
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
get_submodules
python
def get_submodules(app, module): submodules = _get_submodules(app, module) return [name for name, ispkg in submodules if not ispkg]
Get all submodules without packages for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of module names excluding packages :rtype: list :raises: Type...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L247-L259
[ "def _get_submodules(app, module):\n \"\"\"Get all submodules for the given module/package\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module to query or module path\n :type module: module | str\n :returns: list of module names and boolean wh...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
get_subpackages
python
def get_subpackages(app, module): submodules = _get_submodules(app, module) return [name for name, ispkg in submodules if ispkg]
Get all subpackages for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of packages names :rtype: list :raises: TypeError
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L262-L274
[ "def _get_submodules(app, module):\n \"\"\"Get all submodules for the given module/package\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module to query or module path\n :type module: module | str\n :returns: list of module names and boolean wh...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
get_context
python
def get_context(app, package, module, fullname): var = {'package': package, 'module': module, 'fullname': fullname} logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname) obj = import_name(app, fullname) if not obj: for k in ('su...
Return a dict for template rendering Variables: * :package: The top package * :module: the module * :fullname: package.module * :subpkgs: packages beneath module * :submods: modules beneath module * :classes: public classes in module * :allclasses: public and private clas...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L277-L330
[ "def import_name(app, name):\n \"\"\"Import the given name and return name, obj, parent, mod_name\n\n :param name: name to import\n :type name: str\n :returns: the imported object or None\n :rtype: object | None\n :raises: None\n \"\"\"\n try:\n logger.debug('Importing %r', name)\n ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
create_module_file
python
def create_module_file(app, env, package, module, dest, suffix, dryrun, force): logger.debug('Create module file: package %s, module %s', package, module) template_file = MODULE_TEMPLATE_NAME template = env.get_template(template_file) fn = makename(package, module) var = get_context(app, package, mo...
Build the text of the file and write the file. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment for the templates :type env: :class:`jinja2.Environment` :param package: the package name :type package: :class:`str` :param module: the ...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L333-L362
[ "def get_context(app, package, module, fullname):\n \"\"\"Return a dict for template rendering\n\n Variables:\n\n * :package: The top package\n * :module: the module\n * :fullname: package.module\n * :subpkgs: packages beneath module\n * :submods: modules beneath module\n * :clas...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
create_package_file
python
def create_package_file(app, env, root_package, sub_package, private, dest, suffix, dryrun, force): logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package) template_file = PACKAGE_TEMPLATE_NAME template = env.get_template(template_file) fn =...
Build the text of the file and write the file. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment for the templates :type env: :class:`jinja2.Environment` :param root_package: the parent package :type root_package: :class:`str` :param ...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L365-L401
[ "def get_context(app, package, module, fullname):\n \"\"\"Return a dict for template rendering\n\n Variables:\n\n * :package: The top package\n * :module: the module\n * :fullname: package.module\n * :subpkgs: packages beneath module\n * :submods: modules beneath module\n * :clas...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
shall_skip
python
def shall_skip(app, module, private): logger.debug('Testing if %s should be skipped.', module) # skip if it has a "private" name and this is selected if module != '__init__.py' and module.startswith('_') and \ not private: logger.debug('Skip %s because its either private or __init__.', module...
Check if we want to skip this module. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module name :type module: :class:`str` :param private: True, if privates are allowed :type private: :class:`bool`
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L404-L421
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
recurse_tree
python
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix): # check if the base directory is a package and get its name if INITPY in os.listdir(src): root_package = src.split(os.path.sep)[-1] else: # otherwise, the base is a directory with packages r...
Look for every file in the directory tree and create the corresponding ReST files. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment :type env: :class:`jinja2.Environment` :param src: the path to the python source files :type src: :cl...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L424-L495
[ "def makename(package, module):\n \"\"\"Join package and module with a dot.\n\n Package or Module can be empty.\n\n :param package: the package name\n :type package: :class:`str`\n :param module: the module name\n :type module: :class:`str`\n :returns: the joined name\n :rtype: :class:`str`\...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
normalize_excludes
python
def normalize_excludes(excludes): return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
Normalize the excluded directory list.
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L498-L500
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
is_excluded
python
def is_excluded(root, excludes): root = os.path.normpath(root) for exclude in excludes: if root == exclude: return True return False
Check if the directory is in the exclude list. Note: by having trailing slashes, we avoid common prefix issues, like e.g. an exlude "foo" also accidentally excluding "foobar".
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L503-L513
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
generate
python
def generate(app, src, dest, exclude=[], followlinks=False, force=False, dryrun=False, private=False, suffix='rst', template_dirs=None): suffix = suffix.strip('.') if not os.path.isdir(src): raise OSError("%s is not a directory" % src) if not os.path.isdir(dest) and not dry...
Generage the rst files Raises an :class:`OSError` if the source path is not a directory. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param src: path to python source files :type src: :class:`str` :param dest: output directory :type dest: :class:`str` :para...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L516-L556
[ "def make_loader(template_dirs):\n \"\"\"Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs\n\n :param template_dirs: directories to search for templates\n :type template_dirs: None | :class:`list`\n :returns: a new loader\n :rtype: :class:`jinja2.FileSystemLoader`\n :raises...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
main
python
def main(app): c = app.config src = c.jinjaapi_srcdir if not src: return suffix = "rst" out = c.jinjaapi_outputdir or app.env.srcdir if c.jinjaapi_addsummarytemplate: tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR) c.templates_path.append...
Parse the config of the app and initiate the generation process :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :returns: None :rtype: None :raises: None
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L559-L593
[ "def prepare_dir(app, directory, delete=False):\n \"\"\"Create apidoc dir, delete contents if delete is True.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param directory: the apidoc directory. you can use relative paths here\n :type directory: str\n :param del...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/__init__.py
setup
python
def setup(app): """Setup the sphinx extension This will setup autodoc and autosummary. Add the :class:`ext.ModDocstringDocumenter`. Add the config values. Connect builder-inited event to :func:`gendoc.main`. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` ...
Setup the sphinx extension This will setup autodoc and autosummary. Add the :class:`ext.ModDocstringDocumenter`. Add the config values. Connect builder-inited event to :func:`gendoc.main`. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :returns: None ...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/__init__.py#L9-L42
null
import jinjaapidoc.ext as ext import jinjaapidoc.gendoc as gendoc __author__ = 'David Zuber' __email__ = 'zuber.david@gmx.de' __version__ = '0.5.0' def setup(app): """Setup the sphinx extension This will setup autodoc and autosummary. Add the :class:`ext.ModDocstringDocumenter`. Add the config value...
storax/jinjaapidoc
src/jinjaapidoc/ext.py
ModDocstringDocumenter.add_directive_header
python
def add_directive_header(self, sig): domain = getattr(self, 'domain', 'py') directive = getattr(self, 'directivetype', "module") name = self.format_name() self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig), '<autodoc>') if self.options.noindex...
Add the directive header and options to the generated content.
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/ext.py#L13-L25
null
class ModDocstringDocumenter(autodoc.ModuleDocumenter): """A documenter for modules which only inserts the docstring of the module.""" objtype = "moddoconly" # do not indent the content content_indent = "" # do not add a header to the docstring def document_members(self, all_members=False): ...
stephantul/reach
reach/reach.py
Reach.load
python
def load(pathtovector, wordlist=(), num_to_load=None, truncate_embeddings=None, unk_word=None, sep=" "): r""" Read a file in word2vec .txt format. The load function will raise a ValueError when trying to load items which d...
r""" Read a file in word2vec .txt format. The load function will raise a ValueError when trying to load items which do not conform to line lengths. Parameters ---------- pathtovector : string The path to the vector file. header : bool Whe...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L74-L133
[ "def _load(pathtovector,\n wordlist,\n num_to_load=None,\n truncate_embeddings=None,\n sep=\" \"):\n \"\"\"Load a matrix and wordlist from a .vec file.\"\"\"\n vectors = []\n addedwords = set()\n words = []\n\n try:\n wordlist = set(wordlist)\n except Val...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach._load
python
def _load(pathtovector, wordlist, num_to_load=None, truncate_embeddings=None, sep=" "): vectors = [] addedwords = set() words = [] try: wordlist = set(wordlist) except ValueError: wordlist = set() ...
Load a matrix and wordlist from a .vec file.
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L136-L205
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.vectorize
python
def vectorize(self, tokens, remove_oov=False, norm=False): if not tokens: raise ValueError("You supplied an empty list.") index = list(self.bow(tokens, remove_oov=remove_oov)) if not index: raise ValueError("You supplied a list with only OOV tokens: {}, " ...
Vectorize a sentence by replacing all items with their vectors. Parameters ---------- tokens : object or list of objects The tokens to vectorize. remove_oov : bool, optional, default False Whether to remove OOV items. If False, OOV items are replaced by ...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L211-L245
[ "def bow(self, tokens, remove_oov=False):\n \"\"\"\n Create a bow representation of a list of tokens.\n\n Parameters\n ----------\n tokens : list.\n The list of items to change into a bag of words representation.\n remove_oov : bool.\n Whether to remove OOV items from the input.\n ...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.bow
python
def bow(self, tokens, remove_oov=False): if remove_oov: tokens = [x for x in tokens if x in self.items] for t in tokens: try: yield self.items[t] except KeyError: if self.unk_index is None: raise ValueError("You sup...
Create a bow representation of a list of tokens. Parameters ---------- tokens : list. The list of items to change into a bag of words representation. remove_oov : bool. Whether to remove OOV items from the input. If this is True, the length of the ret...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L247-L279
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.transform
python
def transform(self, corpus, remove_oov=False, norm=False): return [self.vectorize(s, remove_oov=remove_oov, norm=norm) for s in corpus]
Transform a corpus by repeated calls to vectorize, defined above. Parameters ---------- corpus : A list of strings, list of list of strings. Represents a corpus as a list of sentences, where sentences can either be strings or lists of tokens. remove_oov : bool, o...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L281-L303
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.most_similar
python
def most_similar(self, items, num=10, batch_size=100, show_progressbar=False, return_names=True): # This line allows users to input single items. # We used to rely on string identities, but we now al...
Return the num most similar items to a given list of items. Parameters ---------- items : list of objects or a single object. The items to get the most similar items to. num : int, optional, default 10 The number of most similar items to retrieve. batch_s...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L305-L356
[ "def _batch(self,\n vectors,\n batch_size,\n num,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes things faster.\n reference_transposed = self.norm_vectors.T\n\...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.threshold
python
def threshold(self, items, threshold=.5, batch_size=100, show_progressbar=False, return_names=True): # This line allows users to input single items. # We used to rely on string identities, but we now also allow ...
Return all items whose similarity is higher than threshold. Parameters ---------- items : list of objects or a single object. The items to get the most similar items to. threshold : float, optional, default .5 The radius within which to retrieve items. ba...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L358-L409
[ "def _threshold_batch(self,\n vectors,\n batch_size,\n threshold,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.nearest_neighbor
python
def nearest_neighbor(self, vectors, num=10, batch_size=100, show_progressbar=False, return_names=True): vectors = np.array(vectors) if np.ndim(vectors) == 1: vectors =...
Find the nearest neighbors to some arbitrary vector. This function is meant to be used in composition operations. The most_similar function can only handle items that are in vocab, and looks up their vector through a dictionary. Compositions, e.g. "King - man + woman" are necessarily no...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L411-L459
[ "def _batch(self,\n vectors,\n batch_size,\n num,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes things faster.\n reference_transposed = self.norm_vectors.T\n\...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.nearest_neighbor_threshold
python
def nearest_neighbor_threshold(self, vectors, threshold=.5, batch_size=100, show_progressbar=False, return_names=True): vectors = np.arra...
Find the nearest neighbors to some arbitrary vector. This function is meant to be used in composition operations. The most_similar function can only handle items that are in vocab, and looks up their vector through a dictionary. Compositions, e.g. "King - man + woman" are necessarily no...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L461-L509
[ "def _threshold_batch(self,\n vectors,\n batch_size,\n threshold,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach._threshold_batch
python
def _threshold_batch(self, vectors, batch_size, threshold, show_progressbar, return_names): vectors = self.normalize(vectors) # Single transpose, makes things faster. ref...
Batched cosine distance.
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L511-L536
[ "def normalize(vectors):\n \"\"\"\n Normalize a matrix of row vectors to unit length.\n\n Contains a shortcut if there are no zero vectors in the matrix.\n If there are zero vectors, we do some indexing tricks to avoid\n dividing by 0.\n\n Parameters\n ----------\n vectors : np.array\n ...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach._batch
python
def _batch(self, vectors, batch_size, num, show_progressbar, return_names): vectors = self.normalize(vectors) # Single transpose, makes things faster. reference_transposed = self.norm_vectors.T for i in tqdm(ran...
Batched cosine distance.
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L538-L568
[ "def normalize(vectors):\n \"\"\"\n Normalize a matrix of row vectors to unit length.\n\n Contains a shortcut if there are no zero vectors in the matrix.\n If there are zero vectors, we do some indexing tricks to avoid\n dividing by 0.\n\n Parameters\n ----------\n vectors : np.array\n ...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.normalize
python
def normalize(vectors): if np.ndim(vectors) == 1: norm = np.linalg.norm(vectors) if norm == 0: return np.zeros_like(vectors) return vectors / norm norm = np.linalg.norm(vectors, axis=1) if np.any(norm == 0): nonzero = norm > 0 ...
Normalize a matrix of row vectors to unit length. Contains a shortcut if there are no zero vectors in the matrix. If there are zero vectors, we do some indexing tricks to avoid dividing by 0. Parameters ---------- vectors : np.array The vectors to normalize....
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L571-L610
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.vector_similarity
python
def vector_similarity(self, vector, items): vector = self.normalize(vector) items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items]) return vector.dot(items_vec.T)
Compute the similarity between a vector and a set of items.
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L612-L616
[ "def normalize(vectors):\n \"\"\"\n Normalize a matrix of row vectors to unit length.\n\n Contains a shortcut if there are no zero vectors in the matrix.\n If there are zero vectors, we do some indexing tricks to avoid\n dividing by 0.\n\n Parameters\n ----------\n vectors : np.array\n ...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.similarity
python
def similarity(self, i1, i2): try: if i1 in self.items: i1 = [i1] except TypeError: pass try: if i2 in self.items: i2 = [i2] except TypeError: pass i1_vec = np.stack([self.norm_vectors[self.items[x]] ...
Compute the similarity between two sets of items. Parameters ---------- i1 : object The first set of items. i2 : object The second set of item. Returns ------- sim : array of floats An array of similarity scores between 1 and ...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L618-L647
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.prune
python
def prune(self, wordlist): # Remove duplicates wordlist = set(wordlist).intersection(set(self.items.keys())) indices = [self.items[w] for w in wordlist if w in self.items] if self.unk_index is not None and self.unk_index not in indices: raise ValueError("Your unknown item is ...
Prune the current reach instance by removing items. Parameters ---------- wordlist : list of str A list of words to keep. Note that this wordlist need not include all words in the Reach instance. Any words which are in the wordlist, but not in the reach insta...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L649-L673
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.save
python
def save(self, path, write_header=True): with open(path, 'w') as f: if write_header: f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]), str(self.vectors.shape[1]))) for i in range(len(self.items)): w = self.indices[i] ...
Save the current vector space in word2vec format. Parameters ---------- path : str The path to save the vector file to. write_header : bool, optional, default True Whether to write a word2vec-style header as the first line of the file
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L675-L700
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.save_fast_format
python
def save_fast_format(self, filename): items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1])) items = {"items": items, "unk_index": self.unk_index, "name": self.name} json.dump(items, open("{}_items.json".format(filename), 'w')) np.save(open("{}...
Save a reach instance in a fast format. The reach fast format stores the words and vectors of a Reach instance separately in a JSON and numpy format, respectively. Parameters ---------- filename : str The prefix to add to the saved filename. Note that this is not th...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L702-L724
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach.load_fast_format
python
def load_fast_format(filename): words, unk_index, name, vectors = Reach._load_fast(filename) return Reach(vectors, words, unk_index=unk_index, name=name)
Load a reach instance in fast format. As described above, the fast format stores the words and vectors of the Reach instance separately, and is drastically faster than loading from .txt files. Parameters ---------- filename : str The filename prefix from whi...
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L727-L745
[ "def _load_fast(filename):\n \"\"\"Sub for fast loader.\"\"\"\n it = json.load(open(\"{}_items.json\".format(filename)))\n words, unk_index, name = it[\"items\"], it[\"unk_index\"], it[\"name\"]\n vectors = np.load(open(\"{}_vectors.npy\".format(filename), 'rb'))\n return words, unk_index, name, vect...
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
stephantul/reach
reach/reach.py
Reach._load_fast
python
def _load_fast(filename): it = json.load(open("{}_items.json".format(filename))) words, unk_index, name = it["items"], it["unk_index"], it["name"] vectors = np.load(open("{}_vectors.npy".format(filename), 'rb')) return words, unk_index, name, vectors
Sub for fast loader.
train
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L748-L753
null
class Reach(object): """ Work with vector representations of items. Supports functions for calculating fast batched similarity between items or composite representations of items. Parameters ---------- vectors : numpy array The vector space. items : list A list of items...
niklasb/webkit-server
webkit_server.py
SelectionMixin.xpath
python
def xpath(self, xpath): return [self.get_node_factory().create(node_id) for node_id in self._get_xpath_ids(xpath).split(",") if node_id]
Finds another node by XPath originating at the current node.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L21-L25
[ "def _get_xpath_ids(self, xpath):\n \"\"\" Implements a mechanism to get a list of node IDs for an relative XPath\n query. \"\"\"\n return self._invoke(\"findXpathWithin\", xpath)\n" ]
class SelectionMixin(object): """ Implements a generic XPath selection for a class providing ``_get_xpath_ids``, ``_get_css_ids`` and ``get_node_factory`` methods. """ def css(self, css): """ Finds another node by a CSS selector relative to the current node. """ return [self.get_node_factory().create(no...
niklasb/webkit-server
webkit_server.py
SelectionMixin.css
python
def css(self, css): return [self.get_node_factory().create(node_id) for node_id in self._get_css_ids(css).split(",") if node_id]
Finds another node by a CSS selector relative to the current node.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L27-L31
null
class SelectionMixin(object): """ Implements a generic XPath selection for a class providing ``_get_xpath_ids``, ``_get_css_ids`` and ``get_node_factory`` methods. """ def xpath(self, xpath): """ Finds another node by XPath originating at the current node. """ return [self.get_node_factory().create(node_...
niklasb/webkit-server
webkit_server.py
Node.get_bool_attr
python
def get_bool_attr(self, name): val = self.get_attr(name) return val is not None and val.lower() in ("true", name)
Returns the value of a boolean HTML attribute like `checked` or `disabled`
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L68-L72
[ "def get_attr(self, name):\n \"\"\" Returns the value of an attribute. \"\"\"\n return self._invoke(\"attribute\", name)\n" ]
class Node(SelectionMixin): """ Represents a DOM node in our Webkit session. `client` is the associated client instance. `node_id` is the internal ID that is used to identify the node when communicating with the server. """ def __init__(self, client, node_id): super(Node, self).__init__() self.clie...
niklasb/webkit-server
webkit_server.py
Node.set_attr
python
def set_attr(self, name, value): self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value)))
Sets the value of an attribute.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L78-L80
[ "def exec_script(self, js):\n \"\"\" Execute arbitrary Javascript with the ``node`` variable bound to\n the current node. \"\"\"\n self.client.exec_script(self._build_script(js))\n" ]
class Node(SelectionMixin): """ Represents a DOM node in our Webkit session. `client` is the associated client instance. `node_id` is the internal ID that is used to identify the node when communicating with the server. """ def __init__(self, client, node_id): super(Node, self).__init__() self.clie...
niklasb/webkit-server
webkit_server.py
Node.value
python
def value(self): if self.is_multi_select(): return [opt.value() for opt in self.xpath(".//option") if opt["selected"]] else: return self._invoke("value")
Returns the node's value.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L82-L89
[ "def is_multi_select(self):\n \"\"\" is this node a multi-select? \"\"\"\n return self.tag_name() == \"select\" and self.get_bool_attr(\"multiple\")\n" ]
class Node(SelectionMixin): """ Represents a DOM node in our Webkit session. `client` is the associated client instance. `node_id` is the internal ID that is used to identify the node when communicating with the server. """ def __init__(self, client, node_id): super(Node, self).__init__() self.clie...
niklasb/webkit-server
webkit_server.py
Client.set_header
python
def set_header(self, key, value): self.conn.issue_command("Header", _normalize_header(key), value)
Sets a HTTP header for future requests.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L250-L252
[ "def _normalize_header(key):\n return \"-\".join(part[0].upper() + part[1:].lower() for part in key.split(\"-\"))\n" ]
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Client.headers
python
def headers(self): headers = self.conn.issue_command("Headers") res = [] for header in headers.split("\r"): key, value = header.split(": ", 1) for line in value.split("\n"): res.append((_normalize_header(key), line)) return res
Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form, as in `User-Agent`.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L262-L272
[ "def _normalize_header(key):\n return \"-\".join(part[0].upper() + part[1:].lower() for part in key.split(\"-\"))\n" ]
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Client.eval_script
python
def eval_script(self, expr): ret = self.conn.issue_command("Evaluate", expr) return json.loads("[%s]" % ret)[0]
Evaluates a piece of Javascript in the context of the current page and returns its value.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L274-L278
null
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Client.render
python
def render(self, path, width = 1024, height = 1024): self.conn.issue_command("Render", path, width, height)
Renders the current page to a PNG file (viewport size in pixels).
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L284-L286
null
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Client.cookies
python
def cookies(self): return [line.strip() for line in self.conn.issue_command("GetCookies").split("\n") if line.strip()]
Returns a list of all cookies in cookie string format.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L301-L305
null
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Client.set_attribute
python
def set_attribute(self, attr, value = True): value = "true" if value else "false" self.conn.issue_command("SetAttribute", self._normalize_attr(attr), value)
Sets a custom attribute for our Webkit instance. Possible attributes are: * ``auto_load_images`` * ``dns_prefetch_enabled`` * ``plugins_enabled`` * ``private_browsing_enabled`` * ``javascript_can_open_windows`` * ``javascript_can_access_clipboard`` * ``offline_storage_database...
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L314-L339
[ "def _normalize_attr(self, attr):\n \"\"\" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``\n (allows Webkit option names to blend in with Python naming). \"\"\"\n return ''.join(x.capitalize() for x in attr.split(\"_\"))\n" ]
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Client.set_html
python
def set_html(self, html, url = None): if url: self.conn.issue_command('SetHtml', html, url) else: self.conn.issue_command('SetHtml', html)
Sets custom HTML in our Webkit session and allows to specify a fake URL. Scripts and CSS is dynamically fetched as if the HTML had been loaded from the given URL.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L347-L354
null
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Client.set_proxy
python
def set_proxy(self, host = "localhost", port = 0, user = "", password = ""): self.conn.issue_command("SetProxy", host, port, user, password)
Sets a custom HTTP proxy to use for future requests.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L356-L361
null
class Client(SelectionMixin): """ Wrappers for the webkit_server commands. If `connection` is not specified, a new instance of ``ServerConnection`` is created. `node_factory_class` can be set to a value different from the default, in which case a new instance of the given class will be used to create nodes....
niklasb/webkit-server
webkit_server.py
Server.connect
python
def connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", self._port)) return sock
Returns a new socket connection to this server.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L437-L441
null
class Server(object): """ Manages a Webkit server process. If `binary` is given, the specified ``webkit_server`` binary is used instead of the included one. """ def __init__(self, binary = None): binary = binary or SERVER_EXEC self._server = subprocess.Popen([binary], ...
niklasb/webkit-server
webkit_server.py
SocketBuffer.read_line
python
def read_line(self): while True: newline_idx = self.buf.find(b"\n") if newline_idx >= 0: res = self.buf[:newline_idx] self.buf = self.buf[newline_idx + 1:] return res chunk = self.f.recv(4096) if not chunk: raise EndOfStreamError() self.buf += chunk
Consume one line from the stream.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L475-L486
null
class SocketBuffer(object): """ A convenience class for buffered reads from a socket. """ def __init__(self, f): """ `f` is expected to be an open socket. """ self.f = f self.buf = b'' def read(self, n): """ Consume `n` characters from the stream. """ while len(self.buf) < n: chunk = s...
niklasb/webkit-server
webkit_server.py
SocketBuffer.read
python
def read(self, n): while len(self.buf) < n: chunk = self.f.recv(4096) if not chunk: raise EndOfStreamError() self.buf += chunk res, self.buf = self.buf[:n], self.buf[n:] return res
Consume `n` characters from the stream.
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L488-L496
null
class SocketBuffer(object): """ A convenience class for buffered reads from a socket. """ def __init__(self, f): """ `f` is expected to be an open socket. """ self.f = f self.buf = b'' def read_line(self): """ Consume one line from the stream. """ while True: newline_idx = self.buf.find...
niklasb/webkit-server
webkit_server.py
ServerConnection.issue_command
python
def issue_command(self, cmd, *args): self._writeline(cmd) self._writeline(str(len(args))) for arg in args: arg = str(arg) self._writeline(str(len(arg))) self._sock.sendall(arg.encode("utf-8")) return self._read_response()
Sends and receives a message to/from the server
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L511-L520
[ "def _read_response(self):\n \"\"\" Reads a complete response packet from the server \"\"\"\n result = self.buf.read_line().decode(\"utf-8\")\n if not result:\n raise NoResponseError(\"No response received from server.\")\n\n msg = self._read_message()\n if result != \"ok\":\n raise InvalidResponseError(...
class ServerConnection(object): """ A connection to a Webkit server. `server` is a server instance or `None` if a singleton server should be connected to (will be started if necessary). """ def __init__(self, server = None): super(ServerConnection, self).__init__() self._sock = (server or get_default_...
niklasb/webkit-server
webkit_server.py
ServerConnection._read_response
python
def _read_response(self): result = self.buf.read_line().decode("utf-8") if not result: raise NoResponseError("No response received from server.") msg = self._read_message() if result != "ok": raise InvalidResponseError(msg) return msg
Reads a complete response packet from the server
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L522-L532
[ "def _read_message(self):\n \"\"\" Reads a single size-annotated message from the server \"\"\"\n size = int(self.buf.read_line().decode(\"utf-8\"))\n return self.buf.read(size).decode(\"utf-8\")\n" ]
class ServerConnection(object): """ A connection to a Webkit server. `server` is a server instance or `None` if a singleton server should be connected to (will be started if necessary). """ def __init__(self, server = None): super(ServerConnection, self).__init__() self._sock = (server or get_default_...
niklasb/webkit-server
webkit_server.py
ServerConnection._read_message
python
def _read_message(self): size = int(self.buf.read_line().decode("utf-8")) return self.buf.read(size).decode("utf-8")
Reads a single size-annotated message from the server
train
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L534-L537
null
class ServerConnection(object): """ A connection to a Webkit server. `server` is a server instance or `None` if a singleton server should be connected to (will be started if necessary). """ def __init__(self, server = None): super(ServerConnection, self).__init__() self._sock = (server or get_default_...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._encode_utf8
python
def _encode_utf8(self, **kwargs): if is_py3: # This is only valid for Python 2. In Python 3, unicode is # everywhere (yay). return kwargs unencoded_pairs = kwargs for i in unencoded_pairs.keys(): #noinspection PyUnresolvedReferences if...
UTF8 encodes all of the NVP values.
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L58-L72
null
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._check_required
python
def _check_required(self, requires, **kwargs): for req in requires: # PayPal api is never mixed-case. if req.lower() not in kwargs and req.upper() not in kwargs: raise PayPalError('missing required : %s' % req)
Checks kwargs for the values specified in 'requires', which is a tuple of strings. These strings are the NVP names of the required values.
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L74-L82
null
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._call
python
def _call(self, method, **kwargs): post_params = self._get_call_params(method, **kwargs) payload = post_params['data'] api_endpoint = post_params['url'] # This shows all of the key/val pairs we're sending to PayPal. if logger.isEnabledFor(logging.DEBUG): logger.debug...
Wrapper method for executing all API commands over HTTP. This method is further used to implement wrapper methods listed here: https://www.x.com/docs/DOC-1374 ``method`` must be a supported NVP method listed at the above address. ``kwargs`` the actual call parameters
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L95-L120
[ "def _get_call_params(self, method, **kwargs):\n \"\"\"\n Returns the prepared call parameters. Mind, these will be keyword\n arguments to ``requests.post``.\n\n ``method`` the NVP method\n ``kwargs`` the actual call parameters\n \"\"\"\n payload = {'METHOD': method,\n 'VERSION': ...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._get_call_params
python
def _get_call_params(self, method, **kwargs): payload = {'METHOD': method, 'VERSION': self.config.API_VERSION} certificate = None if self.config.API_AUTHENTICATION_MODE == "3TOKEN": payload['USER'] = self.config.API_USERNAME payload['PWD'] = self.confi...
Returns the prepared call parameters. Mind, these will be keyword arguments to ``requests.post``. ``method`` the NVP method ``kwargs`` the actual call parameters
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L122-L161
null
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.address_verify
python
def address_verify(self, email, street, zip): args = self._sanitize_locals(locals()) return self._call('AddressVerify', **args)
Shortcut for the AddressVerify method. ``email``:: Email address of a PayPal member to verify. Maximum string length: 255 single-byte characters Input mask: ?@?.?? ``street``:: First line of the billing or shipping postal address to verify. T...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L163-L190
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.do_authorization
python
def do_authorization(self, transactionid, amt): args = self._sanitize_locals(locals()) return self._call('DoAuthorization', **args)
Shortcut for the DoAuthorization method. Use the TRANSACTIONID from DoExpressCheckoutPayment for the ``transactionid``. The latest version of the API does not support the creation of an Order from `DoDirectPayment`. The `amt` should be the same as passed to `DoExpressCheckoutPayment`. ...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L228-L251
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.do_capture
python
def do_capture(self, authorizationid, amt, completetype='Complete', **kwargs): kwargs.update(self._sanitize_locals(locals())) return self._call('DoCapture', **kwargs)
Shortcut for the DoCapture method. Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or DoExpressCheckoutPayment for the ``authorizationid``. The `amt` should be the same as the authorized transaction.
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L253-L263
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.do_direct_payment
python
def do_direct_payment(self, paymentaction="Sale", **kwargs): kwargs.update(self._sanitize_locals(locals())) return self._call('DoDirectPayment', **kwargs)
Shortcut for the DoDirectPayment method. ``paymentaction`` could be 'Authorization' or 'Sale' To issue a Sale immediately:: charge = { 'amt': '10.00', 'creditcardtype': 'Visa', 'acct': '4812177017895760', 'expdate': '012010',...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L265-L302
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.transaction_search
python
def transaction_search(self, **kwargs): plain = self._call('TransactionSearch', **kwargs) return PayPalResponseList(plain.raw, self.config)
Shortcut for the TransactionSearch method. Returns a PayPalResponseList object, which merges the L_ syntax list to a list of dictionaries with properly named keys. Note that the API will limit returned transactions to 100. Required Kwargs --------------- * STARTDATE ...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L338-L355
[ "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.refund_transaction
python
def refund_transaction(self, transactionid=None, payerid=None, **kwargs): # This line seems like a complete waste of time... kwargs should not # be populated if (transactionid is None) and (payerid is None): raise PayPalError( 'RefundTransaction requires either a tran...
Shortcut for RefundTransaction method. Note new API supports passing a PayerID instead of a transaction id, exactly one must be provided. Optional: INVOICEID REFUNDTYPE AMT CURRENCYCODE NOTE RETRY...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L375-L412
[ "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.generate_express_checkout_redirect_url
python
def generate_express_checkout_redirect_url(self, token, useraction=None): url_vars = (self.config.PAYPAL_URL_BASE, token) url = "%s?cmd=_express-checkout&token=%s" % url_vars if useraction: if not useraction.lower() in ('commit', 'continue'): warnings.warn('useraction...
Returns the URL to redirect the user to for the Express checkout. Express Checkouts must be verified by the customer by redirecting them to the PayPal website. Use the token returned in the response from :meth:`set_express_checkout` with this function to figure out where to redirect the...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L430-L454
null
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.generate_cart_upload_redirect_url
python
def generate_cart_upload_redirect_url(self, **kwargs): required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1') self._check_required(required_vals, **kwargs) url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE additional = self._encode_utf8(**kwargs) addition...
https://www.sandbox.paypal.com/webscr ?cmd=_cart &upload=1
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L456-L466
[ "def _encode_utf8(self, **kwargs):\n \"\"\"\n UTF8 encodes all of the NVP values.\n \"\"\"\n if is_py3:\n # This is only valid for Python 2. In Python 3, unicode is\n # everywhere (yay).\n return kwargs\n\n unencoded_pairs = kwargs\n for i in unencoded_pairs.keys():\n #...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.get_recurring_payments_profile_details
python
def get_recurring_payments_profile_details(self, profileid): args = self._sanitize_locals(locals()) return self._call('GetRecurringPaymentsProfileDetails', **args)
Shortcut for the GetRecurringPaymentsProfile method. This returns details for a recurring payment plan. The ``profileid`` is a value included in the response retrieved by the function ``create_recurring_payments_profile``. The profile details include the data provided when the profile w...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L468-L487
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.manage_recurring_payments_profile_status
python
def manage_recurring_payments_profile_status(self, profileid, action, note=None): args = self._sanitize_locals(locals()) if not note: del args['note'] return self._call('ManageRecurringPaymentsProfileStatus', **args)
Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'. ``note`` is optional and is visible to the user. It contains the reason for the chang...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L489-L501
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.update_recurring_payments_profile
python
def update_recurring_payments_profile(self, profileid, **kwargs): kwargs.update(self._sanitize_locals(locals())) return self._call('UpdateRecurringPaymentsProfile', **kwargs)
Shortcut to the UpdateRecurringPaymentsProfile method. ``profileid`` is the same profile id used for getting profile details. The keyed arguments are data in the payment profile which you wish to change. The profileid does not change. Anything else will take the new value. Most of, tho...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L503-L516
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.bm_create_button
python
def bm_create_button(self, **kwargs): kwargs.update(self._sanitize_locals(locals())) return self._call('BMCreateButton', **kwargs)
Shortcut to the BMCreateButton method. See the docs for details on arguments: https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton The L_BUTTONVARn fields are especially important, so make sure to read those and act accordingly. See...
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L518-L528
[ "def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n", "def _call(self, method, **kwargs):\n \"\"\"\n Wrapper metho...
class PayPalInterface(object): __credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT'] """ The end developers will do 95% of their work through this class. API queries, configuration, etc, all go through here. See the __init__ method for config related details. """ def __init__(self, confi...
gtaylor/paypal-python
paypal/response.py
PayPalResponse.success
python
def success(self): return self.ack.upper() in (self.config.ACK_SUCCESS, self.config.ACK_SUCCESS_WITH_WARNING)
Checks for the presence of errors in the response. Returns ``True`` if all is well, ``False`` otherwise. :rtype: bool :returns ``True`` if PayPal says our query was successful.
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/response.py#L109-L118
null
class PayPalResponse(object): """ Parse and prepare the reponse from PayPal's API. Acts as somewhat of a glorified dictionary for API responses. NOTE: Don't access self.raw directly. Just do something like PayPalResponse.someattr, going through PayPalResponse.__getattr__(). """ def __init__...
gtaylor/paypal-python
paypal/countries.py
is_valid_country_abbrev
python
def is_valid_country_abbrev(abbrev, case_sensitive=False): if case_sensitive: country_code = abbrev else: country_code = abbrev.upper() for code, full_name in COUNTRY_TUPLES: if country_code == code: return True return False
Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not.
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/countries.py#L254-L273
null
""" Country Code List: ISO 3166-1993 (E) http://xml.coverpages.org/country3166.html A tuple of tuples of country codes and their full names. There are a few helper functions provided if you'd rather not use the dict directly. Examples provided in the test_countries.py unit tests. """ COUNTRY_TUPLES = ( ('US', 'U...
gtaylor/paypal-python
paypal/countries.py
get_name_from_abbrev
python
def get_name_from_abbrev(abbrev, case_sensitive=False): if case_sensitive: country_code = abbrev else: country_code = abbrev.upper() for code, full_name in COUNTRY_TUPLES: if country_code == code: return full_name raise KeyError('No country with that country code.')
Given a country code abbreviation, get the full name from the table. abbrev: (str) Country code to retrieve the full name of. case_sensitive: (bool) When True, enforce case sensitivity.
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/countries.py#L276-L292
null
""" Country Code List: ISO 3166-1993 (E) http://xml.coverpages.org/country3166.html A tuple of tuples of country codes and their full names. There are a few helper functions provided if you'd rather not use the dict directly. Examples provided in the test_countries.py unit tests. """ COUNTRY_TUPLES = ( ('US', 'U...
erijo/tellcore-py
tellcore/library.py
Library.tdSensor
python
def tdSensor(self): protocol = create_string_buffer(20) model = create_string_buffer(20) sid = c_int() datatypes = c_int() self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model), byref(sid), byref(datatypes)) return {'protocol': se...
Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/library.py#L409-L423
[ "def _to_str(self, char_p):\n return char_p.value.decode(Library.STRING_ENCODING)\n" ]
class Library(object): """Wrapper around the Telldus Core C API. With the exception of tdInit, tdClose and tdReleaseString, all functions in the C API (see `Telldus Core documentation <http://developer.telldus.com/doxygen/group__core.html>`_) can be called. The parameters are the same as in the C A...
erijo/tellcore-py
tellcore/library.py
Library.tdSensorValue
python
def tdSensorValue(self, protocol, model, sid, datatype): value = create_string_buffer(20) timestamp = c_int() self._lib.tdSensorValue(protocol, model, sid, datatype, value, sizeof(value), byref(timestamp)) return {'value': self._to_str(value), 'timestamp'...
Get the sensor value for a given sensor. :return: a dict with the keys: value, timestamp.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/library.py#L425-L435
[ "def _to_str(self, char_p):\n return char_p.value.decode(Library.STRING_ENCODING)\n" ]
class Library(object): """Wrapper around the Telldus Core C API. With the exception of tdInit, tdClose and tdReleaseString, all functions in the C API (see `Telldus Core documentation <http://developer.telldus.com/doxygen/group__core.html>`_) can be called. The parameters are the same as in the C A...
erijo/tellcore-py
tellcore/library.py
Library.tdController
python
def tdController(self): cid = c_int() ctype = c_int() name = create_string_buffer(255) available = c_int() self._lib.tdController(byref(cid), byref(ctype), name, sizeof(name), byref(available)) return {'id': cid.value, 'type': ctype.value, ...
Get the next controller while iterating. :return: a dict with the keys: id, type, name, available.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/library.py#L437-L450
[ "def _to_str(self, char_p):\n return char_p.value.decode(Library.STRING_ENCODING)\n" ]
class Library(object): """Wrapper around the Telldus Core C API. With the exception of tdInit, tdClose and tdReleaseString, all functions in the C API (see `Telldus Core documentation <http://developer.telldus.com/doxygen/group__core.html>`_) can be called. The parameters are the same as in the C A...
erijo/tellcore-py
tellcore/telldus.py
DeviceFactory
python
def DeviceFactory(id, lib=None): lib = lib or Library() if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP: return DeviceGroup(id, lib=lib) return Device(id, lib=lib)
Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L266-L274
null
# Copyright (c) 2012-2014 Erik Johansson <erik@ejohansson.se> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This...
erijo/tellcore-py
tellcore/telldus.py
QueuedCallbackDispatcher.process_callback
python
def process_callback(self, block=True): try: (callback, args) = self._queue.get(block=block) try: callback(*args) finally: self._queue.task_done() except queue.Empty: return False return True
Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come. :return: True if a callback was processed; otherwise False.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L48-L62
null
class QueuedCallbackDispatcher(BaseCallbackDispatcher): """The default callback dispatcher used by :class:`TelldusCore`. Queues callbacks that arrive from Telldus Core. Then calls them in the main thread (or more precise: the thread calling :func:`process_callback`) instead of the callback thread used ...
erijo/tellcore-py
tellcore/telldus.py
TelldusCore.devices
python
def devices(self): devices = [] count = self.lib.tdGetNumberOfDevices() for i in range(count): device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib) devices.append(device) return devices
Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L169-L179
[ "def DeviceFactory(id, lib=None):\n \"\"\"Create the correct device instance based on device type and return it.\n\n :return: a :class:`Device` or :class:`DeviceGroup` instance.\n \"\"\"\n lib = lib or Library()\n if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP:\n return DeviceGroup(i...
class TelldusCore(object): """The main class for tellcore-py. Has methods for adding devices and for enumerating controllers, devices and sensors. Also handles callbacks; both registration and making sure the callbacks are processed in the main thread instead of the callback thread. """ def __...
erijo/tellcore-py
tellcore/telldus.py
TelldusCore.sensors
python
def sensors(self): sensors = [] try: while True: sensor = self.lib.tdSensor() sensors.append(Sensor(lib=self.lib, **sensor)) except TelldusError as e: if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND: raise retur...
Return all known sensors. :return: list of :class:`Sensor` instances.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L181-L194
[ "def tdSensor(self):\n \"\"\"Get the next sensor while iterating.\n\n :return: a dict with the keys: protocol, model, id, datatypes.\n \"\"\"\n protocol = create_string_buffer(20)\n model = create_string_buffer(20)\n sid = c_int()\n datatypes = c_int()\n\n self._lib.tdSensor(protocol, sizeof...
class TelldusCore(object): """The main class for tellcore-py. Has methods for adding devices and for enumerating controllers, devices and sensors. Also handles callbacks; both registration and making sure the callbacks are processed in the main thread instead of the callback thread. """ def __...
erijo/tellcore-py
tellcore/telldus.py
TelldusCore.controllers
python
def controllers(self): controllers = [] try: while True: controller = self.lib.tdController() del controller["name"] del controller["available"] controllers.append(Controller(lib=self.lib, **controller)) except TelldusEr...
Return all known controllers. Requires Telldus core library version >= 2.1.2. :return: list of :class:`Controller` instances.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L196-L213
[ "def tdController(self):\n \"\"\"Get the next controller while iterating.\n\n :return: a dict with the keys: id, type, name, available.\n \"\"\"\n cid = c_int()\n ctype = c_int()\n name = create_string_buffer(255)\n available = c_int()\n\n self._lib.tdController(byref(cid), byref(ctype), nam...
class TelldusCore(object): """The main class for tellcore-py. Has methods for adding devices and for enumerating controllers, devices and sensors. Also handles callbacks; both registration and making sure the callbacks are processed in the main thread instead of the callback thread. """ def __...
erijo/tellcore-py
tellcore/telldus.py
TelldusCore.add_device
python
def add_device(self, name, protocol, model=None, **parameters): device = Device(self.lib.tdAddDevice(), lib=self.lib) try: device.name = name device.protocol = protocol if model: device.model = model for key, value in parameters.items(): ...
Add a new device. :return: a :class:`Device` or :class:`DeviceGroup` instance.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L215-L242
[ "def DeviceFactory(id, lib=None):\n \"\"\"Create the correct device instance based on device type and return it.\n\n :return: a :class:`Device` or :class:`DeviceGroup` instance.\n \"\"\"\n lib = lib or Library()\n if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP:\n return DeviceGroup(i...
class TelldusCore(object): """The main class for tellcore-py. Has methods for adding devices and for enumerating controllers, devices and sensors. Also handles callbacks; both registration and making sure the callbacks are processed in the main thread instead of the callback thread. """ def __...
erijo/tellcore-py
tellcore/telldus.py
TelldusCore.add_group
python
def add_group(self, name, devices): device = self.add_device(name, "group") device.add_to_group(devices) return device
Add a new device group. :return: a :class:`DeviceGroup` instance.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L244-L251
[ "def add_device(self, name, protocol, model=None, **parameters):\n \"\"\"Add a new device.\n\n :return: a :class:`Device` or :class:`DeviceGroup` instance.\n \"\"\"\n device = Device(self.lib.tdAddDevice(), lib=self.lib)\n try:\n device.name = name\n device.protocol = protocol\n ...
class TelldusCore(object): """The main class for tellcore-py. Has methods for adding devices and for enumerating controllers, devices and sensors. Also handles callbacks; both registration and making sure the callbacks are processed in the main thread instead of the callback thread. """ def __...
erijo/tellcore-py
tellcore/telldus.py
TelldusCore.connect_controller
python
def connect_controller(self, vid, pid, serial): self.lib.tdConnectTellStickController(vid, pid, serial)
Connect a controller.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L257-L259
null
class TelldusCore(object): """The main class for tellcore-py. Has methods for adding devices and for enumerating controllers, devices and sensors. Also handles callbacks; both registration and making sure the callbacks are processed in the main thread instead of the callback thread. """ def __...
erijo/tellcore-py
tellcore/telldus.py
TelldusCore.disconnect_controller
python
def disconnect_controller(self, vid, pid, serial): self.lib.tdDisconnectTellStickController(vid, pid, serial)
Disconnect a controller.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L261-L263
null
class TelldusCore(object): """The main class for tellcore-py. Has methods for adding devices and for enumerating controllers, devices and sensors. Also handles callbacks; both registration and making sure the callbacks are processed in the main thread instead of the callback thread. """ def __...
erijo/tellcore-py
tellcore/telldus.py
Device.parameters
python
def parameters(self): parameters = {} for name in self.PARAMETERS: try: parameters[name] = self.get_parameter(name) except AttributeError: pass return parameters
Get dict with all set parameters.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L323-L331
[ "def get_parameter(self, name):\n \"\"\"Get a parameter.\"\"\"\n default_value = \"$%!)(INVALID)(!%$\"\n value = self.lib.tdGetDeviceParameter(self.id, name, default_value)\n if value == default_value:\n raise AttributeError(name)\n return value\n" ]
class Device(object): """A device that can be controlled by Telldus Core. Can be instantiated directly if the id is known, but using :func:`DeviceFactory` is recommended. Otherwise returned from :func:`TelldusCore.add_device` or :func:`TelldusCore.devices`. """ PARAMETERS = ["devices", "house"...
erijo/tellcore-py
tellcore/telldus.py
Device.get_parameter
python
def get_parameter(self, name): default_value = "$%!)(INVALID)(!%$" value = self.lib.tdGetDeviceParameter(self.id, name, default_value) if value == default_value: raise AttributeError(name) return value
Get a parameter.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L333-L339
null
class Device(object): """A device that can be controlled by Telldus Core. Can be instantiated directly if the id is known, but using :func:`DeviceFactory` is recommended. Otherwise returned from :func:`TelldusCore.add_device` or :func:`TelldusCore.devices`. """ PARAMETERS = ["devices", "house"...
erijo/tellcore-py
tellcore/telldus.py
Device.set_parameter
python
def set_parameter(self, name, value): self.lib.tdSetDeviceParameter(self.id, name, str(value))
Set a parameter.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L341-L343
null
class Device(object): """A device that can be controlled by Telldus Core. Can be instantiated directly if the id is known, but using :func:`DeviceFactory` is recommended. Otherwise returned from :func:`TelldusCore.add_device` or :func:`TelldusCore.devices`. """ PARAMETERS = ["devices", "house"...
erijo/tellcore-py
tellcore/telldus.py
DeviceGroup.add_to_group
python
def add_to_group(self, devices): ids = {d.id for d in self.devices_in_group()} ids.update(self._device_ids(devices)) self._set_group(ids)
Add device(s) to the group.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L406-L410
[ "def devices_in_group(self):\n \"\"\"Fetch list of devices in group.\"\"\"\n try:\n devices = self.get_parameter('devices')\n except AttributeError:\n return []\n\n ctor = DeviceFactory\n return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]\n", "def _device_ids(devices...
class DeviceGroup(Device): """Extends :class:`Device` with methods for managing a group E.g. when a group is turned on, all devices in that group are turned on. """ def remove_from_group(self, devices): """Remove device(s) from the group.""" ids = {d.id for d in self.devices_in_group(...
erijo/tellcore-py
tellcore/telldus.py
DeviceGroup.remove_from_group
python
def remove_from_group(self, devices): ids = {d.id for d in self.devices_in_group()} ids.difference_update(self._device_ids(devices)) self._set_group(ids)
Remove device(s) from the group.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L412-L416
[ "def devices_in_group(self):\n \"\"\"Fetch list of devices in group.\"\"\"\n try:\n devices = self.get_parameter('devices')\n except AttributeError:\n return []\n\n ctor = DeviceFactory\n return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]\n", "def _device_ids(devices...
class DeviceGroup(Device): """Extends :class:`Device` with methods for managing a group E.g. when a group is turned on, all devices in that group are turned on. """ def add_to_group(self, devices): """Add device(s) to the group.""" ids = {d.id for d in self.devices_in_group()} ...
erijo/tellcore-py
tellcore/telldus.py
DeviceGroup.devices_in_group
python
def devices_in_group(self): try: devices = self.get_parameter('devices') except AttributeError: return [] ctor = DeviceFactory return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
Fetch list of devices in group.
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L418-L426
[ "def get_parameter(self, name):\n \"\"\"Get a parameter.\"\"\"\n default_value = \"$%!)(INVALID)(!%$\"\n value = self.lib.tdGetDeviceParameter(self.id, name, default_value)\n if value == default_value:\n raise AttributeError(name)\n return value\n" ]
class DeviceGroup(Device): """Extends :class:`Device` with methods for managing a group E.g. when a group is turned on, all devices in that group are turned on. """ def add_to_group(self, devices): """Add device(s) to the group.""" ids = {d.id for d in self.devices_in_group()} ...
erijo/tellcore-py
tellcore/telldus.py
Sensor.value
python
def value(self, datatype): value = self.lib.tdSensorValue( self.protocol, self.model, self.id, datatype) return SensorValue(datatype, value['value'], value['timestamp'])
Return the :class:`SensorValue` for the given data type. sensor.value(TELLSTICK_TEMPERATURE) is identical to calling sensor.temperature().
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L478-L486
null
class Sensor(object): """Represents a sensor. Returned from :func:`TelldusCore.sensors` """ DATATYPES = {"temperature": const.TELLSTICK_TEMPERATURE, "humidity": const.TELLSTICK_HUMIDITY, "rainrate": const.TELLSTICK_RAINRATE, "raintotal": const.TELLSTI...
mozilla-services/python-dockerflow
src/dockerflow/version.py
get_version
python
def get_version(root): version_json = os.path.join(root, 'version.json') if os.path.exists(version_json): with open(version_json, 'r') as version_json_file: return json.load(version_json_file) return None
Load and return the contents of version.json. :param root: The root path that the ``version.json`` file will be opened :type root: str :returns: Content of ``version.json`` or None :rtype: dict or None
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/version.py#L10-L23
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import json import os __all__ = ['get_version']
mozilla-services/python-dockerflow
src/dockerflow/django/views.py
version
python
def version(request): version_json = import_string(version_callback)(settings.BASE_DIR) if version_json is None: return HttpResponseNotFound('version.json not found') else: return JsonResponse(version_json)
Returns the contents of version.json or a 404.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/views.py#L20-L28
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. from django.conf import settings from django.core import checks from django.http import HttpResponse, HttpResponseNotFoun...
mozilla-services/python-dockerflow
src/dockerflow/django/views.py
heartbeat
python
def heartbeat(request): all_checks = checks.registry.registry.get_checks( include_deployment_checks=not settings.DEBUG, ) details = {} statuses = {} level = 0 for check in all_checks: detail = heartbeat_check_detail(check) statuses[check.__name__] = detail['status'] ...
Runs all the Django checks and returns a JsonResponse with either a status code of 200 or 500 depending on the results of the checks. Any check that returns a warning or worse (error, critical) will return a 500 response.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/views.py#L40-L75
[ "def level_to_text(level):\n statuses = {\n 0: 'ok',\n checks.messages.DEBUG: 'debug',\n checks.messages.INFO: 'info',\n checks.messages.WARNING: 'warning',\n checks.messages.ERROR: 'error',\n checks.messages.CRITICAL: 'critical',\n }\n return statuses.get(level, '...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. from django.conf import settings from django.core import checks from django.http import HttpResponse, HttpResponseNotFoun...
mozilla-services/python-dockerflow
src/dockerflow/django/checks.py
check_database_connected
python
def check_database_connected(app_configs, **kwargs): errors = [] try: connection.ensure_connection() except OperationalError as e: msg = 'Could not connect to database: {!s}'.format(e) errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_...
A Django check to see if connecting to the configured default database backend succeeds.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L26-L48
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. from django.conf import settings from django.core import checks from django.core.exceptions import ImproperlyConfigured f...
mozilla-services/python-dockerflow
src/dockerflow/django/checks.py
check_migrations_applied
python
def check_migrations_applied(app_configs, **kwargs): from django.db.migrations.loader import MigrationLoader errors = [] # Load migrations from disk/DB try: loader = MigrationLoader(connection, ignore_no_migrations=True) except (ImproperlyConfigured, ProgrammingError, OperationalError): ...
A Django check to see if all migrations have been applied correctly.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L51-L80
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. from django.conf import settings from django.core import checks from django.core.exceptions import ImproperlyConfigured f...
mozilla-services/python-dockerflow
src/dockerflow/django/checks.py
check_redis_connected
python
def check_redis_connected(app_configs, **kwargs): import redis from django_redis import get_redis_connection errors = [] try: connection = get_redis_connection('default') except redis.ConnectionError as e: msg = 'Could not connect to redis: {!s}'.format(e) errors.append(chec...
A Django check to connect to the default redis connection using ``django_redis.get_redis_connection`` and see if Redis responds to a ``PING`` command.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L83-L109
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. from django.conf import settings from django.core import checks from django.core.exceptions import ImproperlyConfigured f...
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow.init_check
python
def init_check(self, check, obj): self.logger.info('Adding extension check %s' % check.__name__) check = functools.wraps(check)(functools.partial(check, obj)) self.check(func=check)
Adds a given check callback with the provided object to the list of checks. Useful for built-ins but also advanced custom checks.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L135-L142
[ "def check(self, func=None, name=None):\n \"\"\"\n A decorator to register a new Dockerflow check to be run\n when the /__heartbeat__ endpoint is called., e.g.::\n\n from dockerflow.flask import checks\n\n @dockerflow.check\n def storage_reachable():\n try:\n ...
class Dockerflow(object): """ The Dockerflow Flask extension. Set it up like this: .. code-block:: python :caption: ``myproject.py`` from flask import Flask from dockerflow.flask import Dockerflow app = Flask(__name__) dockerflow = Dockerflow(app) Or if you use the...
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow.init_app
python
def init_app(self, app): # If no version path was provided in the init of the Dockerflow # class we'll use the parent directory of the app root path. if self.version_path is None: self.version_path = os.path.dirname(app.root_path) for view in ( ('/__version__', '...
Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L144-L169
null
class Dockerflow(object): """ The Dockerflow Flask extension. Set it up like this: .. code-block:: python :caption: ``myproject.py`` from flask import Flask from dockerflow.flask import Dockerflow app = Flask(__name__) dockerflow = Dockerflow(app) Or if you use the...
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow._before_request
python
def _before_request(self): g._request_id = str(uuid.uuid4()) g._start_timestamp = time.time()
The before_request callback.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L178-L183
null
class Dockerflow(object): """ The Dockerflow Flask extension. Set it up like this: .. code-block:: python :caption: ``myproject.py`` from flask import Flask from dockerflow.flask import Dockerflow app = Flask(__name__) dockerflow = Dockerflow(app) Or if you use the...
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow._after_request
python
def _after_request(self, response): if not getattr(g, '_has_exception', False): extra = self.summary_extra() self.summary_logger.info('', extra=extra) return response
The signal handler for the request_finished signal.
train
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L185-L192
null
class Dockerflow(object): """ The Dockerflow Flask extension. Set it up like this: .. code-block:: python :caption: ``myproject.py`` from flask import Flask from dockerflow.flask import Dockerflow app = Flask(__name__) dockerflow = Dockerflow(app) Or if you use the...