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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel.refresh | def refresh(self):
"""Get the latest representation of the current model."""
client = self._get_client()
endpoint = self._endpoint.format(
resource_id=self.resource_id or "",
parent_id=self.parent_id or "",
grandparent_id=self.grandparent_id or "")
res... | python | def refresh(self):
"""Get the latest representation of the current model."""
client = self._get_client()
endpoint = self._endpoint.format(
resource_id=self.resource_id or "",
parent_id=self.parent_id or "",
grandparent_id=self.grandparent_id or "")
res... | [
"def",
"refresh",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"endpoint",
"=",
"self",
".",
"_endpoint",
".",
"format",
"(",
"resource_id",
"=",
"self",
".",
"resource_id",
"or",
"\"\"",
",",
"parent_id",
"=",
"self",
".... | Get the latest representation of the current model. | [
"Get",
"the",
"latest",
"representation",
"of",
"the",
"current",
"model",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L245-L253 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel.commit | def commit(self, if_match=None, wait=True, timeout=None):
"""Apply all the changes on the current model.
:param wait: Whether to wait until the operation is completed
:param timeout: The maximum amount of time required for this
operation to be completed.
If o... | python | def commit(self, if_match=None, wait=True, timeout=None):
"""Apply all the changes on the current model.
:param wait: Whether to wait until the operation is completed
:param timeout: The maximum amount of time required for this
operation to be completed.
If o... | [
"def",
"commit",
"(",
"self",
",",
"if_match",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_changes",
":",
"LOG",
".",
"debug",
"(",
"\"No changes available for %s: %s\"",
",",
"self",
".",
"... | Apply all the changes on the current model.
:param wait: Whether to wait until the operation is completed
:param timeout: The maximum amount of time required for this
operation to be completed.
If optional :param wait: is True and timeout is None (the default),
... | [
"Apply",
"all",
"the",
"changes",
"on",
"the",
"current",
"model",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L255-L303 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel._set_fields | def _set_fields(self, fields):
"""Set or update the fields value."""
super(_BaseHNVModel, self)._set_fields(fields)
if not self.resource_ref:
endpoint = self._endpoint.format(
resource_id=self.resource_id, parent_id=self.parent_id,
grandparent_id=self.... | python | def _set_fields(self, fields):
"""Set or update the fields value."""
super(_BaseHNVModel, self)._set_fields(fields)
if not self.resource_ref:
endpoint = self._endpoint.format(
resource_id=self.resource_id, parent_id=self.parent_id,
grandparent_id=self.... | [
"def",
"_set_fields",
"(",
"self",
",",
"fields",
")",
":",
"super",
"(",
"_BaseHNVModel",
",",
"self",
")",
".",
"_set_fields",
"(",
"fields",
")",
"if",
"not",
"self",
".",
"resource_ref",
":",
"endpoint",
"=",
"self",
".",
"_endpoint",
".",
"format",
... | Set or update the fields value. | [
"Set",
"or",
"update",
"the",
"fields",
"value",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L322-L329 | train |
cloudbase/python-hnvclient | hnv/client.py | Resource.get_resource | def get_resource(self):
"""Return the associated resource."""
references = {"resource_id": None, "parent_id": None,
"grandparent_id": None}
for model_cls, regexp in self._regexp.iteritems():
match = regexp.search(self.resource_ref)
if match is not No... | python | def get_resource(self):
"""Return the associated resource."""
references = {"resource_id": None, "parent_id": None,
"grandparent_id": None}
for model_cls, regexp in self._regexp.iteritems():
match = regexp.search(self.resource_ref)
if match is not No... | [
"def",
"get_resource",
"(",
"self",
")",
":",
"references",
"=",
"{",
"\"resource_id\"",
":",
"None",
",",
"\"parent_id\"",
":",
"None",
",",
"\"grandparent_id\"",
":",
"None",
"}",
"for",
"model_cls",
",",
"regexp",
"in",
"self",
".",
"_regexp",
".",
"ite... | Return the associated resource. | [
"Return",
"the",
"associated",
"resource",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L364-L375 | train |
geophysics-ubonn/reda | lib/reda/plotters/histograms.py | _get_nr_bins | def _get_nr_bins(count):
"""depending on the number of data points, compute a best guess for an
optimal number of bins
https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width
"""
if count <= 30:
# use the square-root choice, used by Excel and Co
k = np.ceil(np.sqrt(count))
... | python | def _get_nr_bins(count):
"""depending on the number of data points, compute a best guess for an
optimal number of bins
https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width
"""
if count <= 30:
# use the square-root choice, used by Excel and Co
k = np.ceil(np.sqrt(count))
... | [
"def",
"_get_nr_bins",
"(",
"count",
")",
":",
"if",
"count",
"<=",
"30",
":",
"k",
"=",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"count",
")",
")",
"else",
":",
"k",
"=",
"np",
".",
"ceil",
"(",
"np",
".",
"log2",
"(",
"count",
")",
... | depending on the number of data points, compute a best guess for an
optimal number of bins
https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width | [
"depending",
"on",
"the",
"number",
"of",
"data",
"points",
"compute",
"a",
"best",
"guess",
"for",
"an",
"optimal",
"number",
"of",
"bins"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/histograms.py#L14-L26 | train |
geophysics-ubonn/reda | lib/reda/plotters/histograms.py | plot_histograms | def plot_histograms(ertobj, keys, **kwargs):
"""Generate histograms for one or more keys in the given container.
Parameters
----------
ertobj : container instance or :class:`pandas.DataFrame`
data object which contains the data.
keys : str or list of strings
which keys (column names... | python | def plot_histograms(ertobj, keys, **kwargs):
"""Generate histograms for one or more keys in the given container.
Parameters
----------
ertobj : container instance or :class:`pandas.DataFrame`
data object which contains the data.
keys : str or list of strings
which keys (column names... | [
"def",
"plot_histograms",
"(",
"ertobj",
",",
"keys",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"ertobj",
",",
"pd",
".",
"DataFrame",
")",
":",
"df",
"=",
"ertobj",
"else",
":",
"df",
"=",
"ertobj",
".",
"data",
"if",
"df",
".",
"sha... | Generate histograms for one or more keys in the given container.
Parameters
----------
ertobj : container instance or :class:`pandas.DataFrame`
data object which contains the data.
keys : str or list of strings
which keys (column names) to plot
merge : bool, optional
if True... | [
"Generate",
"histograms",
"for",
"one",
"or",
"more",
"keys",
"in",
"the",
"given",
"container",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/histograms.py#L29-L130 | train |
geophysics-ubonn/reda | lib/reda/plotters/histograms.py | plot_histograms_extra_dims | def plot_histograms_extra_dims(dataobj, keys, **kwargs):
"""Produce histograms grouped by the extra dimensions.
Extra dimensions are:
* timesteps
* frequency
Parameters
----------
dataobj : :py:class:`pandas.DataFrame` or reda container
The data container/data frame which holds th... | python | def plot_histograms_extra_dims(dataobj, keys, **kwargs):
"""Produce histograms grouped by the extra dimensions.
Extra dimensions are:
* timesteps
* frequency
Parameters
----------
dataobj : :py:class:`pandas.DataFrame` or reda container
The data container/data frame which holds th... | [
"def",
"plot_histograms_extra_dims",
"(",
"dataobj",
",",
"keys",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"dataobj",
",",
"pd",
".",
"DataFrame",
")",
":",
"df_raw",
"=",
"dataobj",
"else",
":",
"df_raw",
"=",
"dataobj",
".",
"data",
"if"... | Produce histograms grouped by the extra dimensions.
Extra dimensions are:
* timesteps
* frequency
Parameters
----------
dataobj : :py:class:`pandas.DataFrame` or reda container
The data container/data frame which holds the data
keys: list|tuple|iterable
The keys (columns... | [
"Produce",
"histograms",
"grouped",
"by",
"the",
"extra",
"dimensions",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/histograms.py#L133-L252 | train |
openvax/mhcnames | mhcnames/parsing_helpers.py | parse_substring | def parse_substring(allele, pred, max_len=None):
"""
Extract substring of letters for which predicate is True
"""
result = ""
pos = 0
if max_len is None:
max_len = len(allele)
else:
max_len = min(max_len, len(allele))
while pos < max_len and pred(allele[pos]):
res... | python | def parse_substring(allele, pred, max_len=None):
"""
Extract substring of letters for which predicate is True
"""
result = ""
pos = 0
if max_len is None:
max_len = len(allele)
else:
max_len = min(max_len, len(allele))
while pos < max_len and pred(allele[pos]):
res... | [
"def",
"parse_substring",
"(",
"allele",
",",
"pred",
",",
"max_len",
"=",
"None",
")",
":",
"result",
"=",
"\"\"",
"pos",
"=",
"0",
"if",
"max_len",
"is",
"None",
":",
"max_len",
"=",
"len",
"(",
"allele",
")",
"else",
":",
"max_len",
"=",
"min",
... | Extract substring of letters for which predicate is True | [
"Extract",
"substring",
"of",
"letters",
"for",
"which",
"predicate",
"is",
"True"
] | 71694b9d620db68ceee44da1b8422ff436f15bd3 | https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/parsing_helpers.py#L18-L31 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.fetch | def fetch(self):
""" just pull files from PG
"""
if not self.local_path:
self.make_local_path()
fetcher = BookFetcher(self)
fetcher.fetch() | python | def fetch(self):
""" just pull files from PG
"""
if not self.local_path:
self.make_local_path()
fetcher = BookFetcher(self)
fetcher.fetch() | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"local_path",
":",
"self",
".",
"make_local_path",
"(",
")",
"fetcher",
"=",
"BookFetcher",
"(",
"self",
")",
"fetcher",
".",
"fetch",
"(",
")"
] | just pull files from PG | [
"just",
"pull",
"files",
"from",
"PG"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L174-L180 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.make | def make(self):
""" turn fetched files into a local repo, make auxiliary files
"""
logger.debug("preparing to add all git files")
num_added = self.local_repo.add_all_files()
if num_added:
self.local_repo.commit("Initial import from Project Gutenberg")
file_ha... | python | def make(self):
""" turn fetched files into a local repo, make auxiliary files
"""
logger.debug("preparing to add all git files")
num_added = self.local_repo.add_all_files()
if num_added:
self.local_repo.commit("Initial import from Project Gutenberg")
file_ha... | [
"def",
"make",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"preparing to add all git files\"",
")",
"num_added",
"=",
"self",
".",
"local_repo",
".",
"add_all_files",
"(",
")",
"if",
"num_added",
":",
"self",
".",
"local_repo",
".",
"commit",
"(",
... | turn fetched files into a local repo, make auxiliary files | [
"turn",
"fetched",
"files",
"into",
"a",
"local",
"repo",
"make",
"auxiliary",
"files"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L193-L208 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.push | def push(self):
""" create a github repo and push the local repo into it
"""
self.github_repo.create_and_push()
self._repo = self.github_repo.repo
return self._repo | python | def push(self):
""" create a github repo and push the local repo into it
"""
self.github_repo.create_and_push()
self._repo = self.github_repo.repo
return self._repo | [
"def",
"push",
"(",
"self",
")",
":",
"self",
".",
"github_repo",
".",
"create_and_push",
"(",
")",
"self",
".",
"_repo",
"=",
"self",
".",
"github_repo",
".",
"repo",
"return",
"self",
".",
"_repo"
] | create a github repo and push the local repo into it | [
"create",
"a",
"github",
"repo",
"and",
"push",
"the",
"local",
"repo",
"into",
"it"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L213-L218 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.tag | def tag(self, version='bump', message=''):
""" tag and commit
"""
self.clone_from_github()
self.github_repo.tag(version, message=message) | python | def tag(self, version='bump', message=''):
""" tag and commit
"""
self.clone_from_github()
self.github_repo.tag(version, message=message) | [
"def",
"tag",
"(",
"self",
",",
"version",
"=",
"'bump'",
",",
"message",
"=",
"''",
")",
":",
"self",
".",
"clone_from_github",
"(",
")",
"self",
".",
"github_repo",
".",
"tag",
"(",
"version",
",",
"message",
"=",
"message",
")"
] | tag and commit | [
"tag",
"and",
"commit"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L225-L229 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.format_title | def format_title(self):
def asciify(_title):
_title = unicodedata.normalize('NFD', unicode(_title))
ascii = True
out = []
ok = u"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM- ',"
for ch in _title:
if ch in ok:
... | python | def format_title(self):
def asciify(_title):
_title = unicodedata.normalize('NFD', unicode(_title))
ascii = True
out = []
ok = u"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM- ',"
for ch in _title:
if ch in ok:
... | [
"def",
"format_title",
"(",
"self",
")",
":",
"def",
"asciify",
"(",
"_title",
")",
":",
"_title",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
",",
"unicode",
"(",
"_title",
")",
")",
"ascii",
"=",
"True",
"out",
"=",
"[",
"]",
"ok",
"=",
"... | Takes a string and sanitizes it for Github's url name format | [
"Takes",
"a",
"string",
"and",
"sanitizes",
"it",
"for",
"Github",
"s",
"url",
"name",
"format"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L266-L296 | train |
rfverbruggen/rachiopy | rachiopy/__init__.py | Rachio._request | def _request(self, path, method, body=None):
"""Make a request from the API."""
url = '/'.join([_SERVER, path])
(resp, content) = _HTTP.request(url, method,
headers=self._headers, body=body)
content_type = resp.get('content-type')
if conte... | python | def _request(self, path, method, body=None):
"""Make a request from the API."""
url = '/'.join([_SERVER, path])
(resp, content) = _HTTP.request(url, method,
headers=self._headers, body=body)
content_type = resp.get('content-type')
if conte... | [
"def",
"_request",
"(",
"self",
",",
"path",
",",
"method",
",",
"body",
"=",
"None",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"_SERVER",
",",
"path",
"]",
")",
"(",
"resp",
",",
"content",
")",
"=",
"_HTTP",
".",
"request",
"(",
"ur... | Make a request from the API. | [
"Make",
"a",
"request",
"from",
"the",
"API",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L32-L42 | train |
rfverbruggen/rachiopy | rachiopy/__init__.py | Rachio.put | def put(self, path, payload):
"""Make a PUT request from the API."""
body = json.dumps(payload)
return self._request(path, 'PUT', body) | python | def put(self, path, payload):
"""Make a PUT request from the API."""
body = json.dumps(payload)
return self._request(path, 'PUT', body) | [
"def",
"put",
"(",
"self",
",",
"path",
",",
"payload",
")",
":",
"body",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"'PUT'",
",",
"body",
")"
] | Make a PUT request from the API. | [
"Make",
"a",
"PUT",
"request",
"from",
"the",
"API",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L52-L55 | train |
rfverbruggen/rachiopy | rachiopy/__init__.py | Rachio.post | def post(self, path, payload):
"""Make a POST request from the API."""
body = json.dumps(payload)
return self._request(path, 'POST', body) | python | def post(self, path, payload):
"""Make a POST request from the API."""
body = json.dumps(payload)
return self._request(path, 'POST', body) | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"payload",
")",
":",
"body",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"'POST'",
",",
"body",
")"
] | Make a POST request from the API. | [
"Make",
"a",
"POST",
"request",
"from",
"the",
"API",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L57-L60 | train |
dstanek/snake-guice | snakeguice/injector.py | Injector.create_child | def create_child(self, modules):
"""Create a new injector that inherits the state from this injector.
All bindings are inherited. In the future this may become closer to
child injectors on google-guice.
"""
binder = self._binder.create_child()
return Injector(modules, bi... | python | def create_child(self, modules):
"""Create a new injector that inherits the state from this injector.
All bindings are inherited. In the future this may become closer to
child injectors on google-guice.
"""
binder = self._binder.create_child()
return Injector(modules, bi... | [
"def",
"create_child",
"(",
"self",
",",
"modules",
")",
":",
"binder",
"=",
"self",
".",
"_binder",
".",
"create_child",
"(",
")",
"return",
"Injector",
"(",
"modules",
",",
"binder",
"=",
"binder",
",",
"stage",
"=",
"self",
".",
"_stage",
")"
] | Create a new injector that inherits the state from this injector.
All bindings are inherited. In the future this may become closer to
child injectors on google-guice. | [
"Create",
"a",
"new",
"injector",
"that",
"inherits",
"the",
"state",
"from",
"this",
"injector",
"."
] | d20b62de3ee31e84119c801756398c35ed803fb3 | https://github.com/dstanek/snake-guice/blob/d20b62de3ee31e84119c801756398c35ed803fb3/snakeguice/injector.py#L92-L99 | train |
spotify/gordon-gcp | src/gordon_gcp/schema/validate.py | MessageValidator.validate | def validate(self, message, schema_name):
"""Validate a message given a schema.
Args:
message (dict): Loaded JSON of pulled message from Google
PubSub.
schema_name (str): Name of schema to validate ``message``
against. ``schema_name`` will be used... | python | def validate(self, message, schema_name):
"""Validate a message given a schema.
Args:
message (dict): Loaded JSON of pulled message from Google
PubSub.
schema_name (str): Name of schema to validate ``message``
against. ``schema_name`` will be used... | [
"def",
"validate",
"(",
"self",
",",
"message",
",",
"schema_name",
")",
":",
"err",
"=",
"None",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"message",
",",
"self",
".",
"schemas",
"[",
"schema_name",
"]",
")",
"except",
"KeyError",
":",
"msg",
"=... | Validate a message given a schema.
Args:
message (dict): Loaded JSON of pulled message from Google
PubSub.
schema_name (str): Name of schema to validate ``message``
against. ``schema_name`` will be used to look up
schema from :py:attr:`.Me... | [
"Validate",
"a",
"message",
"given",
"a",
"schema",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/schema/validate.py#L111-L141 | train |
fabianvf/schema-transformer | schema_transformer/helpers.py | compose | def compose(*functions):
''' evaluates functions from right to left.
>>> add = lambda x, y: x + y
>>> add3 = lambda x: x + 3
>>> divide2 = lambda x: x/2
>>> subtract4 = lambda x: x - 4
>>> subtract1 = compose(add3, subtract4)
>>> subtract1(1)
0
>>> co... | python | def compose(*functions):
''' evaluates functions from right to left.
>>> add = lambda x, y: x + y
>>> add3 = lambda x: x + 3
>>> divide2 = lambda x: x/2
>>> subtract4 = lambda x: x - 4
>>> subtract1 = compose(add3, subtract4)
>>> subtract1(1)
0
>>> co... | [
"def",
"compose",
"(",
"*",
"functions",
")",
":",
"def",
"inner",
"(",
"func1",
",",
"func2",
")",
":",
"return",
"lambda",
"*",
"x",
",",
"**",
"y",
":",
"func1",
"(",
"func2",
"(",
"*",
"x",
",",
"**",
"y",
")",
")",
"return",
"functools",
"... | evaluates functions from right to left.
>>> add = lambda x, y: x + y
>>> add3 = lambda x: x + 3
>>> divide2 = lambda x: x/2
>>> subtract4 = lambda x: x - 4
>>> subtract1 = compose(add3, subtract4)
>>> subtract1(1)
0
>>> compose(subtract1, add3)(4)
... | [
"evaluates",
"functions",
"from",
"right",
"to",
"left",
"."
] | 1ddce4f7615de71593a1adabee4dbfc4ae086433 | https://github.com/fabianvf/schema-transformer/blob/1ddce4f7615de71593a1adabee4dbfc4ae086433/schema_transformer/helpers.py#L19-L40 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | validate_instance | def validate_instance(instance):
"""Validating if the instance should be logged, or is excluded"""
excludes = settings.AUTOMATED_LOGGING['exclude']['model']
for excluded in excludes:
if (excluded in [instance._meta.app_label.lower(),
instance.__class__.__name__.lower()] or
... | python | def validate_instance(instance):
"""Validating if the instance should be logged, or is excluded"""
excludes = settings.AUTOMATED_LOGGING['exclude']['model']
for excluded in excludes:
if (excluded in [instance._meta.app_label.lower(),
instance.__class__.__name__.lower()] or
... | [
"def",
"validate_instance",
"(",
"instance",
")",
":",
"excludes",
"=",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'exclude'",
"]",
"[",
"'model'",
"]",
"for",
"excluded",
"in",
"excludes",
":",
"if",
"(",
"excluded",
"in",
"[",
"instance",
".",
"_meta",
... | Validating if the instance should be logged, or is excluded | [
"Validating",
"if",
"the",
"instance",
"should",
"be",
"logged",
"or",
"is",
"excluded"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L23-L33 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | get_current_user | def get_current_user():
"""Get current user object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'current_user'):
user = thread_local.current_user
if isinstance(user, AnonymousUser):
user = None
else:
user = None
... | python | def get_current_user():
"""Get current user object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'current_user'):
user = thread_local.current_user
if isinstance(user, AnonymousUser):
user = None
else:
user = None
... | [
"def",
"get_current_user",
"(",
")",
":",
"thread_local",
"=",
"AutomatedLoggingMiddleware",
".",
"thread_local",
"if",
"hasattr",
"(",
"thread_local",
",",
"'current_user'",
")",
":",
"user",
"=",
"thread_local",
".",
"current_user",
"if",
"isinstance",
"(",
"use... | Get current user object from middleware | [
"Get",
"current",
"user",
"object",
"from",
"middleware"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L36-L46 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | get_current_environ | def get_current_environ():
"""Get current application and path object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'request_uri'):
request_uri = thread_local.request_uri
else:
request_uri = None
if hasattr(thread_local, 'applicat... | python | def get_current_environ():
"""Get current application and path object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'request_uri'):
request_uri = thread_local.request_uri
else:
request_uri = None
if hasattr(thread_local, 'applicat... | [
"def",
"get_current_environ",
"(",
")",
":",
"thread_local",
"=",
"AutomatedLoggingMiddleware",
".",
"thread_local",
"if",
"hasattr",
"(",
"thread_local",
",",
"'request_uri'",
")",
":",
"request_uri",
"=",
"thread_local",
".",
"request_uri",
"else",
":",
"request_u... | Get current application and path object from middleware | [
"Get",
"current",
"application",
"and",
"path",
"object",
"from",
"middleware"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L49-L73 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | processor | def processor(status, sender, instance, updated=None, addition=''):
"""
This is the standard logging processor.
This is used to send the log to the handler and to other systems.
"""
logger = logging.getLogger(__name__)
if validate_instance(instance):
user = get_current_user()
ap... | python | def processor(status, sender, instance, updated=None, addition=''):
"""
This is the standard logging processor.
This is used to send the log to the handler and to other systems.
"""
logger = logging.getLogger(__name__)
if validate_instance(instance):
user = get_current_user()
ap... | [
"def",
"processor",
"(",
"status",
",",
"sender",
",",
"instance",
",",
"updated",
"=",
"None",
",",
"addition",
"=",
"''",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"validate_instance",
"(",
"instance",
")",
":",
... | This is the standard logging processor.
This is used to send the log to the handler and to other systems. | [
"This",
"is",
"the",
"standard",
"logging",
"processor",
"."
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L76-L106 | train |
bunchesofdonald/django-hermes | hermes/models.py | Category.parents | def parents(self):
""" Returns a list of all the current category's parents."""
parents = []
if self.parent is None:
return []
category = self
while category.parent is not None:
parents.append(category.parent)
category = category.parent
... | python | def parents(self):
""" Returns a list of all the current category's parents."""
parents = []
if self.parent is None:
return []
category = self
while category.parent is not None:
parents.append(category.parent)
category = category.parent
... | [
"def",
"parents",
"(",
"self",
")",
":",
"parents",
"=",
"[",
"]",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"[",
"]",
"category",
"=",
"self",
"while",
"category",
".",
"parent",
"is",
"not",
"None",
":",
"parents",
".",
"append",
... | Returns a list of all the current category's parents. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"current",
"category",
"s",
"parents",
"."
] | ff5395a7b5debfd0756aab43db61f7a6cfa06aea | https://github.com/bunchesofdonald/django-hermes/blob/ff5395a7b5debfd0756aab43db61f7a6cfa06aea/hermes/models.py#L72-L84 | train |
bunchesofdonald/django-hermes | hermes/models.py | Category.root_parent | def root_parent(self, category=None):
""" Returns the topmost parent of the current category. """
return next(filter(lambda c: c.is_root, self.hierarchy())) | python | def root_parent(self, category=None):
""" Returns the topmost parent of the current category. """
return next(filter(lambda c: c.is_root, self.hierarchy())) | [
"def",
"root_parent",
"(",
"self",
",",
"category",
"=",
"None",
")",
":",
"return",
"next",
"(",
"filter",
"(",
"lambda",
"c",
":",
"c",
".",
"is_root",
",",
"self",
".",
"hierarchy",
"(",
")",
")",
")"
] | Returns the topmost parent of the current category. | [
"Returns",
"the",
"topmost",
"parent",
"of",
"the",
"current",
"category",
"."
] | ff5395a7b5debfd0756aab43db61f7a6cfa06aea | https://github.com/bunchesofdonald/django-hermes/blob/ff5395a7b5debfd0756aab43db61f7a6cfa06aea/hermes/models.py#L89-L91 | train |
rohankapoorcom/zm-py | zoneminder/run_state.py | RunState.active | def active(self) -> bool:
"""Indicate if this RunState is currently active."""
states = self._client.get_state(self._state_url)['states']
for state in states:
state = state['State']
if int(state['Id']) == self._state_id:
# yes, the ZM API uses the *string*... | python | def active(self) -> bool:
"""Indicate if this RunState is currently active."""
states = self._client.get_state(self._state_url)['states']
for state in states:
state = state['State']
if int(state['Id']) == self._state_id:
# yes, the ZM API uses the *string*... | [
"def",
"active",
"(",
"self",
")",
"->",
"bool",
":",
"states",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"self",
".",
"_state_url",
")",
"[",
"'states'",
"]",
"for",
"state",
"in",
"states",
":",
"state",
"=",
"state",
"[",
"'State'",
"]",... | Indicate if this RunState is currently active. | [
"Indicate",
"if",
"this",
"RunState",
"is",
"currently",
"active",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/run_state.py#L26-L34 | train |
mgk/urwid_timed_progress | urwid_timed_progress/__init__.py | to_reasonable_unit | def to_reasonable_unit(value, units, round_digits=2):
"""Convert a value to the most reasonable unit.
The most reasonable unit is roughly the one with the smallest exponent
absolute value when written in scientific notation. For example
`1.5` is more reasonable that `.0015` and `22` is more reasonable
... | python | def to_reasonable_unit(value, units, round_digits=2):
"""Convert a value to the most reasonable unit.
The most reasonable unit is roughly the one with the smallest exponent
absolute value when written in scientific notation. For example
`1.5` is more reasonable that `.0015` and `22` is more reasonable
... | [
"def",
"to_reasonable_unit",
"(",
"value",
",",
"units",
",",
"round_digits",
"=",
"2",
")",
":",
"def",
"to_unit",
"(",
"unit",
")",
":",
"return",
"float",
"(",
"value",
")",
"/",
"unit",
"[",
"1",
"]",
"exponents",
"=",
"[",
"abs",
"(",
"Decimal",... | Convert a value to the most reasonable unit.
The most reasonable unit is roughly the one with the smallest exponent
absolute value when written in scientific notation. For example
`1.5` is more reasonable that `.0015` and `22` is more reasonable
than `22000`. There is a bias towards numbers > 1, so `3.... | [
"Convert",
"a",
"value",
"to",
"the",
"most",
"reasonable",
"unit",
"."
] | b7292e78a58f35f285736988c48e815e71fa2060 | https://github.com/mgk/urwid_timed_progress/blob/b7292e78a58f35f285736988c48e815e71fa2060/urwid_timed_progress/__init__.py#L170-L185 | train |
mgk/urwid_timed_progress | urwid_timed_progress/__init__.py | FancyProgressBar.get_text | def get_text(self):
"""Return extended progress bar text"""
done_units = to_reasonable_unit(self.done, self.units)
current = round(self.current / done_units['multiplier'], 2)
percent = int(self.current * 100 / self.done)
return '{0:.2f} of {1:.2f} {2} ({3}%)'.format(current,
... | python | def get_text(self):
"""Return extended progress bar text"""
done_units = to_reasonable_unit(self.done, self.units)
current = round(self.current / done_units['multiplier'], 2)
percent = int(self.current * 100 / self.done)
return '{0:.2f} of {1:.2f} {2} ({3}%)'.format(current,
... | [
"def",
"get_text",
"(",
"self",
")",
":",
"done_units",
"=",
"to_reasonable_unit",
"(",
"self",
".",
"done",
",",
"self",
".",
"units",
")",
"current",
"=",
"round",
"(",
"self",
".",
"current",
"/",
"done_units",
"[",
"'multiplier'",
"]",
",",
"2",
")... | Return extended progress bar text | [
"Return",
"extended",
"progress",
"bar",
"text"
] | b7292e78a58f35f285736988c48e815e71fa2060 | https://github.com/mgk/urwid_timed_progress/blob/b7292e78a58f35f285736988c48e815e71fa2060/urwid_timed_progress/__init__.py#L19-L27 | train |
mgk/urwid_timed_progress | urwid_timed_progress/__init__.py | TimedProgressBar.add_progress | def add_progress(self, delta, done=None):
"""Add to the current progress amount
Add `delta` to the current progress amount. This also updates
:attr:`rate` and :attr:`remaining_time`.
The :attr:`current` progress is never less than 0 or greater
than :attr:`done`.
:param... | python | def add_progress(self, delta, done=None):
"""Add to the current progress amount
Add `delta` to the current progress amount. This also updates
:attr:`rate` and :attr:`remaining_time`.
The :attr:`current` progress is never less than 0 or greater
than :attr:`done`.
:param... | [
"def",
"add_progress",
"(",
"self",
",",
"delta",
",",
"done",
"=",
"None",
")",
":",
"if",
"done",
"is",
"not",
"None",
":",
"self",
".",
"done",
"=",
"done",
"self",
".",
"bar",
".",
"current",
"=",
"max",
"(",
"min",
"(",
"self",
".",
"done",
... | Add to the current progress amount
Add `delta` to the current progress amount. This also updates
:attr:`rate` and :attr:`remaining_time`.
The :attr:`current` progress is never less than 0 or greater
than :attr:`done`.
:param delta: amount to add, may be negative
:param... | [
"Add",
"to",
"the",
"current",
"progress",
"amount"
] | b7292e78a58f35f285736988c48e815e71fa2060 | https://github.com/mgk/urwid_timed_progress/blob/b7292e78a58f35f285736988c48e815e71fa2060/urwid_timed_progress/__init__.py#L90-L107 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.valid_token_set | async def valid_token_set(self):
"""Check for validity of token, and refresh if none or expired."""
is_valid = False
if self._auth_client.token:
# Account for a token near expiration
now = datetime.datetime.utcnow()
skew = datetime.timedelta(seconds=60)
... | python | async def valid_token_set(self):
"""Check for validity of token, and refresh if none or expired."""
is_valid = False
if self._auth_client.token:
# Account for a token near expiration
now = datetime.datetime.utcnow()
skew = datetime.timedelta(seconds=60)
... | [
"async",
"def",
"valid_token_set",
"(",
"self",
")",
":",
"is_valid",
"=",
"False",
"if",
"self",
".",
"_auth_client",
".",
"token",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"skew",
"=",
"datetime",
".",
"timedelta",
"(",
... | Check for validity of token, and refresh if none or expired. | [
"Check",
"for",
"validity",
"of",
"token",
"and",
"refresh",
"if",
"none",
"or",
"expired",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L72-L82 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.request | async def request(self, method, url, params=None, headers=None,
data=None, json=None, token_refresh_attempts=2,
**kwargs):
"""Make an asynchronous HTTP request.
Args:
method (str): HTTP method to use for the request.
url (str): URL to ... | python | async def request(self, method, url, params=None, headers=None,
data=None, json=None, token_refresh_attempts=2,
**kwargs):
"""Make an asynchronous HTTP request.
Args:
method (str): HTTP method to use for the request.
url (str): URL to ... | [
"async",
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"token_refresh_attempts",
"=",
"2",
",",
"**",
"kwargs",
")",
":",
... | Make an asynchronous HTTP request.
Args:
method (str): HTTP method to use for the request.
url (str): URL to be requested.
params (dict): (optional) Query parameters for the request.
Defaults to ``None``.
headers (dict): (optional) HTTP headers to... | [
"Make",
"an",
"asynchronous",
"HTTP",
"request",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L84-L189 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.get_json | async def get_json(self, url, json_callback=None, **kwargs):
"""Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional ... | python | async def get_json(self, url, json_callback=None, **kwargs):
"""Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional ... | [
"async",
"def",
"get_json",
"(",
"self",
",",
"url",
",",
"json_callback",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"json_callback",
":",
"json_callback",
"=",
"json",
".",
"loads",
"response",
"=",
"await",
"self",
".",
"request",
"(",
... | Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional arguments to pass through to the
request.
Return... | [
"Get",
"a",
"URL",
"and",
"return",
"its",
"JSON",
"response",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L191-L206 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.get_all | async def get_all(self, url, params=None):
"""Aggregate data from all pages of an API query.
Args:
url (str): Google API endpoint URL.
params (dict): (optional) URL query parameters.
Returns:
list: Parsed JSON query response results.
"""
if n... | python | async def get_all(self, url, params=None):
"""Aggregate data from all pages of an API query.
Args:
url (str): Google API endpoint URL.
params (dict): (optional) URL query parameters.
Returns:
list: Parsed JSON query response results.
"""
if n... | [
"async",
"def",
"get_all",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"items",
"=",
"[",
"]",
"next_page_token",
"=",
"None",
"while",
"True",
":",
"if",
"next_page_token",
":",... | Aggregate data from all pages of an API query.
Args:
url (str): Google API endpoint URL.
params (dict): (optional) URL query parameters.
Returns:
list: Parsed JSON query response results. | [
"Aggregate",
"data",
"from",
"all",
"pages",
"of",
"an",
"API",
"query",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L208-L232 | train |
gitenberg-dev/gitberg | gitenberg/config.py | check_config | def check_config():
""" Report if there is an existing config file
"""
configfile = ConfigFile()
global data
if data.keys() > 0:
# FIXME: run a better check of this file
print("gitberg config file exists")
print("\twould you like to edit your gitberg config file?")
else:
... | python | def check_config():
""" Report if there is an existing config file
"""
configfile = ConfigFile()
global data
if data.keys() > 0:
# FIXME: run a better check of this file
print("gitberg config file exists")
print("\twould you like to edit your gitberg config file?")
else:
... | [
"def",
"check_config",
"(",
")",
":",
"configfile",
"=",
"ConfigFile",
"(",
")",
"global",
"data",
"if",
"data",
".",
"keys",
"(",
")",
">",
"0",
":",
"print",
"(",
"\"gitberg config file exists\"",
")",
"print",
"(",
"\"\\twould you like to edit your gitberg co... | Report if there is an existing config file | [
"Report",
"if",
"there",
"is",
"an",
"existing",
"config",
"file"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/config.py#L94-L122 | train |
fabaff/python-luftdaten | example.py | main | async def main():
"""Sample code to retrieve the data."""
async with aiohttp.ClientSession() as session:
data = Luftdaten(SENSOR_ID, loop, session)
await data.get_data()
if not await data.validate_sensor():
print("Station is not available:", data.sensor_id)
retur... | python | async def main():
"""Sample code to retrieve the data."""
async with aiohttp.ClientSession() as session:
data = Luftdaten(SENSOR_ID, loop, session)
await data.get_data()
if not await data.validate_sensor():
print("Station is not available:", data.sensor_id)
retur... | [
"async",
"def",
"main",
"(",
")",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"data",
"=",
"Luftdaten",
"(",
"SENSOR_ID",
",",
"loop",
",",
"session",
")",
"await",
"data",
".",
"get_data",
"(",
")",
"if",
"... | Sample code to retrieve the data. | [
"Sample",
"code",
"to",
"retrieve",
"the",
"data",
"."
] | 30be973257fccb19baa8dbd55206da00f62dc81c | https://github.com/fabaff/python-luftdaten/blob/30be973257fccb19baa8dbd55206da00f62dc81c/example.py#L11-L26 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/gce.py | GCEClient.list_instances | async def list_instances(self,
project,
page_size=100,
instance_filter=None):
"""Fetch all instances in a GCE project.
You can find the endpoint documentation `here <https://cloud.
google.com/compute/docs/ref... | python | async def list_instances(self,
project,
page_size=100,
instance_filter=None):
"""Fetch all instances in a GCE project.
You can find the endpoint documentation `here <https://cloud.
google.com/compute/docs/ref... | [
"async",
"def",
"list_instances",
"(",
"self",
",",
"project",
",",
"page_size",
"=",
"100",
",",
"instance_filter",
"=",
"None",
")",
":",
"url",
"=",
"(",
"f'{self.BASE_URL}{self.api_version}/projects/{project}'",
"'/aggregated/instances'",
")",
"params",
"=",
"{"... | Fetch all instances in a GCE project.
You can find the endpoint documentation `here <https://cloud.
google.com/compute/docs/reference/latest/instances/
aggregatedList>`__.
Args:
project (str): unique, user-provided project ID.
page_size (int): hint for the clien... | [
"Fetch",
"all",
"instances",
"in",
"a",
"GCE",
"project",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/gce.py#L89-L118 | train |
openvax/mhcnames | mhcnames/class2.py | infer_alpha_chain | def infer_alpha_chain(beta):
"""
Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain.
"""
if beta.gene.startswith("DRB"):
return AlleleName(species="HLA", gene="DRA1", allele_family="01", allele_code="01")
elif beta.gene.startswith("DPB"):
... | python | def infer_alpha_chain(beta):
"""
Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain.
"""
if beta.gene.startswith("DRB"):
return AlleleName(species="HLA", gene="DRA1", allele_family="01", allele_code="01")
elif beta.gene.startswith("DPB"):
... | [
"def",
"infer_alpha_chain",
"(",
"beta",
")",
":",
"if",
"beta",
".",
"gene",
".",
"startswith",
"(",
"\"DRB\"",
")",
":",
"return",
"AlleleName",
"(",
"species",
"=",
"\"HLA\"",
",",
"gene",
"=",
"\"DRA1\"",
",",
"allele_family",
"=",
"\"01\"",
",",
"al... | Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain. | [
"Given",
"a",
"parsed",
"beta",
"chain",
"of",
"a",
"class",
"II",
"MHC",
"infer",
"the",
"most",
"frequent",
"corresponding",
"alpha",
"chain",
"."
] | 71694b9d620db68ceee44da1b8422ff436f15bd3 | https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/class2.py#L21-L39 | train |
ministryofjustice/django-zendesk-tickets | zendesk_tickets/client.py | create_ticket | def create_ticket(subject, tags, ticket_body, requester_email=None,
custom_fields=[]):
""" Create a new Zendesk ticket """
payload = {'ticket': {
'subject': subject,
'comment': {
'body': ticket_body
},
'group_id': settings.ZENDESK_GROUP_ID,
... | python | def create_ticket(subject, tags, ticket_body, requester_email=None,
custom_fields=[]):
""" Create a new Zendesk ticket """
payload = {'ticket': {
'subject': subject,
'comment': {
'body': ticket_body
},
'group_id': settings.ZENDESK_GROUP_ID,
... | [
"def",
"create_ticket",
"(",
"subject",
",",
"tags",
",",
"ticket_body",
",",
"requester_email",
"=",
"None",
",",
"custom_fields",
"=",
"[",
"]",
")",
":",
"payload",
"=",
"{",
"'ticket'",
":",
"{",
"'subject'",
":",
"subject",
",",
"'comment'",
":",
"{... | Create a new Zendesk ticket | [
"Create",
"a",
"new",
"Zendesk",
"ticket"
] | 8c1332b5536dc1cf967b612aad5d07e02439d280 | https://github.com/ministryofjustice/django-zendesk-tickets/blob/8c1332b5536dc1cf967b612aad5d07e02439d280/zendesk_tickets/client.py#L19-L45 | train |
ponty/psidialogs | psidialogs/__init__.py | message | def message(message, title=''):
"""
Display a message
:ref:`screenshots<message>`
:param message: message to be displayed.
:param title: window title
:rtype: None
"""
return backend_api.opendialog("message", dict(message=message, title=title)) | python | def message(message, title=''):
"""
Display a message
:ref:`screenshots<message>`
:param message: message to be displayed.
:param title: window title
:rtype: None
"""
return backend_api.opendialog("message", dict(message=message, title=title)) | [
"def",
"message",
"(",
"message",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"message\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"title",
"=",
"title",
")",
")"
] | Display a message
:ref:`screenshots<message>`
:param message: message to be displayed.
:param title: window title
:rtype: None | [
"Display",
"a",
"message"
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L9-L19 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_file | def ask_file(message='Select file for open.', default='', title='', save=False):
"""
A dialog to get a file name.
The "default" argument specifies a file path.
save=False -> file for loading
save=True -> file for saving
Return the file path that the user entered, or None if he cancels the oper... | python | def ask_file(message='Select file for open.', default='', title='', save=False):
"""
A dialog to get a file name.
The "default" argument specifies a file path.
save=False -> file for loading
save=True -> file for saving
Return the file path that the user entered, or None if he cancels the oper... | [
"def",
"ask_file",
"(",
"message",
"=",
"'Select file for open.'",
",",
"default",
"=",
"''",
",",
"title",
"=",
"''",
",",
"save",
"=",
"False",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_file\"",
",",
"dict",
"(",
"message",
"=",
... | A dialog to get a file name.
The "default" argument specifies a file path.
save=False -> file for loading
save=True -> file for saving
Return the file path that the user entered, or None if he cancels the operation.
:param message: message to be displayed.
:param save: bool 0 -> load , 1 -> s... | [
"A",
"dialog",
"to",
"get",
"a",
"file",
"name",
".",
"The",
"default",
"argument",
"specifies",
"a",
"file",
"path",
"."
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L82-L98 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_folder | def ask_folder(message='Select folder.', default='', title=''):
"""
A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.... | python | def ask_folder(message='Select folder.', default='', title=''):
"""
A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.... | [
"def",
"ask_folder",
"(",
"message",
"=",
"'Select folder.'",
",",
"default",
"=",
"''",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_folder\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"default",
"=",... | A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.
:param message: message to be displayed.
:param title: window titl... | [
"A",
"dialog",
"to",
"get",
"a",
"directory",
"name",
".",
"Returns",
"the",
"name",
"of",
"a",
"directory",
"or",
"None",
"if",
"user",
"chose",
"to",
"cancel",
".",
"If",
"the",
"default",
"argument",
"specifies",
"a",
"directory",
"name",
"and",
"that... | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L101-L113 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_ok_cancel | def ask_ok_cancel(message='', default=0, title=''):
"""
Display a message with choices of OK and Cancel.
returned value:
OK -> True
Cancel -> False
:ref:`screenshots<ask_ok_cancel>`
:param message: message to be displayed.
:param title: window title
:param default:... | python | def ask_ok_cancel(message='', default=0, title=''):
"""
Display a message with choices of OK and Cancel.
returned value:
OK -> True
Cancel -> False
:ref:`screenshots<ask_ok_cancel>`
:param message: message to be displayed.
:param title: window title
:param default:... | [
"def",
"ask_ok_cancel",
"(",
"message",
"=",
"''",
",",
"default",
"=",
"0",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_ok_cancel\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"default",
"=",
"defau... | Display a message with choices of OK and Cancel.
returned value:
OK -> True
Cancel -> False
:ref:`screenshots<ask_ok_cancel>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (OK=True, Cancel=False)
:rtype: b... | [
"Display",
"a",
"message",
"with",
"choices",
"of",
"OK",
"and",
"Cancel",
"."
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L151-L166 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_yes_no | def ask_yes_no(message='', default=0, title=''):
"""
Display a message with choices of Yes and No.
returned value:
Yes -> True
No -> False
:ref:`screenshots<ask_yes_no>`
:param message: message to be displayed.
:param title: window title
:param default: default button a... | python | def ask_yes_no(message='', default=0, title=''):
"""
Display a message with choices of Yes and No.
returned value:
Yes -> True
No -> False
:ref:`screenshots<ask_yes_no>`
:param message: message to be displayed.
:param title: window title
:param default: default button a... | [
"def",
"ask_yes_no",
"(",
"message",
"=",
"''",
",",
"default",
"=",
"0",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_yes_no\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"default",
"=",
"default",
... | Display a message with choices of Yes and No.
returned value:
Yes -> True
No -> False
:ref:`screenshots<ask_yes_no>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (YES=True, NO=False)
:rtype: bool | [
"Display",
"a",
"message",
"with",
"choices",
"of",
"Yes",
"and",
"No",
"."
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L169-L184 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/ext.py | _WebhooksState.register | def register(self, receiver_id, receiver):
"""Register a receiver."""
assert receiver_id not in self.receivers
self.receivers[receiver_id] = receiver(receiver_id) | python | def register(self, receiver_id, receiver):
"""Register a receiver."""
assert receiver_id not in self.receivers
self.receivers[receiver_id] = receiver(receiver_id) | [
"def",
"register",
"(",
"self",
",",
"receiver_id",
",",
"receiver",
")",
":",
"assert",
"receiver_id",
"not",
"in",
"self",
".",
"receivers",
"self",
".",
"receivers",
"[",
"receiver_id",
"]",
"=",
"receiver",
"(",
"receiver_id",
")"
] | Register a receiver. | [
"Register",
"a",
"receiver",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/ext.py#L45-L48 | train |
rfverbruggen/rachiopy | rachiopy/schedulerule.py | Schedulerule.get | def get(self, sched_rule_id):
"""Retrieve the information for a scheduleRule entity."""
path = '/'.join(['schedulerule', sched_rule_id])
return self.rachio.get(path) | python | def get(self, sched_rule_id):
"""Retrieve the information for a scheduleRule entity."""
path = '/'.join(['schedulerule', sched_rule_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"sched_rule_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'schedulerule'",
",",
"sched_rule_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a scheduleRule entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"scheduleRule",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/schedulerule.py#L33-L36 | train |
spotify/gordon-gcp | src/gordon_gcp/schema/parse.py | MessageParser.parse | def parse(self, message, schema):
"""Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
... | python | def parse(self, message, schema):
"""Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
... | [
"def",
"parse",
"(",
"self",
",",
"message",
",",
"schema",
")",
":",
"func",
"=",
"{",
"'audit-log'",
":",
"self",
".",
"_parse_audit_log_msg",
",",
"'event'",
":",
"self",
".",
"_parse_event_msg",
",",
"}",
"[",
"schema",
"]",
"return",
"func",
"(",
... | Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
Returns:
(dict): parsed mes... | [
"Parse",
"message",
"according",
"to",
"schema",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/schema/parse.py#L69-L85 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | Zone.start | def start(self, zone_id, duration):
"""Start a zone."""
path = 'zone/start'
payload = {'id': zone_id, 'duration': duration}
return self.rachio.put(path, payload) | python | def start(self, zone_id, duration):
"""Start a zone."""
path = 'zone/start'
payload = {'id': zone_id, 'duration': duration}
return self.rachio.put(path, payload) | [
"def",
"start",
"(",
"self",
",",
"zone_id",
",",
"duration",
")",
":",
"path",
"=",
"'zone/start'",
"payload",
"=",
"{",
"'id'",
":",
"zone_id",
",",
"'duration'",
":",
"duration",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
... | Start a zone. | [
"Start",
"a",
"zone",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L11-L15 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | Zone.startMultiple | def startMultiple(self, zones):
"""Start multiple zones."""
path = 'zone/start_multiple'
payload = {'zones': zones}
return self.rachio.put(path, payload) | python | def startMultiple(self, zones):
"""Start multiple zones."""
path = 'zone/start_multiple'
payload = {'zones': zones}
return self.rachio.put(path, payload) | [
"def",
"startMultiple",
"(",
"self",
",",
"zones",
")",
":",
"path",
"=",
"'zone/start_multiple'",
"payload",
"=",
"{",
"'zones'",
":",
"zones",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Start multiple zones. | [
"Start",
"multiple",
"zones",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L17-L21 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | Zone.get | def get(self, zone_id):
"""Retrieve the information for a zone entity."""
path = '/'.join(['zone', zone_id])
return self.rachio.get(path) | python | def get(self, zone_id):
"""Retrieve the information for a zone entity."""
path = '/'.join(['zone', zone_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"zone_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'zone'",
",",
"zone_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a zone entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"zone",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L27-L30 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | ZoneSchedule.start | def start(self):
"""Start the schedule."""
zones = [{"id": data[0], "duration": data[1], "sortOrder": count}
for (count, data) in enumerate(self._zones, 1)]
self._api.startMultiple(zones) | python | def start(self):
"""Start the schedule."""
zones = [{"id": data[0], "duration": data[1], "sortOrder": count}
for (count, data) in enumerate(self._zones, 1)]
self._api.startMultiple(zones) | [
"def",
"start",
"(",
"self",
")",
":",
"zones",
"=",
"[",
"{",
"\"id\"",
":",
"data",
"[",
"0",
"]",
",",
"\"duration\"",
":",
"data",
"[",
"1",
"]",
",",
"\"sortOrder\"",
":",
"count",
"}",
"for",
"(",
"count",
",",
"data",
")",
"in",
"enumerate... | Start the schedule. | [
"Start",
"the",
"schedule",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L45-L49 | train |
angvp/django-klingon | klingon/admin.py | TranslationInlineForm.clean_translation | def clean_translation(self):
"""
Do not allow translations longer than the max_lenght of the field to
be translated.
"""
translation = self.cleaned_data['translation']
if self.instance and self.instance.content_object:
# do not allow string longer than transl... | python | def clean_translation(self):
"""
Do not allow translations longer than the max_lenght of the field to
be translated.
"""
translation = self.cleaned_data['translation']
if self.instance and self.instance.content_object:
# do not allow string longer than transl... | [
"def",
"clean_translation",
"(",
"self",
")",
":",
"translation",
"=",
"self",
".",
"cleaned_data",
"[",
"'translation'",
"]",
"if",
"self",
".",
"instance",
"and",
"self",
".",
"instance",
".",
"content_object",
":",
"obj",
"=",
"self",
".",
"instance",
"... | Do not allow translations longer than the max_lenght of the field to
be translated. | [
"Do",
"not",
"allow",
"translations",
"longer",
"than",
"the",
"max_lenght",
"of",
"the",
"field",
"to",
"be",
"translated",
"."
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/admin.py#L54-L80 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | _get_merge_rules | def _get_merge_rules(properties, path=None):
"""
Yields merge rules as key-value pairs, in which the first element is a JSON path as a tuple, and the second element
is a list of merge properties whose values are `true`.
"""
if path is None:
path = ()
for key, value in properties.items()... | python | def _get_merge_rules(properties, path=None):
"""
Yields merge rules as key-value pairs, in which the first element is a JSON path as a tuple, and the second element
is a list of merge properties whose values are `true`.
"""
if path is None:
path = ()
for key, value in properties.items()... | [
"def",
"_get_merge_rules",
"(",
"properties",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"(",
")",
"for",
"key",
",",
"value",
"in",
"properties",
".",
"items",
"(",
")",
":",
"new_path",
"=",
"path",
"+",
"("... | Yields merge rules as key-value pairs, in which the first element is a JSON path as a tuple, and the second element
is a list of merge properties whose values are `true`. | [
"Yields",
"merge",
"rules",
"as",
"key",
"-",
"value",
"pairs",
"in",
"which",
"the",
"first",
"element",
"is",
"a",
"JSON",
"path",
"as",
"a",
"tuple",
"and",
"the",
"second",
"element",
"is",
"a",
"list",
"of",
"merge",
"properties",
"whose",
"values",... | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L60-L92 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | get_merge_rules | def get_merge_rules(schema=None):
"""
Returns merge rules as key-value pairs, in which the key is a JSON path as a tuple, and the value is a list of
merge properties whose values are `true`.
"""
schema = schema or get_release_schema_url(get_tags()[-1])
if isinstance(schema, dict):
deref_... | python | def get_merge_rules(schema=None):
"""
Returns merge rules as key-value pairs, in which the key is a JSON path as a tuple, and the value is a list of
merge properties whose values are `true`.
"""
schema = schema or get_release_schema_url(get_tags()[-1])
if isinstance(schema, dict):
deref_... | [
"def",
"get_merge_rules",
"(",
"schema",
"=",
"None",
")",
":",
"schema",
"=",
"schema",
"or",
"get_release_schema_url",
"(",
"get_tags",
"(",
")",
"[",
"-",
"1",
"]",
")",
"if",
"isinstance",
"(",
"schema",
",",
"dict",
")",
":",
"deref_schema",
"=",
... | Returns merge rules as key-value pairs, in which the key is a JSON path as a tuple, and the value is a list of
merge properties whose values are `true`. | [
"Returns",
"merge",
"rules",
"as",
"key",
"-",
"value",
"pairs",
"in",
"which",
"the",
"key",
"is",
"a",
"JSON",
"path",
"as",
"a",
"tuple",
"and",
"the",
"value",
"is",
"a",
"list",
"of",
"merge",
"properties",
"whose",
"values",
"are",
"true",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L106-L116 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | unflatten | def unflatten(processed, merge_rules):
"""
Unflattens a processed object into a JSON object.
"""
unflattened = OrderedDict()
for key in processed:
current_node = unflattened
for end, part in enumerate(key, 1):
# If this is a path to an item of an array.
# See... | python | def unflatten(processed, merge_rules):
"""
Unflattens a processed object into a JSON object.
"""
unflattened = OrderedDict()
for key in processed:
current_node = unflattened
for end, part in enumerate(key, 1):
# If this is a path to an item of an array.
# See... | [
"def",
"unflatten",
"(",
"processed",
",",
"merge_rules",
")",
":",
"unflattened",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
"in",
"processed",
":",
"current_node",
"=",
"unflattened",
"for",
"end",
",",
"part",
"in",
"enumerate",
"(",
"key",
",",
"1",
... | Unflattens a processed object into a JSON object. | [
"Unflattens",
"a",
"processed",
"object",
"into",
"a",
"JSON",
"object",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L180-L234 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | merge | def merge(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a compiledRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict({('tag',): ['compiled']})
for release in sorted(releases, key=lambda release: release['date']):
... | python | def merge(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a compiledRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict({('tag',): ['compiled']})
for release in sorted(releases, key=lambda release: release['date']):
... | [
"def",
"merge",
"(",
"releases",
",",
"schema",
"=",
"None",
",",
"merge_rules",
"=",
"None",
")",
":",
"if",
"not",
"merge_rules",
":",
"merge_rules",
"=",
"get_merge_rules",
"(",
"schema",
")",
"merged",
"=",
"OrderedDict",
"(",
"{",
"(",
"'tag'",
",",... | Merges a list of releases into a compiledRelease. | [
"Merges",
"a",
"list",
"of",
"releases",
"into",
"a",
"compiledRelease",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L277-L305 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | merge_versioned | def merge_versioned(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a versionedRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict()
for release in sorted(releases, key=lambda release: release['date']):
release... | python | def merge_versioned(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a versionedRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict()
for release in sorted(releases, key=lambda release: release['date']):
release... | [
"def",
"merge_versioned",
"(",
"releases",
",",
"schema",
"=",
"None",
",",
"merge_rules",
"=",
"None",
")",
":",
"if",
"not",
"merge_rules",
":",
"merge_rules",
"=",
"get_merge_rules",
"(",
"schema",
")",
"merged",
"=",
"OrderedDict",
"(",
")",
"for",
"re... | Merges a list of releases into a versionedRelease. | [
"Merges",
"a",
"list",
"of",
"releases",
"into",
"a",
"versionedRelease",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L308-L346 | train |
F483/btctxstore | btctxstore/common.py | chunks | def chunks(items, size):
""" Split list into chunks of the given size.
Original order is preserved.
Example:
> chunks([1,2,3,4,5,6,7,8], 3)
[[1, 2, 3], [4, 5, 6], [7, 8]]
"""
return [items[i:i+size] for i in range(0, len(items), size)] | python | def chunks(items, size):
""" Split list into chunks of the given size.
Original order is preserved.
Example:
> chunks([1,2,3,4,5,6,7,8], 3)
[[1, 2, 3], [4, 5, 6], [7, 8]]
"""
return [items[i:i+size] for i in range(0, len(items), size)] | [
"def",
"chunks",
"(",
"items",
",",
"size",
")",
":",
"return",
"[",
"items",
"[",
"i",
":",
"i",
"+",
"size",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"items",
")",
",",
"size",
")",
"]"
] | Split list into chunks of the given size.
Original order is preserved.
Example:
> chunks([1,2,3,4,5,6,7,8], 3)
[[1, 2, 3], [4, 5, 6], [7, 8]] | [
"Split",
"list",
"into",
"chunks",
"of",
"the",
"given",
"size",
".",
"Original",
"order",
"is",
"preserved",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/common.py#L22-L30 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.login | def login(self):
"""Login to the ZoneMinder API."""
_LOGGER.debug("Attempting to login to ZoneMinder")
login_post = {'view': 'console', 'action': 'login'}
if self._username:
login_post['username'] = self._username
if self._password:
login_post['password']... | python | def login(self):
"""Login to the ZoneMinder API."""
_LOGGER.debug("Attempting to login to ZoneMinder")
login_post = {'view': 'console', 'action': 'login'}
if self._username:
login_post['username'] = self._username
if self._password:
login_post['password']... | [
"def",
"login",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Attempting to login to ZoneMinder\"",
")",
"login_post",
"=",
"{",
"'view'",
":",
"'console'",
",",
"'action'",
":",
"'login'",
"}",
"if",
"self",
".",
"_username",
":",
"login_post",
"[... | Login to the ZoneMinder API. | [
"Login",
"to",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L35-L62 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder._zm_request | def _zm_request(self, method, api_url, data=None,
timeout=DEFAULT_TIMEOUT) -> dict:
"""Perform a request to the ZoneMinder API."""
try:
# Since the API uses sessions that expire, sometimes we need to
# re-auth if the call fails.
for _ in range(Zone... | python | def _zm_request(self, method, api_url, data=None,
timeout=DEFAULT_TIMEOUT) -> dict:
"""Perform a request to the ZoneMinder API."""
try:
# Since the API uses sessions that expire, sometimes we need to
# re-auth if the call fails.
for _ in range(Zone... | [
"def",
"_zm_request",
"(",
"self",
",",
"method",
",",
"api_url",
",",
"data",
"=",
"None",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
"->",
"dict",
":",
"try",
":",
"for",
"_",
"in",
"range",
"(",
"ZoneMinder",
".",
"LOGIN_RETRIES",
")",
":",
"req",... | Perform a request to the ZoneMinder API. | [
"Perform",
"a",
"request",
"to",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L72-L100 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.get_monitors | def get_monitors(self) -> List[Monitor]:
"""Get a list of Monitors from the ZoneMinder API."""
raw_monitors = self._zm_request('get', ZoneMinder.MONITOR_URL)
if not raw_monitors:
_LOGGER.warning("Could not fetch monitors from ZoneMinder")
return []
monitors = []
... | python | def get_monitors(self) -> List[Monitor]:
"""Get a list of Monitors from the ZoneMinder API."""
raw_monitors = self._zm_request('get', ZoneMinder.MONITOR_URL)
if not raw_monitors:
_LOGGER.warning("Could not fetch monitors from ZoneMinder")
return []
monitors = []
... | [
"def",
"get_monitors",
"(",
"self",
")",
"->",
"List",
"[",
"Monitor",
"]",
":",
"raw_monitors",
"=",
"self",
".",
"_zm_request",
"(",
"'get'",
",",
"ZoneMinder",
".",
"MONITOR_URL",
")",
"if",
"not",
"raw_monitors",
":",
"_LOGGER",
".",
"warning",
"(",
... | Get a list of Monitors from the ZoneMinder API. | [
"Get",
"a",
"list",
"of",
"Monitors",
"from",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L102-L115 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.get_run_states | def get_run_states(self) -> List[RunState]:
"""Get a list of RunStates from the ZoneMinder API."""
raw_states = self.get_state('api/states.json')
if not raw_states:
_LOGGER.warning("Could not fetch runstates from ZoneMinder")
return []
run_states = []
for... | python | def get_run_states(self) -> List[RunState]:
"""Get a list of RunStates from the ZoneMinder API."""
raw_states = self.get_state('api/states.json')
if not raw_states:
_LOGGER.warning("Could not fetch runstates from ZoneMinder")
return []
run_states = []
for... | [
"def",
"get_run_states",
"(",
"self",
")",
"->",
"List",
"[",
"RunState",
"]",
":",
"raw_states",
"=",
"self",
".",
"get_state",
"(",
"'api/states.json'",
")",
"if",
"not",
"raw_states",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not fetch runstates from Zone... | Get a list of RunStates from the ZoneMinder API. | [
"Get",
"a",
"list",
"of",
"RunStates",
"from",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L117-L130 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.get_active_state | def get_active_state(self) -> Optional[str]:
"""Get the name of the active run state from the ZoneMinder API."""
for state in self.get_run_states():
if state.active:
return state.name
return None | python | def get_active_state(self) -> Optional[str]:
"""Get the name of the active run state from the ZoneMinder API."""
for state in self.get_run_states():
if state.active:
return state.name
return None | [
"def",
"get_active_state",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"for",
"state",
"in",
"self",
".",
"get_run_states",
"(",
")",
":",
"if",
"state",
".",
"active",
":",
"return",
"state",
".",
"name",
"return",
"None"
] | Get the name of the active run state from the ZoneMinder API. | [
"Get",
"the",
"name",
"of",
"the",
"active",
"run",
"state",
"from",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L132-L137 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.set_active_state | def set_active_state(self, state_name):
"""
Set the ZoneMinder run state to the given state name, via ZM API.
Note that this is a long-running API call; ZoneMinder changes the state
of each camera in turn, and this GET does not receive a response until
all cameras have been upda... | python | def set_active_state(self, state_name):
"""
Set the ZoneMinder run state to the given state name, via ZM API.
Note that this is a long-running API call; ZoneMinder changes the state
of each camera in turn, and this GET does not receive a response until
all cameras have been upda... | [
"def",
"set_active_state",
"(",
"self",
",",
"state_name",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'Setting ZoneMinder run state to state %s'",
",",
"state_name",
")",
"return",
"self",
".",
"_zm_request",
"(",
"'GET'",
",",
"'api/states/change/{}.json'",
".",
"form... | Set the ZoneMinder run state to the given state name, via ZM API.
Note that this is a long-running API call; ZoneMinder changes the state
of each camera in turn, and this GET does not receive a response until
all cameras have been updated. Even on a reasonably powerful machine,
this cal... | [
"Set",
"the",
"ZoneMinder",
"run",
"state",
"to",
"the",
"given",
"state",
"name",
"via",
"ZM",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L139-L152 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.is_available | def is_available(self) -> bool:
"""Indicate if this ZoneMinder service is currently available."""
status_response = self.get_state(
'api/host/daemonCheck.json'
)
if not status_response:
return False
return status_response.get('result') == 1 | python | def is_available(self) -> bool:
"""Indicate if this ZoneMinder service is currently available."""
status_response = self.get_state(
'api/host/daemonCheck.json'
)
if not status_response:
return False
return status_response.get('result') == 1 | [
"def",
"is_available",
"(",
"self",
")",
"->",
"bool",
":",
"status_response",
"=",
"self",
".",
"get_state",
"(",
"'api/host/daemonCheck.json'",
")",
"if",
"not",
"status_response",
":",
"return",
"False",
"return",
"status_response",
".",
"get",
"(",
"'result'... | Indicate if this ZoneMinder service is currently available. | [
"Indicate",
"if",
"this",
"ZoneMinder",
"service",
"is",
"currently",
"available",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L171-L180 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder._build_server_url | def _build_server_url(server_host, server_path) -> str:
"""Build the server url making sure it ends in a trailing slash."""
server_url = urljoin(server_host, server_path)
if server_url[-1] == '/':
return server_url
return '{}/'.format(server_url) | python | def _build_server_url(server_host, server_path) -> str:
"""Build the server url making sure it ends in a trailing slash."""
server_url = urljoin(server_host, server_path)
if server_url[-1] == '/':
return server_url
return '{}/'.format(server_url) | [
"def",
"_build_server_url",
"(",
"server_host",
",",
"server_path",
")",
"->",
"str",
":",
"server_url",
"=",
"urljoin",
"(",
"server_host",
",",
"server_path",
")",
"if",
"server_url",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"return",
"server_url",
"return",
... | Build the server url making sure it ends in a trailing slash. | [
"Build",
"the",
"server",
"url",
"making",
"sure",
"it",
"ends",
"in",
"a",
"trailing",
"slash",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L193-L198 | train |
rfverbruggen/rachiopy | rachiopy/flexschedulerule.py | FlexSchedulerule.get | def get(self, flex_sched_rule_id):
"""Retrieve the information for a flexscheduleRule entity."""
path = '/'.join(['flexschedulerule', flex_sched_rule_id])
return self.rachio.get(path) | python | def get(self, flex_sched_rule_id):
"""Retrieve the information for a flexscheduleRule entity."""
path = '/'.join(['flexschedulerule', flex_sched_rule_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"flex_sched_rule_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'flexschedulerule'",
",",
"flex_sched_rule_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a flexscheduleRule entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"flexscheduleRule",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/flexschedulerule.py#L11-L14 | train |
gitenberg-dev/gitberg | gitenberg/workflow.py | upload_all_books | def upload_all_books(book_id_start, book_id_end, rdf_library=None):
""" Uses the fetch, make, push subcommands to
mirror Project Gutenberg to a github3 api
"""
# TODO refactor appname into variable
logger.info(
"starting a gitberg mass upload: {0} -> {1}".format(
book_id_sta... | python | def upload_all_books(book_id_start, book_id_end, rdf_library=None):
""" Uses the fetch, make, push subcommands to
mirror Project Gutenberg to a github3 api
"""
# TODO refactor appname into variable
logger.info(
"starting a gitberg mass upload: {0} -> {1}".format(
book_id_sta... | [
"def",
"upload_all_books",
"(",
"book_id_start",
",",
"book_id_end",
",",
"rdf_library",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"starting a gitberg mass upload: {0} -> {1}\"",
".",
"format",
"(",
"book_id_start",
",",
"book_id_end",
")",
")",
"for",
... | Uses the fetch, make, push subcommands to
mirror Project Gutenberg to a github3 api | [
"Uses",
"the",
"fetch",
"make",
"push",
"subcommands",
"to",
"mirror",
"Project",
"Gutenberg",
"to",
"a",
"github3",
"api"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/workflow.py#L15-L41 | train |
gitenberg-dev/gitberg | gitenberg/workflow.py | upload_list | def upload_list(book_id_list, rdf_library=None):
""" Uses the fetch, make, push subcommands to add a list of pg books
"""
with open(book_id_list, 'r') as f:
cache = {}
for book_id in f:
book_id = book_id.strip()
try:
if int(book_id) in missing_pgid:
... | python | def upload_list(book_id_list, rdf_library=None):
""" Uses the fetch, make, push subcommands to add a list of pg books
"""
with open(book_id_list, 'r') as f:
cache = {}
for book_id in f:
book_id = book_id.strip()
try:
if int(book_id) in missing_pgid:
... | [
"def",
"upload_list",
"(",
"book_id_list",
",",
"rdf_library",
"=",
"None",
")",
":",
"with",
"open",
"(",
"book_id_list",
",",
"'r'",
")",
"as",
"f",
":",
"cache",
"=",
"{",
"}",
"for",
"book_id",
"in",
"f",
":",
"book_id",
"=",
"book_id",
".",
"str... | Uses the fetch, make, push subcommands to add a list of pg books | [
"Uses",
"the",
"fetch",
"make",
"push",
"subcommands",
"to",
"add",
"a",
"list",
"of",
"pg",
"books"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/workflow.py#L43-L57 | train |
angvp/django-klingon | klingon/models.py | Translatable.translate | def translate(self):
"""
Create all translations objects for this Translatable instance.
@rtype: list of Translation objects
@return: Returns a list of translations objects
"""
translations = []
for lang in settings.LANGUAGES:
# do not create an trans... | python | def translate(self):
"""
Create all translations objects for this Translatable instance.
@rtype: list of Translation objects
@return: Returns a list of translations objects
"""
translations = []
for lang in settings.LANGUAGES:
# do not create an trans... | [
"def",
"translate",
"(",
"self",
")",
":",
"translations",
"=",
"[",
"]",
"for",
"lang",
"in",
"settings",
".",
"LANGUAGES",
":",
"if",
"lang",
"[",
"0",
"]",
"==",
"self",
".",
"_get_default_language",
"(",
")",
":",
"continue",
"if",
"self",
".",
"... | Create all translations objects for this Translatable instance.
@rtype: list of Translation objects
@return: Returns a list of translations objects | [
"Create",
"all",
"translations",
"objects",
"for",
"this",
"Translatable",
"instance",
"."
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L57-L84 | train |
angvp/django-klingon | klingon/models.py | Translatable.translations_objects | def translations_objects(self, lang):
"""
Return the complete list of translation objects of a Translatable
instance
@type lang: string
@param lang: a string with the name of the language
@rtype: list of Translation
@return: Returns a list of translations object... | python | def translations_objects(self, lang):
"""
Return the complete list of translation objects of a Translatable
instance
@type lang: string
@param lang: a string with the name of the language
@rtype: list of Translation
@return: Returns a list of translations object... | [
"def",
"translations_objects",
"(",
"self",
",",
"lang",
")",
":",
"return",
"Translation",
".",
"objects",
".",
"filter",
"(",
"object_id",
"=",
"self",
".",
"id",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
... | Return the complete list of translation objects of a Translatable
instance
@type lang: string
@param lang: a string with the name of the language
@rtype: list of Translation
@return: Returns a list of translations objects | [
"Return",
"the",
"complete",
"list",
"of",
"translation",
"objects",
"of",
"a",
"Translatable",
"instance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L86-L101 | train |
angvp/django-klingon | klingon/models.py | Translatable.translations | def translations(self, lang):
"""
Return the list of translation strings of a Translatable
instance in a dictionary form
@type lang: string
@param lang: a string with the name of the language
@rtype: python Dictionary
@return: Returns a all fieldname / translati... | python | def translations(self, lang):
"""
Return the list of translation strings of a Translatable
instance in a dictionary form
@type lang: string
@param lang: a string with the name of the language
@rtype: python Dictionary
@return: Returns a all fieldname / translati... | [
"def",
"translations",
"(",
"self",
",",
"lang",
")",
":",
"key",
"=",
"self",
".",
"_get_translations_cache_key",
"(",
"lang",
")",
"trans_dict",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
"if",
"self",
".",
"translatable_slug",
"is",
"... | Return the list of translation strings of a Translatable
instance in a dictionary form
@type lang: string
@param lang: a string with the name of the language
@rtype: python Dictionary
@return: Returns a all fieldname / translations (key / value) | [
"Return",
"the",
"list",
"of",
"translation",
"strings",
"of",
"a",
"Translatable",
"instance",
"in",
"a",
"dictionary",
"form"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L103-L128 | train |
angvp/django-klingon | klingon/models.py | Translatable.get_translation_obj | def get_translation_obj(self, lang, field, create=False):
"""
Return the translation object of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the ... | python | def get_translation_obj(self, lang, field, create=False):
"""
Return the translation object of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the ... | [
"def",
"get_translation_obj",
"(",
"self",
",",
"lang",
",",
"field",
",",
"create",
"=",
"False",
")",
":",
"trans",
"=",
"None",
"try",
":",
"trans",
"=",
"Translation",
".",
"objects",
".",
"get",
"(",
"object_id",
"=",
"self",
".",
"id",
",",
"co... | Return the translation object of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: Translation
@return: Returns ... | [
"Return",
"the",
"translation",
"object",
"of",
"an",
"specific",
"field",
"in",
"a",
"Translatable",
"istance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L130-L160 | train |
angvp/django-klingon | klingon/models.py | Translatable.get_translation | def get_translation(self, lang, field):
"""
Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try t... | python | def get_translation(self, lang, field):
"""
Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try t... | [
"def",
"get_translation",
"(",
"self",
",",
"lang",
",",
"field",
")",
":",
"key",
"=",
"self",
".",
"_get_translation_cache_key",
"(",
"lang",
",",
"field",
")",
"trans",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"''",
")",
"if",
"not",
"trans",
":... | Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: string
@return: Returns a tra... | [
"Return",
"the",
"translation",
"string",
"of",
"an",
"specific",
"field",
"in",
"a",
"Translatable",
"istance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L162-L188 | train |
angvp/django-klingon | klingon/models.py | Translatable.set_translation | def set_translation(self, lang, field, text):
"""
Store a translation string in the specified field for a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we... | python | def set_translation(self, lang, field, text):
"""
Store a translation string in the specified field for a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we... | [
"def",
"set_translation",
"(",
"self",
",",
"lang",
",",
"field",
",",
"text",
")",
":",
"auto_slug_obj",
"=",
"None",
"if",
"lang",
"==",
"self",
".",
"_get_default_language",
"(",
")",
":",
"raise",
"CanNotTranslate",
"(",
"_",
"(",
"'You are not supposed ... | Store a translation string in the specified field for a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@type text: string
@param text: a str... | [
"Store",
"a",
"translation",
"string",
"in",
"the",
"specified",
"field",
"for",
"a",
"Translatable",
"istance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L190-L237 | train |
angvp/django-klingon | klingon/models.py | Translatable.translations_link | def translations_link(self):
"""
Print on admin change list the link to see all translations for this object
@type text: string
@param text: a string with the html to link to the translations admin interface
"""
translation_type = ContentType.objects.get_for_model(Transl... | python | def translations_link(self):
"""
Print on admin change list the link to see all translations for this object
@type text: string
@param text: a string with the html to link to the translations admin interface
"""
translation_type = ContentType.objects.get_for_model(Transl... | [
"def",
"translations_link",
"(",
"self",
")",
":",
"translation_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"Translation",
")",
"link",
"=",
"urlresolvers",
".",
"reverse",
"(",
"'admin:%s_%s_changelist'",
"%",
"(",
"translation_type",
".... | Print on admin change list the link to see all translations for this object
@type text: string
@param text: a string with the html to link to the translations admin interface | [
"Print",
"on",
"admin",
"change",
"list",
"the",
"link",
"to",
"see",
"all",
"translations",
"for",
"this",
"object"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L239-L254 | train |
indietyp/django-automated-logging | automated_logging/signals/database.py | comparison_callback | def comparison_callback(sender, instance, **kwargs):
"""Comparing old and new object to determin which fields changed how"""
if validate_instance(instance) and settings.AUTOMATED_LOGGING['to_database']:
try:
old = sender.objects.get(pk=instance.pk)
except Exception:
retur... | python | def comparison_callback(sender, instance, **kwargs):
"""Comparing old and new object to determin which fields changed how"""
if validate_instance(instance) and settings.AUTOMATED_LOGGING['to_database']:
try:
old = sender.objects.get(pk=instance.pk)
except Exception:
retur... | [
"def",
"comparison_callback",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"if",
"validate_instance",
"(",
"instance",
")",
"and",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'to_database'",
"]",
":",
"try",
":",
"old",
"=",
"sender",
".",
... | Comparing old and new object to determin which fields changed how | [
"Comparing",
"old",
"and",
"new",
"object",
"to",
"determin",
"which",
"fields",
"changed",
"how"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/database.py#L18-L92 | train |
indietyp/django-automated-logging | automated_logging/signals/database.py | save_callback | def save_callback(sender, instance, created, update_fields, **kwargs):
"""Save object & link logging entry"""
if validate_instance(instance):
status = 'add' if created is True else 'change'
change = ''
if status == 'change' and 'al_chl' in instance.__dict__.keys():
changelog... | python | def save_callback(sender, instance, created, update_fields, **kwargs):
"""Save object & link logging entry"""
if validate_instance(instance):
status = 'add' if created is True else 'change'
change = ''
if status == 'change' and 'al_chl' in instance.__dict__.keys():
changelog... | [
"def",
"save_callback",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"update_fields",
",",
"**",
"kwargs",
")",
":",
"if",
"validate_instance",
"(",
"instance",
")",
":",
"status",
"=",
"'add'",
"if",
"created",
"is",
"True",
"else",
"'change'",
"c... | Save object & link logging entry | [
"Save",
"object",
"&",
"link",
"logging",
"entry"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/database.py#L97-L107 | train |
Xaroth/libzfs-python | libzfs/handle.py | LibZFSHandle.requires_refcount | def requires_refcount(cls, func):
"""
The ``requires_refcount`` decorator adds a check prior to call ``func`` to verify
that there is an active handle. if there is no such handle, a ``NoHandleException`` exception is thrown.
"""
@functools.wraps(func)
def requires_active_... | python | def requires_refcount(cls, func):
"""
The ``requires_refcount`` decorator adds a check prior to call ``func`` to verify
that there is an active handle. if there is no such handle, a ``NoHandleException`` exception is thrown.
"""
@functools.wraps(func)
def requires_active_... | [
"def",
"requires_refcount",
"(",
"cls",
",",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"requires_active_handle",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"cls",
".",
"refcount",
"(",
")",
"==",
"0",
":",... | The ``requires_refcount`` decorator adds a check prior to call ``func`` to verify
that there is an active handle. if there is no such handle, a ``NoHandleException`` exception is thrown. | [
"The",
"requires_refcount",
"decorator",
"adds",
"a",
"check",
"prior",
"to",
"call",
"func",
"to",
"verify",
"that",
"there",
"is",
"an",
"active",
"handle",
".",
"if",
"there",
"is",
"no",
"such",
"handle",
"a",
"NoHandleException",
"exception",
"is",
"thr... | 146e5f28de5971bb6eb64fd82b098c5f302f0b33 | https://github.com/Xaroth/libzfs-python/blob/146e5f28de5971bb6eb64fd82b098c5f302f0b33/libzfs/handle.py#L49-L59 | train |
Xaroth/libzfs-python | libzfs/handle.py | LibZFSHandle.auto | def auto(cls, func):
"""
The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's... | python | def auto(cls, func):
"""
The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's... | [
"def",
"auto",
"(",
"cls",
",",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"auto_claim_handle",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"with",
"cls",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
","... | The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's advisable to use the `requires_refcount`... | [
"The",
"auto",
"decorator",
"wraps",
"func",
"in",
"a",
"context",
"manager",
"so",
"that",
"a",
"handle",
"is",
"obtained",
"."
] | 146e5f28de5971bb6eb64fd82b098c5f302f0b33 | https://github.com/Xaroth/libzfs-python/blob/146e5f28de5971bb6eb64fd82b098c5f302f0b33/libzfs/handle.py#L62-L75 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/janitor/__init__.py | get_gpubsub_publisher | def get_gpubsub_publisher(config, metrics, changes_channel, **kw):
"""Get a GPubsubPublisher client.
A factory function that validates configuration, creates an auth
and pubsub API client, and returns a Google Pub/Sub Publisher
provider.
Args:
config (dict): Google Cloud Pub/Sub-related co... | python | def get_gpubsub_publisher(config, metrics, changes_channel, **kw):
"""Get a GPubsubPublisher client.
A factory function that validates configuration, creates an auth
and pubsub API client, and returns a Google Pub/Sub Publisher
provider.
Args:
config (dict): Google Cloud Pub/Sub-related co... | [
"def",
"get_gpubsub_publisher",
"(",
"config",
",",
"metrics",
",",
"changes_channel",
",",
"**",
"kw",
")",
":",
"builder",
"=",
"gpubsub_publisher",
".",
"GPubsubPublisherBuilder",
"(",
"config",
",",
"metrics",
",",
"changes_channel",
",",
"**",
"kw",
")",
... | Get a GPubsubPublisher client.
A factory function that validates configuration, creates an auth
and pubsub API client, and returns a Google Pub/Sub Publisher
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementati... | [
"Get",
"a",
"GPubsubPublisher",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/janitor/__init__.py#L34-L53 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/janitor/__init__.py | get_reconciler | def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw):
"""Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-rel... | python | def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw):
"""Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-rel... | [
"def",
"get_reconciler",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"changes_channel",
",",
"**",
"kw",
")",
":",
"builder",
"=",
"reconciler",
".",
"GDNSReconcilerBuilder",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"changes_channe... | Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementatio... | [
"Get",
"a",
"GDNSReconciler",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/janitor/__init__.py#L56-L77 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/janitor/__init__.py | get_authority | def get_authority(config, metrics, rrset_channel, **kwargs):
"""Get a GCEAuthority client.
A factory function that validates configuration and creates a
proper GCEAuthority.
Args:
config (dict): GCEAuthority related configuration.
metrics (obj): :interface:`IMetricRelay` implementation... | python | def get_authority(config, metrics, rrset_channel, **kwargs):
"""Get a GCEAuthority client.
A factory function that validates configuration and creates a
proper GCEAuthority.
Args:
config (dict): GCEAuthority related configuration.
metrics (obj): :interface:`IMetricRelay` implementation... | [
"def",
"get_authority",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"**",
"kwargs",
")",
":",
"builder",
"=",
"authority",
".",
"GCEAuthorityBuilder",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"**",
"kwargs",
")",
"return",
"bui... | Get a GCEAuthority client.
A factory function that validates configuration and creates a
proper GCEAuthority.
Args:
config (dict): GCEAuthority related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue): Queue used for sending mess... | [
"Get",
"a",
"GCEAuthority",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/janitor/__init__.py#L80-L98 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/auth.py | GAuthClient.refresh_token | async def refresh_token(self):
"""Refresh oauth access token attached to this HTTP session.
Raises:
:exc:`.GCPAuthError`: if no token was found in the
response.
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponse... | python | async def refresh_token(self):
"""Refresh oauth access token attached to this HTTP session.
Raises:
:exc:`.GCPAuthError`: if no token was found in the
response.
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponse... | [
"async",
"def",
"refresh_token",
"(",
"self",
")",
":",
"url",
",",
"headers",
",",
"body",
"=",
"self",
".",
"_setup_token_request",
"(",
")",
"request_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
"logging",
".",
"debug",
"(",
"_utils",
".",
"REQ_LOG_FMT",... | Refresh oauth access token attached to this HTTP session.
Raises:
:exc:`.GCPAuthError`: if no token was found in the
response.
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponseError`, if the
exception i... | [
"Refresh",
"oauth",
"access",
"token",
"attached",
"to",
"this",
"HTTP",
"session",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/auth.py#L168-L208 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.get | def get(self, dev_id):
"""Retrieve the information for a device entity."""
path = '/'.join(['device', dev_id])
return self.rachio.get(path) | python | def get(self, dev_id):
"""Retrieve the information for a device entity."""
path = '/'.join(['device', dev_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'device'",
",",
"dev_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a device entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"device",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L11-L14 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.getEvent | def getEvent(self, dev_id, starttime, endtime):
"""Retrieve events for a device entity."""
path = 'device/%s/event?startTime=%s&endTime=%s' % \
(dev_id, starttime, endtime)
return self.rachio.get(path) | python | def getEvent(self, dev_id, starttime, endtime):
"""Retrieve events for a device entity."""
path = 'device/%s/event?startTime=%s&endTime=%s' % \
(dev_id, starttime, endtime)
return self.rachio.get(path) | [
"def",
"getEvent",
"(",
"self",
",",
"dev_id",
",",
"starttime",
",",
"endtime",
")",
":",
"path",
"=",
"'device/%s/event?startTime=%s&endTime=%s'",
"%",
"(",
"dev_id",
",",
"starttime",
",",
"endtime",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
... | Retrieve events for a device entity. | [
"Retrieve",
"events",
"for",
"a",
"device",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L21-L25 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.getForecast | def getForecast(self, dev_id, units):
"""Retrieve current and predicted forecast."""
assert units in ['US', 'METRIC'], 'units must be either US or METRIC'
path = 'device/%s/forecast?units=%s' % (dev_id, units)
return self.rachio.get(path) | python | def getForecast(self, dev_id, units):
"""Retrieve current and predicted forecast."""
assert units in ['US', 'METRIC'], 'units must be either US or METRIC'
path = 'device/%s/forecast?units=%s' % (dev_id, units)
return self.rachio.get(path) | [
"def",
"getForecast",
"(",
"self",
",",
"dev_id",
",",
"units",
")",
":",
"assert",
"units",
"in",
"[",
"'US'",
",",
"'METRIC'",
"]",
",",
"'units must be either US or METRIC'",
"path",
"=",
"'device/%s/forecast?units=%s'",
"%",
"(",
"dev_id",
",",
"units",
")... | Retrieve current and predicted forecast. | [
"Retrieve",
"current",
"and",
"predicted",
"forecast",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L32-L36 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.stopWater | def stopWater(self, dev_id):
"""Stop all watering on device."""
path = 'device/stop_water'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | python | def stopWater(self, dev_id):
"""Stop all watering on device."""
path = 'device/stop_water'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | [
"def",
"stopWater",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'device/stop_water'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Stop all watering on device. | [
"Stop",
"all",
"watering",
"on",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L38-L42 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.rainDelay | def rainDelay(self, dev_id, duration):
"""Rain delay device."""
path = 'device/rain_delay'
payload = {'id': dev_id, 'duration': duration}
return self.rachio.put(path, payload) | python | def rainDelay(self, dev_id, duration):
"""Rain delay device."""
path = 'device/rain_delay'
payload = {'id': dev_id, 'duration': duration}
return self.rachio.put(path, payload) | [
"def",
"rainDelay",
"(",
"self",
",",
"dev_id",
",",
"duration",
")",
":",
"path",
"=",
"'device/rain_delay'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
",",
"'duration'",
":",
"duration",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
... | Rain delay device. | [
"Rain",
"delay",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L44-L48 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.on | def on(self, dev_id):
"""Turn ON all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/on'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | python | def on(self, dev_id):
"""Turn ON all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/on'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | [
"def",
"on",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'device/on'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Turn ON all features of the device.
schedules, weather intelligence, water budget, etc. | [
"Turn",
"ON",
"all",
"features",
"of",
"the",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L50-L57 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.off | def off(self, dev_id):
"""Turn OFF all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/off'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | python | def off(self, dev_id):
"""Turn OFF all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/off'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | [
"def",
"off",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'device/off'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Turn OFF all features of the device.
schedules, weather intelligence, water budget, etc. | [
"Turn",
"OFF",
"all",
"features",
"of",
"the",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L59-L66 | train |
F483/btctxstore | btctxstore/api.py | BtcTxStore.create_wallet | def create_wallet(self, master_secret=b""):
"""Create a BIP0032-style hierarchical wallet.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
... | python | def create_wallet(self, master_secret=b""):
"""Create a BIP0032-style hierarchical wallet.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
... | [
"def",
"create_wallet",
"(",
"self",
",",
"master_secret",
"=",
"b\"\"",
")",
":",
"master_secret",
"=",
"deserialize",
".",
"bytes_str",
"(",
"master_secret",
")",
"bip32node",
"=",
"control",
".",
"create_wallet",
"(",
"self",
".",
"testnet",
",",
"master_se... | Create a BIP0032-style hierarchical wallet.
@param: master_secret Create from master secret, otherwise random. | [
"Create",
"a",
"BIP0032",
"-",
"style",
"hierarchical",
"wallet",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L33-L41 | train |
F483/btctxstore | btctxstore/api.py | BtcTxStore.create_key | def create_key(self, master_secret=b""):
"""Create new private key and return in wif format.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
... | python | def create_key(self, master_secret=b""):
"""Create new private key and return in wif format.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
... | [
"def",
"create_key",
"(",
"self",
",",
"master_secret",
"=",
"b\"\"",
")",
":",
"master_secret",
"=",
"deserialize",
".",
"bytes_str",
"(",
"master_secret",
")",
"bip32node",
"=",
"control",
".",
"create_wallet",
"(",
"self",
".",
"testnet",
",",
"master_secre... | Create new private key and return in wif format.
@param: master_secret Create from master secret, otherwise random. | [
"Create",
"new",
"private",
"key",
"and",
"return",
"in",
"wif",
"format",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L54-L62 | train |
F483/btctxstore | btctxstore/api.py | BtcTxStore.confirms | def confirms(self, txid):
"""Returns number of confirms or None if unpublished."""
txid = deserialize.txid(txid)
return self.service.confirms(txid) | python | def confirms(self, txid):
"""Returns number of confirms or None if unpublished."""
txid = deserialize.txid(txid)
return self.service.confirms(txid) | [
"def",
"confirms",
"(",
"self",
",",
"txid",
")",
":",
"txid",
"=",
"deserialize",
".",
"txid",
"(",
"txid",
")",
"return",
"self",
".",
"service",
".",
"confirms",
"(",
"txid",
")"
] | Returns number of confirms or None if unpublished. | [
"Returns",
"number",
"of",
"confirms",
"or",
"None",
"if",
"unpublished",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L328-L331 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | TimePeriod.get_time_period | def get_time_period(value):
"""Get the corresponding TimePeriod from the value.
Example values: 'all', 'hour', 'day', 'week', or 'month'.
"""
for time_period in TimePeriod:
if time_period.period == value:
return time_period
raise ValueError('{} is not... | python | def get_time_period(value):
"""Get the corresponding TimePeriod from the value.
Example values: 'all', 'hour', 'day', 'week', or 'month'.
"""
for time_period in TimePeriod:
if time_period.period == value:
return time_period
raise ValueError('{} is not... | [
"def",
"get_time_period",
"(",
"value",
")",
":",
"for",
"time_period",
"in",
"TimePeriod",
":",
"if",
"time_period",
".",
"period",
"==",
"value",
":",
"return",
"time_period",
"raise",
"ValueError",
"(",
"'{} is not a valid TimePeriod'",
".",
"format",
"(",
"v... | Get the corresponding TimePeriod from the value.
Example values: 'all', 'hour', 'day', 'week', or 'month'. | [
"Get",
"the",
"corresponding",
"TimePeriod",
"from",
"the",
"value",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L41-L49 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.update_monitor | def update_monitor(self):
"""Update the monitor and monitor status from the ZM server."""
result = self._client.get_state(self._monitor_url)
self._raw_result = result['monitor'] | python | def update_monitor(self):
"""Update the monitor and monitor status from the ZM server."""
result = self._client.get_state(self._monitor_url)
self._raw_result = result['monitor'] | [
"def",
"update_monitor",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"self",
".",
"_monitor_url",
")",
"self",
".",
"_raw_result",
"=",
"result",
"[",
"'monitor'",
"]"
] | Update the monitor and monitor status from the ZM server. | [
"Update",
"the",
"monitor",
"and",
"monitor",
"status",
"from",
"the",
"ZM",
"server",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L86-L89 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.function | def function(self, new_function):
"""Set the MonitorState of this Monitor."""
self._client.change_state(
self._monitor_url,
{'Monitor[Function]': new_function.value}) | python | def function(self, new_function):
"""Set the MonitorState of this Monitor."""
self._client.change_state(
self._monitor_url,
{'Monitor[Function]': new_function.value}) | [
"def",
"function",
"(",
"self",
",",
"new_function",
")",
":",
"self",
".",
"_client",
".",
"change_state",
"(",
"self",
".",
"_monitor_url",
",",
"{",
"'Monitor[Function]'",
":",
"new_function",
".",
"value",
"}",
")"
] | Set the MonitorState of this Monitor. | [
"Set",
"the",
"MonitorState",
"of",
"this",
"Monitor",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L99-L103 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.is_recording | def is_recording(self) -> Optional[bool]:
"""Indicate if this Monitor is currently recording."""
status_response = self._client.get_state(
'api/monitors/alarm/id:{}/command:status.json'.format(
self._monitor_id
)
)
if not status_response:
... | python | def is_recording(self) -> Optional[bool]:
"""Indicate if this Monitor is currently recording."""
status_response = self._client.get_state(
'api/monitors/alarm/id:{}/command:status.json'.format(
self._monitor_id
)
)
if not status_response:
... | [
"def",
"is_recording",
"(",
"self",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"status_response",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"'api/monitors/alarm/id:{}/command:status.json'",
".",
"format",
"(",
"self",
".",
"_monitor_id",
")",
")",
... | Indicate if this Monitor is currently recording. | [
"Indicate",
"if",
"this",
"Monitor",
"is",
"currently",
"recording",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L121-L140 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.is_available | def is_available(self) -> bool:
"""Indicate if this Monitor is currently available."""
status_response = self._client.get_state(
'api/monitors/daemonStatus/id:{}/daemon:zmc.json'.format(
self._monitor_id
)
)
if not status_response:
_LO... | python | def is_available(self) -> bool:
"""Indicate if this Monitor is currently available."""
status_response = self._client.get_state(
'api/monitors/daemonStatus/id:{}/daemon:zmc.json'.format(
self._monitor_id
)
)
if not status_response:
_LO... | [
"def",
"is_available",
"(",
"self",
")",
"->",
"bool",
":",
"status_response",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"'api/monitors/daemonStatus/id:{}/daemon:zmc.json'",
".",
"format",
"(",
"self",
".",
"_monitor_id",
")",
")",
"if",
"not",
"status... | Indicate if this Monitor is currently available. | [
"Indicate",
"if",
"this",
"Monitor",
"is",
"currently",
"available",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L143-L161 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.get_events | def get_events(self, time_period, include_archived=False) -> Optional[int]:
"""Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided.
"""
date_filter = '1%20{}'.format(time_period.period)
... | python | def get_events(self, time_period, include_archived=False) -> Optional[int]:
"""Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided.
"""
date_filter = '1%20{}'.format(time_period.period)
... | [
"def",
"get_events",
"(",
"self",
",",
"time_period",
",",
"include_archived",
"=",
"False",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"date_filter",
"=",
"'1%20{}'",
".",
"format",
"(",
"time_period",
".",
"period",
")",
"if",
"time_period",
"==",
"Tim... | Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided. | [
"Get",
"the",
"number",
"of",
"events",
"that",
"have",
"occurred",
"on",
"this",
"Monitor",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L163-L192 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor._build_image_url | def _build_image_url(self, monitor, mode) -> str:
"""Build and return a ZoneMinder camera image url."""
query = urlencode({
'mode': mode,
'buffer': monitor['StreamReplayBuffer'],
'monitor': monitor['Id'],
})
url = '{zms_url}?{query}'.format(
... | python | def _build_image_url(self, monitor, mode) -> str:
"""Build and return a ZoneMinder camera image url."""
query = urlencode({
'mode': mode,
'buffer': monitor['StreamReplayBuffer'],
'monitor': monitor['Id'],
})
url = '{zms_url}?{query}'.format(
... | [
"def",
"_build_image_url",
"(",
"self",
",",
"monitor",
",",
"mode",
")",
"->",
"str",
":",
"query",
"=",
"urlencode",
"(",
"{",
"'mode'",
":",
"mode",
",",
"'buffer'",
":",
"monitor",
"[",
"'StreamReplayBuffer'",
"]",
",",
"'monitor'",
":",
"monitor",
"... | Build and return a ZoneMinder camera image url. | [
"Build",
"and",
"return",
"a",
"ZoneMinder",
"camera",
"image",
"url",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L194-L205 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.