repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
squaresLab/BugZoo
bugzoo/client/api.py
APIClient.handle_erroneous_response
def handle_erroneous_response(self, response: requests.Response ) -> NoReturn: """ Attempts to decode an erroneous response into an exception, and to subsequently throw that exception. Raises: BugZooException: the exception described by the error response. UnexpectedResponse: if the response cannot be decoded to an exception. """ logger.debug("handling erroneous response: %s", response) try: err = BugZooException.from_dict(response.json()) except Exception: err = UnexpectedResponse(response) raise err
python
def handle_erroneous_response(self, response: requests.Response ) -> NoReturn: """ Attempts to decode an erroneous response into an exception, and to subsequently throw that exception. Raises: BugZooException: the exception described by the error response. UnexpectedResponse: if the response cannot be decoded to an exception. """ logger.debug("handling erroneous response: %s", response) try: err = BugZooException.from_dict(response.json()) except Exception: err = UnexpectedResponse(response) raise err
[ "def", "handle_erroneous_response", "(", "self", ",", "response", ":", "requests", ".", "Response", ")", "->", "NoReturn", ":", "logger", ".", "debug", "(", "\"handling erroneous response: %s\"", ",", "response", ")", "try", ":", "err", "=", "BugZooException", "...
Attempts to decode an erroneous response into an exception, and to subsequently throw that exception. Raises: BugZooException: the exception described by the error response. UnexpectedResponse: if the response cannot be decoded to an exception.
[ "Attempts", "to", "decode", "an", "erroneous", "response", "into", "an", "exception", "and", "to", "subsequently", "throw", "that", "exception", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/api.py#L79-L96
train
30,100
squaresLab/BugZoo
bugzoo/client/dockerm.py
DockerManager.has_image
def has_image(self, name: str) -> bool: """ Determines whether the server has a Docker image with a given name. """ path = "docker/images/{}".format(name) r = self.__api.head(path) if r.status_code == 204: return True elif r.status_code == 404: return False self.__api.handle_erroneous_response(r)
python
def has_image(self, name: str) -> bool: """ Determines whether the server has a Docker image with a given name. """ path = "docker/images/{}".format(name) r = self.__api.head(path) if r.status_code == 204: return True elif r.status_code == 404: return False self.__api.handle_erroneous_response(r)
[ "def", "has_image", "(", "self", ",", "name", ":", "str", ")", "->", "bool", ":", "path", "=", "\"docker/images/{}\"", ".", "format", "(", "name", ")", "r", "=", "self", ".", "__api", ".", "head", "(", "path", ")", "if", "r", ".", "status_code", "=...
Determines whether the server has a Docker image with a given name.
[ "Determines", "whether", "the", "server", "has", "a", "Docker", "image", "with", "a", "given", "name", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/dockerm.py#L18-L28
train
30,101
squaresLab/BugZoo
bugzoo/client/dockerm.py
DockerManager.delete_image
def delete_image(self, name: str) -> None: """ Deletes a Docker image with a given name. Parameters: name: the name of the Docker image. """ logger.debug("deleting Docker image: %s", name) path = "docker/images/{}".format(name) response = self.__api.delete(path) if response.status_code != 204: try: self.__api.handle_erroneous_response(response) except Exception: logger.exception("failed to delete Docker image: %s", name) raise else: logger.info("deleted Docker image: %s", name)
python
def delete_image(self, name: str) -> None: """ Deletes a Docker image with a given name. Parameters: name: the name of the Docker image. """ logger.debug("deleting Docker image: %s", name) path = "docker/images/{}".format(name) response = self.__api.delete(path) if response.status_code != 204: try: self.__api.handle_erroneous_response(response) except Exception: logger.exception("failed to delete Docker image: %s", name) raise else: logger.info("deleted Docker image: %s", name)
[ "def", "delete_image", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"deleting Docker image: %s\"", ",", "name", ")", "path", "=", "\"docker/images/{}\"", ".", "format", "(", "name", ")", "response", "=", "sel...
Deletes a Docker image with a given name. Parameters: name: the name of the Docker image.
[ "Deletes", "a", "Docker", "image", "with", "a", "given", "name", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/dockerm.py#L30-L47
train
30,102
squaresLab/BugZoo
bugzoo/client/file.py
FileManager._file_path
def _file_path(self, container: Container, fn: str) -> str: """ Computes the base path for a given file. """ fn = self.resolve(container, fn) assert fn[0] == '/' fn = fn[1:] path = "files/{}/{}".format(container.uid, fn) return path
python
def _file_path(self, container: Container, fn: str) -> str: """ Computes the base path for a given file. """ fn = self.resolve(container, fn) assert fn[0] == '/' fn = fn[1:] path = "files/{}/{}".format(container.uid, fn) return path
[ "def", "_file_path", "(", "self", ",", "container", ":", "Container", ",", "fn", ":", "str", ")", "->", "str", ":", "fn", "=", "self", ".", "resolve", "(", "container", ",", "fn", ")", "assert", "fn", "[", "0", "]", "==", "'/'", "fn", "=", "fn", ...
Computes the base path for a given file.
[ "Computes", "the", "base", "path", "for", "a", "given", "file", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/file.py#L38-L46
train
30,103
squaresLab/BugZoo
bugzoo/client/file.py
FileManager.write
def write(self, container: Container, filepath: str, contents: str ) -> None: """ Dumps the contents of a given string into a file at a specified location inside the container. Parameters: container: the container to which the file should be written. filepath: the path to the file inside the container. If a relative path is given, the path will be interpreted as being relative to the source directory for the program under test inside the container. contents: the contents that should be written to the specified file. """ logger.debug("writing to file [%s] in container [%s].", filepath, container.uid) path = self._file_path(container, filepath) try: response = self.__api.put(path, data=contents) if response.status_code != 204: self.__api.handle_erroneous_response(response) except BugZooException: logger.exception("failed to write to file [%s] in container [%s].", filepath, container.uid) raise logger.debug("wrote to file [%s] in container [%s].", filepath, container.uid)
python
def write(self, container: Container, filepath: str, contents: str ) -> None: """ Dumps the contents of a given string into a file at a specified location inside the container. Parameters: container: the container to which the file should be written. filepath: the path to the file inside the container. If a relative path is given, the path will be interpreted as being relative to the source directory for the program under test inside the container. contents: the contents that should be written to the specified file. """ logger.debug("writing to file [%s] in container [%s].", filepath, container.uid) path = self._file_path(container, filepath) try: response = self.__api.put(path, data=contents) if response.status_code != 204: self.__api.handle_erroneous_response(response) except BugZooException: logger.exception("failed to write to file [%s] in container [%s].", filepath, container.uid) raise logger.debug("wrote to file [%s] in container [%s].", filepath, container.uid)
[ "def", "write", "(", "self", ",", "container", ":", "Container", ",", "filepath", ":", "str", ",", "contents", ":", "str", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"writing to file [%s] in container [%s].\"", ",", "filepath", ",", "container", ...
Dumps the contents of a given string into a file at a specified location inside the container. Parameters: container: the container to which the file should be written. filepath: the path to the file inside the container. If a relative path is given, the path will be interpreted as being relative to the source directory for the program under test inside the container. contents: the contents that should be written to the specified file.
[ "Dumps", "the", "contents", "of", "a", "given", "string", "into", "a", "file", "at", "a", "specified", "location", "inside", "the", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/file.py#L48-L78
train
30,104
squaresLab/BugZoo
bugzoo/client/file.py
FileManager.read
def read(self, container: Container, filepath: str) -> str: """ Attempts to retrieve the contents of a given file in a running container. Parameters: container: the container from which the file should be fetched. filepath: the path to the file. If a relative path is given, the path will be interpreted as being relative to the source directory for the program under test inside the container. Returns: the contents of the file as a string. Raises: KeyError: if the given file was not found. """ logger.debug("reading contents of file [%s] in container [%s].", filepath, container.uid) path = self._file_path(container, filepath) response = self.__api.get(path) if response.status_code == 200: contents = response.text logger.debug("fetched contents of file [%s] in container [%s]:%s", filepath, container.uid, indent("\n[CONTENTS]\n{}\n[/CONTENTS]".format(contents), 2)) # noqa: pycodestyle return contents try: self.__api.handle_erroneous_response(response) except BugZooException as err: logger.exception("failed to read contents of file [%s] in container [%s]: %s", # noqa: pycodestyle filepath, container.uid, err) raise
python
def read(self, container: Container, filepath: str) -> str: """ Attempts to retrieve the contents of a given file in a running container. Parameters: container: the container from which the file should be fetched. filepath: the path to the file. If a relative path is given, the path will be interpreted as being relative to the source directory for the program under test inside the container. Returns: the contents of the file as a string. Raises: KeyError: if the given file was not found. """ logger.debug("reading contents of file [%s] in container [%s].", filepath, container.uid) path = self._file_path(container, filepath) response = self.__api.get(path) if response.status_code == 200: contents = response.text logger.debug("fetched contents of file [%s] in container [%s]:%s", filepath, container.uid, indent("\n[CONTENTS]\n{}\n[/CONTENTS]".format(contents), 2)) # noqa: pycodestyle return contents try: self.__api.handle_erroneous_response(response) except BugZooException as err: logger.exception("failed to read contents of file [%s] in container [%s]: %s", # noqa: pycodestyle filepath, container.uid, err) raise
[ "def", "read", "(", "self", ",", "container", ":", "Container", ",", "filepath", ":", "str", ")", "->", "str", ":", "logger", ".", "debug", "(", "\"reading contents of file [%s] in container [%s].\"", ",", "filepath", ",", "container", ".", "uid", ")", "path",...
Attempts to retrieve the contents of a given file in a running container. Parameters: container: the container from which the file should be fetched. filepath: the path to the file. If a relative path is given, the path will be interpreted as being relative to the source directory for the program under test inside the container. Returns: the contents of the file as a string. Raises: KeyError: if the given file was not found.
[ "Attempts", "to", "retrieve", "the", "contents", "of", "a", "given", "file", "in", "a", "running", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/file.py#L80-L112
train
30,105
matiskay/html-similarity
html_similarity/style_similarity.py
style_similarity
def style_similarity(page1, page2): """ Computes CSS style Similarity between two DOM trees A = classes(Document_1) B = classes(Document_2) style_similarity = |A & B| / (|A| + |B| - |A & B|) :param page1: html of the page1 :param page2: html of the page2 :return: Number between 0 and 1. If the number is next to 1 the page are really similar. """ classes_page1 = get_classes(page1) classes_page2 = get_classes(page2) return jaccard_similarity(classes_page1, classes_page2)
python
def style_similarity(page1, page2): """ Computes CSS style Similarity between two DOM trees A = classes(Document_1) B = classes(Document_2) style_similarity = |A & B| / (|A| + |B| - |A & B|) :param page1: html of the page1 :param page2: html of the page2 :return: Number between 0 and 1. If the number is next to 1 the page are really similar. """ classes_page1 = get_classes(page1) classes_page2 = get_classes(page2) return jaccard_similarity(classes_page1, classes_page2)
[ "def", "style_similarity", "(", "page1", ",", "page2", ")", ":", "classes_page1", "=", "get_classes", "(", "page1", ")", "classes_page2", "=", "get_classes", "(", "page2", ")", "return", "jaccard_similarity", "(", "classes_page1", ",", "classes_page2", ")" ]
Computes CSS style Similarity between two DOM trees A = classes(Document_1) B = classes(Document_2) style_similarity = |A & B| / (|A| + |B| - |A & B|) :param page1: html of the page1 :param page2: html of the page2 :return: Number between 0 and 1. If the number is next to 1 the page are really similar.
[ "Computes", "CSS", "style", "Similarity", "between", "two", "DOM", "trees" ]
eef5586b1cf30134254690b2150260ef82cbd18f
https://github.com/matiskay/html-similarity/blob/eef5586b1cf30134254690b2150260ef82cbd18f/html_similarity/style_similarity.py#L26-L41
train
30,106
squaresLab/BugZoo
bugzoo/core/spectra.py
Spectra.restricted_to_files
def restricted_to_files(self, filenames: List[str] ) -> 'Spectra': """ Returns a variant of this spectra that only contains entries for lines that appear in any of the files whose name appear in the given list. """ tally_passing = \ {fn: entries for (fn, entries) in self.__tally_passing.items() \ if fn in filenames} tally_failing = \ {fn: entries for (fn, entries) in self.__tally_failing.items() \ if fn in filenames} return Spectra(self.__num_passing, self.__num_failing, tally_passing, tally_failing)
python
def restricted_to_files(self, filenames: List[str] ) -> 'Spectra': """ Returns a variant of this spectra that only contains entries for lines that appear in any of the files whose name appear in the given list. """ tally_passing = \ {fn: entries for (fn, entries) in self.__tally_passing.items() \ if fn in filenames} tally_failing = \ {fn: entries for (fn, entries) in self.__tally_failing.items() \ if fn in filenames} return Spectra(self.__num_passing, self.__num_failing, tally_passing, tally_failing)
[ "def", "restricted_to_files", "(", "self", ",", "filenames", ":", "List", "[", "str", "]", ")", "->", "'Spectra'", ":", "tally_passing", "=", "{", "fn", ":", "entries", "for", "(", "fn", ",", "entries", ")", "in", "self", ".", "__tally_passing", ".", "...
Returns a variant of this spectra that only contains entries for lines that appear in any of the files whose name appear in the given list.
[ "Returns", "a", "variant", "of", "this", "spectra", "that", "only", "contains", "entries", "for", "lines", "that", "appear", "in", "any", "of", "the", "files", "whose", "name", "appear", "in", "the", "given", "list", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/spectra.py#L132-L149
train
30,107
squaresLab/BugZoo
bugzoo/core/fileline.py
FileLineSet.filter
def filter(self, predicate: Callable[[FileLine], 'FileLineSet'] ) -> 'FileLineSet': """ Returns a subset of the file lines within this set that satisfy a given filtering criterion. """ filtered = [fileline for fileline in self if predicate(fileline)] return FileLineSet.from_list(filtered)
python
def filter(self, predicate: Callable[[FileLine], 'FileLineSet'] ) -> 'FileLineSet': """ Returns a subset of the file lines within this set that satisfy a given filtering criterion. """ filtered = [fileline for fileline in self if predicate(fileline)] return FileLineSet.from_list(filtered)
[ "def", "filter", "(", "self", ",", "predicate", ":", "Callable", "[", "[", "FileLine", "]", ",", "'FileLineSet'", "]", ")", "->", "'FileLineSet'", ":", "filtered", "=", "[", "fileline", "for", "fileline", "in", "self", "if", "predicate", "(", "fileline", ...
Returns a subset of the file lines within this set that satisfy a given filtering criterion.
[ "Returns", "a", "subset", "of", "the", "file", "lines", "within", "this", "set", "that", "satisfy", "a", "given", "filtering", "criterion", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/fileline.py#L137-L145
train
30,108
squaresLab/BugZoo
bugzoo/core/fileline.py
FileLineSet.union
def union(self, other: 'FileLineSet') -> 'FileLineSet': """ Returns a set of file lines that contains the union of the lines within this set and a given set. """ # this isn't the most efficient implementation, but frankly, it doesn't # need to be. assert isinstance(other, FileLineSet) l_self = list(self) l_other = list(other) l_union = l_self + l_other return FileLineSet.from_list(l_union)
python
def union(self, other: 'FileLineSet') -> 'FileLineSet': """ Returns a set of file lines that contains the union of the lines within this set and a given set. """ # this isn't the most efficient implementation, but frankly, it doesn't # need to be. assert isinstance(other, FileLineSet) l_self = list(self) l_other = list(other) l_union = l_self + l_other return FileLineSet.from_list(l_union)
[ "def", "union", "(", "self", ",", "other", ":", "'FileLineSet'", ")", "->", "'FileLineSet'", ":", "# this isn't the most efficient implementation, but frankly, it doesn't", "# need to be.", "assert", "isinstance", "(", "other", ",", "FileLineSet", ")", "l_self", "=", "l...
Returns a set of file lines that contains the union of the lines within this set and a given set.
[ "Returns", "a", "set", "of", "file", "lines", "that", "contains", "the", "union", "of", "the", "lines", "within", "this", "set", "and", "a", "given", "set", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/fileline.py#L147-L158
train
30,109
squaresLab/BugZoo
bugzoo/core/fileline.py
FileLineSet.intersection
def intersection(self, other: 'FileLineSet') -> 'FileLineSet': """ Returns a set of file lines that contains the intersection of the lines within this set and a given set. """ assert isinstance(other, FileLineSet) set_self = set(self) set_other = set(other) set_union = set_self & set_other return FileLineSet.from_list(list(set_union))
python
def intersection(self, other: 'FileLineSet') -> 'FileLineSet': """ Returns a set of file lines that contains the intersection of the lines within this set and a given set. """ assert isinstance(other, FileLineSet) set_self = set(self) set_other = set(other) set_union = set_self & set_other return FileLineSet.from_list(list(set_union))
[ "def", "intersection", "(", "self", ",", "other", ":", "'FileLineSet'", ")", "->", "'FileLineSet'", ":", "assert", "isinstance", "(", "other", ",", "FileLineSet", ")", "set_self", "=", "set", "(", "self", ")", "set_other", "=", "set", "(", "other", ")", ...
Returns a set of file lines that contains the intersection of the lines within this set and a given set.
[ "Returns", "a", "set", "of", "file", "lines", "that", "contains", "the", "intersection", "of", "the", "lines", "within", "this", "set", "and", "a", "given", "set", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/fileline.py#L160-L169
train
30,110
squaresLab/BugZoo
bugzoo/mgr/tool.py
ToolManager.provision
def provision(self, tool: Tool) -> docker.models.containers.Container: """ Provisions a mountable Docker container for a given tool. """ if not self.is_installed(tool): raise Exception("tool is not installed: {}".format(tool.name)) client = self.__installation.docker return client.containers.create(tool.image)
python
def provision(self, tool: Tool) -> docker.models.containers.Container: """ Provisions a mountable Docker container for a given tool. """ if not self.is_installed(tool): raise Exception("tool is not installed: {}".format(tool.name)) client = self.__installation.docker return client.containers.create(tool.image)
[ "def", "provision", "(", "self", ",", "tool", ":", "Tool", ")", "->", "docker", ".", "models", ".", "containers", ".", "Container", ":", "if", "not", "self", ".", "is_installed", "(", "tool", ")", ":", "raise", "Exception", "(", "\"tool is not installed: {...
Provisions a mountable Docker container for a given tool.
[ "Provisions", "a", "mountable", "Docker", "container", "for", "a", "given", "tool", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/tool.py#L30-L38
train
30,111
squaresLab/BugZoo
bugzoo/mgr/tool.py
ToolManager.is_installed
def is_installed(self, tool: Tool) -> bool: """ Determines whether or not the Docker image for a given tool has been installed onto this server. See: `BuildManager.is_installed` """ return self.__installation.build.is_installed(tool.image)
python
def is_installed(self, tool: Tool) -> bool: """ Determines whether or not the Docker image for a given tool has been installed onto this server. See: `BuildManager.is_installed` """ return self.__installation.build.is_installed(tool.image)
[ "def", "is_installed", "(", "self", ",", "tool", ":", "Tool", ")", "->", "bool", ":", "return", "self", ".", "__installation", ".", "build", ".", "is_installed", "(", "tool", ".", "image", ")" ]
Determines whether or not the Docker image for a given tool has been installed onto this server. See: `BuildManager.is_installed`
[ "Determines", "whether", "or", "not", "the", "Docker", "image", "for", "a", "given", "tool", "has", "been", "installed", "onto", "this", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/tool.py#L56-L63
train
30,112
squaresLab/BugZoo
bugzoo/mgr/tool.py
ToolManager.build
def build(self, tool: Tool, force: bool = False, quiet: bool = False ) -> None: """ Builds the Docker image associated with a given tool. See: `BuildManager.build` """ self.__installation.build.build(tool.image, force=force, quiet=quiet)
python
def build(self, tool: Tool, force: bool = False, quiet: bool = False ) -> None: """ Builds the Docker image associated with a given tool. See: `BuildManager.build` """ self.__installation.build.build(tool.image, force=force, quiet=quiet)
[ "def", "build", "(", "self", ",", "tool", ":", "Tool", ",", "force", ":", "bool", "=", "False", ",", "quiet", ":", "bool", "=", "False", ")", "->", "None", ":", "self", ".", "__installation", ".", "build", ".", "build", "(", "tool", ".", "image", ...
Builds the Docker image associated with a given tool. See: `BuildManager.build`
[ "Builds", "the", "Docker", "image", "associated", "with", "a", "given", "tool", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/tool.py#L65-L77
train
30,113
squaresLab/BugZoo
bugzoo/mgr/tool.py
ToolManager.uninstall
def uninstall(self, tool: Tool, force: bool = False, noprune: bool = False ) -> None: """ Uninstalls all Docker images associated with this tool. See: `BuildManager.uninstall` """ self.__installation.build.uninstall(tool.image, force=force, noprune=noprune)
python
def uninstall(self, tool: Tool, force: bool = False, noprune: bool = False ) -> None: """ Uninstalls all Docker images associated with this tool. See: `BuildManager.uninstall` """ self.__installation.build.uninstall(tool.image, force=force, noprune=noprune)
[ "def", "uninstall", "(", "self", ",", "tool", ":", "Tool", ",", "force", ":", "bool", "=", "False", ",", "noprune", ":", "bool", "=", "False", ")", "->", "None", ":", "self", ".", "__installation", ".", "build", ".", "uninstall", "(", "tool", ".", ...
Uninstalls all Docker images associated with this tool. See: `BuildManager.uninstall`
[ "Uninstalls", "all", "Docker", "images", "associated", "with", "this", "tool", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/tool.py#L79-L91
train
30,114
squaresLab/BugZoo
bugzoo/core/source.py
RemoteSource.to_dict
def to_dict(self) -> Dict[str, str]: """ Produces a dictionary-based description of this source. """ return { 'type': 'remote', 'name': self.name, 'location': self.location, 'url': self.url, 'version': self.version }
python
def to_dict(self) -> Dict[str, str]: """ Produces a dictionary-based description of this source. """ return { 'type': 'remote', 'name': self.name, 'location': self.location, 'url': self.url, 'version': self.version }
[ "def", "to_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "return", "{", "'type'", ":", "'remote'", ",", "'name'", ":", "self", ".", "name", ",", "'location'", ":", "self", ".", "location", ",", "'url'", ":", "self", ".", ...
Produces a dictionary-based description of this source.
[ "Produces", "a", "dictionary", "-", "based", "description", "of", "this", "source", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/source.py#L143-L153
train
30,115
squaresLab/BugZoo
bugzoo/mgr/build.py
BuildManager.is_installed
def is_installed(self, name: str) -> bool: """ Indicates a given Docker image is installed on this server. Parameters: name: the name of the Docker image. Returns: `True` if installed; `False` if not. """ assert name is not None try: self.__docker.images.get(name) return True except docker.errors.ImageNotFound: return False
python
def is_installed(self, name: str) -> bool: """ Indicates a given Docker image is installed on this server. Parameters: name: the name of the Docker image. Returns: `True` if installed; `False` if not. """ assert name is not None try: self.__docker.images.get(name) return True except docker.errors.ImageNotFound: return False
[ "def", "is_installed", "(", "self", ",", "name", ":", "str", ")", "->", "bool", ":", "assert", "name", "is", "not", "None", "try", ":", "self", ".", "__docker", ".", "images", ".", "get", "(", "name", ")", "return", "True", "except", "docker", ".", ...
Indicates a given Docker image is installed on this server. Parameters: name: the name of the Docker image. Returns: `True` if installed; `False` if not.
[ "Indicates", "a", "given", "Docker", "image", "is", "installed", "on", "this", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/build.py#L58-L73
train
30,116
squaresLab/BugZoo
bugzoo/mgr/build.py
BuildManager.build
def build(self, name: str, force: bool = False, quiet: bool = False ) -> None: """ Constructs a Docker image, given by its name, using the set of build instructions associated with that image. Parameters: name: the name of the Docker image. force: if `True`, the image will be rebuilt, regardless of whether or not it is already installed on the server. If `False` and a (possibly outdated) version of the image has already been built, then the build will be skipped. quiet: used to enable and disable output from the Docker build process. """ logger.debug("request to build image: %s", name) instructions = self[name] if instructions.depends_on: logger.info("building dependent image: %s", instructions.depends_on) self.build(instructions.depends_on, force=force, quiet=quiet) if not force and self.is_installed(instructions.name): return if not quiet: logger.info("building image: %s", name) context = instructions.abs_context tf = os.path.join(context, '.Dockerfile') try: success = False shutil.copy(instructions.filename_abs, tf) response = self.__docker.api.build(path=context, dockerfile='.Dockerfile', tag=name, # pull=force, buildargs=instructions.arguments, decode=True, rm=True) log = [] # type: List[str] for line in response: if 'stream' in line: line_msg = line['stream'].rstrip() log.append(line_msg) if not quiet: print(line_msg) if line_msg.startswith('Successfully built'): success = True if not success: raise ImageBuildFailed(name, log) if success and not quiet: logger.info("built image: %s", name) return finally: if os.path.exists(tf): os.remove(tf)
python
def build(self, name: str, force: bool = False, quiet: bool = False ) -> None: """ Constructs a Docker image, given by its name, using the set of build instructions associated with that image. Parameters: name: the name of the Docker image. force: if `True`, the image will be rebuilt, regardless of whether or not it is already installed on the server. If `False` and a (possibly outdated) version of the image has already been built, then the build will be skipped. quiet: used to enable and disable output from the Docker build process. """ logger.debug("request to build image: %s", name) instructions = self[name] if instructions.depends_on: logger.info("building dependent image: %s", instructions.depends_on) self.build(instructions.depends_on, force=force, quiet=quiet) if not force and self.is_installed(instructions.name): return if not quiet: logger.info("building image: %s", name) context = instructions.abs_context tf = os.path.join(context, '.Dockerfile') try: success = False shutil.copy(instructions.filename_abs, tf) response = self.__docker.api.build(path=context, dockerfile='.Dockerfile', tag=name, # pull=force, buildargs=instructions.arguments, decode=True, rm=True) log = [] # type: List[str] for line in response: if 'stream' in line: line_msg = line['stream'].rstrip() log.append(line_msg) if not quiet: print(line_msg) if line_msg.startswith('Successfully built'): success = True if not success: raise ImageBuildFailed(name, log) if success and not quiet: logger.info("built image: %s", name) return finally: if os.path.exists(tf): os.remove(tf)
[ "def", "build", "(", "self", ",", "name", ":", "str", ",", "force", ":", "bool", "=", "False", ",", "quiet", ":", "bool", "=", "False", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"request to build image: %s\"", ",", "name", ")", "instructio...
Constructs a Docker image, given by its name, using the set of build instructions associated with that image. Parameters: name: the name of the Docker image. force: if `True`, the image will be rebuilt, regardless of whether or not it is already installed on the server. If `False` and a (possibly outdated) version of the image has already been built, then the build will be skipped. quiet: used to enable and disable output from the Docker build process.
[ "Constructs", "a", "Docker", "image", "given", "by", "its", "name", "using", "the", "set", "of", "build", "instructions", "associated", "with", "that", "image", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/build.py#L75-L138
train
30,117
squaresLab/BugZoo
bugzoo/mgr/build.py
BuildManager.uninstall
def uninstall(self, name: str, force: bool = False, noprune: bool = False ) -> None: """ Attempts to uninstall a given Docker image. Parameters: name: the name of the Docker image. force: a flag indicating whether or not an exception should be thrown if the image associated with the given build instructions is not installed. If `True`, no exception will be thrown; if `False`, exception will be thrown. noprune: a flag indicating whether or not dangling image layers should also be removed. Raises: docker.errors.ImageNotFound: if the image associated with the given instructions can't be found. """ try: self.__docker.images.remove(image=name, force=force, noprune=noprune) except docker.errors.ImageNotFound as e: if force: return raise e
python
def uninstall(self, name: str, force: bool = False, noprune: bool = False ) -> None: """ Attempts to uninstall a given Docker image. Parameters: name: the name of the Docker image. force: a flag indicating whether or not an exception should be thrown if the image associated with the given build instructions is not installed. If `True`, no exception will be thrown; if `False`, exception will be thrown. noprune: a flag indicating whether or not dangling image layers should also be removed. Raises: docker.errors.ImageNotFound: if the image associated with the given instructions can't be found. """ try: self.__docker.images.remove(image=name, force=force, noprune=noprune) except docker.errors.ImageNotFound as e: if force: return raise e
[ "def", "uninstall", "(", "self", ",", "name", ":", "str", ",", "force", ":", "bool", "=", "False", ",", "noprune", ":", "bool", "=", "False", ")", "->", "None", ":", "try", ":", "self", ".", "__docker", ".", "images", ".", "remove", "(", "image", ...
Attempts to uninstall a given Docker image. Parameters: name: the name of the Docker image. force: a flag indicating whether or not an exception should be thrown if the image associated with the given build instructions is not installed. If `True`, no exception will be thrown; if `False`, exception will be thrown. noprune: a flag indicating whether or not dangling image layers should also be removed. Raises: docker.errors.ImageNotFound: if the image associated with the given instructions can't be found.
[ "Attempts", "to", "uninstall", "a", "given", "Docker", "image", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/build.py#L140-L168
train
30,118
squaresLab/BugZoo
bugzoo/mgr/build.py
BuildManager.upload
def upload(self, name: str) -> bool: """ Attempts to upload a given Docker image from this server to DockerHub. Parameters: name: the name of the Docker image. Returns: `True` if successfully uploaded, otherwise `False`. """ try: out = self.__docker.images.push(name, stream=True) for line in out: line = line.strip().decode('utf-8') jsn = json.loads(line) if 'progress' in jsn: line = "{}. {}.".format(jsn['status'], jsn['progress']) print(line, end='\r') elif 'status' in jsn: print(jsn['status']) print('uploaded image to DockerHub: {}'.format(name)) return True except docker.errors.NotFound: print("Failed to push image ({}): not installed.".format(name)) return False
python
def upload(self, name: str) -> bool: """ Attempts to upload a given Docker image from this server to DockerHub. Parameters: name: the name of the Docker image. Returns: `True` if successfully uploaded, otherwise `False`. """ try: out = self.__docker.images.push(name, stream=True) for line in out: line = line.strip().decode('utf-8') jsn = json.loads(line) if 'progress' in jsn: line = "{}. {}.".format(jsn['status'], jsn['progress']) print(line, end='\r') elif 'status' in jsn: print(jsn['status']) print('uploaded image to DockerHub: {}'.format(name)) return True except docker.errors.NotFound: print("Failed to push image ({}): not installed.".format(name)) return False
[ "def", "upload", "(", "self", ",", "name", ":", "str", ")", "->", "bool", ":", "try", ":", "out", "=", "self", ".", "__docker", ".", "images", ".", "push", "(", "name", ",", "stream", "=", "True", ")", "for", "line", "in", "out", ":", "line", "...
Attempts to upload a given Docker image from this server to DockerHub. Parameters: name: the name of the Docker image. Returns: `True` if successfully uploaded, otherwise `False`.
[ "Attempts", "to", "upload", "a", "given", "Docker", "image", "from", "this", "server", "to", "DockerHub", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/build.py#L192-L216
train
30,119
squaresLab/BugZoo
bugzoo/util.py
printflush
def printflush(s: str, end: str = '\n') -> None: """ Prints a given string to the standard output and immediately flushes. """ print(s, end=end) sys.stdout.flush()
python
def printflush(s: str, end: str = '\n') -> None: """ Prints a given string to the standard output and immediately flushes. """ print(s, end=end) sys.stdout.flush()
[ "def", "printflush", "(", "s", ":", "str", ",", "end", ":", "str", "=", "'\\n'", ")", "->", "None", ":", "print", "(", "s", ",", "end", "=", "end", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Prints a given string to the standard output and immediately flushes.
[ "Prints", "a", "given", "string", "to", "the", "standard", "output", "and", "immediately", "flushes", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/util.py#L8-L13
train
30,120
squaresLab/BugZoo
bugzoo/core/coverage.py
CoverageInstructions.from_dict
def from_dict(d: Dict[str, Any]) -> 'CoverageInstructions': """ Loads a set of coverage instructions from a given dictionary. Raises: BadCoverageInstructions: if the given coverage instructions are illegal. """ name_type = d['type'] cls = _NAME_TO_INSTRUCTIONS[name_type] return cls.from_dict(d)
python
def from_dict(d: Dict[str, Any]) -> 'CoverageInstructions': """ Loads a set of coverage instructions from a given dictionary. Raises: BadCoverageInstructions: if the given coverage instructions are illegal. """ name_type = d['type'] cls = _NAME_TO_INSTRUCTIONS[name_type] return cls.from_dict(d)
[ "def", "from_dict", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "'CoverageInstructions'", ":", "name_type", "=", "d", "[", "'type'", "]", "cls", "=", "_NAME_TO_INSTRUCTIONS", "[", "name_type", "]", "return", "cls", ".", "from_dict", "(...
Loads a set of coverage instructions from a given dictionary. Raises: BadCoverageInstructions: if the given coverage instructions are illegal.
[ "Loads", "a", "set", "of", "coverage", "instructions", "from", "a", "given", "dictionary", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/coverage.py#L93-L103
train
30,121
Geotab/mygeotab-python
mygeotab/serializers.py
object_deserializer
def object_deserializer(obj): """Helper to deserialize a raw result dict into a proper dict. :param obj: The dict. """ for key, val in obj.items(): if isinstance(val, six.string_types) and DATETIME_REGEX.search(val): try: obj[key] = dates.localize_datetime(parser.parse(val)) except ValueError: obj[key] = val return obj
python
def object_deserializer(obj): """Helper to deserialize a raw result dict into a proper dict. :param obj: The dict. """ for key, val in obj.items(): if isinstance(val, six.string_types) and DATETIME_REGEX.search(val): try: obj[key] = dates.localize_datetime(parser.parse(val)) except ValueError: obj[key] = val return obj
[ "def", "object_deserializer", "(", "obj", ")", ":", "for", "key", ",", "val", "in", "obj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "six", ".", "string_types", ")", "and", "DATETIME_REGEX", ".", "search", "(", "val", ")", ":"...
Helper to deserialize a raw result dict into a proper dict. :param obj: The dict.
[ "Helper", "to", "deserialize", "a", "raw", "result", "dict", "into", "a", "proper", "dict", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/serializers.py#L28-L39
train
30,122
Geotab/mygeotab-python
mygeotab/cli.py
login
def login(session, user, password, database=None, server=None): """Logs into a MyGeotab server and stores the returned credentials. :param session: The current Session object. :param user: The username used for MyGeotab servers. Usually an email address. :param password: The password associated with the username. Optional if `session_id` is provided. :param database: The database or company name. Optional as this usually gets resolved upon authentication. :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication. """ if not user: user = click.prompt("Username", type=str) if not password: password = click.prompt("Password", hide_input=True, type=str) try: with click.progressbar(length=1, label="Logging in...") as progressbar: session.login(user, password, database, server) progressbar.update(1) if session.credentials: click.echo('Logged in as: %s' % session.credentials) session.load(database) return session.get_api() except mygeotab.AuthenticationException: click.echo('Incorrect credentials. Please try again.') sys.exit(0)
python
def login(session, user, password, database=None, server=None): """Logs into a MyGeotab server and stores the returned credentials. :param session: The current Session object. :param user: The username used for MyGeotab servers. Usually an email address. :param password: The password associated with the username. Optional if `session_id` is provided. :param database: The database or company name. Optional as this usually gets resolved upon authentication. :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication. """ if not user: user = click.prompt("Username", type=str) if not password: password = click.prompt("Password", hide_input=True, type=str) try: with click.progressbar(length=1, label="Logging in...") as progressbar: session.login(user, password, database, server) progressbar.update(1) if session.credentials: click.echo('Logged in as: %s' % session.credentials) session.load(database) return session.get_api() except mygeotab.AuthenticationException: click.echo('Incorrect credentials. Please try again.') sys.exit(0)
[ "def", "login", "(", "session", ",", "user", ",", "password", ",", "database", "=", "None", ",", "server", "=", "None", ")", ":", "if", "not", "user", ":", "user", "=", "click", ".", "prompt", "(", "\"Username\"", ",", "type", "=", "str", ")", "if"...
Logs into a MyGeotab server and stores the returned credentials. :param session: The current Session object. :param user: The username used for MyGeotab servers. Usually an email address. :param password: The password associated with the username. Optional if `session_id` is provided. :param database: The database or company name. Optional as this usually gets resolved upon authentication. :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication.
[ "Logs", "into", "a", "MyGeotab", "server", "and", "stores", "the", "returned", "credentials", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/cli.py#L128-L151
train
30,123
Geotab/mygeotab-python
mygeotab/cli.py
sessions
def sessions(session): """Shows the current logged in sessions. :param session: The current Session object. """ active_sessions = session.get_sessions() if not active_sessions: click.echo('(No active sessions)') return for active_session in active_sessions: click.echo(active_session)
python
def sessions(session): """Shows the current logged in sessions. :param session: The current Session object. """ active_sessions = session.get_sessions() if not active_sessions: click.echo('(No active sessions)') return for active_session in active_sessions: click.echo(active_session)
[ "def", "sessions", "(", "session", ")", ":", "active_sessions", "=", "session", ".", "get_sessions", "(", ")", "if", "not", "active_sessions", ":", "click", ".", "echo", "(", "'(No active sessions)'", ")", "return", "for", "active_session", "in", "active_session...
Shows the current logged in sessions. :param session: The current Session object.
[ "Shows", "the", "current", "logged", "in", "sessions", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/cli.py#L156-L166
train
30,124
Geotab/mygeotab-python
mygeotab/cli.py
console
def console(session, database=None, user=None, password=None, server=None): """An interactive Python API console for MyGeotab If IPython is installed, it will launch an interactive IPython console instead of the built-in Python console. The IPython console has numerous advantages over the stock Python console, including: colors, pretty printing, command auto-completion, and more. By default, all library objects are available as locals in the script, with 'myg' being the active API object. :param session: The current Session object. :param database: The database name to open a console to. :param user: The username used for MyGeotab servers. Usually an email address. :param password: The password associated with the username. Optional if `session_id` is provided. :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication. """ local_vars = _populate_locals(database, password, server, session, user) version = 'MyGeotab Console {0} [Python {1}]'.format(mygeotab.__version__, sys.version.replace('\n', '')) auth_line = ('Logged in as: %s' % session.credentials) if session.credentials else 'Not logged in' banner = '\n'.join([version, auth_line]) try: from IPython import embed embed(banner1=banner, user_ns=local_vars) except ImportError: import code code.interact(banner, local=local_vars)
python
def console(session, database=None, user=None, password=None, server=None): """An interactive Python API console for MyGeotab If IPython is installed, it will launch an interactive IPython console instead of the built-in Python console. The IPython console has numerous advantages over the stock Python console, including: colors, pretty printing, command auto-completion, and more. By default, all library objects are available as locals in the script, with 'myg' being the active API object. :param session: The current Session object. :param database: The database name to open a console to. :param user: The username used for MyGeotab servers. Usually an email address. :param password: The password associated with the username. Optional if `session_id` is provided. :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication. """ local_vars = _populate_locals(database, password, server, session, user) version = 'MyGeotab Console {0} [Python {1}]'.format(mygeotab.__version__, sys.version.replace('\n', '')) auth_line = ('Logged in as: %s' % session.credentials) if session.credentials else 'Not logged in' banner = '\n'.join([version, auth_line]) try: from IPython import embed embed(banner1=banner, user_ns=local_vars) except ImportError: import code code.interact(banner, local=local_vars)
[ "def", "console", "(", "session", ",", "database", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "server", "=", "None", ")", ":", "local_vars", "=", "_populate_locals", "(", "database", ",", "password", ",", "server", ",", "...
An interactive Python API console for MyGeotab If IPython is installed, it will launch an interactive IPython console instead of the built-in Python console. The IPython console has numerous advantages over the stock Python console, including: colors, pretty printing, command auto-completion, and more. By default, all library objects are available as locals in the script, with 'myg' being the active API object. :param session: The current Session object. :param database: The database name to open a console to. :param user: The username used for MyGeotab servers. Usually an email address. :param password: The password associated with the username. Optional if `session_id` is provided. :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication.
[ "An", "interactive", "Python", "API", "console", "for", "MyGeotab" ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/cli.py#L188-L215
train
30,125
Geotab/mygeotab-python
mygeotab/py3/api_async.py
run
def run(*tasks: Awaitable, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()): """Helper to run tasks in the event loop :param tasks: Tasks to run in the event loop. :param loop: The event loop. """ futures = [asyncio.ensure_future(task, loop=loop) for task in tasks] return loop.run_until_complete(asyncio.gather(*futures))
python
def run(*tasks: Awaitable, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()): """Helper to run tasks in the event loop :param tasks: Tasks to run in the event loop. :param loop: The event loop. """ futures = [asyncio.ensure_future(task, loop=loop) for task in tasks] return loop.run_until_complete(asyncio.gather(*futures))
[ "def", "run", "(", "*", "tasks", ":", "Awaitable", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "asyncio", ".", "get_event_loop", "(", ")", ")", ":", "futures", "=", "[", "asyncio", ".", "ensure_future", "(", "task", ",", "loop", "=", "l...
Helper to run tasks in the event loop :param tasks: Tasks to run in the event loop. :param loop: The event loop.
[ "Helper", "to", "run", "tasks", "in", "the", "event", "loop" ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/py3/api_async.py#L157-L164
train
30,126
Geotab/mygeotab-python
mygeotab/py3/api_async.py
server_call_async
async def server_call_async(method, server, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop(), timeout=DEFAULT_TIMEOUT, verify_ssl=True, **parameters): """Makes an asynchronous call to an un-authenticated method on a server. :param method: The method name. :param server: The MyGeotab server. :param loop: The event loop. :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :param parameters: Additional parameters to send (for example, search=dict(id='b123') ). :return: The JSON result (decoded into a dict) from the server. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. """ if method is None: raise Exception("A method name must be specified") if server is None: raise Exception("A server (eg. my3.geotab.com) must be specified") parameters = api.process_parameters(parameters) return await _query(server, method, parameters, timeout=timeout, verify_ssl=verify_ssl, loop=loop)
python
async def server_call_async(method, server, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop(), timeout=DEFAULT_TIMEOUT, verify_ssl=True, **parameters): """Makes an asynchronous call to an un-authenticated method on a server. :param method: The method name. :param server: The MyGeotab server. :param loop: The event loop. :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :param parameters: Additional parameters to send (for example, search=dict(id='b123') ). :return: The JSON result (decoded into a dict) from the server. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. """ if method is None: raise Exception("A method name must be specified") if server is None: raise Exception("A server (eg. my3.geotab.com) must be specified") parameters = api.process_parameters(parameters) return await _query(server, method, parameters, timeout=timeout, verify_ssl=verify_ssl, loop=loop)
[ "async", "def", "server_call_async", "(", "method", ",", "server", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "asyncio", ".", "get_event_loop", "(", ")", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "verify_ssl", "=", "True", ",", "*", "*", ...
Makes an asynchronous call to an un-authenticated method on a server. :param method: The method name. :param server: The MyGeotab server. :param loop: The event loop. :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :param parameters: Additional parameters to send (for example, search=dict(id='b123') ). :return: The JSON result (decoded into a dict) from the server. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time.
[ "Makes", "an", "asynchronous", "call", "to", "an", "un", "-", "authenticated", "method", "on", "a", "server", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/py3/api_async.py#L167-L186
train
30,127
Geotab/mygeotab-python
mygeotab/py3/api_async.py
_query
async def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True, loop: asyncio.AbstractEventLoop=None): """Formats and performs the asynchronous query against the API :param server: The server to query. :param method: The method name. :param parameters: A dict of parameters to send :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :param verify_ssl: Whether or not to verify SSL connections :return: The JSON-decoded result from the server :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server :raise TimeoutException: Raises when the request does not respond after some time. :raise aiohttp.ClientResponseError: Raises when there is an HTTP status code that indicates failure. """ api_endpoint = api.get_api_url(server) params = dict(id=-1, method=method, params=parameters) headers = get_headers() ssl_context = None verify = verify_ssl if verify_ssl: ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) conn = aiohttp.TCPConnector(verify_ssl=verify, ssl_context=ssl_context, loop=loop) try: async with aiohttp.ClientSession(connector=conn, loop=loop) as session: response = await session.post(api_endpoint, data=json.dumps(params, default=object_serializer), headers=headers, timeout=timeout, allow_redirects=True) response.raise_for_status() content_type = response.headers.get('Content-Type') body = await response.text() except TimeoutError: raise TimeoutException(server) if content_type and 'application/json' not in content_type.lower(): return body return api._process(json.loads(body, object_hook=object_deserializer))
python
async def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True, loop: asyncio.AbstractEventLoop=None): """Formats and performs the asynchronous query against the API :param server: The server to query. :param method: The method name. :param parameters: A dict of parameters to send :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :param verify_ssl: Whether or not to verify SSL connections :return: The JSON-decoded result from the server :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server :raise TimeoutException: Raises when the request does not respond after some time. :raise aiohttp.ClientResponseError: Raises when there is an HTTP status code that indicates failure. """ api_endpoint = api.get_api_url(server) params = dict(id=-1, method=method, params=parameters) headers = get_headers() ssl_context = None verify = verify_ssl if verify_ssl: ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) conn = aiohttp.TCPConnector(verify_ssl=verify, ssl_context=ssl_context, loop=loop) try: async with aiohttp.ClientSession(connector=conn, loop=loop) as session: response = await session.post(api_endpoint, data=json.dumps(params, default=object_serializer), headers=headers, timeout=timeout, allow_redirects=True) response.raise_for_status() content_type = response.headers.get('Content-Type') body = await response.text() except TimeoutError: raise TimeoutException(server) if content_type and 'application/json' not in content_type.lower(): return body return api._process(json.loads(body, object_hook=object_deserializer))
[ "async", "def", "_query", "(", "server", ",", "method", ",", "parameters", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "verify_ssl", "=", "True", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ")", ":", "api_endpoint", "=", "api", "."...
Formats and performs the asynchronous query against the API :param server: The server to query. :param method: The method name. :param parameters: A dict of parameters to send :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :param verify_ssl: Whether or not to verify SSL connections :return: The JSON-decoded result from the server :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server :raise TimeoutException: Raises when the request does not respond after some time. :raise aiohttp.ClientResponseError: Raises when there is an HTTP status code that indicates failure.
[ "Formats", "and", "performs", "the", "asynchronous", "query", "against", "the", "API" ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/py3/api_async.py#L189-L226
train
30,128
Geotab/mygeotab-python
mygeotab/py3/api_async.py
API.call_async
async def call_async(self, method, **parameters): """Makes an async call to the API. :param method: The method name. :param params: Additional parameters to send (for example, search=dict(id='b123') ) :return: The JSON result (decoded into a dict) from the server.abs :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. """ if method is None: raise Exception('A method name must be specified') params = api.process_parameters(parameters) if self.credentials and not self.credentials.session_id: self.authenticate() if 'credentials' not in params and self.credentials.session_id: params['credentials'] = self.credentials.get_param() try: result = await _query(self._server, method, params, verify_ssl=self._is_verify_ssl, loop=self.loop) if result is not None: self.__reauthorize_count = 0 return result except MyGeotabException as exception: if exception.name == 'InvalidUserException': if self.__reauthorize_count == 0 and self.credentials.password: self.__reauthorize_count += 1 self.authenticate() return await self.call_async(method, **parameters) else: raise AuthenticationException(self.credentials.username, self.credentials.database, self.credentials.server) raise
python
async def call_async(self, method, **parameters): """Makes an async call to the API. :param method: The method name. :param params: Additional parameters to send (for example, search=dict(id='b123') ) :return: The JSON result (decoded into a dict) from the server.abs :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. """ if method is None: raise Exception('A method name must be specified') params = api.process_parameters(parameters) if self.credentials and not self.credentials.session_id: self.authenticate() if 'credentials' not in params and self.credentials.session_id: params['credentials'] = self.credentials.get_param() try: result = await _query(self._server, method, params, verify_ssl=self._is_verify_ssl, loop=self.loop) if result is not None: self.__reauthorize_count = 0 return result except MyGeotabException as exception: if exception.name == 'InvalidUserException': if self.__reauthorize_count == 0 and self.credentials.password: self.__reauthorize_count += 1 self.authenticate() return await self.call_async(method, **parameters) else: raise AuthenticationException(self.credentials.username, self.credentials.database, self.credentials.server) raise
[ "async", "def", "call_async", "(", "self", ",", "method", ",", "*", "*", "parameters", ")", ":", "if", "method", "is", "None", ":", "raise", "Exception", "(", "'A method name must be specified'", ")", "params", "=", "api", ".", "process_parameters", "(", "pa...
Makes an async call to the API. :param method: The method name. :param params: Additional parameters to send (for example, search=dict(id='b123') ) :return: The JSON result (decoded into a dict) from the server.abs :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time.
[ "Makes", "an", "async", "call", "to", "the", "API", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/py3/api_async.py#L49-L82
train
30,129
Geotab/mygeotab-python
mygeotab/py3/api_async.py
API.multi_call_async
async def multi_call_async(self, calls): """Performs an async multi-call to the API :param calls: A list of call 2-tuples with method name and params (for example, ('Get', dict(typeName='Trip')) ) :return: The JSON result (decoded into a dict) from the server :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server :raise TimeoutException: Raises when the request does not respond after some time. """ formatted_calls = [dict(method=call[0], params=call[1] if len(call) > 1 else {}) for call in calls] return await self.call_async('ExecuteMultiCall', calls=formatted_calls)
python
async def multi_call_async(self, calls): """Performs an async multi-call to the API :param calls: A list of call 2-tuples with method name and params (for example, ('Get', dict(typeName='Trip')) ) :return: The JSON result (decoded into a dict) from the server :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server :raise TimeoutException: Raises when the request does not respond after some time. """ formatted_calls = [dict(method=call[0], params=call[1] if len(call) > 1 else {}) for call in calls] return await self.call_async('ExecuteMultiCall', calls=formatted_calls)
[ "async", "def", "multi_call_async", "(", "self", ",", "calls", ")", ":", "formatted_calls", "=", "[", "dict", "(", "method", "=", "call", "[", "0", "]", ",", "params", "=", "call", "[", "1", "]", "if", "len", "(", "call", ")", ">", "1", "else", "...
Performs an async multi-call to the API :param calls: A list of call 2-tuples with method name and params (for example, ('Get', dict(typeName='Trip')) ) :return: The JSON result (decoded into a dict) from the server :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server :raise TimeoutException: Raises when the request does not respond after some time.
[ "Performs", "an", "async", "multi", "-", "call", "to", "the", "API" ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/py3/api_async.py#L84-L93
train
30,130
Geotab/mygeotab-python
mygeotab/py3/api_async.py
API.from_credentials
def from_credentials(credentials, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()): """Returns a new async API object from an existing Credentials object. :param credentials: The existing saved credentials. :param loop: The asyncio loop. :return: A new API object populated with MyGeotab credentials. """ return API(username=credentials.username, password=credentials.password, database=credentials.database, session_id=credentials.session_id, server=credentials.server, loop=loop)
python
def from_credentials(credentials, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()): """Returns a new async API object from an existing Credentials object. :param credentials: The existing saved credentials. :param loop: The asyncio loop. :return: A new API object populated with MyGeotab credentials. """ return API(username=credentials.username, password=credentials.password, database=credentials.database, session_id=credentials.session_id, server=credentials.server, loop=loop)
[ "def", "from_credentials", "(", "credentials", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "asyncio", ".", "get_event_loop", "(", ")", ")", ":", "return", "API", "(", "username", "=", "credentials", ".", "username", ",", "password", "=", "cre...
Returns a new async API object from an existing Credentials object. :param credentials: The existing saved credentials. :param loop: The asyncio loop. :return: A new API object populated with MyGeotab credentials.
[ "Returns", "a", "new", "async", "API", "object", "from", "an", "existing", "Credentials", "object", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/py3/api_async.py#L145-L154
train
30,131
Geotab/mygeotab-python
mygeotab/dates.py
format_iso_datetime
def format_iso_datetime(datetime_obj): """Formats the given datetime as a UTC-zoned ISO 8601 date string. :param datetime_obj: The datetime object. :type datetime_obj: datetime :return: The datetime object in 8601 string form. :rtype: datetime """ datetime_obj = localize_datetime(datetime_obj, pytz.utc) if datetime_obj < MIN_DATE: datetime_obj = MIN_DATE elif datetime_obj > MAX_DATE: datetime_obj = MAX_DATE return datetime_obj.replace(tzinfo=None).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
python
def format_iso_datetime(datetime_obj): """Formats the given datetime as a UTC-zoned ISO 8601 date string. :param datetime_obj: The datetime object. :type datetime_obj: datetime :return: The datetime object in 8601 string form. :rtype: datetime """ datetime_obj = localize_datetime(datetime_obj, pytz.utc) if datetime_obj < MIN_DATE: datetime_obj = MIN_DATE elif datetime_obj > MAX_DATE: datetime_obj = MAX_DATE return datetime_obj.replace(tzinfo=None).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
[ "def", "format_iso_datetime", "(", "datetime_obj", ")", ":", "datetime_obj", "=", "localize_datetime", "(", "datetime_obj", ",", "pytz", ".", "utc", ")", "if", "datetime_obj", "<", "MIN_DATE", ":", "datetime_obj", "=", "MIN_DATE", "elif", "datetime_obj", ">", "M...
Formats the given datetime as a UTC-zoned ISO 8601 date string. :param datetime_obj: The datetime object. :type datetime_obj: datetime :return: The datetime object in 8601 string form. :rtype: datetime
[ "Formats", "the", "given", "datetime", "as", "a", "UTC", "-", "zoned", "ISO", "8601", "date", "string", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/dates.py#L18-L31
train
30,132
Geotab/mygeotab-python
mygeotab/dates.py
localize_datetime
def localize_datetime(datetime_obj, tz=pytz.utc): """Converts a naive or UTC-localized date into the provided timezone. :param datetime_obj: The datetime object. :type datetime_obj: datetime :param tz: The timezone. If blank or None, UTC is used. :type tz: datetime.tzinfo :return: The localized datetime object. :rtype: datetime """ if not datetime_obj.tzinfo: return tz.localize(datetime_obj) else: try: return datetime_obj.astimezone(tz) except OverflowError: if datetime_obj < datetime(2, 1, 1, tzinfo=pytz.utc): return MIN_DATE.astimezone(tz) return MAX_DATE.astimezone(tz)
python
def localize_datetime(datetime_obj, tz=pytz.utc): """Converts a naive or UTC-localized date into the provided timezone. :param datetime_obj: The datetime object. :type datetime_obj: datetime :param tz: The timezone. If blank or None, UTC is used. :type tz: datetime.tzinfo :return: The localized datetime object. :rtype: datetime """ if not datetime_obj.tzinfo: return tz.localize(datetime_obj) else: try: return datetime_obj.astimezone(tz) except OverflowError: if datetime_obj < datetime(2, 1, 1, tzinfo=pytz.utc): return MIN_DATE.astimezone(tz) return MAX_DATE.astimezone(tz)
[ "def", "localize_datetime", "(", "datetime_obj", ",", "tz", "=", "pytz", ".", "utc", ")", ":", "if", "not", "datetime_obj", ".", "tzinfo", ":", "return", "tz", ".", "localize", "(", "datetime_obj", ")", "else", ":", "try", ":", "return", "datetime_obj", ...
Converts a naive or UTC-localized date into the provided timezone. :param datetime_obj: The datetime object. :type datetime_obj: datetime :param tz: The timezone. If blank or None, UTC is used. :type tz: datetime.tzinfo :return: The localized datetime object. :rtype: datetime
[ "Converts", "a", "naive", "or", "UTC", "-", "localized", "date", "into", "the", "provided", "timezone", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/dates.py#L34-L52
train
30,133
Geotab/mygeotab-python
mygeotab/ext/feed.py
DataFeed._run
def _run(self): """Runner for the Data Feed. """ while self.running: try: result = self.client_api.call('GetFeed', type_name=self.type_name, search=self.search, from_version=self._version, results_limit=self.results_limit) self._version = result['toVersion'] self.listener.on_data(result['data']) except api.MyGeotabException as exception: if self.listener.on_error(exception) is False: break if not self.running: break sleep(self.interval) self.running = False
python
def _run(self): """Runner for the Data Feed. """ while self.running: try: result = self.client_api.call('GetFeed', type_name=self.type_name, search=self.search, from_version=self._version, results_limit=self.results_limit) self._version = result['toVersion'] self.listener.on_data(result['data']) except api.MyGeotabException as exception: if self.listener.on_error(exception) is False: break if not self.running: break sleep(self.interval) self.running = False
[ "def", "_run", "(", "self", ")", ":", "while", "self", ".", "running", ":", "try", ":", "result", "=", "self", ".", "client_api", ".", "call", "(", "'GetFeed'", ",", "type_name", "=", "self", ".", "type_name", ",", "search", "=", "self", ".", "search...
Runner for the Data Feed.
[ "Runner", "for", "the", "Data", "Feed", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/ext/feed.py#L67-L82
train
30,134
Geotab/mygeotab-python
mygeotab/ext/feed.py
DataFeed.start
def start(self, threaded=True): """Start the data feed. :param threaded: If True, run in a separate thread. """ self.running = True if threaded: self._thread = Thread(target=self._run) self._thread.start() else: self._run()
python
def start(self, threaded=True): """Start the data feed. :param threaded: If True, run in a separate thread. """ self.running = True if threaded: self._thread = Thread(target=self._run) self._thread.start() else: self._run()
[ "def", "start", "(", "self", ",", "threaded", "=", "True", ")", ":", "self", ".", "running", "=", "True", "if", "threaded", ":", "self", ".", "_thread", "=", "Thread", "(", "target", "=", "self", ".", "_run", ")", "self", ".", "_thread", ".", "star...
Start the data feed. :param threaded: If True, run in a separate thread.
[ "Start", "the", "data", "feed", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/ext/feed.py#L84-L94
train
30,135
Geotab/mygeotab-python
mygeotab/api.py
_query
def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True): """Formats and performs the query against the API. :param server: The MyGeotab server. :type server: str :param method: The method name. :type method: str :param parameters: The parameters to send with the query. :type parameters: dict :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :type timeout: float :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :type verify_ssl: bool :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :raise urllib2.HTTPError: Raises when there is an HTTP status code that indicates failure. :return: The JSON-decoded result from the server. """ api_endpoint = get_api_url(server) params = dict(id=-1, method=method, params=parameters or {}) headers = get_headers() with requests.Session() as session: session.mount('https://', GeotabHTTPAdapter()) try: response = session.post(api_endpoint, data=json.dumps(params, default=object_serializer), headers=headers, allow_redirects=True, timeout=timeout, verify=verify_ssl) except Timeout: raise TimeoutException(server) response.raise_for_status() content_type = response.headers.get('Content-Type') if content_type and 'application/json' not in content_type.lower(): return response.text return _process(response.json(object_hook=object_deserializer))
python
def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True): """Formats and performs the query against the API. :param server: The MyGeotab server. :type server: str :param method: The method name. :type method: str :param parameters: The parameters to send with the query. :type parameters: dict :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :type timeout: float :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :type verify_ssl: bool :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :raise urllib2.HTTPError: Raises when there is an HTTP status code that indicates failure. :return: The JSON-decoded result from the server. """ api_endpoint = get_api_url(server) params = dict(id=-1, method=method, params=parameters or {}) headers = get_headers() with requests.Session() as session: session.mount('https://', GeotabHTTPAdapter()) try: response = session.post(api_endpoint, data=json.dumps(params, default=object_serializer), headers=headers, allow_redirects=True, timeout=timeout, verify=verify_ssl) except Timeout: raise TimeoutException(server) response.raise_for_status() content_type = response.headers.get('Content-Type') if content_type and 'application/json' not in content_type.lower(): return response.text return _process(response.json(object_hook=object_deserializer))
[ "def", "_query", "(", "server", ",", "method", ",", "parameters", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "verify_ssl", "=", "True", ")", ":", "api_endpoint", "=", "get_api_url", "(", "server", ")", "params", "=", "dict", "(", "id", "=", "-", "1", ...
Formats and performs the query against the API. :param server: The MyGeotab server. :type server: str :param method: The method name. :type method: str :param parameters: The parameters to send with the query. :type parameters: dict :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :type timeout: float :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :type verify_ssl: bool :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :raise urllib2.HTTPError: Raises when there is an HTTP status code that indicates failure. :return: The JSON-decoded result from the server.
[ "Formats", "and", "performs", "the", "query", "against", "the", "API", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L283-L318
train
30,136
Geotab/mygeotab-python
mygeotab/api.py
server_call
def server_call(method, server, timeout=DEFAULT_TIMEOUT, verify_ssl=True, **parameters): """Makes a call to an un-authenticated method on a server :param method: The method name. :type method: str :param server: The MyGeotab server. :type server: str :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :type timeout: float :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :type verify_ssl: bool :param parameters: Additional parameters to send (for example, search=dict(id='b123') ). :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The result from the server. """ if method is None: raise Exception("A method name must be specified") if server is None: raise Exception("A server (eg. my3.geotab.com) must be specified") parameters = process_parameters(parameters) return _query(server, method, parameters, timeout=timeout, verify_ssl=verify_ssl)
python
def server_call(method, server, timeout=DEFAULT_TIMEOUT, verify_ssl=True, **parameters): """Makes a call to an un-authenticated method on a server :param method: The method name. :type method: str :param server: The MyGeotab server. :type server: str :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :type timeout: float :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :type verify_ssl: bool :param parameters: Additional parameters to send (for example, search=dict(id='b123') ). :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The result from the server. """ if method is None: raise Exception("A method name must be specified") if server is None: raise Exception("A server (eg. my3.geotab.com) must be specified") parameters = process_parameters(parameters) return _query(server, method, parameters, timeout=timeout, verify_ssl=verify_ssl)
[ "def", "server_call", "(", "method", ",", "server", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "verify_ssl", "=", "True", ",", "*", "*", "parameters", ")", ":", "if", "method", "is", "None", ":", "raise", "Exception", "(", "\"A method name must be specified\...
Makes a call to an un-authenticated method on a server :param method: The method name. :type method: str :param server: The MyGeotab server. :type server: str :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :type timeout: float :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this. :type verify_ssl: bool :param parameters: Additional parameters to send (for example, search=dict(id='b123') ). :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The result from the server.
[ "Makes", "a", "call", "to", "an", "un", "-", "authenticated", "method", "on", "a", "server" ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L336-L357
train
30,137
Geotab/mygeotab-python
mygeotab/api.py
process_parameters
def process_parameters(parameters): """Allows the use of Pythonic-style parameters with underscores instead of camel-case. :param parameters: The parameters object. :type parameters: dict :return: The processed parameters. :rtype: dict """ if not parameters: return {} params = copy.copy(parameters) for param_name in parameters: value = parameters[param_name] server_param_name = re.sub(r'_(\w)', lambda m: m.group(1).upper(), param_name) if isinstance(value, dict): value = process_parameters(value) params[server_param_name] = value if server_param_name != param_name: del params[param_name] return params
python
def process_parameters(parameters): """Allows the use of Pythonic-style parameters with underscores instead of camel-case. :param parameters: The parameters object. :type parameters: dict :return: The processed parameters. :rtype: dict """ if not parameters: return {} params = copy.copy(parameters) for param_name in parameters: value = parameters[param_name] server_param_name = re.sub(r'_(\w)', lambda m: m.group(1).upper(), param_name) if isinstance(value, dict): value = process_parameters(value) params[server_param_name] = value if server_param_name != param_name: del params[param_name] return params
[ "def", "process_parameters", "(", "parameters", ")", ":", "if", "not", "parameters", ":", "return", "{", "}", "params", "=", "copy", ".", "copy", "(", "parameters", ")", "for", "param_name", "in", "parameters", ":", "value", "=", "parameters", "[", "param_...
Allows the use of Pythonic-style parameters with underscores instead of camel-case. :param parameters: The parameters object. :type parameters: dict :return: The processed parameters. :rtype: dict
[ "Allows", "the", "use", "of", "Pythonic", "-", "style", "parameters", "with", "underscores", "instead", "of", "camel", "-", "case", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L360-L379
train
30,138
Geotab/mygeotab-python
mygeotab/api.py
get_api_url
def get_api_url(server): """Formats the server URL properly in order to query the API. :return: A valid MyGeotab API request URL. :rtype: str """ parsed = urlparse(server) base_url = parsed.netloc if parsed.netloc else parsed.path base_url.replace('/', '') return 'https://' + base_url + '/apiv1'
python
def get_api_url(server): """Formats the server URL properly in order to query the API. :return: A valid MyGeotab API request URL. :rtype: str """ parsed = urlparse(server) base_url = parsed.netloc if parsed.netloc else parsed.path base_url.replace('/', '') return 'https://' + base_url + '/apiv1'
[ "def", "get_api_url", "(", "server", ")", ":", "parsed", "=", "urlparse", "(", "server", ")", "base_url", "=", "parsed", ".", "netloc", "if", "parsed", ".", "netloc", "else", "parsed", ".", "path", "base_url", ".", "replace", "(", "'/'", ",", "''", ")"...
Formats the server URL properly in order to query the API. :return: A valid MyGeotab API request URL. :rtype: str
[ "Formats", "the", "server", "URL", "properly", "in", "order", "to", "query", "the", "API", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L382-L391
train
30,139
Geotab/mygeotab-python
mygeotab/api.py
API.multi_call
def multi_call(self, calls): """Performs a multi-call to the API. :param calls: A list of call 2-tuples with method name and params (for example, ('Get', dict(typeName='Trip')) ). :type calls: list((str, dict)) :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The results from the server. :rtype: list """ formatted_calls = [dict(method=call[0], params=call[1] if len(call) > 1 else {}) for call in calls] return self.call('ExecuteMultiCall', calls=formatted_calls)
python
def multi_call(self, calls): """Performs a multi-call to the API. :param calls: A list of call 2-tuples with method name and params (for example, ('Get', dict(typeName='Trip')) ). :type calls: list((str, dict)) :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The results from the server. :rtype: list """ formatted_calls = [dict(method=call[0], params=call[1] if len(call) > 1 else {}) for call in calls] return self.call('ExecuteMultiCall', calls=formatted_calls)
[ "def", "multi_call", "(", "self", ",", "calls", ")", ":", "formatted_calls", "=", "[", "dict", "(", "method", "=", "call", "[", "0", "]", ",", "params", "=", "call", "[", "1", "]", "if", "len", "(", "call", ")", ">", "1", "else", "{", "}", ")",...
Performs a multi-call to the API. :param calls: A list of call 2-tuples with method name and params (for example, ('Get', dict(typeName='Trip')) ). :type calls: list((str, dict)) :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The results from the server. :rtype: list
[ "Performs", "a", "multi", "-", "call", "to", "the", "API", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L112-L124
train
30,140
Geotab/mygeotab-python
mygeotab/api.py
API.authenticate
def authenticate(self, is_global=True): """Authenticates against the API server. :param is_global: If True, authenticate globally. Local login if False. :raise AuthenticationException: Raises if there was an issue with authenticating or logging in. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: A Credentials object with a session ID created by the server. :rtype: Credentials """ auth_data = dict(database=self.credentials.database, userName=self.credentials.username, password=self.credentials.password) auth_data['global'] = is_global try: result = _query(self._server, 'Authenticate', auth_data, self.timeout, verify_ssl=self._is_verify_ssl) if result: new_server = result['path'] server = self.credentials.server if new_server != 'ThisServer': server = new_server credentials = result['credentials'] self.credentials = Credentials(credentials['userName'], credentials['sessionId'], credentials['database'], server) return self.credentials except MyGeotabException as exception: if exception.name == 'InvalidUserException': raise AuthenticationException(self.credentials.username, self.credentials.database, self.credentials.server) raise
python
def authenticate(self, is_global=True): """Authenticates against the API server. :param is_global: If True, authenticate globally. Local login if False. :raise AuthenticationException: Raises if there was an issue with authenticating or logging in. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: A Credentials object with a session ID created by the server. :rtype: Credentials """ auth_data = dict(database=self.credentials.database, userName=self.credentials.username, password=self.credentials.password) auth_data['global'] = is_global try: result = _query(self._server, 'Authenticate', auth_data, self.timeout, verify_ssl=self._is_verify_ssl) if result: new_server = result['path'] server = self.credentials.server if new_server != 'ThisServer': server = new_server credentials = result['credentials'] self.credentials = Credentials(credentials['userName'], credentials['sessionId'], credentials['database'], server) return self.credentials except MyGeotabException as exception: if exception.name == 'InvalidUserException': raise AuthenticationException(self.credentials.username, self.credentials.database, self.credentials.server) raise
[ "def", "authenticate", "(", "self", ",", "is_global", "=", "True", ")", ":", "auth_data", "=", "dict", "(", "database", "=", "self", ".", "credentials", ".", "database", ",", "userName", "=", "self", ".", "credentials", ".", "username", ",", "password", ...
Authenticates against the API server. :param is_global: If True, authenticate globally. Local login if False. :raise AuthenticationException: Raises if there was an issue with authenticating or logging in. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: A Credentials object with a session ID created by the server. :rtype: Credentials
[ "Authenticates", "against", "the", "API", "server", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L184-L214
train
30,141
Geotab/mygeotab-python
mygeotab/api.py
API.from_credentials
def from_credentials(credentials): """Returns a new API object from an existing Credentials object. :param credentials: The existing saved credentials. :type credentials: Credentials :return: A new API object populated with MyGeotab credentials. :rtype: API """ return API(username=credentials.username, password=credentials.password, database=credentials.database, session_id=credentials.session_id, server=credentials.server)
python
def from_credentials(credentials): """Returns a new API object from an existing Credentials object. :param credentials: The existing saved credentials. :type credentials: Credentials :return: A new API object populated with MyGeotab credentials. :rtype: API """ return API(username=credentials.username, password=credentials.password, database=credentials.database, session_id=credentials.session_id, server=credentials.server)
[ "def", "from_credentials", "(", "credentials", ")", ":", "return", "API", "(", "username", "=", "credentials", ".", "username", ",", "password", "=", "credentials", ".", "password", ",", "database", "=", "credentials", ".", "database", ",", "session_id", "=", ...
Returns a new API object from an existing Credentials object. :param credentials: The existing saved credentials. :type credentials: Credentials :return: A new API object populated with MyGeotab credentials. :rtype: API
[ "Returns", "a", "new", "API", "object", "from", "an", "existing", "Credentials", "object", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L217-L227
train
30,142
Geotab/mygeotab-python
examples/data_feed/feeder.py
ExceptionDataFeedListener._populate_sub_entity
def _populate_sub_entity(self, entity, type_name): """ Simple API-backed cache for populating MyGeotab entities :param entity: The entity to populate a sub-entity for :param type_name: The type of the sub-entity to populate """ key = type_name.lower() if isinstance(entity[key], str): # If the expected sub-entity is a string, it's a unknown ID entity[key] = dict(id=entity[key]) return cache = self._cache[key] subentity = cache.get(entity[key]['id']) if not subentity: subentities = self.api.get(type_name, id=entity[key]['id'], results_limit=1) if len(subentities) > 0: subentity = subentities[0] entity[key] = subentity else: entity[key] = subentity
python
def _populate_sub_entity(self, entity, type_name): """ Simple API-backed cache for populating MyGeotab entities :param entity: The entity to populate a sub-entity for :param type_name: The type of the sub-entity to populate """ key = type_name.lower() if isinstance(entity[key], str): # If the expected sub-entity is a string, it's a unknown ID entity[key] = dict(id=entity[key]) return cache = self._cache[key] subentity = cache.get(entity[key]['id']) if not subentity: subentities = self.api.get(type_name, id=entity[key]['id'], results_limit=1) if len(subentities) > 0: subentity = subentities[0] entity[key] = subentity else: entity[key] = subentity
[ "def", "_populate_sub_entity", "(", "self", ",", "entity", ",", "type_name", ")", ":", "key", "=", "type_name", ".", "lower", "(", ")", "if", "isinstance", "(", "entity", "[", "key", "]", ",", "str", ")", ":", "# If the expected sub-entity is a string, it's a ...
Simple API-backed cache for populating MyGeotab entities :param entity: The entity to populate a sub-entity for :param type_name: The type of the sub-entity to populate
[ "Simple", "API", "-", "backed", "cache", "for", "populating", "MyGeotab", "entities" ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/examples/data_feed/feeder.py#L22-L42
train
30,143
Geotab/mygeotab-python
examples/data_feed/feeder.py
ExceptionDataFeedListener.on_data
def on_data(self, data): """ The function called when new data has arrived. :param data: The list of data records received. """ for d in data: self._populate_sub_entity(d, 'Device') self._populate_sub_entity(d, 'Rule') date = dates.localize_datetime(d['activeFrom']) click.echo( '[{date}] {device} ({rule})'.format(date=date, device=d['device'].get('name', '**Unknown Vehicle'), rule=d['rule'].get('name', '**Unknown Rule')))
python
def on_data(self, data): """ The function called when new data has arrived. :param data: The list of data records received. """ for d in data: self._populate_sub_entity(d, 'Device') self._populate_sub_entity(d, 'Rule') date = dates.localize_datetime(d['activeFrom']) click.echo( '[{date}] {device} ({rule})'.format(date=date, device=d['device'].get('name', '**Unknown Vehicle'), rule=d['rule'].get('name', '**Unknown Rule')))
[ "def", "on_data", "(", "self", ",", "data", ")", ":", "for", "d", "in", "data", ":", "self", ".", "_populate_sub_entity", "(", "d", ",", "'Device'", ")", "self", ".", "_populate_sub_entity", "(", "d", ",", "'Rule'", ")", "date", "=", "dates", ".", "l...
The function called when new data has arrived. :param data: The list of data records received.
[ "The", "function", "called", "when", "new", "data", "has", "arrived", "." ]
baa678e7df90bdd15f5dc55c1374b5c048791a94
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/examples/data_feed/feeder.py#L44-L56
train
30,144
google/python_portpicker
src/portserver.py
_should_allocate_port
def _should_allocate_port(pid): """Determine if we should allocate a port for use by the given process id.""" if pid <= 0: log.info('Not allocating a port to invalid pid') return False if pid == 1: # The client probably meant to send us its parent pid but # had been reparented to init. log.info('Not allocating a port to init.') return False try: os.kill(pid, 0) except ProcessLookupError: log.info('Not allocating a port to a non-existent process') return False return True
python
def _should_allocate_port(pid): """Determine if we should allocate a port for use by the given process id.""" if pid <= 0: log.info('Not allocating a port to invalid pid') return False if pid == 1: # The client probably meant to send us its parent pid but # had been reparented to init. log.info('Not allocating a port to init.') return False try: os.kill(pid, 0) except ProcessLookupError: log.info('Not allocating a port to a non-existent process') return False return True
[ "def", "_should_allocate_port", "(", "pid", ")", ":", "if", "pid", "<=", "0", ":", "log", ".", "info", "(", "'Not allocating a port to invalid pid'", ")", "return", "False", "if", "pid", "==", "1", ":", "# The client probably meant to send us its parent pid but", "#...
Determine if we should allocate a port for use by the given process id.
[ "Determine", "if", "we", "should", "allocate", "a", "port", "for", "use", "by", "the", "given", "process", "id", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L108-L123
train
30,145
google/python_portpicker
src/portserver.py
_parse_command_line
def _parse_command_line(): """Configure and parse our command line flags.""" parser = argparse.ArgumentParser() parser.add_argument( '--portserver_static_pool', type=str, default='15000-24999', help='Comma separated N-P Range(s) of ports to manage (inclusive).') parser.add_argument( '--portserver_unix_socket_address', type=str, default='@unittest-portserver', help='Address of AF_UNIX socket on which to listen (first @ is a NUL).') parser.add_argument('--verbose', action='store_true', default=False, help='Enable verbose messages.') parser.add_argument('--debug', action='store_true', default=False, help='Enable full debug messages.') return parser.parse_args(sys.argv[1:])
python
def _parse_command_line(): """Configure and parse our command line flags.""" parser = argparse.ArgumentParser() parser.add_argument( '--portserver_static_pool', type=str, default='15000-24999', help='Comma separated N-P Range(s) of ports to manage (inclusive).') parser.add_argument( '--portserver_unix_socket_address', type=str, default='@unittest-portserver', help='Address of AF_UNIX socket on which to listen (first @ is a NUL).') parser.add_argument('--verbose', action='store_true', default=False, help='Enable verbose messages.') parser.add_argument('--debug', action='store_true', default=False, help='Enable full debug messages.') return parser.parse_args(sys.argv[1:])
[ "def", "_parse_command_line", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--portserver_static_pool'", ",", "type", "=", "str", ",", "default", "=", "'15000-24999'", ",", "help", "=", "'Comma ...
Configure and parse our command line flags.
[ "Configure", "and", "parse", "our", "command", "line", "flags", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L280-L301
train
30,146
google/python_portpicker
src/portserver.py
_parse_port_ranges
def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(','): try: a, b = range_str.split('-', 1) start, end = int(a), int(b) except ValueError: log.error('Ignoring unparsable port range %r.', range_str) continue if start < 1 or end > 65535: log.error('Ignoring out of bounds port range %r.', range_str) continue ports.update(set(range(start, end + 1))) return ports
python
def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(','): try: a, b = range_str.split('-', 1) start, end = int(a), int(b) except ValueError: log.error('Ignoring unparsable port range %r.', range_str) continue if start < 1 or end > 65535: log.error('Ignoring out of bounds port range %r.', range_str) continue ports.update(set(range(start, end + 1))) return ports
[ "def", "_parse_port_ranges", "(", "pool_str", ")", ":", "ports", "=", "set", "(", ")", "for", "range_str", "in", "pool_str", ".", "split", "(", "','", ")", ":", "try", ":", "a", ",", "b", "=", "range_str", ".", "split", "(", "'-'", ",", "1", ")", ...
Given a 'N-P,X-Y' description of port ranges, return a set of ints.
[ "Given", "a", "N", "-", "P", "X", "-", "Y", "description", "of", "port", "ranges", "return", "a", "set", "of", "ints", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L304-L318
train
30,147
google/python_portpicker
src/portserver.py
_configure_logging
def _configure_logging(verbose=False, debug=False): """Configure the log global, message format, and verbosity settings.""" overall_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format=('{levelname[0]}{asctime}.{msecs:03.0f} {thread} ' '{filename}:{lineno}] {message}'), datefmt='%m%d %H:%M:%S', style='{', level=overall_level) global log log = logging.getLogger('portserver') # The verbosity controls our loggers logging level, not the global # one above. This avoids debug messages from libraries such as asyncio. log.setLevel(logging.DEBUG if verbose else overall_level)
python
def _configure_logging(verbose=False, debug=False): """Configure the log global, message format, and verbosity settings.""" overall_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format=('{levelname[0]}{asctime}.{msecs:03.0f} {thread} ' '{filename}:{lineno}] {message}'), datefmt='%m%d %H:%M:%S', style='{', level=overall_level) global log log = logging.getLogger('portserver') # The verbosity controls our loggers logging level, not the global # one above. This avoids debug messages from libraries such as asyncio. log.setLevel(logging.DEBUG if verbose else overall_level)
[ "def", "_configure_logging", "(", "verbose", "=", "False", ",", "debug", "=", "False", ")", ":", "overall_level", "=", "logging", ".", "DEBUG", "if", "debug", "else", "logging", ".", "INFO", "logging", ".", "basicConfig", "(", "format", "=", "(", "'{leveln...
Configure the log global, message format, and verbosity settings.
[ "Configure", "the", "log", "global", "message", "format", "and", "verbosity", "settings", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L321-L334
train
30,148
google/python_portpicker
src/portserver.py
_PortPool.get_port_for_process
def get_port_for_process(self, pid): """Allocates and returns port for pid or 0 if none could be allocated.""" if not self._port_queue: raise RuntimeError('No ports being managed.') # Avoid an infinite loop if all ports are currently assigned. check_count = 0 max_ports_to_test = len(self._port_queue) while check_count < max_ports_to_test: # Get the next candidate port and move it to the back of the queue. candidate = self._port_queue.pop() self._port_queue.appendleft(candidate) check_count += 1 if (candidate.start_time == 0 or candidate.start_time != _get_process_start_time(candidate.pid)): if _is_port_free(candidate.port): candidate.pid = pid candidate.start_time = _get_process_start_time(pid) if not candidate.start_time: log.info("Can't read start time for pid %d.", pid) self.ports_checked_for_last_request = check_count return candidate.port else: log.info( 'Port %d unexpectedly in use, last owning pid %d.', candidate.port, candidate.pid) log.info('All ports in use.') self.ports_checked_for_last_request = check_count return 0
python
def get_port_for_process(self, pid): """Allocates and returns port for pid or 0 if none could be allocated.""" if not self._port_queue: raise RuntimeError('No ports being managed.') # Avoid an infinite loop if all ports are currently assigned. check_count = 0 max_ports_to_test = len(self._port_queue) while check_count < max_ports_to_test: # Get the next candidate port and move it to the back of the queue. candidate = self._port_queue.pop() self._port_queue.appendleft(candidate) check_count += 1 if (candidate.start_time == 0 or candidate.start_time != _get_process_start_time(candidate.pid)): if _is_port_free(candidate.port): candidate.pid = pid candidate.start_time = _get_process_start_time(pid) if not candidate.start_time: log.info("Can't read start time for pid %d.", pid) self.ports_checked_for_last_request = check_count return candidate.port else: log.info( 'Port %d unexpectedly in use, last owning pid %d.', candidate.port, candidate.pid) log.info('All ports in use.') self.ports_checked_for_last_request = check_count return 0
[ "def", "get_port_for_process", "(", "self", ",", "pid", ")", ":", "if", "not", "self", ".", "_port_queue", ":", "raise", "RuntimeError", "(", "'No ports being managed.'", ")", "# Avoid an infinite loop if all ports are currently assigned.", "check_count", "=", "0", "max...
Allocates and returns port for pid or 0 if none could be allocated.
[ "Allocates", "and", "returns", "port", "for", "pid", "or", "0", "if", "none", "could", "be", "allocated", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L168-L197
train
30,149
google/python_portpicker
src/portserver.py
_PortPool.add_port_to_free_pool
def add_port_to_free_pool(self, port): """Add a new port to the free pool for allocation.""" if port < 1 or port > 65535: raise ValueError( 'Port must be in the [1, 65535] range, not %d.' % port) port_info = _PortInfo(port=port) self._port_queue.append(port_info)
python
def add_port_to_free_pool(self, port): """Add a new port to the free pool for allocation.""" if port < 1 or port > 65535: raise ValueError( 'Port must be in the [1, 65535] range, not %d.' % port) port_info = _PortInfo(port=port) self._port_queue.append(port_info)
[ "def", "add_port_to_free_pool", "(", "self", ",", "port", ")", ":", "if", "port", "<", "1", "or", "port", ">", "65535", ":", "raise", "ValueError", "(", "'Port must be in the [1, 65535] range, not %d.'", "%", "port", ")", "port_info", "=", "_PortInfo", "(", "p...
Add a new port to the free pool for allocation.
[ "Add", "a", "new", "port", "to", "the", "free", "pool", "for", "allocation", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L199-L205
train
30,150
google/python_portpicker
src/portserver.py
_PortServerRequestHandler._handle_port_request
def _handle_port_request(self, client_data, writer): """Given a port request body, parse it and respond appropriately. Args: client_data: The request bytes from the client. writer: The asyncio Writer for the response to be written to. """ try: pid = int(client_data) except ValueError as error: self._client_request_errors += 1 log.warning('Could not parse request: %s', error) return log.info('Request on behalf of pid %d.', pid) log.info('cmdline: %s', _get_process_command_line(pid)) if not _should_allocate_port(pid): self._denied_allocations += 1 return port = self._port_pool.get_port_for_process(pid) if port > 0: self._total_allocations += 1 writer.write('{:d}\n'.format(port).encode('utf-8')) log.debug('Allocated port %d to pid %d', port, pid) else: self._denied_allocations += 1
python
def _handle_port_request(self, client_data, writer): """Given a port request body, parse it and respond appropriately. Args: client_data: The request bytes from the client. writer: The asyncio Writer for the response to be written to. """ try: pid = int(client_data) except ValueError as error: self._client_request_errors += 1 log.warning('Could not parse request: %s', error) return log.info('Request on behalf of pid %d.', pid) log.info('cmdline: %s', _get_process_command_line(pid)) if not _should_allocate_port(pid): self._denied_allocations += 1 return port = self._port_pool.get_port_for_process(pid) if port > 0: self._total_allocations += 1 writer.write('{:d}\n'.format(port).encode('utf-8')) log.debug('Allocated port %d to pid %d', port, pid) else: self._denied_allocations += 1
[ "def", "_handle_port_request", "(", "self", ",", "client_data", ",", "writer", ")", ":", "try", ":", "pid", "=", "int", "(", "client_data", ")", "except", "ValueError", "as", "error", ":", "self", ".", "_client_request_errors", "+=", "1", "log", ".", "warn...
Given a port request body, parse it and respond appropriately. Args: client_data: The request bytes from the client. writer: The asyncio Writer for the response to be written to.
[ "Given", "a", "port", "request", "body", "parse", "it", "and", "respond", "appropriately", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L236-L263
train
30,151
google/python_portpicker
src/portserver.py
_PortServerRequestHandler.dump_stats
def dump_stats(self): """Logs statistics of our operation.""" log.info('Dumping statistics:') stats = [] stats.append( 'client-request-errors {}'.format(self._client_request_errors)) stats.append('denied-allocations {}'.format(self._denied_allocations)) stats.append('num-ports-managed {}'.format(self._port_pool.num_ports())) stats.append('num-ports-checked-for-last-request {}'.format( self._port_pool.ports_checked_for_last_request)) stats.append('total-allocations {}'.format(self._total_allocations)) for stat in stats: log.info(stat)
python
def dump_stats(self): """Logs statistics of our operation.""" log.info('Dumping statistics:') stats = [] stats.append( 'client-request-errors {}'.format(self._client_request_errors)) stats.append('denied-allocations {}'.format(self._denied_allocations)) stats.append('num-ports-managed {}'.format(self._port_pool.num_ports())) stats.append('num-ports-checked-for-last-request {}'.format( self._port_pool.ports_checked_for_last_request)) stats.append('total-allocations {}'.format(self._total_allocations)) for stat in stats: log.info(stat)
[ "def", "dump_stats", "(", "self", ")", ":", "log", ".", "info", "(", "'Dumping statistics:'", ")", "stats", "=", "[", "]", "stats", ".", "append", "(", "'client-request-errors {}'", ".", "format", "(", "self", ".", "_client_request_errors", ")", ")", "stats"...
Logs statistics of our operation.
[ "Logs", "statistics", "of", "our", "operation", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portserver.py#L265-L277
train
30,152
google/python_portpicker
src/portpicker.py
return_port
def return_port(port): """Return a port that is no longer being used so it can be reused.""" if port in _random_ports: _random_ports.remove(port) elif port in _owned_ports: _owned_ports.remove(port) _free_ports.add(port) elif port in _free_ports: logging.info("Returning a port that was already returned: %s", port) else: logging.info("Returning a port that wasn't given by portpicker: %s", port)
python
def return_port(port): """Return a port that is no longer being used so it can be reused.""" if port in _random_ports: _random_ports.remove(port) elif port in _owned_ports: _owned_ports.remove(port) _free_ports.add(port) elif port in _free_ports: logging.info("Returning a port that was already returned: %s", port) else: logging.info("Returning a port that wasn't given by portpicker: %s", port)
[ "def", "return_port", "(", "port", ")", ":", "if", "port", "in", "_random_ports", ":", "_random_ports", ".", "remove", "(", "port", ")", "elif", "port", "in", "_owned_ports", ":", "_owned_ports", ".", "remove", "(", "port", ")", "_free_ports", ".", "add", ...
Return a port that is no longer being used so it can be reused.
[ "Return", "a", "port", "that", "is", "no", "longer", "being", "used", "so", "it", "can", "be", "reused", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portpicker.py#L74-L85
train
30,153
google/python_portpicker
src/portpicker.py
bind
def bind(port, socket_type, socket_proto): """Try to bind to a socket of the specified type, protocol, and port. This is primarily a helper function for PickUnusedPort, used to see if a particular port number is available. For the port to be considered available, the kernel must support at least one of (IPv6, IPv4), and the port must be available on each supported family. Args: port: The port number to bind to, or 0 to have the OS pick a free port. socket_type: The type of the socket (ex: socket.SOCK_STREAM). socket_proto: The protocol of the socket (ex: socket.IPPROTO_TCP). Returns: The port number on success or None on failure. """ got_socket = False for family in (socket.AF_INET6, socket.AF_INET): try: sock = socket.socket(family, socket_type, socket_proto) got_socket = True except socket.error: continue try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', port)) if socket_type == socket.SOCK_STREAM: sock.listen(1) port = sock.getsockname()[1] except socket.error: return None finally: sock.close() return port if got_socket else None
python
def bind(port, socket_type, socket_proto): """Try to bind to a socket of the specified type, protocol, and port. This is primarily a helper function for PickUnusedPort, used to see if a particular port number is available. For the port to be considered available, the kernel must support at least one of (IPv6, IPv4), and the port must be available on each supported family. Args: port: The port number to bind to, or 0 to have the OS pick a free port. socket_type: The type of the socket (ex: socket.SOCK_STREAM). socket_proto: The protocol of the socket (ex: socket.IPPROTO_TCP). Returns: The port number on success or None on failure. """ got_socket = False for family in (socket.AF_INET6, socket.AF_INET): try: sock = socket.socket(family, socket_type, socket_proto) got_socket = True except socket.error: continue try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', port)) if socket_type == socket.SOCK_STREAM: sock.listen(1) port = sock.getsockname()[1] except socket.error: return None finally: sock.close() return port if got_socket else None
[ "def", "bind", "(", "port", ",", "socket_type", ",", "socket_proto", ")", ":", "got_socket", "=", "False", "for", "family", "in", "(", "socket", ".", "AF_INET6", ",", "socket", ".", "AF_INET", ")", ":", "try", ":", "sock", "=", "socket", ".", "socket",...
Try to bind to a socket of the specified type, protocol, and port. This is primarily a helper function for PickUnusedPort, used to see if a particular port number is available. For the port to be considered available, the kernel must support at least one of (IPv6, IPv4), and the port must be available on each supported family. Args: port: The port number to bind to, or 0 to have the OS pick a free port. socket_type: The type of the socket (ex: socket.SOCK_STREAM). socket_proto: The protocol of the socket (ex: socket.IPPROTO_TCP). Returns: The port number on success or None on failure.
[ "Try", "to", "bind", "to", "a", "socket", "of", "the", "specified", "type", "protocol", "and", "port", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portpicker.py#L88-L123
train
30,154
google/python_portpicker
src/portpicker.py
pick_unused_port
def pick_unused_port(pid=None, portserver_address=None): """A pure python implementation of PickUnusedPort. Args: pid: PID to tell the portserver to associate the reservation with. If None, the current process's PID is used. portserver_address: The address (path) of a unix domain socket with which to connect to a portserver, a leading '@' character indicates an address in the "abstract namespace". OR On systems without socket.AF_UNIX, this is an AF_INET address. If None, or no port is returned by the portserver at the provided address, the environment will be checked for a PORTSERVER_ADDRESS variable. If that is not set, no port server will be used. Returns: A port number that is unused on both TCP and UDP. Raises: NoFreePortFoundError: No free port could be found. """ try: # Instead of `if _free_ports:` to handle the race condition. port = _free_ports.pop() except KeyError: pass else: _owned_ports.add(port) return port # Provide access to the portserver on an opt-in basis. if portserver_address: port = get_port_from_port_server(portserver_address, pid=pid) if port: return port if 'PORTSERVER_ADDRESS' in os.environ: port = get_port_from_port_server(os.environ['PORTSERVER_ADDRESS'], pid=pid) if port: return port return _pick_unused_port_without_server()
python
def pick_unused_port(pid=None, portserver_address=None): """A pure python implementation of PickUnusedPort. Args: pid: PID to tell the portserver to associate the reservation with. If None, the current process's PID is used. portserver_address: The address (path) of a unix domain socket with which to connect to a portserver, a leading '@' character indicates an address in the "abstract namespace". OR On systems without socket.AF_UNIX, this is an AF_INET address. If None, or no port is returned by the portserver at the provided address, the environment will be checked for a PORTSERVER_ADDRESS variable. If that is not set, no port server will be used. Returns: A port number that is unused on both TCP and UDP. Raises: NoFreePortFoundError: No free port could be found. """ try: # Instead of `if _free_ports:` to handle the race condition. port = _free_ports.pop() except KeyError: pass else: _owned_ports.add(port) return port # Provide access to the portserver on an opt-in basis. if portserver_address: port = get_port_from_port_server(portserver_address, pid=pid) if port: return port if 'PORTSERVER_ADDRESS' in os.environ: port = get_port_from_port_server(os.environ['PORTSERVER_ADDRESS'], pid=pid) if port: return port return _pick_unused_port_without_server()
[ "def", "pick_unused_port", "(", "pid", "=", "None", ",", "portserver_address", "=", "None", ")", ":", "try", ":", "# Instead of `if _free_ports:` to handle the race condition.", "port", "=", "_free_ports", ".", "pop", "(", ")", "except", "KeyError", ":", "pass", "...
A pure python implementation of PickUnusedPort. Args: pid: PID to tell the portserver to associate the reservation with. If None, the current process's PID is used. portserver_address: The address (path) of a unix domain socket with which to connect to a portserver, a leading '@' character indicates an address in the "abstract namespace". OR On systems without socket.AF_UNIX, this is an AF_INET address. If None, or no port is returned by the portserver at the provided address, the environment will be checked for a PORTSERVER_ADDRESS variable. If that is not set, no port server will be used. Returns: A port number that is unused on both TCP and UDP. Raises: NoFreePortFoundError: No free port could be found.
[ "A", "pure", "python", "implementation", "of", "PickUnusedPort", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portpicker.py#L141-L178
train
30,155
google/python_portpicker
src/portpicker.py
_pick_unused_port_without_server
def _pick_unused_port_without_server(): # Protected. pylint: disable=invalid-name """Pick an available network port without the help of a port server. This code ensures that the port is available on both TCP and UDP. This function is an implementation detail of PickUnusedPort(), and should not be called by code outside of this module. Returns: A port number that is unused on both TCP and UDP. Raises: NoFreePortFoundError: No free port could be found. """ # Try random ports first. rng = random.Random() for _ in range(10): port = int(rng.randrange(15000, 25000)) if is_port_free(port): _random_ports.add(port) return port # Next, try a few times to get an OS-assigned port. # Ambrose discovered that on the 2.6 kernel, calling Bind() on UDP socket # returns the same port over and over. So always try TCP first. for _ in range(10): # Ask the OS for an unused port. port = bind(0, _PROTOS[0][0], _PROTOS[0][1]) # Check if this port is unused on the other protocol. if port and bind(port, _PROTOS[1][0], _PROTOS[1][1]): _random_ports.add(port) return port # Give up. raise NoFreePortFoundError()
python
def _pick_unused_port_without_server(): # Protected. pylint: disable=invalid-name """Pick an available network port without the help of a port server. This code ensures that the port is available on both TCP and UDP. This function is an implementation detail of PickUnusedPort(), and should not be called by code outside of this module. Returns: A port number that is unused on both TCP and UDP. Raises: NoFreePortFoundError: No free port could be found. """ # Try random ports first. rng = random.Random() for _ in range(10): port = int(rng.randrange(15000, 25000)) if is_port_free(port): _random_ports.add(port) return port # Next, try a few times to get an OS-assigned port. # Ambrose discovered that on the 2.6 kernel, calling Bind() on UDP socket # returns the same port over and over. So always try TCP first. for _ in range(10): # Ask the OS for an unused port. port = bind(0, _PROTOS[0][0], _PROTOS[0][1]) # Check if this port is unused on the other protocol. if port and bind(port, _PROTOS[1][0], _PROTOS[1][1]): _random_ports.add(port) return port # Give up. raise NoFreePortFoundError()
[ "def", "_pick_unused_port_without_server", "(", ")", ":", "# Protected. pylint: disable=invalid-name", "# Try random ports first.", "rng", "=", "random", ".", "Random", "(", ")", "for", "_", "in", "range", "(", "10", ")", ":", "port", "=", "int", "(", "rng", "."...
Pick an available network port without the help of a port server. This code ensures that the port is available on both TCP and UDP. This function is an implementation detail of PickUnusedPort(), and should not be called by code outside of this module. Returns: A port number that is unused on both TCP and UDP. Raises: NoFreePortFoundError: No free port could be found.
[ "Pick", "an", "available", "network", "port", "without", "the", "help", "of", "a", "port", "server", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portpicker.py#L183-L217
train
30,156
google/python_portpicker
src/portpicker.py
get_port_from_port_server
def get_port_from_port_server(portserver_address, pid=None): """Request a free a port from a system-wide portserver. This follows a very simple portserver protocol: The request consists of our pid (in ASCII) followed by a newline. The response is a port number and a newline, 0 on failure. This function is an implementation detail of pick_unused_port(). It should not normally be called by code outside of this module. Args: portserver_address: The address (path) of a unix domain socket with which to connect to the portserver. A leading '@' character indicates an address in the "abstract namespace." On systems without socket.AF_UNIX, this is an AF_INET address. pid: The PID to tell the portserver to associate the reservation with. If None, the current process's PID is used. Returns: The port number on success or None on failure. """ if not portserver_address: return None # An AF_UNIX address may start with a zero byte, in which case it is in the # "abstract namespace", and doesn't have any filesystem representation. # See 'man 7 unix' for details. # The convention is to write '@' in the address to represent this zero byte. if portserver_address[0] == '@': portserver_address = '\0' + portserver_address[1:] if pid is None: pid = os.getpid() try: # Create socket. if hasattr(socket, 'AF_UNIX'): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) else: # fallback to AF_INET if this is not unix sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Connect to portserver. sock.connect(portserver_address) # Write request. sock.sendall(('%d\n' % pid).encode('ascii')) # Read response. # 1K should be ample buffer space. buf = sock.recv(1024) finally: sock.close() except socket.error as e: print('Socket error when connecting to portserver:', e, file=sys.stderr) return None try: port = int(buf.split(b'\n')[0]) except ValueError: print('Portserver failed to find a port.', file=sys.stderr) return None _owned_ports.add(port) return port
python
def get_port_from_port_server(portserver_address, pid=None): """Request a free a port from a system-wide portserver. This follows a very simple portserver protocol: The request consists of our pid (in ASCII) followed by a newline. The response is a port number and a newline, 0 on failure. This function is an implementation detail of pick_unused_port(). It should not normally be called by code outside of this module. Args: portserver_address: The address (path) of a unix domain socket with which to connect to the portserver. A leading '@' character indicates an address in the "abstract namespace." On systems without socket.AF_UNIX, this is an AF_INET address. pid: The PID to tell the portserver to associate the reservation with. If None, the current process's PID is used. Returns: The port number on success or None on failure. """ if not portserver_address: return None # An AF_UNIX address may start with a zero byte, in which case it is in the # "abstract namespace", and doesn't have any filesystem representation. # See 'man 7 unix' for details. # The convention is to write '@' in the address to represent this zero byte. if portserver_address[0] == '@': portserver_address = '\0' + portserver_address[1:] if pid is None: pid = os.getpid() try: # Create socket. if hasattr(socket, 'AF_UNIX'): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) else: # fallback to AF_INET if this is not unix sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Connect to portserver. sock.connect(portserver_address) # Write request. sock.sendall(('%d\n' % pid).encode('ascii')) # Read response. # 1K should be ample buffer space. buf = sock.recv(1024) finally: sock.close() except socket.error as e: print('Socket error when connecting to portserver:', e, file=sys.stderr) return None try: port = int(buf.split(b'\n')[0]) except ValueError: print('Portserver failed to find a port.', file=sys.stderr) return None _owned_ports.add(port) return port
[ "def", "get_port_from_port_server", "(", "portserver_address", ",", "pid", "=", "None", ")", ":", "if", "not", "portserver_address", ":", "return", "None", "# An AF_UNIX address may start with a zero byte, in which case it is in the", "# \"abstract namespace\", and doesn't have any...
Request a free a port from a system-wide portserver. This follows a very simple portserver protocol: The request consists of our pid (in ASCII) followed by a newline. The response is a port number and a newline, 0 on failure. This function is an implementation detail of pick_unused_port(). It should not normally be called by code outside of this module. Args: portserver_address: The address (path) of a unix domain socket with which to connect to the portserver. A leading '@' character indicates an address in the "abstract namespace." On systems without socket.AF_UNIX, this is an AF_INET address. pid: The PID to tell the portserver to associate the reservation with. If None, the current process's PID is used. Returns: The port number on success or None on failure.
[ "Request", "a", "free", "a", "port", "from", "a", "system", "-", "wide", "portserver", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portpicker.py#L220-L283
train
30,157
google/python_portpicker
src/portpicker.py
main
def main(argv): """If passed an arg, treat it as a PID, otherwise portpicker uses getpid.""" port = pick_unused_port(pid=int(argv[1]) if len(argv) > 1 else None) if not port: sys.exit(1) print(port)
python
def main(argv): """If passed an arg, treat it as a PID, otherwise portpicker uses getpid.""" port = pick_unused_port(pid=int(argv[1]) if len(argv) > 1 else None) if not port: sys.exit(1) print(port)
[ "def", "main", "(", "argv", ")", ":", "port", "=", "pick_unused_port", "(", "pid", "=", "int", "(", "argv", "[", "1", "]", ")", "if", "len", "(", "argv", ")", ">", "1", "else", "None", ")", "if", "not", "port", ":", "sys", ".", "exit", "(", "...
If passed an arg, treat it as a PID, otherwise portpicker uses getpid.
[ "If", "passed", "an", "arg", "treat", "it", "as", "a", "PID", "otherwise", "portpicker", "uses", "getpid", "." ]
f737189ea7a2d4b97048a2f4e37609e293b03546
https://github.com/google/python_portpicker/blob/f737189ea7a2d4b97048a2f4e37609e293b03546/src/portpicker.py#L289-L294
train
30,158
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.soap_request
def soap_request(self, url, urn, action, params, body_elem="m"): """Send a SOAP request to the TV.""" soap_body = ( '<?xml version="1.0" encoding="utf-8"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '<s:Body>' '<{body_elem}:{action} xmlns:{body_elem}="urn:{urn}">' '{params}' '</{body_elem}:{action}>' '</s:Body>' '</s:Envelope>' ).format(action=action, urn=urn, params=params, body_elem=body_elem).encode('utf-8') headers = { 'Host': '{}:{}'.format(self._host, self._port), 'Content-Length': len(soap_body), 'Content-Type': 'text/xml; charset=utf-8"', 'SOAPAction': '"urn:{}#{}"'.format(urn, action), } url = 'http://{}:{}/{}'.format(self._host, self._port, url) _LOGGER.debug("Sending to %s:\n%s\n%s", url, headers, soap_body) req = Request(url, soap_body, headers) res = urlopen(req, timeout=5).read() _LOGGER.debug("Response: %s", res) return res
python
def soap_request(self, url, urn, action, params, body_elem="m"): """Send a SOAP request to the TV.""" soap_body = ( '<?xml version="1.0" encoding="utf-8"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '<s:Body>' '<{body_elem}:{action} xmlns:{body_elem}="urn:{urn}">' '{params}' '</{body_elem}:{action}>' '</s:Body>' '</s:Envelope>' ).format(action=action, urn=urn, params=params, body_elem=body_elem).encode('utf-8') headers = { 'Host': '{}:{}'.format(self._host, self._port), 'Content-Length': len(soap_body), 'Content-Type': 'text/xml; charset=utf-8"', 'SOAPAction': '"urn:{}#{}"'.format(urn, action), } url = 'http://{}:{}/{}'.format(self._host, self._port, url) _LOGGER.debug("Sending to %s:\n%s\n%s", url, headers, soap_body) req = Request(url, soap_body, headers) res = urlopen(req, timeout=5).read() _LOGGER.debug("Response: %s", res) return res
[ "def", "soap_request", "(", "self", ",", "url", ",", "urn", ",", "action", ",", "params", ",", "body_elem", "=", "\"m\"", ")", ":", "soap_body", "=", "(", "'<?xml version=\"1.0\" encoding=\"utf-8\"?>'", "'<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"'"...
Send a SOAP request to the TV.
[ "Send", "a", "SOAP", "request", "to", "the", "TV", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L107-L135
train
30,159
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl._get_local_ip
def _get_local_ip(self): """Try to determine the local IP address of the machine.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Use Google Public DNS server to determine own IP sock.connect(('8.8.8.8', 80)) return sock.getsockname()[0] except socket.error: try: return socket.gethostbyname(socket.gethostname()) except socket.gaierror: return '127.0.0.1' finally: sock.close()
python
def _get_local_ip(self): """Try to determine the local IP address of the machine.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Use Google Public DNS server to determine own IP sock.connect(('8.8.8.8', 80)) return sock.getsockname()[0] except socket.error: try: return socket.gethostbyname(socket.gethostname()) except socket.gaierror: return '127.0.0.1' finally: sock.close()
[ "def", "_get_local_ip", "(", "self", ")", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "# Use Google Public DNS server to determine own IP", "sock", ".", "connect", "(", "(", "'8.8...
Try to determine the local IP address of the machine.
[ "Try", "to", "determine", "the", "local", "IP", "address", "of", "the", "machine", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L138-L153
train
30,160
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.open_webpage
def open_webpage(self, url): """Launch Web Browser and open url""" params = ('<X_AppType>vc_app</X_AppType>' '<X_LaunchKeyword>resource_id={resource_id}</X_LaunchKeyword>' ).format(resource_id=1063) res = self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_LaunchApp', params, body_elem="s") root = ET.fromstring(res) el_sessionId = root.find('.//X_SessionId') #setup a server socket where URL will be served server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) localip = self._get_local_ip() localport = random.randint(1025,65535) server_socket.bind((localip, localport)) server_socket.listen(1) _LOGGER.debug("Listening on {}:{}".format(localip,localport)) params = ('<X_AppType>vc_app</X_AppType>' '<X_SessionId>{sessionId}</X_SessionId>' '<X_ConnectKeyword>panasonic-viera 0.2</X_ConnectKeyword>' '<X_ConnectAddr>{localip}:{localport}</X_ConnectAddr>' ).format(sessionId=el_sessionId.text, localip=localip, localport=localport) res = self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_ConnectApp', params, body_elem="s") sockfd, addr = server_socket.accept() _LOGGER.debug("Client (%s, %s) connected" % addr) packet = bytearray([0xf4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, len(url)]) packet.extend(map(ord, url)) packet.append(0x00) sockfd.send(packet) sockfd.close() server_socket.close()
python
def open_webpage(self, url): """Launch Web Browser and open url""" params = ('<X_AppType>vc_app</X_AppType>' '<X_LaunchKeyword>resource_id={resource_id}</X_LaunchKeyword>' ).format(resource_id=1063) res = self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_LaunchApp', params, body_elem="s") root = ET.fromstring(res) el_sessionId = root.find('.//X_SessionId') #setup a server socket where URL will be served server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) localip = self._get_local_ip() localport = random.randint(1025,65535) server_socket.bind((localip, localport)) server_socket.listen(1) _LOGGER.debug("Listening on {}:{}".format(localip,localport)) params = ('<X_AppType>vc_app</X_AppType>' '<X_SessionId>{sessionId}</X_SessionId>' '<X_ConnectKeyword>panasonic-viera 0.2</X_ConnectKeyword>' '<X_ConnectAddr>{localip}:{localport}</X_ConnectAddr>' ).format(sessionId=el_sessionId.text, localip=localip, localport=localport) res = self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_ConnectApp', params, body_elem="s") sockfd, addr = server_socket.accept() _LOGGER.debug("Client (%s, %s) connected" % addr) packet = bytearray([0xf4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, len(url)]) packet.extend(map(ord, url)) packet.append(0x00) sockfd.send(packet) sockfd.close() server_socket.close()
[ "def", "open_webpage", "(", "self", ",", "url", ")", ":", "params", "=", "(", "'<X_AppType>vc_app</X_AppType>'", "'<X_LaunchKeyword>resource_id={resource_id}</X_LaunchKeyword>'", ")", ".", "format", "(", "resource_id", "=", "1063", ")", "res", "=", "self", ".", "soa...
Launch Web Browser and open url
[ "Launch", "Web", "Browser", "and", "open", "url" ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L155-L191
train
30,161
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.get_volume
def get_volume(self): """Return the current volume level.""" params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'GetVolume', params) root = ET.fromstring(res) el_volume = root.find('.//CurrentVolume') return int(el_volume.text)
python
def get_volume(self): """Return the current volume level.""" params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'GetVolume', params) root = ET.fromstring(res) el_volume = root.find('.//CurrentVolume') return int(el_volume.text)
[ "def", "get_volume", "(", "self", ")", ":", "params", "=", "'<InstanceID>0</InstanceID><Channel>Master</Channel>'", "res", "=", "self", ".", "soap_request", "(", "URL_CONTROL_DMR", ",", "URN_RENDERING_CONTROL", ",", "'GetVolume'", ",", "params", ")", "root", "=", "E...
Return the current volume level.
[ "Return", "the", "current", "volume", "level", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L193-L200
train
30,162
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.set_volume
def set_volume(self, volume): """Set a new volume level.""" if volume > 100 or volume < 0: raise Exception('Bad request to volume control. ' 'Must be between 0 and 100') params = ('<InstanceID>0</InstanceID><Channel>Master</Channel>' '<DesiredVolume>{}</DesiredVolume>').format(volume) self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'SetVolume', params)
python
def set_volume(self, volume): """Set a new volume level.""" if volume > 100 or volume < 0: raise Exception('Bad request to volume control. ' 'Must be between 0 and 100') params = ('<InstanceID>0</InstanceID><Channel>Master</Channel>' '<DesiredVolume>{}</DesiredVolume>').format(volume) self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'SetVolume', params)
[ "def", "set_volume", "(", "self", ",", "volume", ")", ":", "if", "volume", ">", "100", "or", "volume", "<", "0", ":", "raise", "Exception", "(", "'Bad request to volume control. '", "'Must be between 0 and 100'", ")", "params", "=", "(", "'<InstanceID>0</InstanceI...
Set a new volume level.
[ "Set", "a", "new", "volume", "level", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L202-L210
train
30,163
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.get_mute
def get_mute(self): """Return if the TV is muted.""" params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'GetMute', params) root = ET.fromstring(res) el_mute = root.find('.//CurrentMute') return el_mute.text != '0'
python
def get_mute(self): """Return if the TV is muted.""" params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'GetMute', params) root = ET.fromstring(res) el_mute = root.find('.//CurrentMute') return el_mute.text != '0'
[ "def", "get_mute", "(", "self", ")", ":", "params", "=", "'<InstanceID>0</InstanceID><Channel>Master</Channel>'", "res", "=", "self", ".", "soap_request", "(", "URL_CONTROL_DMR", ",", "URN_RENDERING_CONTROL", ",", "'GetMute'", ",", "params", ")", "root", "=", "ET", ...
Return if the TV is muted.
[ "Return", "if", "the", "TV", "is", "muted", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L212-L219
train
30,164
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.set_mute
def set_mute(self, enable): """Mute or unmute the TV.""" data = '1' if enable else '0' params = ('<InstanceID>0</InstanceID><Channel>Master</Channel>' '<DesiredMute>{}</DesiredMute>').format(data) self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'SetMute', params)
python
def set_mute(self, enable): """Mute or unmute the TV.""" data = '1' if enable else '0' params = ('<InstanceID>0</InstanceID><Channel>Master</Channel>' '<DesiredMute>{}</DesiredMute>').format(data) self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'SetMute', params)
[ "def", "set_mute", "(", "self", ",", "enable", ")", ":", "data", "=", "'1'", "if", "enable", "else", "'0'", "params", "=", "(", "'<InstanceID>0</InstanceID><Channel>Master</Channel>'", "'<DesiredMute>{}</DesiredMute>'", ")", ".", "format", "(", "data", ")", "self"...
Mute or unmute the TV.
[ "Mute", "or", "unmute", "the", "TV", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L221-L227
train
30,165
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.send_key
def send_key(self, key): """Send a key command to the TV.""" if isinstance(key, Keys): key = key.value params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key) self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_SendKey', params)
python
def send_key(self, key): """Send a key command to the TV.""" if isinstance(key, Keys): key = key.value params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key) self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_SendKey', params)
[ "def", "send_key", "(", "self", ",", "key", ")", ":", "if", "isinstance", "(", "key", ",", "Keys", ")", ":", "key", "=", "key", ".", "value", "params", "=", "'<X_KeyEvent>{}</X_KeyEvent>'", ".", "format", "(", "key", ")", "self", ".", "soap_request", "...
Send a key command to the TV.
[ "Send", "a", "key", "command", "to", "the", "TV", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L229-L235
train
30,166
florianholzapfel/panasonic-viera
panasonic_viera/__main__.py
main
def main(): """ Handle command line execution. """ parser = argparse.ArgumentParser(prog='panasonic_viera', description='Remote control a Panasonic Viera TV.') parser.add_argument('host', metavar='host', type=str, help='Address of the Panasonic Viera TV') parser.add_argument('port', metavar='port', type=int, nargs='?', default=panasonic_viera.DEFAULT_PORT, help='Port of the Panasonic Viera TV. Defaults to {}.'.format(panasonic_viera.DEFAULT_PORT)) parser.add_argument('--verbose', dest='verbose', action='store_const', const=True, default=False, help='debug output') args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) remote_control = RemoteControl(panasonic_viera.RemoteControl(args.host, args.port)) runner = CommandRunner() runner.command('open_webpage', remote_control.open_webpage) runner.command('get_volume', remote_control.get_volume) runner.command('set_volume', remote_control.set_volume) runner.command('get_mute', remote_control.get_mute) runner.command('set_mute', remote_control.set_mute) runner.command('turn_off', remote_control.turn_off) runner.command('volume_up', remote_control.volume_up) runner.command('volume_down', remote_control.volume_down) runner.command('mute_volume', remote_control.mute_volume) runner.command('turn_off', remote_control.turn_off) runner.command('turn_on', remote_control.turn_on) runner.command('send_key', remote_control.send_key) return Console(runner).run()
python
def main(): """ Handle command line execution. """ parser = argparse.ArgumentParser(prog='panasonic_viera', description='Remote control a Panasonic Viera TV.') parser.add_argument('host', metavar='host', type=str, help='Address of the Panasonic Viera TV') parser.add_argument('port', metavar='port', type=int, nargs='?', default=panasonic_viera.DEFAULT_PORT, help='Port of the Panasonic Viera TV. Defaults to {}.'.format(panasonic_viera.DEFAULT_PORT)) parser.add_argument('--verbose', dest='verbose', action='store_const', const=True, default=False, help='debug output') args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) remote_control = RemoteControl(panasonic_viera.RemoteControl(args.host, args.port)) runner = CommandRunner() runner.command('open_webpage', remote_control.open_webpage) runner.command('get_volume', remote_control.get_volume) runner.command('set_volume', remote_control.set_volume) runner.command('get_mute', remote_control.get_mute) runner.command('set_mute', remote_control.set_mute) runner.command('turn_off', remote_control.turn_off) runner.command('volume_up', remote_control.volume_up) runner.command('volume_down', remote_control.volume_down) runner.command('mute_volume', remote_control.mute_volume) runner.command('turn_off', remote_control.turn_off) runner.command('turn_on', remote_control.turn_on) runner.command('send_key', remote_control.send_key) return Console(runner).run()
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'panasonic_viera'", ",", "description", "=", "'Remote control a Panasonic Viera TV.'", ")", "parser", ".", "add_argument", "(", "'host'", ",", "metavar", "=", "'ho...
Handle command line execution.
[ "Handle", "command", "line", "execution", "." ]
bf912ff6eb03b59e3dde30b994a0fb1d883eb873
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__main__.py#L176-L207
train
30,167
georgebrock/1pass
onepassword/keychain.py
Keychain.item
def item(self, name, fuzzy_threshold=100): """ Extract a password from an unlocked Keychain using fuzzy matching. ``fuzzy_threshold`` can be an integer between 0 and 100, where 100 is an exact match. """ match = process.extractOne( name, self._items.keys(), score_cutoff=(fuzzy_threshold-1), ) if match: exact_name = match[0] item = self._items[exact_name] item.decrypt_with(self) return item else: return None
python
def item(self, name, fuzzy_threshold=100): """ Extract a password from an unlocked Keychain using fuzzy matching. ``fuzzy_threshold`` can be an integer between 0 and 100, where 100 is an exact match. """ match = process.extractOne( name, self._items.keys(), score_cutoff=(fuzzy_threshold-1), ) if match: exact_name = match[0] item = self._items[exact_name] item.decrypt_with(self) return item else: return None
[ "def", "item", "(", "self", ",", "name", ",", "fuzzy_threshold", "=", "100", ")", ":", "match", "=", "process", ".", "extractOne", "(", "name", ",", "self", ".", "_items", ".", "keys", "(", ")", ",", "score_cutoff", "=", "(", "fuzzy_threshold", "-", ...
Extract a password from an unlocked Keychain using fuzzy matching. ``fuzzy_threshold`` can be an integer between 0 and 100, where 100 is an exact match.
[ "Extract", "a", "password", "from", "an", "unlocked", "Keychain", "using", "fuzzy", "matching", ".", "fuzzy_threshold", "can", "be", "an", "integer", "between", "0", "and", "100", "where", "100", "is", "an", "exact", "match", "." ]
9cc68233970f5c725a30cef0f12a744fcef76d3a
https://github.com/georgebrock/1pass/blob/9cc68233970f5c725a30cef0f12a744fcef76d3a/onepassword/keychain.py#L25-L42
train
30,168
georgebrock/1pass
onepassword/keychain.py
Keychain.key
def key(self, identifier=None, security_level=None): """ Tries to find an encryption key, first using the ``identifier`` and if that fails or isn't provided using the ``security_level``. Returns ``None`` if nothing matches. """ if identifier: try: return self._encryption_keys[identifier] except KeyError: pass if security_level: for key in self._encryption_keys.values(): if key.level == security_level: return key
python
def key(self, identifier=None, security_level=None): """ Tries to find an encryption key, first using the ``identifier`` and if that fails or isn't provided using the ``security_level``. Returns ``None`` if nothing matches. """ if identifier: try: return self._encryption_keys[identifier] except KeyError: pass if security_level: for key in self._encryption_keys.values(): if key.level == security_level: return key
[ "def", "key", "(", "self", ",", "identifier", "=", "None", ",", "security_level", "=", "None", ")", ":", "if", "identifier", ":", "try", ":", "return", "self", ".", "_encryption_keys", "[", "identifier", "]", "except", "KeyError", ":", "pass", "if", "sec...
Tries to find an encryption key, first using the ``identifier`` and if that fails or isn't provided using the ``security_level``. Returns ``None`` if nothing matches.
[ "Tries", "to", "find", "an", "encryption", "key", "first", "using", "the", "identifier", "and", "if", "that", "fails", "or", "isn", "t", "provided", "using", "the", "security_level", ".", "Returns", "None", "if", "nothing", "matches", "." ]
9cc68233970f5c725a30cef0f12a744fcef76d3a
https://github.com/georgebrock/1pass/blob/9cc68233970f5c725a30cef0f12a744fcef76d3a/onepassword/keychain.py#L44-L58
train
30,169
georgebrock/1pass
onepassword/cli.py
CLI.run
def run(self): """ The main entry point, performs the appropriate action for the given arguments. """ self._unlock_keychain() item = self.keychain.item( self.arguments.item, fuzzy_threshold=self._fuzzy_threshold(), ) if item is not None: self.stdout.write("%s\n" % item.password) else: self.stderr.write("1pass: Could not find an item named '%s'\n" % ( self.arguments.item, )) sys.exit(os.EX_DATAERR)
python
def run(self): """ The main entry point, performs the appropriate action for the given arguments. """ self._unlock_keychain() item = self.keychain.item( self.arguments.item, fuzzy_threshold=self._fuzzy_threshold(), ) if item is not None: self.stdout.write("%s\n" % item.password) else: self.stderr.write("1pass: Could not find an item named '%s'\n" % ( self.arguments.item, )) sys.exit(os.EX_DATAERR)
[ "def", "run", "(", "self", ")", ":", "self", ".", "_unlock_keychain", "(", ")", "item", "=", "self", ".", "keychain", ".", "item", "(", "self", ".", "arguments", ".", "item", ",", "fuzzy_threshold", "=", "self", ".", "_fuzzy_threshold", "(", ")", ",", ...
The main entry point, performs the appropriate action for the given arguments.
[ "The", "main", "entry", "point", "performs", "the", "appropriate", "action", "for", "the", "given", "arguments", "." ]
9cc68233970f5c725a30cef0f12a744fcef76d3a
https://github.com/georgebrock/1pass/blob/9cc68233970f5c725a30cef0f12a744fcef76d3a/onepassword/cli.py#L24-L42
train
30,170
chriskuehl/identify
identify/identify.py
is_text
def is_text(bytesio): """Return whether the first KB of contents seems to be binary. This is roughly based on libmagic's binary/text detection: https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228 """ text_chars = ( bytearray([7, 8, 9, 10, 11, 12, 13, 27]) + bytearray(range(0x20, 0x7F)) + bytearray(range(0x80, 0X100)) ) return not bool(bytesio.read(1024).translate(None, text_chars))
python
def is_text(bytesio): """Return whether the first KB of contents seems to be binary. This is roughly based on libmagic's binary/text detection: https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228 """ text_chars = ( bytearray([7, 8, 9, 10, 11, 12, 13, 27]) + bytearray(range(0x20, 0x7F)) + bytearray(range(0x80, 0X100)) ) return not bool(bytesio.read(1024).translate(None, text_chars))
[ "def", "is_text", "(", "bytesio", ")", ":", "text_chars", "=", "(", "bytearray", "(", "[", "7", ",", "8", ",", "9", ",", "10", ",", "11", ",", "12", ",", "13", ",", "27", "]", ")", "+", "bytearray", "(", "range", "(", "0x20", ",", "0x7F", ")"...
Return whether the first KB of contents seems to be binary. This is roughly based on libmagic's binary/text detection: https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228
[ "Return", "whether", "the", "first", "KB", "of", "contents", "seems", "to", "be", "binary", "." ]
27ff23a3a5a08fb46e7eac79c393c1d678b4217a
https://github.com/chriskuehl/identify/blob/27ff23a3a5a08fb46e7eac79c393c1d678b4217a/identify/identify.py#L111-L122
train
30,171
chriskuehl/identify
identify/identify.py
parse_shebang
def parse_shebang(bytesio): """Parse the shebang from a file opened for reading binary.""" if bytesio.read(2) != b'#!': return () first_line = bytesio.readline() try: first_line = first_line.decode('UTF-8') except UnicodeDecodeError: return () # Require only printable ascii for c in first_line: if c not in printable: return () cmd = tuple(_shebang_split(first_line.strip())) if cmd[0] == '/usr/bin/env': cmd = cmd[1:] return cmd
python
def parse_shebang(bytesio): """Parse the shebang from a file opened for reading binary.""" if bytesio.read(2) != b'#!': return () first_line = bytesio.readline() try: first_line = first_line.decode('UTF-8') except UnicodeDecodeError: return () # Require only printable ascii for c in first_line: if c not in printable: return () cmd = tuple(_shebang_split(first_line.strip())) if cmd[0] == '/usr/bin/env': cmd = cmd[1:] return cmd
[ "def", "parse_shebang", "(", "bytesio", ")", ":", "if", "bytesio", ".", "read", "(", "2", ")", "!=", "b'#!'", ":", "return", "(", ")", "first_line", "=", "bytesio", ".", "readline", "(", ")", "try", ":", "first_line", "=", "first_line", ".", "decode", ...
Parse the shebang from a file opened for reading binary.
[ "Parse", "the", "shebang", "from", "a", "file", "opened", "for", "reading", "binary", "." ]
27ff23a3a5a08fb46e7eac79c393c1d678b4217a
https://github.com/chriskuehl/identify/blob/27ff23a3a5a08fb46e7eac79c393c1d678b4217a/identify/identify.py#L144-L162
train
30,172
chriskuehl/identify
identify/identify.py
parse_shebang_from_file
def parse_shebang_from_file(path): """Parse the shebang given a file path.""" if not os.path.lexists(path): raise ValueError('{} does not exist.'.format(path)) if not os.access(path, os.X_OK): return () with open(path, 'rb') as f: return parse_shebang(f)
python
def parse_shebang_from_file(path): """Parse the shebang given a file path.""" if not os.path.lexists(path): raise ValueError('{} does not exist.'.format(path)) if not os.access(path, os.X_OK): return () with open(path, 'rb') as f: return parse_shebang(f)
[ "def", "parse_shebang_from_file", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "lexists", "(", "path", ")", ":", "raise", "ValueError", "(", "'{} does not exist.'", ".", "format", "(", "path", ")", ")", "if", "not", "os", ".", "access", ...
Parse the shebang given a file path.
[ "Parse", "the", "shebang", "given", "a", "file", "path", "." ]
27ff23a3a5a08fb46e7eac79c393c1d678b4217a
https://github.com/chriskuehl/identify/blob/27ff23a3a5a08fb46e7eac79c393c1d678b4217a/identify/identify.py#L165-L173
train
30,173
chriskuehl/identify
identify/identify.py
license_id
def license_id(filename): """Return the spdx id for the license contained in `filename`. If no license is detected, returns `None`. spdx: https://spdx.org/licenses/ licenses from choosealicense.com: https://github.com/choosealicense.com Approximate algorithm: 1. strip copyright line 2. normalize whitespace (replace all whitespace with a single space) 3. check exact text match with existing licenses 4. failing that use edit distance """ import editdistance # `pip install identify[license]` with io.open(filename, encoding='UTF-8') as f: contents = f.read() norm = _norm_license(contents) min_edit_dist = sys.maxsize min_edit_dist_spdx = '' # try exact matches for spdx, text in licenses.LICENSES: norm_license = _norm_license(text) if norm == norm_license: return spdx # skip the slow calculation if the lengths are very different if norm and abs(len(norm) - len(norm_license)) / len(norm) > .05: continue edit_dist = editdistance.eval(norm, norm_license) if edit_dist < min_edit_dist: min_edit_dist = edit_dist min_edit_dist_spdx = spdx # if there's less than 5% edited from the license, we found our match if norm and min_edit_dist / len(norm) < .05: return min_edit_dist_spdx else: # no matches :'( return None
python
def license_id(filename): """Return the spdx id for the license contained in `filename`. If no license is detected, returns `None`. spdx: https://spdx.org/licenses/ licenses from choosealicense.com: https://github.com/choosealicense.com Approximate algorithm: 1. strip copyright line 2. normalize whitespace (replace all whitespace with a single space) 3. check exact text match with existing licenses 4. failing that use edit distance """ import editdistance # `pip install identify[license]` with io.open(filename, encoding='UTF-8') as f: contents = f.read() norm = _norm_license(contents) min_edit_dist = sys.maxsize min_edit_dist_spdx = '' # try exact matches for spdx, text in licenses.LICENSES: norm_license = _norm_license(text) if norm == norm_license: return spdx # skip the slow calculation if the lengths are very different if norm and abs(len(norm) - len(norm_license)) / len(norm) > .05: continue edit_dist = editdistance.eval(norm, norm_license) if edit_dist < min_edit_dist: min_edit_dist = edit_dist min_edit_dist_spdx = spdx # if there's less than 5% edited from the license, we found our match if norm and min_edit_dist / len(norm) < .05: return min_edit_dist_spdx else: # no matches :'( return None
[ "def", "license_id", "(", "filename", ")", ":", "import", "editdistance", "# `pip install identify[license]`", "with", "io", ".", "open", "(", "filename", ",", "encoding", "=", "'UTF-8'", ")", "as", "f", ":", "contents", "=", "f", ".", "read", "(", ")", "n...
Return the spdx id for the license contained in `filename`. If no license is detected, returns `None`. spdx: https://spdx.org/licenses/ licenses from choosealicense.com: https://github.com/choosealicense.com Approximate algorithm: 1. strip copyright line 2. normalize whitespace (replace all whitespace with a single space) 3. check exact text match with existing licenses 4. failing that use edit distance
[ "Return", "the", "spdx", "id", "for", "the", "license", "contained", "in", "filename", ".", "If", "no", "license", "is", "detected", "returns", "None", "." ]
27ff23a3a5a08fb46e7eac79c393c1d678b4217a
https://github.com/chriskuehl/identify/blob/27ff23a3a5a08fb46e7eac79c393c1d678b4217a/identify/identify.py#L186-L230
train
30,174
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.access_token
def access_token(self): """Get access_token.""" if self.cache_token: return self.access_token_ or \ self._resolve_credential('access_token') return self.access_token_
python
def access_token(self): """Get access_token.""" if self.cache_token: return self.access_token_ or \ self._resolve_credential('access_token') return self.access_token_
[ "def", "access_token", "(", "self", ")", ":", "if", "self", ".", "cache_token", ":", "return", "self", ".", "access_token_", "or", "self", ".", "_resolve_credential", "(", "'access_token'", ")", "return", "self", ".", "access_token_" ]
Get access_token.
[ "Get", "access_token", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L112-L117
train
30,175
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials._credentials_found_in_envars
def _credentials_found_in_envars(): """Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``. """ return any([os.getenv('PAN_ACCESS_TOKEN'), os.getenv('PAN_CLIENT_ID'), os.getenv('PAN_CLIENT_SECRET'), os.getenv('PAN_REFRESH_TOKEN')])
python
def _credentials_found_in_envars(): """Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``. """ return any([os.getenv('PAN_ACCESS_TOKEN'), os.getenv('PAN_CLIENT_ID'), os.getenv('PAN_CLIENT_SECRET'), os.getenv('PAN_REFRESH_TOKEN')])
[ "def", "_credentials_found_in_envars", "(", ")", ":", "return", "any", "(", "[", "os", ".", "getenv", "(", "'PAN_ACCESS_TOKEN'", ")", ",", "os", ".", "getenv", "(", "'PAN_CLIENT_ID'", ")", ",", "os", ".", "getenv", "(", "'PAN_CLIENT_SECRET'", ")", ",", "os...
Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``.
[ "Check", "for", "credentials", "in", "envars", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L183-L193
train
30,176
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials._resolve_credential
def _resolve_credential(self, credential): """Resolve credential from envars or credentials store. Args: credential (str): Credential to resolve. Returns: str or None: Resolved credential or ``None``. """ if self._credentials_found_in_instance: return elif self._credentials_found_in_envars(): return os.getenv('PAN_' + credential.upper()) else: return self.storage.fetch_credential( credential=credential, profile=self.profile)
python
def _resolve_credential(self, credential): """Resolve credential from envars or credentials store. Args: credential (str): Credential to resolve. Returns: str or None: Resolved credential or ``None``. """ if self._credentials_found_in_instance: return elif self._credentials_found_in_envars(): return os.getenv('PAN_' + credential.upper()) else: return self.storage.fetch_credential( credential=credential, profile=self.profile)
[ "def", "_resolve_credential", "(", "self", ",", "credential", ")", ":", "if", "self", ".", "_credentials_found_in_instance", ":", "return", "elif", "self", ".", "_credentials_found_in_envars", "(", ")", ":", "return", "os", ".", "getenv", "(", "'PAN_'", "+", "...
Resolve credential from envars or credentials store. Args: credential (str): Credential to resolve. Returns: str or None: Resolved credential or ``None``.
[ "Resolve", "credential", "from", "envars", "or", "credentials", "store", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L211-L227
train
30,177
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.decode_jwt_payload
def decode_jwt_payload(self, access_token=None): """Extract payload field from JWT. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: dict: JSON object that contains the claims conveyed by the JWT. """ c = self.get_credentials() jwt = access_token or c.access_token try: _, payload, _ = jwt.split('.') # header, payload, sig rem = len(payload) % 4 if rem > 0: # add padding payload += '=' * (4 - rem) try: decoded_jwt = b64decode(payload).decode("utf-8") except TypeError as e: raise PanCloudError( "Failed to base64 decode JWT: %s" % e) else: try: x = loads(decoded_jwt) except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) except (AttributeError, ValueError) as e: raise PanCloudError("Invalid JWT: %s" % e) return x
python
def decode_jwt_payload(self, access_token=None): """Extract payload field from JWT. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: dict: JSON object that contains the claims conveyed by the JWT. """ c = self.get_credentials() jwt = access_token or c.access_token try: _, payload, _ = jwt.split('.') # header, payload, sig rem = len(payload) % 4 if rem > 0: # add padding payload += '=' * (4 - rem) try: decoded_jwt = b64decode(payload).decode("utf-8") except TypeError as e: raise PanCloudError( "Failed to base64 decode JWT: %s" % e) else: try: x = loads(decoded_jwt) except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) except (AttributeError, ValueError) as e: raise PanCloudError("Invalid JWT: %s" % e) return x
[ "def", "decode_jwt_payload", "(", "self", ",", "access_token", "=", "None", ")", ":", "c", "=", "self", ".", "get_credentials", "(", ")", "jwt", "=", "access_token", "or", "c", ".", "access_token", "try", ":", "_", ",", "payload", ",", "_", "=", "jwt",...
Extract payload field from JWT. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: dict: JSON object that contains the claims conveyed by the JWT.
[ "Extract", "payload", "field", "from", "JWT", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L229-L259
train
30,178
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials._decode_exp
def _decode_exp(self, access_token=None): """Extract exp field from access token. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: int: JWT expiration in epoch seconds. """ c = self.get_credentials() jwt = access_token or c.access_token x = self.decode_jwt_payload(jwt) if 'exp' in x: try: exp = int(x['exp']) except ValueError: raise PanCloudError( "Expiration time (exp) must be an integer") else: self.jwt_exp = exp return exp else: raise PanCloudError("No exp field found in payload")
python
def _decode_exp(self, access_token=None): """Extract exp field from access token. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: int: JWT expiration in epoch seconds. """ c = self.get_credentials() jwt = access_token or c.access_token x = self.decode_jwt_payload(jwt) if 'exp' in x: try: exp = int(x['exp']) except ValueError: raise PanCloudError( "Expiration time (exp) must be an integer") else: self.jwt_exp = exp return exp else: raise PanCloudError("No exp field found in payload")
[ "def", "_decode_exp", "(", "self", ",", "access_token", "=", "None", ")", ":", "c", "=", "self", ".", "get_credentials", "(", ")", "jwt", "=", "access_token", "or", "c", ".", "access_token", "x", "=", "self", ".", "decode_jwt_payload", "(", "jwt", ")", ...
Extract exp field from access token. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: int: JWT expiration in epoch seconds.
[ "Extract", "exp", "field", "from", "access", "token", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L261-L285
train
30,179
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.fetch_tokens
def fetch_tokens(self, client_id=None, client_secret=None, code=None, redirect_uri=None, **kwargs): """Exchange authorization code for token. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. client_secret (str): OAuth2 client secret. Defaults to ``None``. code (str): Authorization code. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. Returns: dict: Response from token URL. """ client_id = client_id or self.client_id client_secret = client_secret or self.client_secret redirect_uri = redirect_uri or self.redirect_uri data = { 'grant_type': 'authorization_code', 'client_id': client_id, 'client_secret': client_secret, 'code': code, 'redirect_uri': redirect_uri } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RequestToken', auth=None, **kwargs ) if not r.ok: raise PanCloudError( '%s %s: %s' % (r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) self.access_token = r_json.get('access_token') self.jwt_exp = self._decode_exp(self.access_token_) self.refresh_token = r_json.get('refresh_token') self.write_credentials() return r_json
python
def fetch_tokens(self, client_id=None, client_secret=None, code=None, redirect_uri=None, **kwargs): """Exchange authorization code for token. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. client_secret (str): OAuth2 client secret. Defaults to ``None``. code (str): Authorization code. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. Returns: dict: Response from token URL. """ client_id = client_id or self.client_id client_secret = client_secret or self.client_secret redirect_uri = redirect_uri or self.redirect_uri data = { 'grant_type': 'authorization_code', 'client_id': client_id, 'client_secret': client_secret, 'code': code, 'redirect_uri': redirect_uri } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RequestToken', auth=None, **kwargs ) if not r.ok: raise PanCloudError( '%s %s: %s' % (r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) self.access_token = r_json.get('access_token') self.jwt_exp = self._decode_exp(self.access_token_) self.refresh_token = r_json.get('refresh_token') self.write_credentials() return r_json
[ "def", "fetch_tokens", "(", "self", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "code", "=", "None", ",", "redirect_uri", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client_id", "=", "client_id", "or", "self", ".", "clie...
Exchange authorization code for token. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. client_secret (str): OAuth2 client secret. Defaults to ``None``. code (str): Authorization code. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. Returns: dict: Response from token URL.
[ "Exchange", "authorization", "code", "for", "token", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L287-L338
train
30,180
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.get_authorization_url
def get_authorization_url(self, client_id=None, instance_id=None, redirect_uri=None, region=None, scope=None, state=None): """Generate authorization URL. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. instance_id (str): App Instance ID. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. region (str): App Region. Defaults to ``None``. scope (str): Permissions. Defaults to ``None``. state (str): UUID to detect CSRF. Defaults to ``None``. Returns: str, str: Auth URL, state """ client_id = client_id or self.client_id instance_id = instance_id or self.instance_id redirect_uri = redirect_uri or self.redirect_uri region = region or self.region scope = scope or self.scope state = state or str(uuid.uuid4()) self.state = state return Request( 'GET', self.auth_base_url, params={ 'client_id': client_id, 'instance_id': instance_id, 'redirect_uri': redirect_uri, 'region': region, 'response_type': 'code', 'scope': scope, 'state': state } ).prepare().url, state
python
def get_authorization_url(self, client_id=None, instance_id=None, redirect_uri=None, region=None, scope=None, state=None): """Generate authorization URL. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. instance_id (str): App Instance ID. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. region (str): App Region. Defaults to ``None``. scope (str): Permissions. Defaults to ``None``. state (str): UUID to detect CSRF. Defaults to ``None``. Returns: str, str: Auth URL, state """ client_id = client_id or self.client_id instance_id = instance_id or self.instance_id redirect_uri = redirect_uri or self.redirect_uri region = region or self.region scope = scope or self.scope state = state or str(uuid.uuid4()) self.state = state return Request( 'GET', self.auth_base_url, params={ 'client_id': client_id, 'instance_id': instance_id, 'redirect_uri': redirect_uri, 'region': region, 'response_type': 'code', 'scope': scope, 'state': state } ).prepare().url, state
[ "def", "get_authorization_url", "(", "self", ",", "client_id", "=", "None", ",", "instance_id", "=", "None", ",", "redirect_uri", "=", "None", ",", "region", "=", "None", ",", "scope", "=", "None", ",", "state", "=", "None", ")", ":", "client_id", "=", ...
Generate authorization URL. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. instance_id (str): App Instance ID. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. region (str): App Region. Defaults to ``None``. scope (str): Permissions. Defaults to ``None``. state (str): UUID to detect CSRF. Defaults to ``None``. Returns: str, str: Auth URL, state
[ "Generate", "authorization", "URL", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L340-L376
train
30,181
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.get_credentials
def get_credentials(self): """Get read-only credentials. Returns: class: Read-only credentials. """ return ReadOnlyCredentials( self.access_token, self.client_id, self.client_secret, self.refresh_token )
python
def get_credentials(self): """Get read-only credentials. Returns: class: Read-only credentials. """ return ReadOnlyCredentials( self.access_token, self.client_id, self.client_secret, self.refresh_token )
[ "def", "get_credentials", "(", "self", ")", ":", "return", "ReadOnlyCredentials", "(", "self", ".", "access_token", ",", "self", ".", "client_id", ",", "self", ".", "client_secret", ",", "self", ".", "refresh_token", ")" ]
Get read-only credentials. Returns: class: Read-only credentials.
[ "Get", "read", "-", "only", "credentials", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L378-L388
train
30,182
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.jwt_is_expired
def jwt_is_expired(self, access_token=None, leeway=0): """Validate JWT access token expiration. Args: access_token (str): Access token to validate. Defaults to ``None``. leeway (float): Time in seconds to adjust for local clock skew. Defaults to 0. Returns: bool: ``True`` if expired, otherwise ``False``. """ if access_token is not None: exp = self._decode_exp(access_token) else: exp = self.jwt_exp now = time() if exp < (now - leeway): return True return False
python
def jwt_is_expired(self, access_token=None, leeway=0): """Validate JWT access token expiration. Args: access_token (str): Access token to validate. Defaults to ``None``. leeway (float): Time in seconds to adjust for local clock skew. Defaults to 0. Returns: bool: ``True`` if expired, otherwise ``False``. """ if access_token is not None: exp = self._decode_exp(access_token) else: exp = self.jwt_exp now = time() if exp < (now - leeway): return True return False
[ "def", "jwt_is_expired", "(", "self", ",", "access_token", "=", "None", ",", "leeway", "=", "0", ")", ":", "if", "access_token", "is", "not", "None", ":", "exp", "=", "self", ".", "_decode_exp", "(", "access_token", ")", "else", ":", "exp", "=", "self"...
Validate JWT access token expiration. Args: access_token (str): Access token to validate. Defaults to ``None``. leeway (float): Time in seconds to adjust for local clock skew. Defaults to 0. Returns: bool: ``True`` if expired, otherwise ``False``.
[ "Validate", "JWT", "access", "token", "expiration", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L390-L408
train
30,183
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.refresh
def refresh(self, access_token=None, **kwargs): """Refresh access and refresh tokens. Args: access_token (str): Access token to refresh. Defaults to ``None``. Returns: str: Refreshed access token. """ if not self.token_lock.locked(): with self.token_lock: if access_token == self.access_token or access_token is None: if self.developer_token is not None: r = self._httpclient.request( method='POST', url=self.developer_token_url, path='/request_token', headers={ 'Authorization': 'Bearer {}'.format( self.developer_token ) }, timeout=30, raise_for_status=True ) elif all( [ self.client_id, self.client_secret, self.refresh_token ] ): data = { 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, 'grant_type': 'refresh_token' } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RequestToken', **kwargs ) else: raise PartialCredentialsError( "Missing one or more required credentials" ) if r: if not r.ok: raise PanCloudError( '%s %s: %s' % ( r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) self.access_token = r_json.get( 'access_token', None ) self.jwt_exp = self._decode_exp( self.access_token_) if r_json.get('refresh_token', None): self.refresh_token = \ r_json.get('refresh_token') self.write_credentials() return self.access_token_
python
def refresh(self, access_token=None, **kwargs): """Refresh access and refresh tokens. Args: access_token (str): Access token to refresh. Defaults to ``None``. Returns: str: Refreshed access token. """ if not self.token_lock.locked(): with self.token_lock: if access_token == self.access_token or access_token is None: if self.developer_token is not None: r = self._httpclient.request( method='POST', url=self.developer_token_url, path='/request_token', headers={ 'Authorization': 'Bearer {}'.format( self.developer_token ) }, timeout=30, raise_for_status=True ) elif all( [ self.client_id, self.client_secret, self.refresh_token ] ): data = { 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, 'grant_type': 'refresh_token' } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RequestToken', **kwargs ) else: raise PartialCredentialsError( "Missing one or more required credentials" ) if r: if not r.ok: raise PanCloudError( '%s %s: %s' % ( r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) self.access_token = r_json.get( 'access_token', None ) self.jwt_exp = self._decode_exp( self.access_token_) if r_json.get('refresh_token', None): self.refresh_token = \ r_json.get('refresh_token') self.write_credentials() return self.access_token_
[ "def", "refresh", "(", "self", ",", "access_token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "token_lock", ".", "locked", "(", ")", ":", "with", "self", ".", "token_lock", ":", "if", "access_token", "==", "self", ".",...
Refresh access and refresh tokens. Args: access_token (str): Access token to refresh. Defaults to ``None``. Returns: str: Refreshed access token.
[ "Refresh", "access", "and", "refresh", "tokens", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L422-L500
train
30,184
PaloAltoNetworks/pancloud
pancloud/credentials.py
Credentials.revoke_access_token
def revoke_access_token(self, **kwargs): """Revoke access token.""" c = self.get_credentials() data = { 'client_id': c.client_id, 'client_secret': c.client_secret, 'token': c.access_token, 'token_type_hint': 'access_token' } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RevokeToken', **kwargs ) if not r.ok: raise PanCloudError( '%s %s: %s' % (r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) return r_json
python
def revoke_access_token(self, **kwargs): """Revoke access token.""" c = self.get_credentials() data = { 'client_id': c.client_id, 'client_secret': c.client_secret, 'token': c.access_token, 'token_type_hint': 'access_token' } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RevokeToken', **kwargs ) if not r.ok: raise PanCloudError( '%s %s: %s' % (r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) return r_json
[ "def", "revoke_access_token", "(", "self", ",", "*", "*", "kwargs", ")", ":", "c", "=", "self", ".", "get_credentials", "(", ")", "data", "=", "{", "'client_id'", ":", "c", ".", "client_id", ",", "'client_secret'", ":", "c", ".", "client_secret", ",", ...
Revoke access token.
[ "Revoke", "access", "token", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L502-L533
train
30,185
PaloAltoNetworks/pancloud
pancloud/logging.py
LoggingService.delete
def delete(self, query_id=None, **kwargs): # pragma: no cover """Delete a query job. Uses the DELETE HTTP method to delete a query job. After calling this endpoint, it is an error to poll for query results using the queryId specified here. Args: query_id (str): Specifies the ID of the query job. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_query.py`` example. """ path = "/logging-service/v1/queries/{}".format(query_id) r = self._httpclient.request( method="DELETE", url=self.url, path=path, **kwargs ) return r
python
def delete(self, query_id=None, **kwargs): # pragma: no cover """Delete a query job. Uses the DELETE HTTP method to delete a query job. After calling this endpoint, it is an error to poll for query results using the queryId specified here. Args: query_id (str): Specifies the ID of the query job. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_query.py`` example. """ path = "/logging-service/v1/queries/{}".format(query_id) r = self._httpclient.request( method="DELETE", url=self.url, path=path, **kwargs ) return r
[ "def", "delete", "(", "self", ",", "query_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "path", "=", "\"/logging-service/v1/queries/{}\"", ".", "format", "(", "query_id", ")", "r", "=", "self", ".", "_httpclient", ".", "request",...
Delete a query job. Uses the DELETE HTTP method to delete a query job. After calling this endpoint, it is an error to poll for query results using the queryId specified here. Args: query_id (str): Specifies the ID of the query job. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_query.py`` example.
[ "Delete", "a", "query", "job", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/logging.py#L62-L87
train
30,186
PaloAltoNetworks/pancloud
pancloud/logging.py
LoggingService.iter_poll
def iter_poll(self, query_id=None, sequence_no=None, params=None, **kwargs): # pragma: no cover """Retrieve pages iteratively in a non-greedy manner. Automatically increments the sequenceNo as it continues to poll for results until the endpoint reports JOB_FINISHED or JOB_FAILED, or an exception is raised by the pancloud library. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: requests.Response: Requests Response() object. Examples: Refer to ``logging_iter_poll.py`` example. """ while True: r = self.poll( query_id, sequence_no, params, enforce_json=True, **kwargs ) if r.json()['queryStatus'] == "FINISHED": if sequence_no is not None: sequence_no += 1 else: sequence_no = 1 yield r elif r.json()['queryStatus'] == "JOB_FINISHED": yield r break elif r.json()['queryStatus'] == "JOB_FAILED": yield r break elif r.json()['queryStatus'] == "RUNNING": yield r time.sleep(1) else: raise PanCloudError( 'Bad queryStatus: %s' % r.json()['queryStatus'] )
python
def iter_poll(self, query_id=None, sequence_no=None, params=None, **kwargs): # pragma: no cover """Retrieve pages iteratively in a non-greedy manner. Automatically increments the sequenceNo as it continues to poll for results until the endpoint reports JOB_FINISHED or JOB_FAILED, or an exception is raised by the pancloud library. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: requests.Response: Requests Response() object. Examples: Refer to ``logging_iter_poll.py`` example. """ while True: r = self.poll( query_id, sequence_no, params, enforce_json=True, **kwargs ) if r.json()['queryStatus'] == "FINISHED": if sequence_no is not None: sequence_no += 1 else: sequence_no = 1 yield r elif r.json()['queryStatus'] == "JOB_FINISHED": yield r break elif r.json()['queryStatus'] == "JOB_FAILED": yield r break elif r.json()['queryStatus'] == "RUNNING": yield r time.sleep(1) else: raise PanCloudError( 'Bad queryStatus: %s' % r.json()['queryStatus'] )
[ "def", "iter_poll", "(", "self", ",", "query_id", "=", "None", ",", "sequence_no", "=", "None", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "while", "True", ":", "r", "=", "self", ".", "poll", "(", "query_id", ...
Retrieve pages iteratively in a non-greedy manner. Automatically increments the sequenceNo as it continues to poll for results until the endpoint reports JOB_FINISHED or JOB_FAILED, or an exception is raised by the pancloud library. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: requests.Response: Requests Response() object. Examples: Refer to ``logging_iter_poll.py`` example.
[ "Retrieve", "pages", "iteratively", "in", "a", "non", "-", "greedy", "manner", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/logging.py#L89-L133
train
30,187
PaloAltoNetworks/pancloud
pancloud/logging.py
LoggingService.poll
def poll(self, query_id=None, sequence_no=None, params=None, **kwargs): # pragma: no cover """Poll for asynchronous query results. Continue to poll for results until this endpoint reports JOB_FINISHED or JOB_FAILED. The results of queries can be returned in multiple pages, each of which may contain many log records. Use this endpoint to poll for query result batches, as well as to track query result status. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_query.py`` example. """ path = "/logging-service/v1/queries/{}/{}".format( query_id, sequence_no ) r = self._httpclient.request( method="GET", url=self.url, params=params, path=path, **kwargs ) return r
python
def poll(self, query_id=None, sequence_no=None, params=None, **kwargs): # pragma: no cover """Poll for asynchronous query results. Continue to poll for results until this endpoint reports JOB_FINISHED or JOB_FAILED. The results of queries can be returned in multiple pages, each of which may contain many log records. Use this endpoint to poll for query result batches, as well as to track query result status. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_query.py`` example. """ path = "/logging-service/v1/queries/{}/{}".format( query_id, sequence_no ) r = self._httpclient.request( method="GET", url=self.url, params=params, path=path, **kwargs ) return r
[ "def", "poll", "(", "self", ",", "query_id", "=", "None", ",", "sequence_no", "=", "None", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "path", "=", "\"/logging-service/v1/queries/{}/{}\"", ".", "format", "(", "query_i...
Poll for asynchronous query results. Continue to poll for results until this endpoint reports JOB_FINISHED or JOB_FAILED. The results of queries can be returned in multiple pages, each of which may contain many log records. Use this endpoint to poll for query result batches, as well as to track query result status. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_query.py`` example.
[ "Poll", "for", "asynchronous", "query", "results", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/logging.py#L135-L168
train
30,188
PaloAltoNetworks/pancloud
pancloud/logging.py
LoggingService.xpoll
def xpoll(self, query_id=None, sequence_no=None, params=None, delete_query=True, **kwargs): # pragma: no cover """Retrieve individual logs iteratively in a non-greedy manner. Generator function to return individual log entries from poll API request. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. delete_query (bool): True for delete, False otherwise. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: dictionary with single log entry. """ def _delete(query_id, **kwargs): r = self.delete(query_id, **kwargs) try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if not (200 <= r.status_code < 300): if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if r.status_code == 200: return else: raise PanCloudError('delete: status_code: %d' % r.status_code) while True: r = self.poll(query_id, sequence_no, params, **kwargs) try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if not (200 <= r.status_code < 300): if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if 'queryStatus' not in r_json: self._debug(r_json) raise PanCloudError('no "queryStatus" in response') self._debug(r_json['queryStatus']) if r_json['queryStatus'] in ['FINISHED', 'JOB_FINISHED']: try: hits = r_json['result']['esResult']['hits']['hits'] except KeyError as e: raise PanCloudError('no "hits" in response' % e) self._debug('hits: %d', len(hits)) for x in hits: yield x if r_json['queryStatus'] == 'JOB_FINISHED': if delete_query: _delete(query_id, **kwargs) return if sequence_no is not None: sequence_no += 1 else: sequence_no = 1 elif r_json['queryStatus'] == 'JOB_FAILED': e = '%s' % r_json['queryStatus'] try: e += ': %s' % r_json['result']['esResult']['error'] except KeyError: self._debug(r_json) raise PanCloudError(e) elif r_json['queryStatus'] == 'RUNNING': if params is not None and 'maxWaitTime' in params: pass else: # XXX time.sleep(1) else: raise PanCloudError('Bad queryStatus: %s' % r_json['queryStatus'])
python
def xpoll(self, query_id=None, sequence_no=None, params=None, delete_query=True, **kwargs): # pragma: no cover """Retrieve individual logs iteratively in a non-greedy manner. Generator function to return individual log entries from poll API request. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. delete_query (bool): True for delete, False otherwise. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: dictionary with single log entry. """ def _delete(query_id, **kwargs): r = self.delete(query_id, **kwargs) try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if not (200 <= r.status_code < 300): if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if r.status_code == 200: return else: raise PanCloudError('delete: status_code: %d' % r.status_code) while True: r = self.poll(query_id, sequence_no, params, **kwargs) try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if not (200 <= r.status_code < 300): if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if 'queryStatus' not in r_json: self._debug(r_json) raise PanCloudError('no "queryStatus" in response') self._debug(r_json['queryStatus']) if r_json['queryStatus'] in ['FINISHED', 'JOB_FINISHED']: try: hits = r_json['result']['esResult']['hits']['hits'] except KeyError as e: raise PanCloudError('no "hits" in response' % e) self._debug('hits: %d', len(hits)) for x in hits: yield x if r_json['queryStatus'] == 'JOB_FINISHED': if delete_query: _delete(query_id, **kwargs) return if sequence_no is not None: sequence_no += 1 else: sequence_no = 1 elif r_json['queryStatus'] == 'JOB_FAILED': e = '%s' % r_json['queryStatus'] try: e += ': %s' % r_json['result']['esResult']['error'] except KeyError: self._debug(r_json) raise PanCloudError(e) elif r_json['queryStatus'] == 'RUNNING': if params is not None and 'maxWaitTime' in params: pass else: # XXX time.sleep(1) else: raise PanCloudError('Bad queryStatus: %s' % r_json['queryStatus'])
[ "def", "xpoll", "(", "self", ",", "query_id", "=", "None", ",", "sequence_no", "=", "None", ",", "params", "=", "None", ",", "delete_query", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "def", "_delete", "(", "query_id", ",", "...
Retrieve individual logs iteratively in a non-greedy manner. Generator function to return individual log entries from poll API request. Args: params (dict): Payload/request dictionary. query_id (str): Specifies the ID of the query job. sequence_no (int): Specifies the sequenceNo. delete_query (bool): True for delete, False otherwise. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: dictionary with single log entry.
[ "Retrieve", "individual", "logs", "iteratively", "in", "a", "non", "-", "greedy", "manner", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/logging.py#L199-L296
train
30,189
PaloAltoNetworks/pancloud
pancloud/logging.py
LoggingService.write
def write(self, vendor_id=None, log_type=None, json=None, **kwargs): """Write log records to the Logging Service. This API requires a JSON array in its request body, each element of which represents a single log record. Log records are provided as JSON objects. Every log record must include the primary timestamp field that you identified when you registered your app. Every log record must also identify the log type. Args: vendor_id (str): Vendor ID. log_type (str): Log type. json (list): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_write.py`` example. """ path = "/logging-service/v1/logs/{}/{}".format( vendor_id, log_type ) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ) return r
python
def write(self, vendor_id=None, log_type=None, json=None, **kwargs): """Write log records to the Logging Service. This API requires a JSON array in its request body, each element of which represents a single log record. Log records are provided as JSON objects. Every log record must include the primary timestamp field that you identified when you registered your app. Every log record must also identify the log type. Args: vendor_id (str): Vendor ID. log_type (str): Log type. json (list): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_write.py`` example. """ path = "/logging-service/v1/logs/{}/{}".format( vendor_id, log_type ) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ) return r
[ "def", "write", "(", "self", ",", "vendor_id", "=", "None", ",", "log_type", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "\"/logging-service/v1/logs/{}/{}\"", ".", "format", "(", "vendor_id", ",", "log_type", ")...
Write log records to the Logging Service. This API requires a JSON array in its request body, each element of which represents a single log record. Log records are provided as JSON objects. Every log record must include the primary timestamp field that you identified when you registered your app. Every log record must also identify the log type. Args: vendor_id (str): Vendor ID. log_type (str): Log type. json (list): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_write.py`` example.
[ "Write", "log", "records", "to", "the", "Logging", "Service", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/logging.py#L298-L330
train
30,190
PaloAltoNetworks/pancloud
pancloud/adapters/tinydb_adapter.py
TinyDBStore.fetch_credential
def fetch_credential(self, credential=None, profile=None): """Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str, None: Fetched credential or ``None``. """ q = self.db.get(self.query.profile == profile) if q is not None: return q.get(credential)
python
def fetch_credential(self, credential=None, profile=None): """Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str, None: Fetched credential or ``None``. """ q = self.db.get(self.query.profile == profile) if q is not None: return q.get(credential)
[ "def", "fetch_credential", "(", "self", ",", "credential", "=", "None", ",", "profile", "=", "None", ")", ":", "q", "=", "self", ".", "db", ".", "get", "(", "self", ".", "query", ".", "profile", "==", "profile", ")", "if", "q", "is", "not", "None",...
Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str, None: Fetched credential or ``None``.
[ "Fetch", "credential", "from", "credentials", "file", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/adapters/tinydb_adapter.py#L24-L37
train
30,191
PaloAltoNetworks/pancloud
pancloud/adapters/tinydb_adapter.py
TinyDBStore.remove_profile
def remove_profile(self, profile=None): """Remove profile from credentials file. Args: profile (str): Credentials profile to remove. Returns: list: List of affected document IDs. """ with self.db: return self.db.remove(self.query.profile == profile)
python
def remove_profile(self, profile=None): """Remove profile from credentials file. Args: profile (str): Credentials profile to remove. Returns: list: List of affected document IDs. """ with self.db: return self.db.remove(self.query.profile == profile)
[ "def", "remove_profile", "(", "self", ",", "profile", "=", "None", ")", ":", "with", "self", ".", "db", ":", "return", "self", ".", "db", ".", "remove", "(", "self", ".", "query", ".", "profile", "==", "profile", ")" ]
Remove profile from credentials file. Args: profile (str): Credentials profile to remove. Returns: list: List of affected document IDs.
[ "Remove", "profile", "from", "credentials", "file", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/adapters/tinydb_adapter.py#L59-L70
train
30,192
PaloAltoNetworks/pancloud
pancloud/event.py
EventService.nack
def nack(self, channel_id=None, **kwargs): # pragma: no cover """Send a negative read-acknowledgement to the service. Causes the channel's read point to move to its previous position prior to the last poll. Args: channel_id (str): The channel ID. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``event_nack.py`` example. """ path = "/event-service/v1/channels/{}/nack".format(channel_id) r = self._httpclient.request( method="POST", url=self.url, path=path, **kwargs ) return r
python
def nack(self, channel_id=None, **kwargs): # pragma: no cover """Send a negative read-acknowledgement to the service. Causes the channel's read point to move to its previous position prior to the last poll. Args: channel_id (str): The channel ID. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``event_nack.py`` example. """ path = "/event-service/v1/channels/{}/nack".format(channel_id) r = self._httpclient.request( method="POST", url=self.url, path=path, **kwargs ) return r
[ "def", "nack", "(", "self", ",", "channel_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "path", "=", "\"/event-service/v1/channels/{}/nack\"", ".", "format", "(", "channel_id", ")", "r", "=", "self", ".", "_httpclient", ".", "req...
Send a negative read-acknowledgement to the service. Causes the channel's read point to move to its previous position prior to the last poll. Args: channel_id (str): The channel ID. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``event_nack.py`` example.
[ "Send", "a", "negative", "read", "-", "acknowledgement", "to", "the", "service", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/event.py#L147-L171
train
30,193
PaloAltoNetworks/pancloud
pancloud/event.py
EventService.poll
def poll(self, channel_id=None, json=None, **kwargs): # pragma: no cover """Read one or more events from a channel. Reads events (log records) from the identified channel. Events are read in chronological order. Args: channel_id (str): The channel ID. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``event_poll.py`` example. """ path = "/event-service/v1/channels/{}/poll".format(channel_id) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ) return r
python
def poll(self, channel_id=None, json=None, **kwargs): # pragma: no cover """Read one or more events from a channel. Reads events (log records) from the identified channel. Events are read in chronological order. Args: channel_id (str): The channel ID. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``event_poll.py`` example. """ path = "/event-service/v1/channels/{}/poll".format(channel_id) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ) return r
[ "def", "poll", "(", "self", ",", "channel_id", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "path", "=", "\"/event-service/v1/channels/{}/poll\"", ".", "format", "(", "channel_id", ")", "r", "=", "self", "...
Read one or more events from a channel. Reads events (log records) from the identified channel. Events are read in chronological order. Args: channel_id (str): The channel ID. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``event_poll.py`` example.
[ "Read", "one", "or", "more", "events", "from", "a", "channel", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/event.py#L173-L199
train
30,194
PaloAltoNetworks/pancloud
pancloud/event.py
EventService.xpoll
def xpoll(self, channel_id=None, json=None, ack=False, follow=False, pause=None, **kwargs): """Retrieve logType, event entries iteratively in a non-greedy manner. Generator function to return logType, event entries from poll API request. Args: channel_id (str): The channel ID. json (dict): Payload/request body. ack (bool): True to acknowledge read. follow (bool): True to continue polling after channelId empty. pause (float): Seconds to sleep between poll when follow and channelId empty. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: dictionary with single logType and event entries. """ def _ack(channel_id, **kwargs): r = self.ack(channel_id, **kwargs) if not (200 <= r.status_code < 300): try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if r.status_code == 200: return else: raise PanCloudError('ack: status_code: %d' % r.status_code) while True: r = self.poll(channel_id, json, **kwargs) try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if not (200 <= r.status_code < 300): if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if not r_json and not follow: return for x in r_json: yield x # XXX don't ack if empty response? if ack: _ack(channel_id, **kwargs) if not r_json and pause is not None: self._debug('sleep %.2fs', pause) time.sleep(pause)
python
def xpoll(self, channel_id=None, json=None, ack=False, follow=False, pause=None, **kwargs): """Retrieve logType, event entries iteratively in a non-greedy manner. Generator function to return logType, event entries from poll API request. Args: channel_id (str): The channel ID. json (dict): Payload/request body. ack (bool): True to acknowledge read. follow (bool): True to continue polling after channelId empty. pause (float): Seconds to sleep between poll when follow and channelId empty. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: dictionary with single logType and event entries. """ def _ack(channel_id, **kwargs): r = self.ack(channel_id, **kwargs) if not (200 <= r.status_code < 300): try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if r.status_code == 200: return else: raise PanCloudError('ack: status_code: %d' % r.status_code) while True: r = self.poll(channel_id, json, **kwargs) try: r_json = r.json() except ValueError as e: raise PanCloudError('Invalid JSON: %s' % e) if not (200 <= r.status_code < 300): if 'errorCode' in r_json and 'errorMessage' in r_json: raise PanCloudError('%s: %s' % (r_json['errorCode'], r_json['errorMessage'])) else: raise PanCloudError('%s %s' % (r.status_code, r.reason)) if not r_json and not follow: return for x in r_json: yield x # XXX don't ack if empty response? if ack: _ack(channel_id, **kwargs) if not r_json and pause is not None: self._debug('sleep %.2fs', pause) time.sleep(pause)
[ "def", "xpoll", "(", "self", ",", "channel_id", "=", "None", ",", "json", "=", "None", ",", "ack", "=", "False", ",", "follow", "=", "False", ",", "pause", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_ack", "(", "channel_id", ",", "*"...
Retrieve logType, event entries iteratively in a non-greedy manner. Generator function to return logType, event entries from poll API request. Args: channel_id (str): The channel ID. json (dict): Payload/request body. ack (bool): True to acknowledge read. follow (bool): True to continue polling after channelId empty. pause (float): Seconds to sleep between poll when follow and channelId empty. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Yields: dictionary with single logType and event entries.
[ "Retrieve", "logType", "event", "entries", "iteratively", "in", "a", "non", "-", "greedy", "manner", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/event.py#L232-L301
train
30,195
PaloAltoNetworks/pancloud
pancloud/httpclient.py
HTTPClient._apply_credentials
def _apply_credentials(auto_refresh=True, credentials=None, headers=None): """Update Authorization header. Update request headers with latest `access_token`. Perform token `refresh` if token is ``None``. Args: auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``. credentials (class): Read-only credentials. headers (class): Requests `CaseInsensitiveDict`. """ token = credentials.get_credentials().access_token if auto_refresh is True: if token is None: token = credentials.refresh( access_token=None, timeout=10) elif credentials.jwt_is_expired(): token = credentials.refresh(timeout=10) headers.update( {'Authorization': "Bearer {}".format(token)} )
python
def _apply_credentials(auto_refresh=True, credentials=None, headers=None): """Update Authorization header. Update request headers with latest `access_token`. Perform token `refresh` if token is ``None``. Args: auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``. credentials (class): Read-only credentials. headers (class): Requests `CaseInsensitiveDict`. """ token = credentials.get_credentials().access_token if auto_refresh is True: if token is None: token = credentials.refresh( access_token=None, timeout=10) elif credentials.jwt_is_expired(): token = credentials.refresh(timeout=10) headers.update( {'Authorization': "Bearer {}".format(token)} )
[ "def", "_apply_credentials", "(", "auto_refresh", "=", "True", ",", "credentials", "=", "None", ",", "headers", "=", "None", ")", ":", "token", "=", "credentials", ".", "get_credentials", "(", ")", ".", "access_token", "if", "auto_refresh", "is", "True", ":"...
Update Authorization header. Update request headers with latest `access_token`. Perform token `refresh` if token is ``None``. Args: auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``. credentials (class): Read-only credentials. headers (class): Requests `CaseInsensitiveDict`.
[ "Update", "Authorization", "header", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/httpclient.py#L123-L145
train
30,196
PaloAltoNetworks/pancloud
pancloud/httpclient.py
HTTPClient.request
def request(self, **kwargs): """Generate HTTP request using given parameters. The request method prepares HTTP requests using class or method-level attributes/variables. Class-level attributes may be overridden by method-level variables offering greater flexibility and efficiency. Parameters: enforce_json (bool): Require properly-formatted JSON or raise :exc:`~pancloud.exceptions.HTTPError`. Defaults to ``False``. path (str): URI path to append to URL. Defaults to ``empty``. raise_for_status (bool): If ``True``, raises :exc:`~pancloud.exceptions.HTTPError` if status_code not in 2XX. Defaults to ``False``. Args: **kwargs: Supported :class:`~requests.Session` and :class:`~requests.adapters.HTTPAdapter` parameters. Returns: requests.Response: Requests Response() object """ url = kwargs.pop('url', self.url) # Session() overrides auth = kwargs.pop('auth', self.session.auth) cert = kwargs.pop('cert', self.session.cert) cookies = kwargs.pop('cookies', self.session.cookies) headers = kwargs.pop('headers', self.session.headers.copy()) params = kwargs.pop('params', self.session.params) proxies = kwargs.pop('proxies', self.session.proxies) stream = kwargs.pop('stream', self.session.stream) verify = kwargs.pop('verify', self.session.verify) # Non-Requests key-word arguments auto_refresh = kwargs.pop('auto_refresh', self.auto_refresh) credentials = kwargs.pop('credentials', self.credentials) enforce_json = kwargs.pop('enforce_json', self.enforce_json) path = kwargs.pop('path', '') # default to empty path raise_for_status = kwargs.pop( 'raise_for_status', self.raise_for_status ) url = "{}:{}{}".format(url, self.port, path) if credentials: self._apply_credentials( auto_refresh=auto_refresh, credentials=credentials, headers=headers ) k = { # Re-pack kwargs to dictionary 'params': params, 'headers': headers, 'cookies': cookies, 'auth': auth, 'proxies': proxies, 'verify': verify, 'stream': stream, 'cert': cert } # Request() overrides for x in ['allow_redirects', 'data', 'json', 'method', 'timeout']: if x in kwargs: k[x] = kwargs.pop(x) # Handle invalid kwargs if len(kwargs) > 0: raise UnexpectedKwargsError(kwargs) try: method = k.pop('method') except KeyError: raise RequiredKwargsError('method') # Prepare and send the Request() and return Response() try: r = self._send_request( enforce_json, method, raise_for_status, url, **k ) return r except requests.RequestException as e: raise HTTPError(e)
python
def request(self, **kwargs): """Generate HTTP request using given parameters. The request method prepares HTTP requests using class or method-level attributes/variables. Class-level attributes may be overridden by method-level variables offering greater flexibility and efficiency. Parameters: enforce_json (bool): Require properly-formatted JSON or raise :exc:`~pancloud.exceptions.HTTPError`. Defaults to ``False``. path (str): URI path to append to URL. Defaults to ``empty``. raise_for_status (bool): If ``True``, raises :exc:`~pancloud.exceptions.HTTPError` if status_code not in 2XX. Defaults to ``False``. Args: **kwargs: Supported :class:`~requests.Session` and :class:`~requests.adapters.HTTPAdapter` parameters. Returns: requests.Response: Requests Response() object """ url = kwargs.pop('url', self.url) # Session() overrides auth = kwargs.pop('auth', self.session.auth) cert = kwargs.pop('cert', self.session.cert) cookies = kwargs.pop('cookies', self.session.cookies) headers = kwargs.pop('headers', self.session.headers.copy()) params = kwargs.pop('params', self.session.params) proxies = kwargs.pop('proxies', self.session.proxies) stream = kwargs.pop('stream', self.session.stream) verify = kwargs.pop('verify', self.session.verify) # Non-Requests key-word arguments auto_refresh = kwargs.pop('auto_refresh', self.auto_refresh) credentials = kwargs.pop('credentials', self.credentials) enforce_json = kwargs.pop('enforce_json', self.enforce_json) path = kwargs.pop('path', '') # default to empty path raise_for_status = kwargs.pop( 'raise_for_status', self.raise_for_status ) url = "{}:{}{}".format(url, self.port, path) if credentials: self._apply_credentials( auto_refresh=auto_refresh, credentials=credentials, headers=headers ) k = { # Re-pack kwargs to dictionary 'params': params, 'headers': headers, 'cookies': cookies, 'auth': auth, 'proxies': proxies, 'verify': verify, 'stream': stream, 'cert': cert } # Request() overrides for x in ['allow_redirects', 'data', 'json', 'method', 'timeout']: if x in kwargs: k[x] = kwargs.pop(x) # Handle invalid kwargs if len(kwargs) > 0: raise UnexpectedKwargsError(kwargs) try: method = k.pop('method') except KeyError: raise RequiredKwargsError('method') # Prepare and send the Request() and return Response() try: r = self._send_request( enforce_json, method, raise_for_status, url, **k ) return r except requests.RequestException as e: raise HTTPError(e)
[ "def", "request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url", "=", "kwargs", ".", "pop", "(", "'url'", ",", "self", ".", "url", ")", "# Session() overrides", "auth", "=", "kwargs", ".", "pop", "(", "'auth'", ",", "self", ".", "session", ...
Generate HTTP request using given parameters. The request method prepares HTTP requests using class or method-level attributes/variables. Class-level attributes may be overridden by method-level variables offering greater flexibility and efficiency. Parameters: enforce_json (bool): Require properly-formatted JSON or raise :exc:`~pancloud.exceptions.HTTPError`. Defaults to ``False``. path (str): URI path to append to URL. Defaults to ``empty``. raise_for_status (bool): If ``True``, raises :exc:`~pancloud.exceptions.HTTPError` if status_code not in 2XX. Defaults to ``False``. Args: **kwargs: Supported :class:`~requests.Session` and :class:`~requests.adapters.HTTPAdapter` parameters. Returns: requests.Response: Requests Response() object
[ "Generate", "HTTP", "request", "using", "given", "parameters", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/httpclient.py#L191-L273
train
30,197
PaloAltoNetworks/pancloud
pancloud/directorysync.py
DirectorySyncService.query
def query(self, object_class=None, json=None, **kwargs): # pragma: no cover """Query data stored in directory. Retrieves directory data by querying a Directory Sync Service cloud-based instance. The directory data is stored with the Directory Sync Service instance using an agent that is installed in the customer's network.This agent retrieves directory data from the customer's Active Directory, and then sends it to the cloud-based Directory Sync Service instance. Args: object_class (str): Directory object class. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Coming soon. """ path = "/directory-sync-service/v1/{}".format(object_class) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ) return r
python
def query(self, object_class=None, json=None, **kwargs): # pragma: no cover """Query data stored in directory. Retrieves directory data by querying a Directory Sync Service cloud-based instance. The directory data is stored with the Directory Sync Service instance using an agent that is installed in the customer's network.This agent retrieves directory data from the customer's Active Directory, and then sends it to the cloud-based Directory Sync Service instance. Args: object_class (str): Directory object class. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Coming soon. """ path = "/directory-sync-service/v1/{}".format(object_class) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ) return r
[ "def", "query", "(", "self", ",", "object_class", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "path", "=", "\"/directory-sync-service/v1/{}\"", ".", "format", "(", "object_class", ")", "r", "=", "self", "...
Query data stored in directory. Retrieves directory data by querying a Directory Sync Service cloud-based instance. The directory data is stored with the Directory Sync Service instance using an agent that is installed in the customer's network.This agent retrieves directory data from the customer's Active Directory, and then sends it to the cloud-based Directory Sync Service instance. Args: object_class (str): Directory object class. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Coming soon.
[ "Query", "data", "stored", "in", "directory", "." ]
c51e4c8aca3c988c60f062291007534edcb55285
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/directorysync.py#L146-L176
train
30,198
Linaro/squad
squad/core/management/commands/users.py
Command.handle
def handle(self, *args, **options): """ Forward to the right sub-handler """ if options["sub_command"] == "add": self.handle_add(options) elif options["sub_command"] == "update": self.handle_update(options) elif options["sub_command"] == "details": self.handle_details(options["username"]) elif options["sub_command"] == "list": self.handle_list(options["all"], options["csv"])
python
def handle(self, *args, **options): """ Forward to the right sub-handler """ if options["sub_command"] == "add": self.handle_add(options) elif options["sub_command"] == "update": self.handle_update(options) elif options["sub_command"] == "details": self.handle_details(options["username"]) elif options["sub_command"] == "list": self.handle_list(options["all"], options["csv"])
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "if", "options", "[", "\"sub_command\"", "]", "==", "\"add\"", ":", "self", ".", "handle_add", "(", "options", ")", "elif", "options", "[", "\"sub_command\"", "]", "=="...
Forward to the right sub-handler
[ "Forward", "to", "the", "right", "sub", "-", "handler" ]
27da5375e119312a86f231df95f99c979b9f48f0
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L148-L157
train
30,199