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:
BugZooExceptio... | 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:
BugZooExceptio... | [
"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:
... | 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:
... | [
"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.d... | 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.d... | [
"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 wh... | 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 wh... | [
"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 wil... | [
"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 pat... | 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 pat... | [
"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 th... | [
"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 ... | 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 ... | [
"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 reall... | [
"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.
"""
t... | 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.
"""
t... | [
"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)]... | 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)]... | [
"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 isinstanc... | 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 isinstanc... | [
"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)
... | 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)
... | [
"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... | 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... | [
"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,
... | 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,
... | [
"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.u... | 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.u... | [
"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:
... | 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:
... | [
"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... | 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... | [
"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 ... | [
"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 indi... | 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 indi... | [
"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 exc... | [
"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 ... | 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 ... | [
"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 = _NAM... | 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 = _NAM... | [
"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.par... | 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.par... | [
"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 th... | 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 th... | [
"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: ... | [
"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(ac... | 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(ac... | [
"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 cons... | 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 cons... | [
"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.
... | [
"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_unti... | 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_unti... | [
"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 My... | 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 My... | [
"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... | [
"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 ... | 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 ... | [
"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... | [
"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 MyGe... | 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 MyGe... | [
"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 MyGeota... | [
"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: R... | 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: R... | [
"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 serve... | [
"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... | 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... | [
"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_o... | 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_o... | [
"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... | 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... | [
"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)... | 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)... | [
"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.
... | 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.
... | [
"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. ... | [
"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... | 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... | [
"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
:para... | [
"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 = c... | 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 = c... | [
"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 +... | 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 +... | [
"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 occ... | 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 occ... | [
"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.
:rai... | [
"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 ... | 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 ... | [
"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.
... | [
"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
"""
r... | 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
"""
r... | [
"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 isinstan... | 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 isinstan... | [
"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_da... | 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_da... | [
"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 reparente... | 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 reparente... | [
"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.ad... | 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.ad... | [
"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('Ig... | 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('Ig... | [
"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}] {m... | 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}] {m... | [
"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_por... | 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_por... | [
"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_in... | 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_in... | [
"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(c... | 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(c... | [
"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.... | 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.... | [
"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... | 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... | [
"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
o... | 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
o... | [
"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... | [
"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
... | 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
... | [
"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 '@'
... | [
"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 cal... | 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 cal... | [
"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 bo... | [
"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 fun... | 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 fun... | [
"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 shou... | [
"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... | 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... | [
"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... | 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... | [
"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,
... | 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,
... | [
"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 = r... | 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 = r... | [
"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>'
'<De... | 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>'
'<De... | [
"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('./... | 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('./... | [
"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,
... | 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,
... | [
"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.a... | 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.a... | [
"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._item... | 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._item... | [
"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:
... | 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:
... | [
"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 no... | 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 no... | [
"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, ... | 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, ... | [
"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 as... | 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 as... | [
"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. n... | 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. n... | [
"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 ... | [
"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_C... | 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_C... | [
"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:
... | 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:
... | [
"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_credent... | 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_credent... | [
"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_... | 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_... | [
"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 t... | 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 t... | [
"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... | [
"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``.
in... | 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``.
in... | [
"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``.
... | [
"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:
... | 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:
... | [
"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 se... | 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 se... | [
"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 = sel... | 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 = sel... | [
"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): Spe... | 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): Spe... | [
"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:`~pa... | [
"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
... | 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
... | [
"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 dict... | [
"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,... | 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,... | [
"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
... | [
"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:
par... | 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:
par... | [
"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): Spe... | [
"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 inc... | 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 inc... | [
"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... | [
"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... | 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... | [
"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 == ... | 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 == ... | [
"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: Supp... | 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: Supp... | [
"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.
... | [
"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 (dic... | 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 (dic... | [
"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... | [
"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)... | 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)... | [
"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.
... | [
"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 re... | 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 re... | [
"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 cr... | [
"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 efficienc... | 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 efficienc... | [
"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:
enfo... | [
"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 i... | 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 i... | [
"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
... | [
"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":
sel... | 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":
sel... | [
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.