repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
nezhar/updatable | updatable/__init__.py | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L94-L183 | def get_package_update_list(package_name, version):
"""
Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict
"""
package_version = semantic_version.Version.coerce(version)
# Get package and version data from pypi
... | [
"def",
"get_package_update_list",
"(",
"package_name",
",",
"version",
")",
":",
"package_version",
"=",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"version",
")",
"# Get package and version data from pypi",
"package_data",
"=",
"get_pypi_package_data",
"(",
... | Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict | [
"Return",
"update",
"information",
"of",
"a",
"package",
"from",
"a",
"given",
"version"
] | python | train |
google/prettytensor | prettytensor/pretty_tensor_image_methods.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_image_methods.py#L43-L71 | def average_pool(input_layer, kernel, stride, edges=PAD_SAME, name=PROVIDED):
"""Performs average pooling.
`kernel` is the patch that will be pooled and it describes the pooling along
each of the 4 dimensions. `stride` is how big to take each step.
Because more often than not, pooling is only done
on the w... | [
"def",
"average_pool",
"(",
"input_layer",
",",
"kernel",
",",
"stride",
",",
"edges",
"=",
"PAD_SAME",
",",
"name",
"=",
"PROVIDED",
")",
":",
"return",
"_pool",
"(",
"input_layer",
",",
"tf",
".",
"nn",
".",
"avg_pool",
",",
"kernel",
",",
"stride",
... | Performs average pooling.
`kernel` is the patch that will be pooled and it describes the pooling along
each of the 4 dimensions. `stride` is how big to take each step.
Because more often than not, pooling is only done
on the width and height of the image, the following shorthands are supported:
* scalar (... | [
"Performs",
"average",
"pooling",
"."
] | python | train |
pokerregion/poker | poker/commands.py | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L123-L145 | def psstatus():
"""Shows PokerStars status such as number of players, tournaments."""
from .website.pokerstars import get_status
_print_header('PokerStars status')
status = get_status()
_print_values(
('Info updated', status.updated),
('Tables', status.tables),
('Players', ... | [
"def",
"psstatus",
"(",
")",
":",
"from",
".",
"website",
".",
"pokerstars",
"import",
"get_status",
"_print_header",
"(",
"'PokerStars status'",
")",
"status",
"=",
"get_status",
"(",
")",
"_print_values",
"(",
"(",
"'Info updated'",
",",
"status",
".",
"upda... | Shows PokerStars status such as number of players, tournaments. | [
"Shows",
"PokerStars",
"status",
"such",
"as",
"number",
"of",
"players",
"tournaments",
"."
] | python | train |
moonso/ped_parser | ped_parser/individual.py | https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/individual.py#L122-L136 | def to_json(self):
"""
Return the individual info in a dictionary for json.
"""
self.logger.debug("Returning json info")
individual_info = {
'family_id': self.family,
'id':self.individual_id,
'sex':str(self.sex),
'phenotype': str(... | [
"def",
"to_json",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Returning json info\"",
")",
"individual_info",
"=",
"{",
"'family_id'",
":",
"self",
".",
"family",
",",
"'id'",
":",
"self",
".",
"individual_id",
",",
"'sex'",
":",
... | Return the individual info in a dictionary for json. | [
"Return",
"the",
"individual",
"info",
"in",
"a",
"dictionary",
"for",
"json",
"."
] | python | train |
pydata/xarray | xarray/core/dataarray.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataarray.py#L552-L588 | def reset_coords(self, names=None, drop=False, inplace=None):
"""Given names of coordinates, reset them to become variables.
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By de... | [
"def",
"reset_coords",
"(",
"self",
",",
"names",
"=",
"None",
",",
"drop",
"=",
"False",
",",
"inplace",
"=",
"None",
")",
":",
"inplace",
"=",
"_check_inplace",
"(",
"inplace",
")",
"if",
"inplace",
"and",
"not",
"drop",
":",
"raise",
"ValueError",
"... | Given names of coordinates, reset them to become variables.
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, optional... | [
"Given",
"names",
"of",
"coordinates",
"reset",
"them",
"to",
"become",
"variables",
"."
] | python | train |
tensorpack/tensorpack | tensorpack/tfutils/symbolic_functions.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L13-L23 | def print_stat(x, message=None):
""" A simple print Op that might be easier to use than :meth:`tf.Print`.
Use it like: ``x = print_stat(x, message='This is x')``.
"""
if message is None:
message = x.op.name
lst = [tf.shape(x), tf.reduce_mean(x)]
if x.dtype.is_floating:
lst.ap... | [
"def",
"print_stat",
"(",
"x",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"x",
".",
"op",
".",
"name",
"lst",
"=",
"[",
"tf",
".",
"shape",
"(",
"x",
")",
",",
"tf",
".",
"reduce_mean",
"(",
"x",
... | A simple print Op that might be easier to use than :meth:`tf.Print`.
Use it like: ``x = print_stat(x, message='This is x')``. | [
"A",
"simple",
"print",
"Op",
"that",
"might",
"be",
"easier",
"to",
"use",
"than",
":",
"meth",
":",
"tf",
".",
"Print",
".",
"Use",
"it",
"like",
":",
"x",
"=",
"print_stat",
"(",
"x",
"message",
"=",
"This",
"is",
"x",
")",
"."
] | python | train |
GNS3/gns3-server | gns3server/ubridge/hypervisor.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/ubridge/hypervisor.py#L249-L259 | def _build_command(self):
"""
Command to start the uBridge hypervisor process.
(to be passed to subprocess.Popen())
"""
command = [self._path]
command.extend(["-H", "{}:{}".format(self._host, self._port)])
if log.getEffectiveLevel() == logging.DEBUG:
... | [
"def",
"_build_command",
"(",
"self",
")",
":",
"command",
"=",
"[",
"self",
".",
"_path",
"]",
"command",
".",
"extend",
"(",
"[",
"\"-H\"",
",",
"\"{}:{}\"",
".",
"format",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
")",
"]",
")",
"if"... | Command to start the uBridge hypervisor process.
(to be passed to subprocess.Popen()) | [
"Command",
"to",
"start",
"the",
"uBridge",
"hypervisor",
"process",
".",
"(",
"to",
"be",
"passed",
"to",
"subprocess",
".",
"Popen",
"()",
")"
] | python | train |
elliterate/capybara.py | capybara/driver/base.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/driver/base.py#L38-L42 | def frame_title(self):
""" str: The title for the current frame. """
elements = self._find_xpath("/html/head/title")
titles = [element.all_text for element in elements]
return titles[0] if len(titles) else "" | [
"def",
"frame_title",
"(",
"self",
")",
":",
"elements",
"=",
"self",
".",
"_find_xpath",
"(",
"\"/html/head/title\"",
")",
"titles",
"=",
"[",
"element",
".",
"all_text",
"for",
"element",
"in",
"elements",
"]",
"return",
"titles",
"[",
"0",
"]",
"if",
... | str: The title for the current frame. | [
"str",
":",
"The",
"title",
"for",
"the",
"current",
"frame",
"."
] | python | test |
google/transitfeed | transitfeed/trip.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L170-L216 | def GetTimeInterpolatedStops(self):
"""Return a list of (secs, stoptime, is_timepoint) tuples.
secs will always be an int. If the StopTime object does not have explict
times this method guesses using distance. stoptime is a StopTime object and
is_timepoint is a bool.
Raises:
ValueError if th... | [
"def",
"GetTimeInterpolatedStops",
"(",
"self",
")",
":",
"rv",
"=",
"[",
"]",
"stoptimes",
"=",
"self",
".",
"GetStopTimes",
"(",
")",
"# If there are no stoptimes [] is the correct return value but if the start",
"# or end are missing times there is no correct return value.",
... | Return a list of (secs, stoptime, is_timepoint) tuples.
secs will always be an int. If the StopTime object does not have explict
times this method guesses using distance. stoptime is a StopTime object and
is_timepoint is a bool.
Raises:
ValueError if this trip does not have the times needed to i... | [
"Return",
"a",
"list",
"of",
"(",
"secs",
"stoptime",
"is_timepoint",
")",
"tuples",
"."
] | python | train |
pyrogram/pyrogram | pyrogram/client/methods/bots/request_callback_answer.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/methods/bots/request_callback_answer.py#L26-L63 | def request_callback_answer(
self,
chat_id: Union[int, str],
message_id: int,
callback_data: bytes
):
"""Use this method to request a callback answer from bots.
This is the equivalent of clicking an inline button containing callback data.
Args:
ch... | [
"def",
"request_callback_answer",
"(",
"self",
",",
"chat_id",
":",
"Union",
"[",
"int",
",",
"str",
"]",
",",
"message_id",
":",
"int",
",",
"callback_data",
":",
"bytes",
")",
":",
"return",
"self",
".",
"send",
"(",
"functions",
".",
"messages",
".",
... | Use this method to request a callback answer from bots.
This is the equivalent of clicking an inline button containing callback data.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Sav... | [
"Use",
"this",
"method",
"to",
"request",
"a",
"callback",
"answer",
"from",
"bots",
".",
"This",
"is",
"the",
"equivalent",
"of",
"clicking",
"an",
"inline",
"button",
"containing",
"callback",
"data",
"."
] | python | train |
osrg/ryu | ryu/services/protocols/bgp/utils/bgp.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/utils/bgp.py#L171-L201 | def create_rt_extended_community(value, subtype=2):
"""
Creates an instance of the BGP Route Target Community (if "subtype=2")
or Route Origin Community ("subtype=3").
:param value: String of Route Target or Route Origin value.
:param subtype: Subtype of Extended Community.
:return: An instance... | [
"def",
"create_rt_extended_community",
"(",
"value",
",",
"subtype",
"=",
"2",
")",
":",
"global_admin",
",",
"local_admin",
"=",
"value",
".",
"split",
"(",
"':'",
")",
"local_admin",
"=",
"int",
"(",
"local_admin",
")",
"if",
"global_admin",
".",
"isdigit"... | Creates an instance of the BGP Route Target Community (if "subtype=2")
or Route Origin Community ("subtype=3").
:param value: String of Route Target or Route Origin value.
:param subtype: Subtype of Extended Community.
:return: An instance of Route Target or Route Origin Community. | [
"Creates",
"an",
"instance",
"of",
"the",
"BGP",
"Route",
"Target",
"Community",
"(",
"if",
"subtype",
"=",
"2",
")",
"or",
"Route",
"Origin",
"Community",
"(",
"subtype",
"=",
"3",
")",
"."
] | python | train |
angr/angr | angr/state_plugins/heap/heap_base.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/heap/heap_base.py#L78-L86 | def _free(self, ptr):
"""
Handler for any libc `free` SimProcedure call. If the heap has faithful support for `free`, it ought to be
implemented in a `free` function (as opposed to the `_free` function).
:param ptr: the location in memory to be freed
"""
raise NotImpleme... | [
"def",
"_free",
"(",
"self",
",",
"ptr",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"%s not implemented for %s\"",
"%",
"(",
"self",
".",
"_free",
".",
"__func__",
".",
"__name__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")"
] | Handler for any libc `free` SimProcedure call. If the heap has faithful support for `free`, it ought to be
implemented in a `free` function (as opposed to the `_free` function).
:param ptr: the location in memory to be freed | [
"Handler",
"for",
"any",
"libc",
"free",
"SimProcedure",
"call",
".",
"If",
"the",
"heap",
"has",
"faithful",
"support",
"for",
"free",
"it",
"ought",
"to",
"be",
"implemented",
"in",
"a",
"free",
"function",
"(",
"as",
"opposed",
"to",
"the",
"_free",
"... | python | train |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L1933-L1941 | def numConnects(self, layerName):
""" Number of incoming weights, including bias. Assumes fully connected. """
count = 0
if self[layerName].active:
count += 1 # 1 = bias
for connection in self.connections:
if connection.active and connection.fromLayer.act... | [
"def",
"numConnects",
"(",
"self",
",",
"layerName",
")",
":",
"count",
"=",
"0",
"if",
"self",
"[",
"layerName",
"]",
".",
"active",
":",
"count",
"+=",
"1",
"# 1 = bias",
"for",
"connection",
"in",
"self",
".",
"connections",
":",
"if",
"connection",
... | Number of incoming weights, including bias. Assumes fully connected. | [
"Number",
"of",
"incoming",
"weights",
"including",
"bias",
".",
"Assumes",
"fully",
"connected",
"."
] | python | train |
ehansis/ozelot | ozelot/cache.py | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/cache.py#L106-L113 | def _query(self, url, xpath):
"""Base query for an url and xpath
Args:
url (str): URL to search
xpath (str): xpath to search (may be ``None``)
"""
return self.session.query(CachedRequest).filter(CachedRequest.url == url).filter(CachedRequest.xpath == xpath) | [
"def",
"_query",
"(",
"self",
",",
"url",
",",
"xpath",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"CachedRequest",
")",
".",
"filter",
"(",
"CachedRequest",
".",
"url",
"==",
"url",
")",
".",
"filter",
"(",
"CachedRequest",
".",
... | Base query for an url and xpath
Args:
url (str): URL to search
xpath (str): xpath to search (may be ``None``) | [
"Base",
"query",
"for",
"an",
"url",
"and",
"xpath"
] | python | train |
gem/oq-engine | openquake/commands/run.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/run.py#L40-L72 | def get_pstats(pstatfile, n):
"""
Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve
"""
with tempfile.TemporaryFile(mode='w+') as stream:
ps = pstats.Stats(pstatfile, stream=stream)
ps.sort_sta... | [
"def",
"get_pstats",
"(",
"pstatfile",
",",
"n",
")",
":",
"with",
"tempfile",
".",
"TemporaryFile",
"(",
"mode",
"=",
"'w+'",
")",
"as",
"stream",
":",
"ps",
"=",
"pstats",
".",
"Stats",
"(",
"pstatfile",
",",
"stream",
"=",
"stream",
")",
"ps",
"."... | Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve | [
"Return",
"profiling",
"information",
"as",
"an",
"RST",
"table",
"."
] | python | train |
lpantano/seqcluster | seqcluster/seqbuster/__init__.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L234-L253 | def _clean_hits(reads):
"""
Select only best matches
"""
new_reads = defaultdict(realign)
for r in reads:
world = {}
sc = 0
for p in reads[r].precursors:
world[p] = reads[r].precursors[p].get_score(len(reads[r].sequence))
if sc < world[p]:
... | [
"def",
"_clean_hits",
"(",
"reads",
")",
":",
"new_reads",
"=",
"defaultdict",
"(",
"realign",
")",
"for",
"r",
"in",
"reads",
":",
"world",
"=",
"{",
"}",
"sc",
"=",
"0",
"for",
"p",
"in",
"reads",
"[",
"r",
"]",
".",
"precursors",
":",
"world",
... | Select only best matches | [
"Select",
"only",
"best",
"matches"
] | python | train |
hyde/fswrap | fswrap.py | https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L531-L535 | def child_folder(self, fragment):
"""
Returns a folder object by combining the fragment to this folder's path
"""
return Folder(os.path.join(self.path, Folder(fragment).path)) | [
"def",
"child_folder",
"(",
"self",
",",
"fragment",
")",
":",
"return",
"Folder",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"Folder",
"(",
"fragment",
")",
".",
"path",
")",
")"
] | Returns a folder object by combining the fragment to this folder's path | [
"Returns",
"a",
"folder",
"object",
"by",
"combining",
"the",
"fragment",
"to",
"this",
"folder",
"s",
"path"
] | python | train |
PSU-OIT-ARC/django-local-settings | local_settings/settings.py | https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/settings.py#L73-L109 | def _traverse(self, name, create_missing=False, action=None, value=NO_DEFAULT):
"""Traverse to the item specified by ``name``.
To create missing items on the way to the ``name``d item, pass
``create_missing=True``. This will insert an item for each
missing segment in ``name``. The type ... | [
"def",
"_traverse",
"(",
"self",
",",
"name",
",",
"create_missing",
"=",
"False",
",",
"action",
"=",
"None",
",",
"value",
"=",
"NO_DEFAULT",
")",
":",
"obj",
"=",
"self",
"segments",
"=",
"self",
".",
"_parse_path",
"(",
"name",
")",
"for",
"segment... | Traverse to the item specified by ``name``.
To create missing items on the way to the ``name``d item, pass
``create_missing=True``. This will insert an item for each
missing segment in ``name``. The type and value of item that
will be inserted for a missing segment depends on the *next*... | [
"Traverse",
"to",
"the",
"item",
"specified",
"by",
"name",
"."
] | python | train |
DallasMorningNews/django-datafreezer | datafreezer/views.py | https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L813-L840 | def generate_sections(self):
"""Return all authors to which datasets have been attributed."""
authors = Dataset.objects.values(
'uploaded_by'
).annotate(
upload_count=Count(
'uploaded_by'
)
).order_by('-upload_count')
email_nam... | [
"def",
"generate_sections",
"(",
"self",
")",
":",
"authors",
"=",
"Dataset",
".",
"objects",
".",
"values",
"(",
"'uploaded_by'",
")",
".",
"annotate",
"(",
"upload_count",
"=",
"Count",
"(",
"'uploaded_by'",
")",
")",
".",
"order_by",
"(",
"'-upload_count'... | Return all authors to which datasets have been attributed. | [
"Return",
"all",
"authors",
"to",
"which",
"datasets",
"have",
"been",
"attributed",
"."
] | python | train |
eshandas/django_rest_swagger_enhancer | django_rest_swagger_enhancer/schema_generator.py | https://github.com/eshandas/django_rest_swagger_enhancer/blob/6b86b53ebd007753707aa4a5f65bdf40f9c9bac5/django_rest_swagger_enhancer/schema_generator.py#L14-L25 | def get_swagger_view(title=None, url=None, generator_class=SchemaGenerator):
"""
Returns schema view which renders Swagger/OpenAPI.
"""
return schemas.get_schema_view(
title=title,
url=url,
renderer_classes=[
CoreJSONRenderer,
renderers.OpenAPIRenderer,
... | [
"def",
"get_swagger_view",
"(",
"title",
"=",
"None",
",",
"url",
"=",
"None",
",",
"generator_class",
"=",
"SchemaGenerator",
")",
":",
"return",
"schemas",
".",
"get_schema_view",
"(",
"title",
"=",
"title",
",",
"url",
"=",
"url",
",",
"renderer_classes",... | Returns schema view which renders Swagger/OpenAPI. | [
"Returns",
"schema",
"view",
"which",
"renders",
"Swagger",
"/",
"OpenAPI",
"."
] | python | train |
BD2KGenomics/protect | src/protect/pipeline/ProTECT.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/pipeline/ProTECT.py#L312-L433 | def _parse_config_file(job, config_file, max_cores=None):
"""
Parse the input yaml config file and download all tool inputs into the file store.
:param str config_file: Path to the input config file
:param int max_cores: The maximum cores to use for any single high-compute job.
:return: tuple of di... | [
"def",
"_parse_config_file",
"(",
"job",
",",
"config_file",
",",
"max_cores",
"=",
"None",
")",
":",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Parsing config file'",
")",
"config_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"config_file",
"... | Parse the input yaml config file and download all tool inputs into the file store.
:param str config_file: Path to the input config file
:param int max_cores: The maximum cores to use for any single high-compute job.
:return: tuple of dict of sample dicts, dict of universal options, dict of dicts of tool o... | [
"Parse",
"the",
"input",
"yaml",
"config",
"file",
"and",
"download",
"all",
"tool",
"inputs",
"into",
"the",
"file",
"store",
"."
] | python | train |
miso-belica/sumy | sumy/summarizers/kl.py | https://github.com/miso-belica/sumy/blob/099ab4938e2c1b6a011297375586bac2953641b9/sumy/summarizers/kl.py#L56-L66 | def compute_tf(self, sentences):
"""
Computes the normalized term frequency as explained in http://www.tfidf.com/
:type sentences: [sumy.models.dom.Sentence]
"""
content_words = self._get_all_content_words_in_doc(sentences)
content_words_count = len(content_words)
... | [
"def",
"compute_tf",
"(",
"self",
",",
"sentences",
")",
":",
"content_words",
"=",
"self",
".",
"_get_all_content_words_in_doc",
"(",
"sentences",
")",
"content_words_count",
"=",
"len",
"(",
"content_words",
")",
"content_words_freq",
"=",
"self",
".",
"_compute... | Computes the normalized term frequency as explained in http://www.tfidf.com/
:type sentences: [sumy.models.dom.Sentence] | [
"Computes",
"the",
"normalized",
"term",
"frequency",
"as",
"explained",
"in",
"http",
":",
"//",
"www",
".",
"tfidf",
".",
"com",
"/"
] | python | train |
saltstack/salt | salt/utils/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vmware.py#L1426-L1447 | def list_objects(service_instance, vim_object, properties=None):
'''
Returns a simple list of objects from a given service instance.
service_instance
The Service Instance for which to obtain a list of objects.
object_type
The type of content for which to obtain information.
proper... | [
"def",
"list_objects",
"(",
"service_instance",
",",
"vim_object",
",",
"properties",
"=",
"None",
")",
":",
"if",
"properties",
"is",
"None",
":",
"properties",
"=",
"[",
"'name'",
"]",
"items",
"=",
"[",
"]",
"item_list",
"=",
"get_mors_with_properties",
"... | Returns a simple list of objects from a given service instance.
service_instance
The Service Instance for which to obtain a list of objects.
object_type
The type of content for which to obtain information.
properties
An optional list of object properties used to return reference r... | [
"Returns",
"a",
"simple",
"list",
"of",
"objects",
"from",
"a",
"given",
"service",
"instance",
"."
] | python | train |
roaet/eh | eh/mdv/markdownviewer.py | https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L849-L872 | def monitor(args):
""" file monitor mode """
filename = args.get('MDFILE')
if not filename:
print col('Need file argument', 2)
raise SystemExit
last_err = ''
last_stat = 0
while True:
if not os.path.exists(filename):
last_err = 'File %s not found. Will continu... | [
"def",
"monitor",
"(",
"args",
")",
":",
"filename",
"=",
"args",
".",
"get",
"(",
"'MDFILE'",
")",
"if",
"not",
"filename",
":",
"print",
"col",
"(",
"'Need file argument'",
",",
"2",
")",
"raise",
"SystemExit",
"last_err",
"=",
"''",
"last_stat",
"=",
... | file monitor mode | [
"file",
"monitor",
"mode"
] | python | train |
gholt/swiftly | swiftly/cli/delete.py | https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/delete.py#L140-L217 | def cli_delete(context, path, body=None, recursive=False,
yes_empty_account=False, yes_delete_account=False,
until_empty=False):
"""
Deletes the item (account, container, or object) at the path.
See :py:mod:`swiftly.cli.delete` for context usage information.
See :py:class... | [
"def",
"cli_delete",
"(",
"context",
",",
"path",
",",
"body",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"yes_empty_account",
"=",
"False",
",",
"yes_delete_account",
"=",
"False",
",",
"until_empty",
"=",
"False",
")",
":",
"path",
"=",
"path",
... | Deletes the item (account, container, or object) at the path.
See :py:mod:`swiftly.cli.delete` for context usage information.
See :py:class:`CLIDelete` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param path: The path of the item (acount, conta... | [
"Deletes",
"the",
"item",
"(",
"account",
"container",
"or",
"object",
")",
"at",
"the",
"path",
"."
] | python | test |
has2k1/plotnine | plotnine/facets/layout.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L161-L183 | def setup_panel_params(self, coord):
"""
Calculate the x & y range & breaks information for each panel
Parameters
----------
coord : coord
Coordinate
"""
if not self.panel_scales_x:
raise PlotnineError('Missing an x scale')
if not... | [
"def",
"setup_panel_params",
"(",
"self",
",",
"coord",
")",
":",
"if",
"not",
"self",
".",
"panel_scales_x",
":",
"raise",
"PlotnineError",
"(",
"'Missing an x scale'",
")",
"if",
"not",
"self",
".",
"panel_scales_y",
":",
"raise",
"PlotnineError",
"(",
"'Mis... | Calculate the x & y range & breaks information for each panel
Parameters
----------
coord : coord
Coordinate | [
"Calculate",
"the",
"x",
"&",
"y",
"range",
"&",
"breaks",
"information",
"for",
"each",
"panel"
] | python | train |
geographika/mappyfile | mappyfile/utils.py | https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L293-L339 | def find(lst, key, value):
"""
Find an item in a list of dicts using a key and a value
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the list
key: value
The value ... | [
"def",
"find",
"(",
"lst",
",",
"key",
",",
"value",
")",
":",
"return",
"next",
"(",
"(",
"item",
"for",
"item",
"in",
"lst",
"if",
"item",
"[",
"key",
".",
"lower",
"(",
")",
"]",
"==",
"value",
")",
",",
"None",
")"
] | Find an item in a list of dicts using a key and a value
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the list
key: value
The value to search for
Returns
-------
... | [
"Find",
"an",
"item",
"in",
"a",
"list",
"of",
"dicts",
"using",
"a",
"key",
"and",
"a",
"value"
] | python | train |
lucastheis/django-publications | publications/models/type.py | https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/type.py#L66-L77 | def mods_genre(self):
"""
Guesses an appropriate MODS XML genre type.
"""
type2genre = {
'conference': 'conference publication',
'book chapter': 'bibliography',
'unpublished': 'article'
}
tp = str(self.type).lower()
return type2genre.get(tp, tp) | [
"def",
"mods_genre",
"(",
"self",
")",
":",
"type2genre",
"=",
"{",
"'conference'",
":",
"'conference publication'",
",",
"'book chapter'",
":",
"'bibliography'",
",",
"'unpublished'",
":",
"'article'",
"}",
"tp",
"=",
"str",
"(",
"self",
".",
"type",
")",
"... | Guesses an appropriate MODS XML genre type. | [
"Guesses",
"an",
"appropriate",
"MODS",
"XML",
"genre",
"type",
"."
] | python | valid |
camsci/meteor-pi | src/pythonModules/meteorpi_server/meteorpi_server/importer_api.py | https://github.com/camsci/meteor-pi/blob/7b01527650bd1b2b76d6f364e8122e25b8812c8d/src/pythonModules/meteorpi_server/meteorpi_server/importer_api.py#L226-L244 | def _get_entity(entity_id):
"""
Uses the request context to retrieve a :class:`meteorpi_model.CameraStatus`, :class:`meteorpi_model.Event` or
:class:`meteorpi_model.FileRecord` from the POSTed JSON string.
:param string entity_id:
The ID of a CameraStatus, Event or FileRecor... | [
"def",
"_get_entity",
"(",
"entity_id",
")",
":",
"entity_type",
"=",
"g",
".",
"request_dict",
"[",
"'type'",
"]",
"if",
"entity_type",
"==",
"'file'",
":",
"return",
"model",
".",
"FileRecord",
".",
"from_dict",
"(",
"g",
".",
"request_dict",
"[",
"'file... | Uses the request context to retrieve a :class:`meteorpi_model.CameraStatus`, :class:`meteorpi_model.Event` or
:class:`meteorpi_model.FileRecord` from the POSTed JSON string.
:param string entity_id:
The ID of a CameraStatus, Event or FileRecord contained within the request
:return:
... | [
"Uses",
"the",
"request",
"context",
"to",
"retrieve",
"a",
":",
"class",
":",
"meteorpi_model",
".",
"CameraStatus",
":",
"class",
":",
"meteorpi_model",
".",
"Event",
"or",
":",
"class",
":",
"meteorpi_model",
".",
"FileRecord",
"from",
"the",
"POSTed",
"J... | python | train |
vmalloc/dessert | dessert/rewrite.py | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L728-L753 | def visit_Call_35(self, call):
"""
visit `ast.Call` nodes on Python3.5 and after
"""
new_func, func_expl = self.visit(call.func)
arg_expls = []
new_args = []
new_kwargs = []
for arg in call.args:
res, expl = self.visit(arg)
arg_expl... | [
"def",
"visit_Call_35",
"(",
"self",
",",
"call",
")",
":",
"new_func",
",",
"func_expl",
"=",
"self",
".",
"visit",
"(",
"call",
".",
"func",
")",
"arg_expls",
"=",
"[",
"]",
"new_args",
"=",
"[",
"]",
"new_kwargs",
"=",
"[",
"]",
"for",
"arg",
"i... | visit `ast.Call` nodes on Python3.5 and after | [
"visit",
"ast",
".",
"Call",
"nodes",
"on",
"Python3",
".",
"5",
"and",
"after"
] | python | train |
iterative/dvc | dvc/command/base.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/base.py#L10-L22 | def fix_subparsers(subparsers):
"""Workaround for bug in Python 3. See more info at:
https://bugs.python.org/issue16308
https://github.com/iterative/dvc/issues/769
Args:
subparsers: subparsers to fix.
"""
from dvc.utils.compat import is_py3
if is_py3: # pragma: no ... | [
"def",
"fix_subparsers",
"(",
"subparsers",
")",
":",
"from",
"dvc",
".",
"utils",
".",
"compat",
"import",
"is_py3",
"if",
"is_py3",
":",
"# pragma: no cover",
"subparsers",
".",
"required",
"=",
"True",
"subparsers",
".",
"dest",
"=",
"\"cmd\""
] | Workaround for bug in Python 3. See more info at:
https://bugs.python.org/issue16308
https://github.com/iterative/dvc/issues/769
Args:
subparsers: subparsers to fix. | [
"Workaround",
"for",
"bug",
"in",
"Python",
"3",
".",
"See",
"more",
"info",
"at",
":",
"https",
":",
"//",
"bugs",
".",
"python",
".",
"org",
"/",
"issue16308",
"https",
":",
"//",
"github",
".",
"com",
"/",
"iterative",
"/",
"dvc",
"/",
"issues",
... | python | train |
mozilla/socorrolib | socorrolib/lib/ooid.py | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/ooid.py#L28-L40 | def uuidToOoid(uuid,timestamp=None, depth= None):
""" Create an ooid from a 32-hex-digit string in regular uuid format.
uuid: must be uuid in expected format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxx7777777
timestamp: the year-month-day is encoded in the ooid. If none, use current day
depth: the expected storage depth is ... | [
"def",
"uuidToOoid",
"(",
"uuid",
",",
"timestamp",
"=",
"None",
",",
"depth",
"=",
"None",
")",
":",
"if",
"not",
"timestamp",
":",
"timestamp",
"=",
"utc_now",
"(",
")",
".",
"date",
"(",
")",
"if",
"not",
"depth",
":",
"depth",
"=",
"defaultDepth"... | Create an ooid from a 32-hex-digit string in regular uuid format.
uuid: must be uuid in expected format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxx7777777
timestamp: the year-month-day is encoded in the ooid. If none, use current day
depth: the expected storage depth is encoded in the ooid. If non, use the defaultDepth
retu... | [
"Create",
"an",
"ooid",
"from",
"a",
"32",
"-",
"hex",
"-",
"digit",
"string",
"in",
"regular",
"uuid",
"format",
".",
"uuid",
":",
"must",
"be",
"uuid",
"in",
"expected",
"format",
":",
"xxxxxxxx",
"-",
"xxxx",
"-",
"xxxx",
"-",
"xxxx",
"-",
"xxxxx7... | python | train |
timothycrosley/short | short/compile.py | https://github.com/timothycrosley/short/blob/dcf25ec01b5406d9e0a35ac7dd8112239c0912a5/short/compile.py#L246-L284 | def indent(text, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method,
get_block=get_indented_block):
"""Returns HTML as a basestring.
Parameters
----------
text : basestring
Source code, typically SHPAML, but could be a different (... | [
"def",
"indent",
"(",
"text",
",",
"branch_method",
",",
"leaf_method",
",",
"pass_syntax",
",",
"flush_left_syntax",
",",
"flush_left_empty_line",
",",
"indentation_method",
",",
"get_block",
"=",
"get_indented_block",
")",
":",
"text",
"=",
"text",
".",
"rstrip"... | Returns HTML as a basestring.
Parameters
----------
text : basestring
Source code, typically SHPAML, but could be a different (but
related) language. The remaining parameters specify details
about the language used in the source code. To parse SHPAML,
pass the same values... | [
"Returns",
"HTML",
"as",
"a",
"basestring",
"."
] | python | train |
openergy/oplus | oplus/epm/epm.py | https://github.com/openergy/oplus/blob/f095868d1990c1d126e906ada6acbab26348b3d3/oplus/epm/epm.py#L187-L195 | def get_external_files(self):
"""
An external file manages file paths.
"""
external_files = []
for table in self._tables.values():
for r in table:
external_files.extend([ef for ef in r.get_external_files()])
return external_files | [
"def",
"get_external_files",
"(",
"self",
")",
":",
"external_files",
"=",
"[",
"]",
"for",
"table",
"in",
"self",
".",
"_tables",
".",
"values",
"(",
")",
":",
"for",
"r",
"in",
"table",
":",
"external_files",
".",
"extend",
"(",
"[",
"ef",
"for",
"... | An external file manages file paths. | [
"An",
"external",
"file",
"manages",
"file",
"paths",
"."
] | python | test |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/classtracker_stats.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/classtracker_stats.py#L603-L634 | def create_lifetime_chart(self, classname, filename=''):
"""
Create chart that depicts the lifetime of the instance registered with
`classname`. The output is written to `filename`.
"""
try:
from pylab import figure, title, xlabel, ylabel, plot, savefig
except... | [
"def",
"create_lifetime_chart",
"(",
"self",
",",
"classname",
",",
"filename",
"=",
"''",
")",
":",
"try",
":",
"from",
"pylab",
"import",
"figure",
",",
"title",
",",
"xlabel",
",",
"ylabel",
",",
"plot",
",",
"savefig",
"except",
"ImportError",
":",
"... | Create chart that depicts the lifetime of the instance registered with
`classname`. The output is written to `filename`. | [
"Create",
"chart",
"that",
"depicts",
"the",
"lifetime",
"of",
"the",
"instance",
"registered",
"with",
"classname",
".",
"The",
"output",
"is",
"written",
"to",
"filename",
"."
] | python | train |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L554-L569 | def field2parameter(self, field, name="body", default_in="body"):
"""Return an OpenAPI parameter as a `dict`, given a marshmallow
:class:`Field <marshmallow.Field>`.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
"""
location = field.m... | [
"def",
"field2parameter",
"(",
"self",
",",
"field",
",",
"name",
"=",
"\"body\"",
",",
"default_in",
"=",
"\"body\"",
")",
":",
"location",
"=",
"field",
".",
"metadata",
".",
"get",
"(",
"\"location\"",
",",
"None",
")",
"prop",
"=",
"self",
".",
"fi... | Return an OpenAPI parameter as a `dict`, given a marshmallow
:class:`Field <marshmallow.Field>`.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject | [
"Return",
"an",
"OpenAPI",
"parameter",
"as",
"a",
"dict",
"given",
"a",
"marshmallow",
":",
"class",
":",
"Field",
"<marshmallow",
".",
"Field",
">",
"."
] | python | train |
NLeSC/noodles | noodles/tutorial.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/tutorial.py#L132-L137 | def snip_line(line, max_width, split_at):
"""Shorten a line to a maximum length."""
if len(line) < max_width:
return line
return line[:split_at] + " … " \
+ line[-(max_width - split_at - 3):] | [
"def",
"snip_line",
"(",
"line",
",",
"max_width",
",",
"split_at",
")",
":",
"if",
"len",
"(",
"line",
")",
"<",
"max_width",
":",
"return",
"line",
"return",
"line",
"[",
":",
"split_at",
"]",
"+",
"\" … \" \\",
"+",
"line",
"[",
"-",
"(",
"max_wid... | Shorten a line to a maximum length. | [
"Shorten",
"a",
"line",
"to",
"a",
"maximum",
"length",
"."
] | python | train |
LuminosoInsight/langcodes | langcodes/__init__.py | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L903-L914 | def _searchable_form(self) -> 'Language':
"""
Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR.
"""
if self._searchable is not None:
return self._searchable
self._searchable = self._f... | [
"def",
"_searchable_form",
"(",
"self",
")",
"->",
"'Language'",
":",
"if",
"self",
".",
"_searchable",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_searchable",
"self",
".",
"_searchable",
"=",
"self",
".",
"_filter_attributes",
"(",
"{",
"'language'"... | Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR. | [
"Convert",
"a",
"parsed",
"language",
"tag",
"so",
"that",
"the",
"information",
"it",
"contains",
"is",
"in",
"the",
"best",
"form",
"for",
"looking",
"up",
"information",
"in",
"the",
"CLDR",
"."
] | python | train |
google/grr | grr/server/grr_response_server/databases/mem_signed_binaries.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_signed_binaries.py#L52-L61 | def ReadSignedBinaryReferences(
self, binary_id
):
"""See db.Database."""
binary_key = _SignedBinaryKeyFromID(binary_id)
try:
references, timestamp = self.signed_binary_references[binary_key]
except KeyError:
raise db.UnknownSignedBinaryError(binary_id)
return references.Copy(), ... | [
"def",
"ReadSignedBinaryReferences",
"(",
"self",
",",
"binary_id",
")",
":",
"binary_key",
"=",
"_SignedBinaryKeyFromID",
"(",
"binary_id",
")",
"try",
":",
"references",
",",
"timestamp",
"=",
"self",
".",
"signed_binary_references",
"[",
"binary_key",
"]",
"exc... | See db.Database. | [
"See",
"db",
".",
"Database",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/vfs/os_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/os_file_system.py#L55-L91 | def FileEntryExistsByPathSpec(self, path_spec):
"""Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise.
"""
location = getattr(path_spec, 'location', None)
if lo... | [
"def",
"FileEntryExistsByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"location",
"=",
"getattr",
"(",
"path_spec",
",",
"'location'",
",",
"None",
")",
"if",
"location",
"is",
"None",
":",
"return",
"False",
"is_device",
"=",
"False",
"if",
"platform... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise. | [
"Determines",
"if",
"a",
"file",
"entry",
"for",
"a",
"path",
"specification",
"exists",
"."
] | python | train |
GoodCloud/django-zebra | zebra/utils.py | https://github.com/GoodCloud/django-zebra/blob/fdb2f2eb9eddb83eebb339359e629c88f4f6ba17/zebra/utils.py#L6-L26 | def audit_customer_subscription(customer, unknown=True):
"""
Audits the provided customer's subscription against stripe and returns a pair
that contains a boolean and a result type.
Default result types can be found in zebra.conf.defaults and can be
overridden in your project's settings.
"""
... | [
"def",
"audit_customer_subscription",
"(",
"customer",
",",
"unknown",
"=",
"True",
")",
":",
"if",
"(",
"hasattr",
"(",
"customer",
",",
"'suspended'",
")",
"and",
"customer",
".",
"suspended",
")",
":",
"result",
"=",
"AUDIT_RESULTS",
"[",
"'suspended'",
"... | Audits the provided customer's subscription against stripe and returns a pair
that contains a boolean and a result type.
Default result types can be found in zebra.conf.defaults and can be
overridden in your project's settings. | [
"Audits",
"the",
"provided",
"customer",
"s",
"subscription",
"against",
"stripe",
"and",
"returns",
"a",
"pair",
"that",
"contains",
"a",
"boolean",
"and",
"a",
"result",
"type",
"."
] | python | train |
KelSolaar/Umbra | umbra/ui/widgets/basic_QPlainTextEdit.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/basic_QPlainTextEdit.py#L500-L514 | def get_word_under_cursor(self):
"""
Returns the document word under cursor.
:return: Word under cursor.
:rtype: QString
"""
if not re.match(r"^\w+$", foundations.strings.to_string(self.get_previous_character())):
return QString()
cursor = self.text... | [
"def",
"get_word_under_cursor",
"(",
"self",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"r\"^\\w+$\"",
",",
"foundations",
".",
"strings",
".",
"to_string",
"(",
"self",
".",
"get_previous_character",
"(",
")",
")",
")",
":",
"return",
"QString",
"(",... | Returns the document word under cursor.
:return: Word under cursor.
:rtype: QString | [
"Returns",
"the",
"document",
"word",
"under",
"cursor",
"."
] | python | train |
adrianoveiga/django-media-fixtures | django_media_fixtures/management/commands/collectmedia.py | https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L70-L83 | def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = options['interactive']
self.verbosity = options['verbosity']
self.symlink = options['link']
self.clear = options['clear']
self.dry_run = options['d... | [
"def",
"set_options",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"interactive",
"=",
"options",
"[",
"'interactive'",
"]",
"self",
".",
"verbosity",
"=",
"options",
"[",
"'verbosity'",
"]",
"self",
".",
"symlink",
"=",
"options",
"[",
... | Set instance variables based on an options dict | [
"Set",
"instance",
"variables",
"based",
"on",
"an",
"options",
"dict"
] | python | valid |
mathandy/svgpathtools | svgpathtools/bezier.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/bezier.py#L281-L335 | def bezier_intersections(bez1, bez2, longer_length, tol=1e-8, tol_deC=1e-8):
"""INPUT:
bez1, bez2 = [P0,P1,P2,...PN], [Q0,Q1,Q2,...,PN] defining the two
Bezier curves to check for intersections between.
longer_length - the length (or an upper bound) on the longer of the two
Bezier curves. Determine... | [
"def",
"bezier_intersections",
"(",
"bez1",
",",
"bez2",
",",
"longer_length",
",",
"tol",
"=",
"1e-8",
",",
"tol_deC",
"=",
"1e-8",
")",
":",
"maxits",
"=",
"int",
"(",
"ceil",
"(",
"1",
"-",
"log",
"(",
"tol_deC",
"/",
"longer_length",
")",
"/",
"l... | INPUT:
bez1, bez2 = [P0,P1,P2,...PN], [Q0,Q1,Q2,...,PN] defining the two
Bezier curves to check for intersections between.
longer_length - the length (or an upper bound) on the longer of the two
Bezier curves. Determines the maximum iterations needed together with tol.
tol - is the smallest distanc... | [
"INPUT",
":",
"bez1",
"bez2",
"=",
"[",
"P0",
"P1",
"P2",
"...",
"PN",
"]",
"[",
"Q0",
"Q1",
"Q2",
"...",
"PN",
"]",
"defining",
"the",
"two",
"Bezier",
"curves",
"to",
"check",
"for",
"intersections",
"between",
".",
"longer_length",
"-",
"the",
"le... | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L11113-L11133 | def set_c(a, op, b):
"""
Given a relational operator, compare two sets of any data type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/set_c.html
:param a: First set.
:type a: spiceypy.utils.support_types.SpiceCell
:param op: Comparison operator.
:type op: str
:param b: Secon... | [
"def",
"set_c",
"(",
"a",
",",
"op",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"isinstance",
"(",
"b",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"a",
".",
"dtype",
"==",
"b",
".",
... | Given a relational operator, compare two sets of any data type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/set_c.html
:param a: First set.
:type a: spiceypy.utils.support_types.SpiceCell
:param op: Comparison operator.
:type op: str
:param b: Second set.
:type b: spiceypy.util... | [
"Given",
"a",
"relational",
"operator",
"compare",
"two",
"sets",
"of",
"any",
"data",
"type",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L675-L688 | def get_interface_detail_input_request_type_get_request_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_det... | [
"def",
"get_interface_detail_input_request_type_get_request_interface_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\""... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
yourcelf/escapejson | escapejson/templatetags/escapejson.py | https://github.com/yourcelf/escapejson/blob/5b39160ae619542cc16db7a443b752d64ff5c416/escapejson/templatetags/escapejson.py#L12-L21 | def escapejson_filter(value):
"""
Escape `value` to prevent </script> and unicode whitespace attacks. If
`value` is not a string, JSON-encode it first.
"""
if isinstance(value, six.string_types):
string = value
else:
string = json.dumps(value, cls=DjangoJSONEncoder)
return ma... | [
"def",
"escapejson_filter",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"string",
"=",
"value",
"else",
":",
"string",
"=",
"json",
".",
"dumps",
"(",
"value",
",",
"cls",
"=",
"DjangoJSONEncoder",... | Escape `value` to prevent </script> and unicode whitespace attacks. If
`value` is not a string, JSON-encode it first. | [
"Escape",
"value",
"to",
"prevent",
"<",
"/",
"script",
">",
"and",
"unicode",
"whitespace",
"attacks",
".",
"If",
"value",
"is",
"not",
"a",
"string",
"JSON",
"-",
"encode",
"it",
"first",
"."
] | python | train |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L4166-L4173 | def reader(self, sock, handler, arg):
"""
Register socket reader with the reactor. When the reader has messages,
the reactor will call the handler, passing the arg. Returns 0 if OK, -1
if there was an error. If you register the same socket more than once,
each instance will invoke its corresponding hand... | [
"def",
"reader",
"(",
"self",
",",
"sock",
",",
"handler",
",",
"arg",
")",
":",
"return",
"lib",
".",
"zloop_reader",
"(",
"self",
".",
"_as_parameter_",
",",
"sock",
",",
"handler",
",",
"arg",
")"
] | Register socket reader with the reactor. When the reader has messages,
the reactor will call the handler, passing the arg. Returns 0 if OK, -1
if there was an error. If you register the same socket more than once,
each instance will invoke its corresponding handler. | [
"Register",
"socket",
"reader",
"with",
"the",
"reactor",
".",
"When",
"the",
"reader",
"has",
"messages",
"the",
"reactor",
"will",
"call",
"the",
"handler",
"passing",
"the",
"arg",
".",
"Returns",
"0",
"if",
"OK",
"-",
"1",
"if",
"there",
"was",
"an",... | python | train |
chdzq/ARPAbetAndIPAConvertor | arpabetandipaconvertor/model/syllable.py | https://github.com/chdzq/ARPAbetAndIPAConvertor/blob/e8b2fdbb5b7134c4f779f4d6dcd5dc30979a0a26/arpabetandipaconvertor/model/syllable.py#L57-L70 | def translate_to_american_phonetic_alphabet(self, hide_stress_mark=False):
'''
转换成美音音。只要一个元音的时候需要隐藏重音标识
:param hide_stress_mark:
:return:
'''
translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else ""
for phoneme in self._phonem... | [
"def",
"translate_to_american_phonetic_alphabet",
"(",
"self",
",",
"hide_stress_mark",
"=",
"False",
")",
":",
"translations",
"=",
"self",
".",
"stress",
".",
"mark_ipa",
"(",
")",
"if",
"(",
"not",
"hide_stress_mark",
")",
"and",
"self",
".",
"have_vowel",
... | 转换成美音音。只要一个元音的时候需要隐藏重音标识
:param hide_stress_mark:
:return: | [
"转换成美音音。只要一个元音的时候需要隐藏重音标识",
":",
"param",
"hide_stress_mark",
":",
":",
"return",
":"
] | python | train |
sernst/cauldron | cauldron/session/writing/components/project_component.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/project_component.py#L56-L76 | def create_many(
project: 'projects.Project',
include_paths: typing.List[str]
) -> COMPONENT:
"""
Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of re... | [
"def",
"create_many",
"(",
"project",
":",
"'projects.Project'",
",",
"include_paths",
":",
"typing",
".",
"List",
"[",
"str",
"]",
")",
"->",
"COMPONENT",
":",
"return",
"definitions",
".",
"merge_components",
"(",
"*",
"map",
"(",
"functools",
".",
"partia... | Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of relative paths within the project directory to files or
directories that should be included in the project
:retu... | [
"Creates",
"a",
"single",
"COMPONENT",
"instance",
"for",
"all",
"of",
"the",
"specified",
"project",
"include",
"paths"
] | python | train |
WhyNotHugo/django-afip | django_afip/models.py | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L321-L341 | def generate_key(self, force=False):
"""
Creates a key file for this TaxPayer
Creates a key file for this TaxPayer if it does not have one, and
immediately saves it.
Returns True if and only if a key was created.
"""
if self.key and not force:
logger... | [
"def",
"generate_key",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"key",
"and",
"not",
"force",
":",
"logger",
".",
"warning",
"(",
"'Tried to generate key for a taxpayer that already had one'",
")",
"return",
"False",
"with",
"NamedTe... | Creates a key file for this TaxPayer
Creates a key file for this TaxPayer if it does not have one, and
immediately saves it.
Returns True if and only if a key was created. | [
"Creates",
"a",
"key",
"file",
"for",
"this",
"TaxPayer"
] | python | train |
PyCQA/pylint | pylint/checkers/imports.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L187-L192 | def _make_graph(filename, dep_info, sect, gtype):
"""generate a dependencies graph and add some information about it in the
report's section
"""
_dependencies_graph(filename, dep_info)
sect.append(Paragraph("%simports graph has been written to %s" % (gtype, filename))) | [
"def",
"_make_graph",
"(",
"filename",
",",
"dep_info",
",",
"sect",
",",
"gtype",
")",
":",
"_dependencies_graph",
"(",
"filename",
",",
"dep_info",
")",
"sect",
".",
"append",
"(",
"Paragraph",
"(",
"\"%simports graph has been written to %s\"",
"%",
"(",
"gtyp... | generate a dependencies graph and add some information about it in the
report's section | [
"generate",
"a",
"dependencies",
"graph",
"and",
"add",
"some",
"information",
"about",
"it",
"in",
"the",
"report",
"s",
"section"
] | python | test |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L878-L890 | def set_drum_motor(self, drum_motor):
"""Set the drum motor config.
:param drum_motor: Value to set the drum motor
:type drum_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(drum_motor) != bool:
raise InvalidInput("Drum motor value must b... | [
"def",
"set_drum_motor",
"(",
"self",
",",
"drum_motor",
")",
":",
"if",
"type",
"(",
"drum_motor",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Drum motor value must be bool\"",
")",
"self",
".",
"_config",
"[",
"'drum_motor'",
"]",
"=",
"bool2int... | Set the drum motor config.
:param drum_motor: Value to set the drum motor
:type drum_motor: bool
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"drum",
"motor",
"config",
"."
] | python | train |
CanopyTax/asyncpgsa | asyncpgsa/pgsingleton.py | https://github.com/CanopyTax/asyncpgsa/blob/22c39681b7141c3b8b9d7913de3909ced81c7967/asyncpgsa/pgsingleton.py#L30-L37 | async def init(self, *args, dialect=None, **kwargs):
"""
:param args: args for pool
:param dialect: sqlalchemy postgres dialect
:param kwargs: kwargs for pool
:return: None
"""
self.__pool = await create_pool(*args, dialect=dialect, **kwargs) | [
"async",
"def",
"init",
"(",
"self",
",",
"*",
"args",
",",
"dialect",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__pool",
"=",
"await",
"create_pool",
"(",
"*",
"args",
",",
"dialect",
"=",
"dialect",
",",
"*",
"*",
"kwargs",
... | :param args: args for pool
:param dialect: sqlalchemy postgres dialect
:param kwargs: kwargs for pool
:return: None | [
":",
"param",
"args",
":",
"args",
"for",
"pool",
":",
"param",
"dialect",
":",
"sqlalchemy",
"postgres",
"dialect",
":",
"param",
"kwargs",
":",
"kwargs",
"for",
"pool",
":",
"return",
":",
"None"
] | python | train |
titusjan/argos | argos/qt/treemodels.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L220-L228 | def rowCount(self, parentIndex=QtCore.QModelIndex()):
""" Returns the number of rows under the given parent. When the parent is valid it means
that rowCount is returning the number of children of parent.
Note: When implementing a table based model, rowCount() should return 0 when the pa... | [
"def",
"rowCount",
"(",
"self",
",",
"parentIndex",
"=",
"QtCore",
".",
"QModelIndex",
"(",
")",
")",
":",
"parentItem",
"=",
"self",
".",
"getItem",
"(",
"parentIndex",
",",
"altItem",
"=",
"self",
".",
"invisibleRootItem",
")",
"return",
"parentItem",
".... | Returns the number of rows under the given parent. When the parent is valid it means
that rowCount is returning the number of children of parent.
Note: When implementing a table based model, rowCount() should return 0 when the parent
is valid. | [
"Returns",
"the",
"number",
"of",
"rows",
"under",
"the",
"given",
"parent",
".",
"When",
"the",
"parent",
"is",
"valid",
"it",
"means",
"that",
"rowCount",
"is",
"returning",
"the",
"number",
"of",
"children",
"of",
"parent",
"."
] | python | train |
daknuett/py_register_machine2 | engine_tools/operations.py | https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/engine_tools/operations.py#L8-L23 | def bitsetxor(b1, b2):
"""
If b1 and b2 would be ``int`` s this would be ``b1 ^ b2`` :
>>> from py_register_machine2.engine_tools.operations import bitsetxor
>>> b1 = [1, 1, 1, 1]
>>> b2 = [1, 1, 0, 1]
>>> bitsetxor(b1, b2)
[0, 0, 1, 0]
>>> bin(0b1111 ^ 0b1101)
'0b10'
"""
res = []
for bit1, bit2 in zip(b1,... | [
"def",
"bitsetxor",
"(",
"b1",
",",
"b2",
")",
":",
"res",
"=",
"[",
"]",
"for",
"bit1",
",",
"bit2",
"in",
"zip",
"(",
"b1",
",",
"b2",
")",
":",
"res",
".",
"append",
"(",
"bit1",
"^",
"bit2",
")",
"return",
"res"
] | If b1 and b2 would be ``int`` s this would be ``b1 ^ b2`` :
>>> from py_register_machine2.engine_tools.operations import bitsetxor
>>> b1 = [1, 1, 1, 1]
>>> b2 = [1, 1, 0, 1]
>>> bitsetxor(b1, b2)
[0, 0, 1, 0]
>>> bin(0b1111 ^ 0b1101)
'0b10' | [
"If",
"b1",
"and",
"b2",
"would",
"be",
"int",
"s",
"this",
"would",
"be",
"b1",
"^",
"b2",
":"
] | python | train |
awslabs/aws-sam-cli | samcli/commands/_utils/template.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/_utils/template.py#L208-L237 | def _resolve_relative_to(path, original_root, new_root):
"""
If the given ``path`` is a relative path, then assume it is relative to ``original_root``. This method will
update the path to be resolve it relative to ``new_root`` and return.
Examples
-------
# Assume a file called template.txt... | [
"def",
"_resolve_relative_to",
"(",
"path",
",",
"original_root",
",",
"new_root",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
"or",
"path",
".",
"startswith",
"(",
"\"s3://\"",
")",
"or",
"os",
".",
"path",
".... | If the given ``path`` is a relative path, then assume it is relative to ``original_root``. This method will
update the path to be resolve it relative to ``new_root`` and return.
Examples
-------
# Assume a file called template.txt at location /tmp/original/root/template.txt expressed as relative pa... | [
"If",
"the",
"given",
"path",
"is",
"a",
"relative",
"path",
"then",
"assume",
"it",
"is",
"relative",
"to",
"original_root",
".",
"This",
"method",
"will",
"update",
"the",
"path",
"to",
"be",
"resolve",
"it",
"relative",
"to",
"new_root",
"and",
"return"... | python | train |
apriha/lineage | src/lineage/resources.py | https://github.com/apriha/lineage/blob/13106a62a959a80ac26c68d1566422de08aa877b/src/lineage/resources.py#L379-L415 | def _load_knownGene(filename):
""" Load UCSC knownGene table.
Parameters
----------
filename : str
path to knownGene file
Returns
-------
df : pandas.DataFrame
knownGene table if loading was successful, else None
"""
try:
... | [
"def",
"_load_knownGene",
"(",
"filename",
")",
":",
"try",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"filename",
",",
"names",
"=",
"[",
"\"name\"",
",",
"\"chrom\"",
",",
"\"strand\"",
",",
"\"txStart\"",
",",
"\"txEnd\"",
",",
"\"cdsStart\"",
",",
... | Load UCSC knownGene table.
Parameters
----------
filename : str
path to knownGene file
Returns
-------
df : pandas.DataFrame
knownGene table if loading was successful, else None | [
"Load",
"UCSC",
"knownGene",
"table",
"."
] | python | train |
gunthercox/ChatterBot | chatterbot/trainers.py | https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L83-L117 | def train(self, conversation):
"""
Train the chat bot based on the provided list of
statements that represents a single conversation.
"""
previous_statement_text = None
previous_statement_search_text = ''
statements_to_create = []
for conversation_count,... | [
"def",
"train",
"(",
"self",
",",
"conversation",
")",
":",
"previous_statement_text",
"=",
"None",
"previous_statement_search_text",
"=",
"''",
"statements_to_create",
"=",
"[",
"]",
"for",
"conversation_count",
",",
"text",
"in",
"enumerate",
"(",
"conversation",
... | Train the chat bot based on the provided list of
statements that represents a single conversation. | [
"Train",
"the",
"chat",
"bot",
"based",
"on",
"the",
"provided",
"list",
"of",
"statements",
"that",
"represents",
"a",
"single",
"conversation",
"."
] | python | train |
chaoss/grimoirelab-perceval-mozilla | perceval/backends/mozilla/kitsune.py | https://github.com/chaoss/grimoirelab-perceval-mozilla/blob/4514f8d3d609d3cb79d83c72d51fcc4b4a7daeb4/perceval/backends/mozilla/kitsune.py#L74-L87 | def fetch(self, category=CATEGORY_QUESTION, offset=DEFAULT_OFFSET):
"""Fetch questions from the Kitsune url.
:param category: the category of items to fetch
:offset: obtain questions after offset
:returns: a generator of questions
"""
if not offset:
offset = ... | [
"def",
"fetch",
"(",
"self",
",",
"category",
"=",
"CATEGORY_QUESTION",
",",
"offset",
"=",
"DEFAULT_OFFSET",
")",
":",
"if",
"not",
"offset",
":",
"offset",
"=",
"DEFAULT_OFFSET",
"kwargs",
"=",
"{",
"\"offset\"",
":",
"offset",
"}",
"items",
"=",
"super"... | Fetch questions from the Kitsune url.
:param category: the category of items to fetch
:offset: obtain questions after offset
:returns: a generator of questions | [
"Fetch",
"questions",
"from",
"the",
"Kitsune",
"url",
"."
] | python | test |
ikalnytskyi/dooku | dooku/conf.py | https://github.com/ikalnytskyi/dooku/blob/77e6c82c9c41211c86ee36ae5e591d477945fedf/dooku/conf.py#L150-L166 | def from_yaml(self, filename, encoding='utf-8', silent=False):
"""
Updates recursively the value in the the config from a YAML file.
The method requires the PyYAML to be installed.
:param filename: (str) a filename of the YAML file
:param encoding: (str) an encoding of the file... | [
"def",
"from_yaml",
"(",
"self",
",",
"filename",
",",
"encoding",
"=",
"'utf-8'",
",",
"silent",
"=",
"False",
")",
":",
"if",
"not",
"yaml",
":",
"raise",
"AttributeError",
"(",
"'You need to install PyYAML before using this method!'",
")",
"self",
".",
"from_... | Updates recursively the value in the the config from a YAML file.
The method requires the PyYAML to be installed.
:param filename: (str) a filename of the YAML file
:param encoding: (str) an encoding of the filename
:param silent: (bool) fails silently if something wrong with yaml file... | [
"Updates",
"recursively",
"the",
"value",
"in",
"the",
"the",
"config",
"from",
"a",
"YAML",
"file",
"."
] | python | train |
thiagopbueno/rddl2tf | rddl2tf/compiler.py | https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/compiler.py#L165-L182 | def compile_cpfs(self,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[Noise] = None) -> Tuple[List[CPFPair], List[CPFPair]]:
'''Compiles the intermediate and next state fluent CPFs given the current `state` and `ac... | [
"def",
"compile_cpfs",
"(",
"self",
",",
"scope",
":",
"Dict",
"[",
"str",
",",
"TensorFluent",
"]",
",",
"batch_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"noise",
":",
"Optional",
"[",
"Noise",
"]",
"=",
"None",
")",
"->",
"Tuple",
... | Compiles the intermediate and next state fluent CPFs given the current `state` and `action` scope.
Args:
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation.
batch_size (Optional[int]): The batch size.
Returns:
Tuple[List[CPFPa... | [
"Compiles",
"the",
"intermediate",
"and",
"next",
"state",
"fluent",
"CPFs",
"given",
"the",
"current",
"state",
"and",
"action",
"scope",
"."
] | python | train |
fabiobatalha/crossrefapi | crossref/restful.py | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L741-L787 | def filter(self, **kwargs):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded and recursively with query, filter,
order, sort and facet m... | [
"def",
"filter",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"str",
"(",
"self",
".",
"context",
")",
"request_url",
"=",
"build_url_endpoint",
"(",
"self",
".",
"ENDPOINT",
",",
"context",
")",
"request_params",
"=",
"dict",
"(",
"... | This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded and recursively with query, filter,
order, sort and facet methods.
kwargs: valid FILTER_VALIDATOR ... | [
"This",
"method",
"retrieve",
"an",
"iterable",
"object",
"that",
"implements",
"the",
"method",
"__iter__",
".",
"The",
"arguments",
"given",
"will",
"compose",
"the",
"parameters",
"in",
"the",
"request",
"url",
"."
] | python | train |
CalebBell/thermo | thermo/eos.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L2656-L2722 | def solve_T(self, P, V, quick=True):
r'''Method to calculate `T` from a specified `P` and `V` for the SRK
EOS. Uses `a`, `b`, and `Tc` obtained from the class's namespace.
Parameters
----------
P : float
Pressure, [Pa]
V : float
Molar volume, [m^3... | [
"def",
"solve_T",
"(",
"self",
",",
"P",
",",
"V",
",",
"quick",
"=",
"True",
")",
":",
"a",
",",
"b",
",",
"Tc",
",",
"m",
"=",
"self",
".",
"a",
",",
"self",
".",
"b",
",",
"self",
".",
"Tc",
",",
"self",
".",
"m",
"if",
"quick",
":",
... | r'''Method to calculate `T` from a specified `P` and `V` for the SRK
EOS. Uses `a`, `b`, and `Tc` obtained from the class's namespace.
Parameters
----------
P : float
Pressure, [Pa]
V : float
Molar volume, [m^3/mol]
quick : bool, optional
... | [
"r",
"Method",
"to",
"calculate",
"T",
"from",
"a",
"specified",
"P",
"and",
"V",
"for",
"the",
"SRK",
"EOS",
".",
"Uses",
"a",
"b",
"and",
"Tc",
"obtained",
"from",
"the",
"class",
"s",
"namespace",
"."
] | python | valid |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L6588-L6597 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'documents') and self.documents is not None:
_dict['documents'] = self.documents._to_dict()
if hasattr(self, 'disk_usage') and self.disk_usage is not None:
_dic... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'documents'",
")",
"and",
"self",
".",
"documents",
"is",
"not",
"None",
":",
"_dict",
"[",
"'documents'",
"]",
"=",
"self",
".",
"documents",
".",
... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
jmgilman/Neolib | neolib/pyamf/sol.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/sol.py#L136-L161 | def load(name_or_file):
"""
Loads a sol file and returns a L{SOL} object.
@param name_or_file: Name of file, or file-object.
@type name_or_file: C{string}
"""
f = name_or_file
opened = False
if isinstance(name_or_file, basestring):
f = open(name_or_file, 'rb')
opened = ... | [
"def",
"load",
"(",
"name_or_file",
")",
":",
"f",
"=",
"name_or_file",
"opened",
"=",
"False",
"if",
"isinstance",
"(",
"name_or_file",
",",
"basestring",
")",
":",
"f",
"=",
"open",
"(",
"name_or_file",
",",
"'rb'",
")",
"opened",
"=",
"True",
"elif",
... | Loads a sol file and returns a L{SOL} object.
@param name_or_file: Name of file, or file-object.
@type name_or_file: C{string} | [
"Loads",
"a",
"sol",
"file",
"and",
"returns",
"a",
"L",
"{",
"SOL",
"}",
"object",
"."
] | python | train |
draios/python-sdc-client | sdcclient/_monitor.py | https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L698-L751 | def create_dashboard_from_file(self, dashboard_name, filename, filter, shared=False, public=False):
'''
**Description**
Create a new dasboard using a dashboard template saved to disk. See :func:`~SdcClient.save_dashboard_to_file` to use the file to create a dashboard (usefl to create and res... | [
"def",
"create_dashboard_from_file",
"(",
"self",
",",
"dashboard_name",
",",
"filename",
",",
"filter",
",",
"shared",
"=",
"False",
",",
"public",
"=",
"False",
")",
":",
"#",
"# Load the Dashboard",
"#",
"with",
"open",
"(",
"filename",
")",
"as",
"data_f... | **Description**
Create a new dasboard using a dashboard template saved to disk. See :func:`~SdcClient.save_dashboard_to_file` to use the file to create a dashboard (usefl to create and restore backups).
The file can contain the following JSON formats:
1. dashboard object in the form... | [
"**",
"Description",
"**",
"Create",
"a",
"new",
"dasboard",
"using",
"a",
"dashboard",
"template",
"saved",
"to",
"disk",
".",
"See",
":",
"func",
":",
"~SdcClient",
".",
"save_dashboard_to_file",
"to",
"use",
"the",
"file",
"to",
"create",
"a",
"dashboard"... | python | test |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/coordination_v1beta1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/coordination_v1beta1_api.py#L283-L310 | def delete_namespaced_lease(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_lease # noqa: E501
delete a Lease # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread ... | [
"def",
"delete_namespaced_lease",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | delete_namespaced_lease # noqa: E501
delete a Lease # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_lease(name, namespace, async_req=True)
>>> result = thr... | [
"delete_namespaced_lease",
"#",
"noqa",
":",
"E501"
] | python | train |
RedFantom/ttkwidgets | ttkwidgets/table.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/table.py#L266-L274 | def _on_motion(self, event):
"""Drag around label if visible."""
if not self._visual_drag.winfo_ismapped():
return
if self._drag_cols and self._dragged_col is not None:
self._drag_col(event)
elif self._drag_rows and self._dragged_row is not None:
self... | [
"def",
"_on_motion",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"_visual_drag",
".",
"winfo_ismapped",
"(",
")",
":",
"return",
"if",
"self",
".",
"_drag_cols",
"and",
"self",
".",
"_dragged_col",
"is",
"not",
"None",
":",
"self",
"... | Drag around label if visible. | [
"Drag",
"around",
"label",
"if",
"visible",
"."
] | python | train |
sci-bots/svg-model | docs/generate_modules.py | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L85-L114 | def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
package = os.path.split(root)[-1]
text = format_heading(1, '%s Package' % package)
# add each package's module
for py_file in py_files:
if shall_skip(os.path.joi... | [
"def",
"create_package_file",
"(",
"root",
",",
"master_package",
",",
"subroot",
",",
"py_files",
",",
"opts",
",",
"subs",
")",
":",
"package",
"=",
"os",
".",
"path",
".",
"split",
"(",
"root",
")",
"[",
"-",
"1",
"]",
"text",
"=",
"format_heading",... | Build the text of the file and write the file. | [
"Build",
"the",
"text",
"of",
"the",
"file",
"and",
"write",
"the",
"file",
"."
] | python | train |
QuantEcon/QuantEcon.py | quantecon/markov/core.py | https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/markov/core.py#L277-L313 | def _get_index(self, value):
"""
Return the index of the given value in `state_values`.
Parameters
----------
value
Value to get the index for.
Returns
-------
idx : int
Index of `value`.
"""
error_msg = 'value {0... | [
"def",
"_get_index",
"(",
"self",
",",
"value",
")",
":",
"error_msg",
"=",
"'value {0} not found'",
".",
"format",
"(",
"value",
")",
"if",
"self",
".",
"state_values",
"is",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Integral",
... | Return the index of the given value in `state_values`.
Parameters
----------
value
Value to get the index for.
Returns
-------
idx : int
Index of `value`. | [
"Return",
"the",
"index",
"of",
"the",
"given",
"value",
"in",
"state_values",
"."
] | python | train |
iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L186-L224 | def connect_async(self, connection_id, connection_string, callback, retries=4):
"""Connect to a device by its connection_string
This function asynchronously connects to a device by its BLE address passed in the
connection_string parameter and calls callback when finished. Callback is called
... | [
"def",
"connect_async",
"(",
"self",
",",
"connection_id",
",",
"connection_string",
",",
"callback",
",",
"retries",
"=",
"4",
")",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'connection_id'",
"]",
"=",
"connection_id",
"context",
"[",
"'callback'",
"]... | Connect to a device by its connection_string
This function asynchronously connects to a device by its BLE address passed in the
connection_string parameter and calls callback when finished. Callback is called
on either success or failure with the signature:
callback(conn_id: int, resu... | [
"Connect",
"to",
"a",
"device",
"by",
"its",
"connection_string"
] | python | train |
openthread/openthread | tools/harness-thci/OpenThread.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread.py#L89-L113 | def _expect(self, expected, times=50):
"""Find the `expected` line within `times` trials.
Args:
expected str: the expected string
times int: number of trials
"""
print '[%s] Expecting [%s]' % (self.port, expected)
retry_times = 10
while ... | [
"def",
"_expect",
"(",
"self",
",",
"expected",
",",
"times",
"=",
"50",
")",
":",
"print",
"'[%s] Expecting [%s]'",
"%",
"(",
"self",
".",
"port",
",",
"expected",
")",
"retry_times",
"=",
"10",
"while",
"times",
">",
"0",
"and",
"retry_times",
">",
"... | Find the `expected` line within `times` trials.
Args:
expected str: the expected string
times int: number of trials | [
"Find",
"the",
"expected",
"line",
"within",
"times",
"trials",
"."
] | python | train |
DataDog/integrations-core | openstack_controller/datadog_checks/openstack_controller/openstack_controller.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/openstack_controller/datadog_checks/openstack_controller/openstack_controller.py#L181-L186 | def _parse_uptime_string(self, uptime):
""" Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' """
uptime = uptime.strip()
load_averages = uptime[uptime.find('load average:') :].split(':')[1].strip().split(',')
load_averages = [float(load_avg) for load_avg in... | [
"def",
"_parse_uptime_string",
"(",
"self",
",",
"uptime",
")",
":",
"uptime",
"=",
"uptime",
".",
"strip",
"(",
")",
"load_averages",
"=",
"uptime",
"[",
"uptime",
".",
"find",
"(",
"'load average:'",
")",
":",
"]",
".",
"split",
"(",
"':'",
")",
"[",... | Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' | [
"Parse",
"u",
"16",
":",
"53",
":",
"48",
"up",
"1",
"day",
"21",
":",
"34",
"3",
"users",
"load",
"average",
":",
"0",
".",
"04",
"0",
".",
"14",
"0",
".",
"19",
"\\",
"n"
] | python | train |
firstprayer/monsql | monsql/db.py | https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/db.py#L158-L186 | def raw(self, sql):
"""
Execute raw sql
:Parameters:
- sql: string, sql to be executed
:Return: the result of this execution
If it's a select, return a list with each element be a DataRow instance
Otherwise return raw result from the cursor (Should be insert o... | [
"def",
"raw",
"(",
"self",
",",
"sql",
")",
":",
"res",
"=",
"self",
".",
"cursor",
".",
"execute",
"(",
"sql",
")",
"if",
"self",
".",
"cursor",
".",
"description",
"is",
"None",
":",
"return",
"res",
"rows",
"=",
"self",
".",
"cursor",
".",
"fe... | Execute raw sql
:Parameters:
- sql: string, sql to be executed
:Return: the result of this execution
If it's a select, return a list with each element be a DataRow instance
Otherwise return raw result from the cursor (Should be insert or update or delete) | [
"Execute",
"raw",
"sql",
":",
"Parameters",
":"
] | python | train |
angr/angr | angr/analyses/reassembler.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/reassembler.py#L1862-L1887 | def main_nonexecutable_region_limbos_contain(self, addr, tolerance_before=64, tolerance_after=64):
"""
Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes
after the beginning of the section. We take care of that here.
:param int ... | [
"def",
"main_nonexecutable_region_limbos_contain",
"(",
"self",
",",
"addr",
",",
"tolerance_before",
"=",
"64",
",",
"tolerance_after",
"=",
"64",
")",
":",
"closest_region",
"=",
"None",
"least_limbo",
"=",
"None",
"for",
"start",
",",
"end",
"in",
"self",
"... | Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes
after the beginning of the section. We take care of that here.
:param int addr: The address to check.
:return: A 2-tuple of (bool, the closest base address)
:rtype: tuple | [
"Sometimes",
"there",
"exists",
"a",
"pointer",
"that",
"points",
"to",
"a",
"few",
"bytes",
"before",
"the",
"beginning",
"of",
"a",
"section",
"or",
"a",
"few",
"bytes",
"after",
"the",
"beginning",
"of",
"the",
"section",
".",
"We",
"take",
"care",
"o... | python | train |
dpkp/kafka-python | benchmarks/varint_speed.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/benchmarks/varint_speed.py#L322-L352 | def decode_varint_1(buffer, pos=0):
""" Decode an integer from a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
buffer (bytes-like): any object acceptable by ``memoryview``
pos (int... | [
"def",
"decode_varint_1",
"(",
"buffer",
",",
"pos",
"=",
"0",
")",
":",
"value",
"=",
"0",
"shift",
"=",
"0",
"memview",
"=",
"memoryview",
"(",
"buffer",
")",
"for",
"i",
"in",
"range",
"(",
"pos",
",",
"pos",
"+",
"10",
")",
":",
"try",
":",
... | Decode an integer from a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
buffer (bytes-like): any object acceptable by ``memoryview``
pos (int): optional position to read from
R... | [
"Decode",
"an",
"integer",
"from",
"a",
"varint",
"presentation",
".",
"See",
"https",
":",
"//",
"developers",
".",
"google",
".",
"com",
"/",
"protocol",
"-",
"buffers",
"/",
"docs",
"/",
"encoding?csw",
"=",
"1#varints",
"on",
"how",
"those",
"can",
"... | python | train |
hearsaycorp/normalize | normalize/visitor.py | https://github.com/hearsaycorp/normalize/blob/8b36522ddca6d41b434580bd848f3bdaa7a999c8/normalize/visitor.py#L554-L559 | def itemtypes(cls, mapped_types, coll_type, visitor):
"""Like :py:meth:`normalize.visitor.VisitorPattern.aggregate`, but
returns . This will normally only get called with a single type.
"""
rv = list(v for k, v in mapped_types)
return rv[0] if len(rv) == 1 else rv | [
"def",
"itemtypes",
"(",
"cls",
",",
"mapped_types",
",",
"coll_type",
",",
"visitor",
")",
":",
"rv",
"=",
"list",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"mapped_types",
")",
"return",
"rv",
"[",
"0",
"]",
"if",
"len",
"(",
"rv",
")",
"==",
"1",
... | Like :py:meth:`normalize.visitor.VisitorPattern.aggregate`, but
returns . This will normally only get called with a single type. | [
"Like",
":",
"py",
":",
"meth",
":",
"normalize",
".",
"visitor",
".",
"VisitorPattern",
".",
"aggregate",
"but",
"returns",
".",
"This",
"will",
"normally",
"only",
"get",
"called",
"with",
"a",
"single",
"type",
"."
] | python | train |
jkenlooper/chill | src/chill/database.py | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/database.py#L127-L146 | def insert_query(**kw):
"""
Insert a query name for a node_id.
`name`
`node_id`
Adds the name to the Query table if not already there. Sets the query field
in Node table.
"""
with current_app.app_context():
result = db.execute(text(fetch_query_string('select_query_where_name.sql... | [
"def",
"insert_query",
"(",
"*",
"*",
"kw",
")",
":",
"with",
"current_app",
".",
"app_context",
"(",
")",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'select_query_where_name.sql'",
")",
")",
",",
"*",
"*",
"k... | Insert a query name for a node_id.
`name`
`node_id`
Adds the name to the Query table if not already there. Sets the query field
in Node table. | [
"Insert",
"a",
"query",
"name",
"for",
"a",
"node_id",
".",
"name",
"node_id"
] | python | train |
jhermann/rudiments | src/rudiments/reamed/click.py | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L97-L102 | def from_context(cls, ctx, config_paths=None, project=None):
"""Create a configuration object, and initialize the Click context with it."""
if ctx.obj is None:
ctx.obj = Bunch()
ctx.obj.cfg = cls(ctx.info_name, config_paths, project=project)
return ctx.obj.cfg | [
"def",
"from_context",
"(",
"cls",
",",
"ctx",
",",
"config_paths",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"if",
"ctx",
".",
"obj",
"is",
"None",
":",
"ctx",
".",
"obj",
"=",
"Bunch",
"(",
")",
"ctx",
".",
"obj",
".",
"cfg",
"=",
"... | Create a configuration object, and initialize the Click context with it. | [
"Create",
"a",
"configuration",
"object",
"and",
"initialize",
"the",
"Click",
"context",
"with",
"it",
"."
] | python | train |
rainwoodman/sharedmem | sharedmem/sharedmem.py | https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L546-L557 | def wait(self):
""" Wait and join the child process.
The return value of the function call is returned.
If any exception occurred it is wrapped and raised.
"""
e, r = self.result.get()
self.slave.join()
self.slave = None
self.result = None
... | [
"def",
"wait",
"(",
"self",
")",
":",
"e",
",",
"r",
"=",
"self",
".",
"result",
".",
"get",
"(",
")",
"self",
".",
"slave",
".",
"join",
"(",
")",
"self",
".",
"slave",
"=",
"None",
"self",
".",
"result",
"=",
"None",
"if",
"isinstance",
"(",
... | Wait and join the child process.
The return value of the function call is returned.
If any exception occurred it is wrapped and raised. | [
"Wait",
"and",
"join",
"the",
"child",
"process",
".",
"The",
"return",
"value",
"of",
"the",
"function",
"call",
"is",
"returned",
".",
"If",
"any",
"exception",
"occurred",
"it",
"is",
"wrapped",
"and",
"raised",
"."
] | python | valid |
miyakogi/m2r | m2r.py | https://github.com/miyakogi/m2r/blob/661a82ccfee48342dcbc3dcca4fd77e6a0a1a900/m2r.py#L644-L659 | def setup(app):
"""When used for sphinx extension."""
global _is_sphinx
_is_sphinx = True
app.add_config_value('no_underscore_emphasis', False, 'env')
app.add_config_value('m2r_parse_relative_links', False, 'env')
app.add_config_value('m2r_anonymous_references', False, 'env')
app.add_config_... | [
"def",
"setup",
"(",
"app",
")",
":",
"global",
"_is_sphinx",
"_is_sphinx",
"=",
"True",
"app",
".",
"add_config_value",
"(",
"'no_underscore_emphasis'",
",",
"False",
",",
"'env'",
")",
"app",
".",
"add_config_value",
"(",
"'m2r_parse_relative_links'",
",",
"Fa... | When used for sphinx extension. | [
"When",
"used",
"for",
"sphinx",
"extension",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/urllib3/util/ssl_.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/ssl_.py#L291-L357 | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None,
ca_cert_dir=None):
"""
All arguments except for server_hostname, ssl_context, and ca_cert_dir ... | [
"def",
"ssl_wrap_socket",
"(",
"sock",
",",
"keyfile",
"=",
"None",
",",
"certfile",
"=",
"None",
",",
"cert_reqs",
"=",
"None",
",",
"ca_certs",
"=",
"None",
",",
"server_hostname",
"=",
"None",
",",
"ssl_version",
"=",
"None",
",",
"ciphers",
"=",
"Non... | All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If n... | [
"All",
"arguments",
"except",
"for",
"server_hostname",
"ssl_context",
"and",
"ca_cert_dir",
"have",
"the",
"same",
"meaning",
"as",
"they",
"do",
"when",
"using",
":",
"func",
":",
"ssl",
".",
"wrap_socket",
"."
] | python | train |
hyperledger/sawtooth-core | validator/sawtooth_validator/execution/scheduler_parallel.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/execution/scheduler_parallel.py#L422-L439 | def add_relationship(self, txn_id, predecessors):
"""Add a predecessor-successor relationship between one txn id and
a set of predecessors.
Args:
txn_id (str): The transaction id of the transaction.
predecessors (set): The transaction ids of the
transacti... | [
"def",
"add_relationship",
"(",
"self",
",",
"txn_id",
",",
"predecessors",
")",
":",
"all_pred",
"=",
"set",
"(",
"predecessors",
")",
"for",
"pred",
"in",
"predecessors",
":",
"all_pred",
".",
"update",
"(",
"self",
".",
"_predecessors_by_id",
"[",
"pred",... | Add a predecessor-successor relationship between one txn id and
a set of predecessors.
Args:
txn_id (str): The transaction id of the transaction.
predecessors (set): The transaction ids of the
transaction's predecessors
Returns:
None | [
"Add",
"a",
"predecessor",
"-",
"successor",
"relationship",
"between",
"one",
"txn",
"id",
"and",
"a",
"set",
"of",
"predecessors",
"."
] | python | train |
pycontribs/pyrax | pyrax/base_identity.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/base_identity.py#L382-L408 | def get_client(self, service, region, public=True, cached=True,
client_class=None):
"""
Returns the client object for the specified service and region.
By default the public endpoint is used. If you wish to work with a
services internal endpoints, specify `public=False`.
... | [
"def",
"get_client",
"(",
"self",
",",
"service",
",",
"region",
",",
"public",
"=",
"True",
",",
"cached",
"=",
"True",
",",
"client_class",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"authenticated",
":",
"raise",
"exc",
".",
"NotAuthenticated",
... | Returns the client object for the specified service and region.
By default the public endpoint is used. If you wish to work with a
services internal endpoints, specify `public=False`.
By default, if a client has already been created for the given service,
region, and public values, tha... | [
"Returns",
"the",
"client",
"object",
"for",
"the",
"specified",
"service",
"and",
"region",
"."
] | python | train |
Contraz/demosys-py | demosys/geometry/quad.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/geometry/quad.py#L17-L64 | def quad_2d(width, height, xpos=0.0, ypos=0.0) -> VAO:
"""
Creates a 2D quad VAO using 2 triangles with normals and texture coordinates.
Args:
width (float): Width of the quad
height (float): Height of the quad
Keyword Args:
xpos (float): Center position x
ypos (float):... | [
"def",
"quad_2d",
"(",
"width",
",",
"height",
",",
"xpos",
"=",
"0.0",
",",
"ypos",
"=",
"0.0",
")",
"->",
"VAO",
":",
"pos",
"=",
"numpy",
".",
"array",
"(",
"[",
"xpos",
"-",
"width",
"/",
"2.0",
",",
"ypos",
"+",
"height",
"/",
"2.0",
",",
... | Creates a 2D quad VAO using 2 triangles with normals and texture coordinates.
Args:
width (float): Width of the quad
height (float): Height of the quad
Keyword Args:
xpos (float): Center position x
ypos (float): Center position y
Returns:
A :py:class:`demosys.openg... | [
"Creates",
"a",
"2D",
"quad",
"VAO",
"using",
"2",
"triangles",
"with",
"normals",
"and",
"texture",
"coordinates",
"."
] | python | valid |
Diaoul/subliminal | subliminal/video.py | https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/video.py#L84-L98 | def fromguess(cls, name, guess):
"""Create an :class:`Episode` or a :class:`Movie` with the given `name` based on the `guess`.
:param str name: name of the video.
:param dict guess: guessed data.
:raise: :class:`ValueError` if the `type` of the `guess` is invalid
"""
if... | [
"def",
"fromguess",
"(",
"cls",
",",
"name",
",",
"guess",
")",
":",
"if",
"guess",
"[",
"'type'",
"]",
"==",
"'episode'",
":",
"return",
"Episode",
".",
"fromguess",
"(",
"name",
",",
"guess",
")",
"if",
"guess",
"[",
"'type'",
"]",
"==",
"'movie'",... | Create an :class:`Episode` or a :class:`Movie` with the given `name` based on the `guess`.
:param str name: name of the video.
:param dict guess: guessed data.
:raise: :class:`ValueError` if the `type` of the `guess` is invalid | [
"Create",
"an",
":",
"class",
":",
"Episode",
"or",
"a",
":",
"class",
":",
"Movie",
"with",
"the",
"given",
"name",
"based",
"on",
"the",
"guess",
"."
] | python | train |
jquast/wcwidth | bin/wcwidth-browser.py | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L539-L554 | def draw_heading(self, writer):
"""
Conditionally redraw screen when ``dirty`` attribute is valued REFRESH.
When Pager attribute ``dirty`` is ``STATE_REFRESH``, cursor is moved
to (0,0), screen is cleared, and heading is displayed.
:param writer: callable writes to output strea... | [
"def",
"draw_heading",
"(",
"self",
",",
"writer",
")",
":",
"if",
"self",
".",
"dirty",
"==",
"self",
".",
"STATE_REFRESH",
":",
"writer",
"(",
"u''",
".",
"join",
"(",
"(",
"self",
".",
"term",
".",
"home",
",",
"self",
".",
"term",
".",
"clear",... | Conditionally redraw screen when ``dirty`` attribute is valued REFRESH.
When Pager attribute ``dirty`` is ``STATE_REFRESH``, cursor is moved
to (0,0), screen is cleared, and heading is displayed.
:param writer: callable writes to output stream, receiving unicode.
:returns: True if clas... | [
"Conditionally",
"redraw",
"screen",
"when",
"dirty",
"attribute",
"is",
"valued",
"REFRESH",
"."
] | python | train |
cslarsen/lyn | lyn/lyn.py | https://github.com/cslarsen/lyn/blob/d615a6a9473083ffc7318a98fcc697cbc28ba5da/lyn/lyn.py#L161-L165 | def state(self):
"""Returns a new JIT state. You have to clean up by calling .destroy()
afterwards.
"""
return Emitter(weakref.proxy(self.lib), self.lib.jit_new_state()) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"Emitter",
"(",
"weakref",
".",
"proxy",
"(",
"self",
".",
"lib",
")",
",",
"self",
".",
"lib",
".",
"jit_new_state",
"(",
")",
")"
] | Returns a new JIT state. You have to clean up by calling .destroy()
afterwards. | [
"Returns",
"a",
"new",
"JIT",
"state",
".",
"You",
"have",
"to",
"clean",
"up",
"by",
"calling",
".",
"destroy",
"()",
"afterwards",
"."
] | python | train |
c0ntrol-x/p4rr0t007 | p4rr0t007/web.py | https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/web.py#L140-L157 | def handle_exception(self, e):
"""called by flask when an exception happens. p4rr0t007 always returns
a 500.html response that must exist under the given
``template_folder`` constructor param.
"""
sys.stderr.write("p4rr0t007 handled an error:")
sys.stderr.write(traceback.... | [
"def",
"handle_exception",
"(",
"self",
",",
"e",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"p4rr0t007 handled an error:\"",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"traceback",
".",
"format_exc",
"(",
"e",
")",
")",
"sys",
".",
"stderr"... | called by flask when an exception happens. p4rr0t007 always returns
a 500.html response that must exist under the given
``template_folder`` constructor param. | [
"called",
"by",
"flask",
"when",
"an",
"exception",
"happens",
".",
"p4rr0t007",
"always",
"returns",
"a",
"500",
".",
"html",
"response",
"that",
"must",
"exist",
"under",
"the",
"given",
"template_folder",
"constructor",
"param",
"."
] | python | train |
ekzhu/datasketch | datasketch/storage.py | https://github.com/ekzhu/datasketch/blob/b3e4129987890a2beb04f2c0b6dc618ae35f2e14/datasketch/storage.py#L13-L46 | def ordered_storage(config, name=None):
'''Return ordered storage system based on the specified config.
The canonical example of such a storage container is
``defaultdict(list)``. Thus, the return value of this method contains
keys and values. The values are ordered lists with the last added
item a... | [
"def",
"ordered_storage",
"(",
"config",
",",
"name",
"=",
"None",
")",
":",
"tp",
"=",
"config",
"[",
"'type'",
"]",
"if",
"tp",
"==",
"'dict'",
":",
"return",
"DictListStorage",
"(",
"config",
")",
"if",
"tp",
"==",
"'redis'",
":",
"return",
"RedisLi... | Return ordered storage system based on the specified config.
The canonical example of such a storage container is
``defaultdict(list)``. Thus, the return value of this method contains
keys and values. The values are ordered lists with the last added
item at the end.
Args:
config (dict): De... | [
"Return",
"ordered",
"storage",
"system",
"based",
"on",
"the",
"specified",
"config",
"."
] | python | test |
MIT-LCP/wfdb-python | wfdb/io/_signal.py | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_signal.py#L516-L622 | def calc_adc_params(self):
"""
Compute appropriate adc_gain and baseline parameters for adc
conversion, given the physical signal and the fmts.
Returns
-------
adc_gains : list
List of calculated `adc_gain` values for each channel.
baselines : list
... | [
"def",
"calc_adc_params",
"(",
"self",
")",
":",
"adc_gains",
"=",
"[",
"]",
"baselines",
"=",
"[",
"]",
"if",
"np",
".",
"where",
"(",
"np",
".",
"isinf",
"(",
"self",
".",
"p_signal",
")",
")",
"[",
"0",
"]",
".",
"size",
":",
"raise",
"ValueEr... | Compute appropriate adc_gain and baseline parameters for adc
conversion, given the physical signal and the fmts.
Returns
-------
adc_gains : list
List of calculated `adc_gain` values for each channel.
baselines : list
List of calculated `baseline` values ... | [
"Compute",
"appropriate",
"adc_gain",
"and",
"baseline",
"parameters",
"for",
"adc",
"conversion",
"given",
"the",
"physical",
"signal",
"and",
"the",
"fmts",
"."
] | python | train |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2966-L3066 | def _parseMessage(self, content):
"""Get message and author name from content. May contain multiple messages in the content."""
self._seq = content.get("seq", "0")
if "lb_info" in content:
self._sticky = content["lb_info"]["sticky"]
self._pool = content["lb_info"]["pool"... | [
"def",
"_parseMessage",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"_seq",
"=",
"content",
".",
"get",
"(",
"\"seq\"",
",",
"\"0\"",
")",
"if",
"\"lb_info\"",
"in",
"content",
":",
"self",
".",
"_sticky",
"=",
"content",
"[",
"\"lb_info\"",
"]... | Get message and author name from content. May contain multiple messages in the content. | [
"Get",
"message",
"and",
"author",
"name",
"from",
"content",
".",
"May",
"contain",
"multiple",
"messages",
"in",
"the",
"content",
"."
] | python | train |
sammchardy/python-binance | examples/save_historical_data.py | https://github.com/sammchardy/python-binance/blob/31c0d0a32f9edd528c6c2c1dd3044d9a34ce43cc/examples/save_historical_data.py#L32-L57 | def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
None if unit not one of m, h, d or w
None if string not in corr... | [
"def",
"interval_to_milliseconds",
"(",
"interval",
")",
":",
"ms",
"=",
"None",
"seconds_per_unit",
"=",
"{",
"\"m\"",
":",
"60",
",",
"\"h\"",
":",
"60",
"*",
"60",
",",
"\"d\"",
":",
"24",
"*",
"60",
"*",
"60",
",",
"\"w\"",
":",
"7",
"*",
"24",... | Convert a Binance interval string to milliseconds
:param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
None if unit not one of m, h, d or w
None if string not in correct format
int value of interval in mi... | [
"Convert",
"a",
"Binance",
"interval",
"string",
"to",
"milliseconds"
] | python | train |
RedHatInsights/insights-core | insights/client/archive.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L114-L132 | def create_tar_file(self, full_archive=False):
"""
Create tar file to be compressed
"""
tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name)
ext = "" if self.compressor == "none" else ".%s" % self.compressor
tar_file_name = tar_file_name + ".tar" + ext
... | [
"def",
"create_tar_file",
"(",
"self",
",",
"full_archive",
"=",
"False",
")",
":",
"tar_file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive_tmp_dir",
",",
"self",
".",
"archive_name",
")",
"ext",
"=",
"\"\"",
"if",
"self",
".",
... | Create tar file to be compressed | [
"Create",
"tar",
"file",
"to",
"be",
"compressed"
] | python | train |
edibledinos/pwnypack | pwnypack/bytecode.py | https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/bytecode.py#L302-L329 | def blocks_from_ops(ops):
"""
Group a list of :class:`Op` and :class:`Label` instances by label.
Everytime a label is found, a new :class:`Block` is created. The resulting
blocks are returned as a dictionary to easily access the target block of a
jump operation. The keys of this dictionary will be ... | [
"def",
"blocks_from_ops",
"(",
"ops",
")",
":",
"blocks",
"=",
"{",
"}",
"current_block",
"=",
"blocks",
"[",
"None",
"]",
"=",
"Block",
"(",
")",
"for",
"op",
"in",
"ops",
":",
"if",
"isinstance",
"(",
"op",
",",
"Label",
")",
":",
"next_block",
"... | Group a list of :class:`Op` and :class:`Label` instances by label.
Everytime a label is found, a new :class:`Block` is created. The resulting
blocks are returned as a dictionary to easily access the target block of a
jump operation. The keys of this dictionary will be the labels, the values
will be the... | [
"Group",
"a",
"list",
"of",
":",
"class",
":",
"Op",
"and",
":",
"class",
":",
"Label",
"instances",
"by",
"label",
"."
] | python | train |
cisco-sas/kitty | kitty/targets/base.py | https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/targets/base.py#L65-L72 | def teardown(self):
'''
Clean up the target once all tests are completed
'''
if self.controller:
self.controller.teardown()
for monitor in self.monitors:
monitor.teardown() | [
"def",
"teardown",
"(",
"self",
")",
":",
"if",
"self",
".",
"controller",
":",
"self",
".",
"controller",
".",
"teardown",
"(",
")",
"for",
"monitor",
"in",
"self",
".",
"monitors",
":",
"monitor",
".",
"teardown",
"(",
")"
] | Clean up the target once all tests are completed | [
"Clean",
"up",
"the",
"target",
"once",
"all",
"tests",
"are",
"completed"
] | python | train |
iotile/coretools | iotilecore/iotile/core/dev/registry.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L61-L77 | def plugins(self):
"""Lazily load iotile plugins only on demand.
This is a slow operation on computers with a slow FS and is rarely
accessed information, so only compute it when it is actually asked
for.
"""
if self._plugins is None:
self._plugins = {}
... | [
"def",
"plugins",
"(",
"self",
")",
":",
"if",
"self",
".",
"_plugins",
"is",
"None",
":",
"self",
".",
"_plugins",
"=",
"{",
"}",
"for",
"_",
",",
"plugin",
"in",
"self",
".",
"load_extensions",
"(",
"'iotile.plugin'",
")",
":",
"links",
"=",
"plugi... | Lazily load iotile plugins only on demand.
This is a slow operation on computers with a slow FS and is rarely
accessed information, so only compute it when it is actually asked
for. | [
"Lazily",
"load",
"iotile",
"plugins",
"only",
"on",
"demand",
"."
] | python | train |
pytroll/satpy | satpy/utils.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/utils.py#L190-L208 | def proj_units_to_meters(proj_str):
"""Convert projection units from kilometers to meters."""
proj_parts = proj_str.split()
new_parts = []
for itm in proj_parts:
key, val = itm.split('=')
key = key.strip('+')
if key in ['a', 'b', 'h']:
val = float(val)
if ... | [
"def",
"proj_units_to_meters",
"(",
"proj_str",
")",
":",
"proj_parts",
"=",
"proj_str",
".",
"split",
"(",
")",
"new_parts",
"=",
"[",
"]",
"for",
"itm",
"in",
"proj_parts",
":",
"key",
",",
"val",
"=",
"itm",
".",
"split",
"(",
"'='",
")",
"key",
"... | Convert projection units from kilometers to meters. | [
"Convert",
"projection",
"units",
"from",
"kilometers",
"to",
"meters",
"."
] | python | train |
vtkiorg/vtki | vtki/pointset.py | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1409-L1474 | def ray_trace(self, origin, end_point, first_point=False, plot=False,
off_screen=False):
"""
Performs a single ray trace calculation given a mesh and a line segment
defined by an origin and end_point.
Parameters
----------
origin : np.ndarray or list
... | [
"def",
"ray_trace",
"(",
"self",
",",
"origin",
",",
"end_point",
",",
"first_point",
"=",
"False",
",",
"plot",
"=",
"False",
",",
"off_screen",
"=",
"False",
")",
":",
"points",
"=",
"vtk",
".",
"vtkPoints",
"(",
")",
"cell_ids",
"=",
"vtk",
".",
"... | Performs a single ray trace calculation given a mesh and a line segment
defined by an origin and end_point.
Parameters
----------
origin : np.ndarray or list
Start of the line segment.
end_point : np.ndarray or list
End of the line segment.
firs... | [
"Performs",
"a",
"single",
"ray",
"trace",
"calculation",
"given",
"a",
"mesh",
"and",
"a",
"line",
"segment",
"defined",
"by",
"an",
"origin",
"and",
"end_point",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.