repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
HazyResearch/fonduer | src/fonduer/features/featurizer.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/features/featurizer.py#L44-L67 | def update(self, docs=None, split=0, parallelism=None, progress_bar=True):
"""Update the features of the specified candidates.
:param docs: If provided, apply features to all the candidates in these
documents.
:param split: If docs is None, apply features to the candidates in this
... | [
"def",
"update",
"(",
"self",
",",
"docs",
"=",
"None",
",",
"split",
"=",
"0",
",",
"parallelism",
"=",
"None",
",",
"progress_bar",
"=",
"True",
")",
":",
"self",
".",
"apply",
"(",
"docs",
"=",
"docs",
",",
"split",
"=",
"split",
",",
"train",
... | Update the features of the specified candidates.
:param docs: If provided, apply features to all the candidates in these
documents.
:param split: If docs is None, apply features to the candidates in this
particular split.
:type split: int
:param parallelism: How ... | [
"Update",
"the",
"features",
"of",
"the",
"specified",
"candidates",
"."
] | python | train | 39.208333 |
mdgoldberg/sportsref | sportsref/nba/players.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/players.py#L142-L157 | def _get_stats_table(self, table_id, kind='R', summary=False):
"""Gets a stats table from the player page; helper function that does
the work for per-game, per-100-poss, etc. stats.
:table_id: the ID of the HTML table.
:kind: specifies regular season, playoffs, or both. One of 'R', 'P',... | [
"def",
"_get_stats_table",
"(",
"self",
",",
"table_id",
",",
"kind",
"=",
"'R'",
",",
"summary",
"=",
"False",
")",
":",
"doc",
"=",
"self",
".",
"get_main_doc",
"(",
")",
"table_id",
"=",
"'table#{}{}'",
".",
"format",
"(",
"'playoffs_'",
"if",
"kind",... | Gets a stats table from the player page; helper function that does
the work for per-game, per-100-poss, etc. stats.
:table_id: the ID of the HTML table.
:kind: specifies regular season, playoffs, or both. One of 'R', 'P',
'B'. Defaults to 'R'.
:returns: A DataFrame of stats. | [
"Gets",
"a",
"stats",
"table",
"from",
"the",
"player",
"page",
";",
"helper",
"function",
"that",
"does",
"the",
"work",
"for",
"per",
"-",
"game",
"per",
"-",
"100",
"-",
"poss",
"etc",
".",
"stats",
"."
] | python | test | 43.6875 |
pkkid/python-plexapi | plexapi/utils.py | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L58-L75 | def cast(func, value):
""" Cast the specified value to the specified type (returned by func). Currently this
only support int, float, bool. Should be extended if needed.
Parameters:
func (func): Calback function to used cast to type (int, bool, float).
value (any): value to ... | [
"def",
"cast",
"(",
"func",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"func",
"==",
"bool",
":",
"return",
"bool",
"(",
"int",
"(",
"value",
")",
")",
"elif",
"func",
"in",
"(",
"int",
",",
"float",
")",
":",
"try",... | Cast the specified value to the specified type (returned by func). Currently this
only support int, float, bool. Should be extended if needed.
Parameters:
func (func): Calback function to used cast to type (int, bool, float).
value (any): value to be cast and returned. | [
"Cast",
"the",
"specified",
"value",
"to",
"the",
"specified",
"type",
"(",
"returned",
"by",
"func",
")",
".",
"Currently",
"this",
"only",
"support",
"int",
"float",
"bool",
".",
"Should",
"be",
"extended",
"if",
"needed",
"."
] | python | train | 34.277778 |
jmgilman/Neolib | neolib/user/User.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/user/User.py#L204-L238 | def save(self):
""" Exports all user attributes to the user's configuration and writes configuration
Saves the values for each attribute stored in User.configVars
into the user's configuration. The password is automatically
encoded and salted to prevent saving it as plaintext. T... | [
"def",
"save",
"(",
"self",
")",
":",
"# Code to load all attributes",
"for",
"prop",
"in",
"dir",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"prop",
")",
"==",
"None",
":",
"continue",
"if",
"not",
"prop",
"in",
"self",
".",
"configVars... | Exports all user attributes to the user's configuration and writes configuration
Saves the values for each attribute stored in User.configVars
into the user's configuration. The password is automatically
encoded and salted to prevent saving it as plaintext. The
session is pickl... | [
"Exports",
"all",
"user",
"attributes",
"to",
"the",
"user",
"s",
"configuration",
"and",
"writes",
"configuration",
"Saves",
"the",
"values",
"for",
"each",
"attribute",
"stored",
"in",
"User",
".",
"configVars",
"into",
"the",
"user",
"s",
"configuration",
"... | python | train | 45.428571 |
LIVVkit/LIVVkit | livvkit/bundles/CISM_glissade/verification.py | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/bundles/CISM_glissade/verification.py#L105-L123 | def parse_config(file_path):
"""
Convert the CISM configuration file to a python dictionary
Args:
file_path: absolute path to the configuration file
Returns:
A dictionary representation of the given file
"""
if not os.path.isfile(file_path):
return {}
parser = Confi... | [
"def",
"parse_config",
"(",
"file_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"return",
"{",
"}",
"parser",
"=",
"ConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"file_path",
")",
"# Strip out inline c... | Convert the CISM configuration file to a python dictionary
Args:
file_path: absolute path to the configuration file
Returns:
A dictionary representation of the given file | [
"Convert",
"the",
"CISM",
"configuration",
"file",
"to",
"a",
"python",
"dictionary"
] | python | train | 29.631579 |
gwastro/pycbc | pycbc/strain/strain.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1502-L1589 | def advance(self, blocksize, timeout=10):
"""Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channe... | [
"def",
"advance",
"(",
"self",
",",
"blocksize",
",",
"timeout",
"=",
"10",
")",
":",
"ts",
"=",
"super",
"(",
"StrainBuffer",
",",
"self",
")",
".",
"attempt_advance",
"(",
"blocksize",
",",
"timeout",
"=",
"timeout",
")",
"self",
".",
"blocksize",
"=... | Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
Returns
-------
status: bo... | [
"Advanced",
"buffer",
"blocksize",
"seconds",
"."
] | python | train | 36.068182 |
PyMLGame/pymlgame | game_example.py | https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L134-L144 | def gameloop(self):
"""
A game loop that circles through the methods.
"""
try:
while True:
self.handle_events()
self.update()
self.render()
except KeyboardInterrupt:
pass | [
"def",
"gameloop",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"self",
".",
"handle_events",
"(",
")",
"self",
".",
"update",
"(",
")",
"self",
".",
"render",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] | A game loop that circles through the methods. | [
"A",
"game",
"loop",
"that",
"circles",
"through",
"the",
"methods",
"."
] | python | train | 24.727273 |
Erotemic/ubelt | ubelt/util_format.py | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L483-L544 | def _format_dict(dict_, **kwargs):
"""
Makes a pretty printable / human-readable string representation of a
dictionary. In most cases this string could be evaled.
Args:
dict_ (dict): a dictionary
**kwargs: si, stritems, strkeys, strvals, sk, sv, nl, newlines, nobr,
no... | [
"def",
"_format_dict",
"(",
"dict_",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_root_info'",
"]",
"=",
"_rectify_root_info",
"(",
"kwargs",
".",
"get",
"(",
"'_root_info'",
",",
"None",
")",
")",
"kwargs",
"[",
"'_root_info'",
"]",
"[",
"'depth... | Makes a pretty printable / human-readable string representation of a
dictionary. In most cases this string could be evaled.
Args:
dict_ (dict): a dictionary
**kwargs: si, stritems, strkeys, strvals, sk, sv, nl, newlines, nobr,
nobraces, cbr, compact_brace, trailing_sep,
... | [
"Makes",
"a",
"pretty",
"printable",
"/",
"human",
"-",
"readable",
"string",
"representation",
"of",
"a",
"dictionary",
".",
"In",
"most",
"cases",
"this",
"string",
"could",
"be",
"evaled",
"."
] | python | valid | 38.564516 |
BreakingBytes/simkit | simkit/contrib/readers.py | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/contrib/readers.py#L77-L91 | def apply_units_to_cache(self, data):
"""
Applies units to data when a proxy reader is used. For example if the
data is cached as JSON and retrieved using the
:class:`~simkit.core.data_readers.JSONReader`, then units can be
applied from the original parameter schema.
:pa... | [
"def",
"apply_units_to_cache",
"(",
"self",
",",
"data",
")",
":",
"# if units key exists then apply",
"for",
"k",
",",
"v",
"in",
"self",
".",
"parameters",
".",
"iteritems",
"(",
")",
":",
"if",
"v",
"and",
"v",
".",
"get",
"(",
"'units'",
")",
":",
... | Applies units to data when a proxy reader is used. For example if the
data is cached as JSON and retrieved using the
:class:`~simkit.core.data_readers.JSONReader`, then units can be
applied from the original parameter schema.
:param data: Data read by proxy reader.
:return: data... | [
"Applies",
"units",
"to",
"data",
"when",
"a",
"proxy",
"reader",
"is",
"used",
".",
"For",
"example",
"if",
"the",
"data",
"is",
"cached",
"as",
"JSON",
"and",
"retrieved",
"using",
"the",
":",
"class",
":",
"~simkit",
".",
"core",
".",
"data_readers",
... | python | train | 39.733333 |
boriel/zxbasic | api/symboltable.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L832-L836 | def labels(self):
""" Returns symbol instances corresponding to labels
in the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label] | [
"def",
"labels",
"(",
"self",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"self",
"[",
"self",
".",
"current_scope",
"]",
".",
"values",
"(",
")",
"if",
"x",
".",
"class_",
"==",
"CLASS",
".",
"label",
"]"
] | Returns symbol instances corresponding to labels
in the current scope. | [
"Returns",
"symbol",
"instances",
"corresponding",
"to",
"labels",
"in",
"the",
"current",
"scope",
"."
] | python | train | 41 |
Netuitive/netuitive-client-python | netuitive/element.py | https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L43-L50 | def merge_metrics(self):
"""
Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics
"""
self.metrics.extend(self._metrics.values())
del self._metrics | [
"def",
"merge_metrics",
"(",
"self",
")",
":",
"self",
".",
"metrics",
".",
"extend",
"(",
"self",
".",
"_metrics",
".",
"values",
"(",
")",
")",
"del",
"self",
".",
"_metrics"
] | Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics | [
"Merge",
"metrics",
"in",
"the",
"internal",
"_metrics",
"dict",
"to",
"metrics",
"list",
"and",
"delete",
"the",
"internal",
"_metrics"
] | python | train | 28.625 |
albertyw/csv-ical | csv_ical/convert.py | https://github.com/albertyw/csv-ical/blob/cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed/csv_ical/convert.py#L86-L90 | def save_ical(self, ical_location): # type: (str) -> None
""" Save the calendar instance to a file """
data = self.cal.to_ical()
with open(ical_location, 'w') as ical_file:
ical_file.write(data.decode('utf-8')) | [
"def",
"save_ical",
"(",
"self",
",",
"ical_location",
")",
":",
"# type: (str) -> None",
"data",
"=",
"self",
".",
"cal",
".",
"to_ical",
"(",
")",
"with",
"open",
"(",
"ical_location",
",",
"'w'",
")",
"as",
"ical_file",
":",
"ical_file",
".",
"write",
... | Save the calendar instance to a file | [
"Save",
"the",
"calendar",
"instance",
"to",
"a",
"file"
] | python | train | 48.6 |
LogicalDash/LiSE | LiSE/LiSE/character.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/character.py#L2010-L2026 | def place2thing(self, name, location):
"""Turn a Place into a Thing with the given location.
It will keep all its attached Portals.
"""
self.engine._set_thing_loc(
self.name, name, location
)
if (self.name, name) in self.engine._node_objs:
... | [
"def",
"place2thing",
"(",
"self",
",",
"name",
",",
"location",
")",
":",
"self",
".",
"engine",
".",
"_set_thing_loc",
"(",
"self",
".",
"name",
",",
"name",
",",
"location",
")",
"if",
"(",
"self",
".",
"name",
",",
"name",
")",
"in",
"self",
".... | Turn a Place into a Thing with the given location.
It will keep all its attached Portals. | [
"Turn",
"a",
"Place",
"into",
"a",
"Thing",
"with",
"the",
"given",
"location",
".",
"It",
"will",
"keep",
"all",
"its",
"attached",
"Portals",
"."
] | python | train | 35.705882 |
spotify/luigi | luigi/contrib/esindex.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L186-L197 | def exists(self):
"""
Test, if this task has been run.
"""
try:
self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id())
return True
except elasticsearch.NotFoundError:
logger.debug('Marker documen... | [
"def",
"exists",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"es",
".",
"get",
"(",
"index",
"=",
"self",
".",
"marker_index",
",",
"doc_type",
"=",
"self",
".",
"marker_doc_type",
",",
"id",
"=",
"self",
".",
"marker_index_document_id",
"(",
")",
... | Test, if this task has been run. | [
"Test",
"if",
"this",
"task",
"has",
"been",
"run",
"."
] | python | train | 36.083333 |
blockstack/blockstack-core | blockstack/lib/atlas.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L736-L761 | def atlasdb_get_zonefiles_by_name(name, max_index=None, con=None, path=None):
"""
Look up the sequence of zone file records by name, optionally up to a specific zonefile index
Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in block... | [
"def",
"atlasdb_get_zonefiles_by_name",
"(",
"name",
",",
"max_index",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",... | Look up the sequence of zone file records by name, optionally up to a specific zonefile index
Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order | [
"Look",
"up",
"the",
"sequence",
"of",
"zone",
"file",
"records",
"by",
"name",
"optionally",
"up",
"to",
"a",
"specific",
"zonefile",
"index",
"Returns",
"[",
"{",
"zonefile_hash",
":",
"...",
"txid",
":",
"...",
"inv_index",
":",
"...",
"block_height",
"... | python | train | 30.730769 |
google/grr | grr/proto/makefile.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/proto/makefile.py#L39-L90 | def MakeProto():
"""Make sure our protos have been compiled to python libraries."""
# Start running from one directory above the grr directory which is found by
# this scripts's location as __file__.
cwd = os.path.dirname(os.path.abspath(__file__))
# Find all the .proto files.
protos_to_compile = []
for ... | [
"def",
"MakeProto",
"(",
")",
":",
"# Start running from one directory above the grr directory which is found by",
"# this scripts's location as __file__.",
"cwd",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",... | Make sure our protos have been compiled to python libraries. | [
"Make",
"sure",
"our",
"protos",
"have",
"been",
"compiled",
"to",
"python",
"libraries",
"."
] | python | train | 34.25 |
aws/sagemaker-python-sdk | src/sagemaker/local/utils.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/local/utils.py#L71-L80 | def recursive_copy(source, destination):
"""A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source
directory does not exist.
Args:
source (str): source path
destination (str): destination path
"""
if os.path.isdir(source):
copy_tree(sourc... | [
"def",
"recursive_copy",
"(",
"source",
",",
"destination",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
":",
"copy_tree",
"(",
"source",
",",
"destination",
")"
] | A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source
directory does not exist.
Args:
source (str): source path
destination (str): destination path | [
"A",
"wrapper",
"around",
"distutils",
".",
"dir_util",
".",
"copy_tree",
"but",
"won",
"t",
"throw",
"any",
"exception",
"when",
"the",
"source",
"directory",
"does",
"not",
"exist",
"."
] | python | train | 32.6 |
biocommons/hgvs | hgvs/dataproviders/uta.py | https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/dataproviders/uta.py#L62-L114 | def connect(db_url=None,
pooling=hgvs.global_config.uta.pooling,
application_name=None,
mode=None,
cache=None):
"""Connect to a UTA database instance and return a UTA interface instance.
:param db_url: URL for database connection
:type db_url: string
:par... | [
"def",
"connect",
"(",
"db_url",
"=",
"None",
",",
"pooling",
"=",
"hgvs",
".",
"global_config",
".",
"uta",
".",
"pooling",
",",
"application_name",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"cache",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
... | Connect to a UTA database instance and return a UTA interface instance.
:param db_url: URL for database connection
:type db_url: string
:param pooling: whether to use connection pooling (postgresql only)
:type pooling: bool
:param application_name: log application name in connection (useful for deb... | [
"Connect",
"to",
"a",
"UTA",
"database",
"instance",
"and",
"return",
"a",
"UTA",
"interface",
"instance",
"."
] | python | train | 35.792453 |
razorpay/razorpay-python | razorpay/resources/card.py | https://github.com/razorpay/razorpay-python/blob/5bc63fd8452165a4b54556888492e555222c8afe/razorpay/resources/card.py#L10-L20 | def fetch(self, card_id, data={}, **kwargs):
""""
Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id
"""
return super(Card, self).fetch(card_id, data, **kwargs) | [
"def",
"fetch",
"(",
"self",
",",
"card_id",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Card",
",",
"self",
")",
".",
"fetch",
"(",
"card_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id | [
"Fetch",
"Card",
"for",
"given",
"Id"
] | python | train | 26.818182 |
nerdvegas/rez | src/rez/packages_.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L592-L604 | def create_package(name, data, package_cls=None):
"""Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
"""
from rez.package_maker__ import PackageMaker
... | [
"def",
"create_package",
"(",
"name",
",",
"data",
",",
"package_cls",
"=",
"None",
")",
":",
"from",
"rez",
".",
"package_maker__",
"import",
"PackageMaker",
"maker",
"=",
"PackageMaker",
"(",
"name",
",",
"data",
",",
"package_cls",
"=",
"package_cls",
")"... | Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object. | [
"Create",
"a",
"package",
"given",
"package",
"data",
"."
] | python | train | 30.692308 |
sametmax/devpy | setup.py | https://github.com/sametmax/devpy/blob/66a150817644edf825d19b80f644e7d05b2a3e86/setup.py#L7-L11 | def get_version(path="src/devpy/__init__.py"):
""" Return the version of by with regex intead of importing it"""
init_content = open(path, "rt").read()
pattern = r"^__version__ = ['\"]([^'\"]*)['\"]"
return re.search(pattern, init_content, re.M).group(1) | [
"def",
"get_version",
"(",
"path",
"=",
"\"src/devpy/__init__.py\"",
")",
":",
"init_content",
"=",
"open",
"(",
"path",
",",
"\"rt\"",
")",
".",
"read",
"(",
")",
"pattern",
"=",
"r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"",
"return",
"re",
".",
"search",
"(... | Return the version of by with regex intead of importing it | [
"Return",
"the",
"version",
"of",
"by",
"with",
"regex",
"intead",
"of",
"importing",
"it"
] | python | train | 53.2 |
wickman/pystachio | pystachio/base.py | https://github.com/wickman/pystachio/blob/601a2c36d7d67efa8f917e7cbf0ab8dc66c7827f/pystachio/base.py#L131-L138 | def in_scope(self, *args, **kw):
"""
Scope this object to a parent environment (like bind but reversed.)
"""
new_self = self.copy()
new_scopes = Object.translate_to_scopes(*args, **kw)
new_self._scopes = new_self._scopes + new_scopes
return new_self | [
"def",
"in_scope",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"new_self",
"=",
"self",
".",
"copy",
"(",
")",
"new_scopes",
"=",
"Object",
".",
"translate_to_scopes",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"new_self",
".",
... | Scope this object to a parent environment (like bind but reversed.) | [
"Scope",
"this",
"object",
"to",
"a",
"parent",
"environment",
"(",
"like",
"bind",
"but",
"reversed",
".",
")"
] | python | train | 34 |
globality-corp/microcosm-flask | microcosm_flask/swagger/schemas.py | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/schemas.py#L56-L65 | def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
"""
Iterate through marshmallow schema fields.
Generates: name, field pairs
"""
for name in sorted(schema.fields.keys()):
field = schema.fields[name]
yield field.dump_to or name, field | [
"def",
"iter_fields",
"(",
"self",
",",
"schema",
":",
"Schema",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Field",
"]",
"]",
":",
"for",
"name",
"in",
"sorted",
"(",
"schema",
".",
"fields",
".",
"keys",
"(",
")",
")",
":",
"field",
... | Iterate through marshmallow schema fields.
Generates: name, field pairs | [
"Iterate",
"through",
"marshmallow",
"schema",
"fields",
"."
] | python | train | 31.1 |
ghukill/pyfc4 | pyfc4/models.py | https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L162-L226 | def get_resource(self, uri, resource_type=None, response_format=None):
'''
Retrieve resource:
- Issues an initial GET request
- If 200, continues, 404, returns False, otherwise raises Exception
- Parse resource type
- If custom resource type parser provided, this fires
- Else, or if custom parser ... | [
"def",
"get_resource",
"(",
"self",
",",
"uri",
",",
"resource_type",
"=",
"None",
",",
"response_format",
"=",
"None",
")",
":",
"# handle uri",
"uri",
"=",
"self",
".",
"parse_uri",
"(",
"uri",
")",
"# remove fcr:metadata if included, as handled below",
"if",
... | Retrieve resource:
- Issues an initial GET request
- If 200, continues, 404, returns False, otherwise raises Exception
- Parse resource type
- If custom resource type parser provided, this fires
- Else, or if custom parser misses, fire HEAD request and parse LDP resource type from Link header
- Retu... | [
"Retrieve",
"resource",
":",
"-",
"Issues",
"an",
"initial",
"GET",
"request",
"-",
"If",
"200",
"continues",
"404",
"returns",
"False",
"otherwise",
"raises",
"Exception",
"-",
"Parse",
"resource",
"type",
"-",
"If",
"custom",
"resource",
"type",
"parser",
... | python | train | 33.738462 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_1/git/git_client_base.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/git/git_client_base.py#L337-L358 | def get_cherry_pick_for_ref_name(self, project, repository_id, ref_name):
"""GetCherryPickForRefName.
[Preview API] Retrieve information about a cherry pick for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:para... | [
"def",
"get_cherry_pick_for_ref_name",
"(",
"self",
",",
"project",
",",
"repository_id",
",",
"ref_name",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serializ... | GetCherryPickForRefName.
[Preview API] Retrieve information about a cherry pick for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:param str ref_name: The GitAsyncRefOperationParameters generatedRefName used for the cher... | [
"GetCherryPickForRefName",
".",
"[",
"Preview",
"API",
"]",
"Retrieve",
"information",
"about",
"a",
"cherry",
"pick",
"for",
"a",
"specific",
"branch",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"str",
... | python | train | 59.409091 |
django-userena-ce/django-userena-ce | userena/models.py | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/models.py#L24-L39 | def upload_to_mugshot(instance, filename):
"""
Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
s... | [
"def",
"upload_to_mugshot",
"(",
"instance",
",",
"filename",
")",
":",
"extension",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"salt",
",",
"hash",
"=",
"generate_sha1",
"(",
"instance",
".",
"pk",
")... | Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory. | [
"Uploads",
"a",
"mugshot",
"for",
"a",
"user",
"to",
"the",
"USERENA_MUGSHOT_PATH",
"and",
"saving",
"it",
"under",
"unique",
"hash",
"for",
"the",
"image",
".",
"This",
"is",
"for",
"privacy",
"reasons",
"so",
"others",
"can",
"t",
"just",
"browse",
"thro... | python | train | 55.1875 |
ianclegg/ntlmlib | ntlmlib/authentication.py | https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L194-L208 | def _expand_des_key(key):
"""
Expand the key from a 7-byte password key into a 8-byte DES key
"""
key = key[:7] + b'\0' * (7 - len(key))
byte = struct.unpack_from('BBBBBBB', key)
s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1)
s += struct.pack("B", ((byte[0] &... | [
"def",
"_expand_des_key",
"(",
"key",
")",
":",
"key",
"=",
"key",
"[",
":",
"7",
"]",
"+",
"b'\\0'",
"*",
"(",
"7",
"-",
"len",
"(",
"key",
")",
")",
"byte",
"=",
"struct",
".",
"unpack_from",
"(",
"'BBBBBBB'",
",",
"key",
")",
"s",
"=",
"stru... | Expand the key from a 7-byte password key into a 8-byte DES key | [
"Expand",
"the",
"key",
"from",
"a",
"7",
"-",
"byte",
"password",
"key",
"into",
"a",
"8",
"-",
"byte",
"DES",
"key"
] | python | train | 56.666667 |
spotify/luigi | luigi/contrib/lsf.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L219-L283 | def _run_job(self):
"""
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
"""
args = []
if isinstance(self.output(), list):
log_output = os.path.split(self.output()[0].path)
else:
log_output = os.path.split(self.... | [
"def",
"_run_job",
"(",
"self",
")",
":",
"args",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
".",
"output",
"(",
")",
",",
"list",
")",
":",
"log_output",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"output",
"(",
")",
"[",
"0"... | Build a bsub argument that will run lsf_runner.py on the directory we've specified. | [
"Build",
"a",
"bsub",
"argument",
"that",
"will",
"run",
"lsf_runner",
".",
"py",
"on",
"the",
"directory",
"we",
"ve",
"specified",
"."
] | python | train | 35.630769 |
aktaylor08/RosbagPandas | src/rosbag_pandas/rosbag_pandas.py | https://github.com/aktaylor08/RosbagPandas/blob/c2af9f22537102696dffdf2e61790362726a8403/src/rosbag_pandas/rosbag_pandas.py#L207-L215 | def get_bag_info(bag_file):
'''Get uamle dict of the bag information
by calling the subprocess -- used to create correct sized
arrays'''
# Get the info on the bag
bag_info = yaml.load(subprocess.Popen(
['rosbag', 'info', '--yaml', bag_file],
stdout=subprocess.PIPE).communicate()[0])
... | [
"def",
"get_bag_info",
"(",
"bag_file",
")",
":",
"# Get the info on the bag",
"bag_info",
"=",
"yaml",
".",
"load",
"(",
"subprocess",
".",
"Popen",
"(",
"[",
"'rosbag'",
",",
"'info'",
",",
"'--yaml'",
",",
"bag_file",
"]",
",",
"stdout",
"=",
"subprocess"... | Get uamle dict of the bag information
by calling the subprocess -- used to create correct sized
arrays | [
"Get",
"uamle",
"dict",
"of",
"the",
"bag",
"information",
"by",
"calling",
"the",
"subprocess",
"--",
"used",
"to",
"create",
"correct",
"sized",
"arrays"
] | python | train | 36.777778 |
roboogle/gtkmvc3 | gtkmvco/gtkmvc3/adapters/containers.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/containers.py#L165-L177 | def update_widget(self, idx=None):
"""Forces the widget at given index to be updated from the
property value. If index is not given, all controlled
widgets will be updated. This method should be called
directly by the user when the property is not observable, or
in very unusual c... | [
"def",
"update_widget",
"(",
"self",
",",
"idx",
"=",
"None",
")",
":",
"if",
"idx",
"is",
"None",
":",
"for",
"w",
"in",
"self",
".",
"_widgets",
":",
"idx",
"=",
"self",
".",
"_get_idx_from_widget",
"(",
"w",
")",
"self",
".",
"_write_widget",
"(",... | Forces the widget at given index to be updated from the
property value. If index is not given, all controlled
widgets will be updated. This method should be called
directly by the user when the property is not observable, or
in very unusual conditions. | [
"Forces",
"the",
"widget",
"at",
"given",
"index",
"to",
"be",
"updated",
"from",
"the",
"property",
"value",
".",
"If",
"index",
"is",
"not",
"given",
"all",
"controlled",
"widgets",
"will",
"be",
"updated",
".",
"This",
"method",
"should",
"be",
"called"... | python | train | 45.692308 |
dmort27/panphon | panphon/_panphon.py | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L77-L101 | def word2array(ft_names, word):
"""Converts `word` [[(value, feature),...],...] to a NumPy array
Given a word consisting of lists of lists/sets of (value, feature) tuples,
return a NumPy array where each row is a segment and each column is a
feature.
Args:
ft_names (list): list of feature ... | [
"def",
"word2array",
"(",
"ft_names",
",",
"word",
")",
":",
"vdict",
"=",
"{",
"'+'",
":",
"1",
",",
"'-'",
":",
"-",
"1",
",",
"'0'",
":",
"0",
"}",
"def",
"seg2col",
"(",
"seg",
")",
":",
"seg",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",... | Converts `word` [[(value, feature),...],...] to a NumPy array
Given a word consisting of lists of lists/sets of (value, feature) tuples,
return a NumPy array where each row is a segment and each column is a
feature.
Args:
ft_names (list): list of feature names (as strings) in order; this
... | [
"Converts",
"word",
"[[",
"(",
"value",
"feature",
")",
"...",
"]",
"...",
"]",
"to",
"a",
"NumPy",
"array"
] | python | train | 39.48 |
linkhub-sdk/popbill.py | popbill/taxinvoiceService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/taxinvoiceService.py#L611-L627 | def getLogs(self, CorpNum, MgtKeyType, MgtKey):
""" 세금계산서 문서이력 목록 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
문서이력 정보 목록 as List
raise
... | [
"def",
"getLogs",
"(",
"self",
",",
"CorpNum",
",",
"MgtKeyType",
",",
"MgtKey",
")",
":",
"if",
"MgtKeyType",
"not",
"in",
"self",
".",
"__MgtKeyTypes",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"관리번호 형태가 올바르지 않습니다.\")",
"",
"if",
"MgtK... | 세금계산서 문서이력 목록 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
문서이력 정보 목록 as List
raise
PopbillException | [
"세금계산서",
"문서이력",
"목록",
"확인",
"args",
"CorpNum",
":",
"회원",
"사업자",
"번호",
"MgtKeyType",
":",
"관리번호",
"유형",
"one",
"of",
"[",
"SELL",
"BUY",
"TRUSTEE",
"]",
"MgtKey",
":",
"파트너",
"관리번호",
"return",
"문서이력",
"정보",
"목록",
"as",
"List",
"raise",
"PopbillExcepti... | python | train | 38.470588 |
b3j0f/aop | b3j0f/aop/advice/utils.py | https://github.com/b3j0f/aop/blob/22b9ba335d103edd929c25eb6dbb94037d3615bc/b3j0f/aop/advice/utils.py#L116-L124 | def unweave(target, *advices):
"""Unweave advices from input target."""
advices = (
advice if isinstance(advice, Advice) else Advice(advice)
for advice in advices
)
unweave(target=target, *advices) | [
"def",
"unweave",
"(",
"target",
",",
"*",
"advices",
")",
":",
"advices",
"=",
"(",
"advice",
"if",
"isinstance",
"(",
"advice",
",",
"Advice",
")",
"else",
"Advice",
"(",
"advice",
")",
"for",
"advice",
"in",
"advices",
")",
"unweave",
"(",
"target",... | Unweave advices from input target. | [
"Unweave",
"advices",
"from",
"input",
"target",
"."
] | python | train | 27.444444 |
Neurita/boyle | boyle/excel_utils.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L149-L156 | def _check_cols(df, col_names):
""" Raise an AttributeError if `df` does not have a column named as an item of
the list of strings `col_names`.
"""
for col in col_names:
if not hasattr(df, col):
raise AttributeError("DataFrame does not have a '{}' column, got {}.".format(col,
... | [
"def",
"_check_cols",
"(",
"df",
",",
"col_names",
")",
":",
"for",
"col",
"in",
"col_names",
":",
"if",
"not",
"hasattr",
"(",
"df",
",",
"col",
")",
":",
"raise",
"AttributeError",
"(",
"\"DataFrame does not have a '{}' column, got {}.\"",
".",
"format",
"("... | Raise an AttributeError if `df` does not have a column named as an item of
the list of strings `col_names`. | [
"Raise",
"an",
"AttributeError",
"if",
"df",
"does",
"not",
"have",
"a",
"column",
"named",
"as",
"an",
"item",
"of",
"the",
"list",
"of",
"strings",
"col_names",
"."
] | python | valid | 50.875 |
noahbenson/neuropythy | neuropythy/geometry/util.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/geometry/util.py#L193-L199 | def points_close(a,b):
'''
points_close(a,b) yields True if points a and b are close to each other and False otherwise.
'''
(a,b) = [np.asarray(u) for u in (a,b)]
if len(a.shape) == 2 or len(b.shape) == 2: (a,b) = [np.reshape(u,(len(u),-1)) for u in (a,b)]
return np.isclose(np.sqrt(np.sum((a - b... | [
"def",
"points_close",
"(",
"a",
",",
"b",
")",
":",
"(",
"a",
",",
"b",
")",
"=",
"[",
"np",
".",
"asarray",
"(",
"u",
")",
"for",
"u",
"in",
"(",
"a",
",",
"b",
")",
"]",
"if",
"len",
"(",
"a",
".",
"shape",
")",
"==",
"2",
"or",
"len... | points_close(a,b) yields True if points a and b are close to each other and False otherwise. | [
"points_close",
"(",
"a",
"b",
")",
"yields",
"True",
"if",
"points",
"a",
"and",
"b",
"are",
"close",
"to",
"each",
"other",
"and",
"False",
"otherwise",
"."
] | python | train | 47.428571 |
ml4ai/delphi | delphi/translators/for2py/format.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L277-L358 | def gen_output_fmt_1(self, fmt):
"""given a single format specifier, get_output_fmt_1() constructs and returns
a list of tuples for matching against that specifier.
Each element of this list is a tuple
(gen_fmt, cvt_fmt, sz)
where:
gen_fmt is the Python forma... | [
"def",
"gen_output_fmt_1",
"(",
"self",
",",
"fmt",
")",
":",
"# first, remove any surrounding space",
"fmt",
"=",
"fmt",
".",
"strip",
"(",
")",
"# get any leading digits indicating repetition",
"match",
"=",
"re",
".",
"match",
"(",
"\"(\\d+)(.+)\"",
",",
"fmt",
... | given a single format specifier, get_output_fmt_1() constructs and returns
a list of tuples for matching against that specifier.
Each element of this list is a tuple
(gen_fmt, cvt_fmt, sz)
where:
gen_fmt is the Python format specifier for assembling this value into
... | [
"given",
"a",
"single",
"format",
"specifier",
"get_output_fmt_1",
"()",
"constructs",
"and",
"returns",
"a",
"list",
"of",
"tuples",
"for",
"matching",
"against",
"that",
"specifier",
".",
"Each",
"element",
"of",
"this",
"list",
"is",
"a",
"tuple"
] | python | train | 36.95122 |
google/grr | grr/server/grr_response_server/gui/wsgiapp.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/wsgiapp.py#L331-L345 | def WSGIHandler(self):
"""Returns GRR's WSGI handler."""
sdm = werkzeug_wsgi.SharedDataMiddleware(self, {
"/": config.CONFIG["AdminUI.document_root"],
})
# Use DispatcherMiddleware to make sure that SharedDataMiddleware is not
# used at all if the URL path doesn't start with "/static". This ... | [
"def",
"WSGIHandler",
"(",
"self",
")",
":",
"sdm",
"=",
"werkzeug_wsgi",
".",
"SharedDataMiddleware",
"(",
"self",
",",
"{",
"\"/\"",
":",
"config",
".",
"CONFIG",
"[",
"\"AdminUI.document_root\"",
"]",
",",
"}",
")",
"# Use DispatcherMiddleware to make sure that... | Returns GRR's WSGI handler. | [
"Returns",
"GRR",
"s",
"WSGI",
"handler",
"."
] | python | train | 46.6 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L756-L781 | def absolute_distance(cls, q0, q1):
"""Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to t... | [
"def",
"absolute_distance",
"(",
"cls",
",",
"q0",
",",
"q1",
")",
":",
"q0_minus_q1",
"=",
"q0",
"-",
"q1",
"q0_plus_q1",
"=",
"q0",
"+",
"q1",
"d_minus",
"=",
"q0_minus_q1",
".",
"norm",
"d_plus",
"=",
"q0_plus_q1",
".",
"norm",
"if",
"(",
"d_minus",... | Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to the chord of the shortest path/arc that
... | [
"Quaternion",
"absolute",
"distance",
"."
] | python | train | 32.461538 |
dmlc/gluon-nlp | scripts/parsing/common/utils.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L497-L512 | def reshape_fortran(tensor, shape):
"""The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result
"""
return tensor.T.reshape(tuple(rever... | [
"def",
"reshape_fortran",
"(",
"tensor",
",",
"shape",
")",
":",
"return",
"tensor",
".",
"T",
".",
"reshape",
"(",
"tuple",
"(",
"reversed",
"(",
"shape",
")",
")",
")",
".",
"T"
] | The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result | [
"The",
"missing",
"Fortran",
"reshape",
"for",
"mx",
".",
"NDArray"
] | python | train | 19.9375 |
msmbuilder/osprey | osprey/plugins/plugin_pylearn2.py | https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L79-L116 | def fit(self, X, y=None):
"""
Build a trainer and run main_loop.
Parameters
----------
X : array_like
Training examples.
y : array_like, optional
Labels.
"""
from pylearn2.config import yaml_parse
from pylearn2.train import... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"from",
"pylearn2",
".",
"config",
"import",
"yaml_parse",
"from",
"pylearn2",
".",
"train",
"import",
"Train",
"# build trainer",
"params",
"=",
"self",
".",
"get_params",
"(",
")",
... | Build a trainer and run main_loop.
Parameters
----------
X : array_like
Training examples.
y : array_like, optional
Labels. | [
"Build",
"a",
"trainer",
"and",
"run",
"main_loop",
"."
] | python | valid | 37.315789 |
PSPC-SPAC-buyandsell/von_agent | von_agent/tails.py | https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/tails.py#L82-L96 | def associate(base_dir: str, rr_id: str, tails_hash: str) -> None:
"""
Create symbolic link to tails file named tails_hash for rev reg id rr_id.
:param rr_id: rev reg id
:param tails_hash: hash of tails file, serving as file name
"""
cd_id = rev_reg_id2cred_def_id(rr_id... | [
"def",
"associate",
"(",
"base_dir",
":",
"str",
",",
"rr_id",
":",
"str",
",",
"tails_hash",
":",
"str",
")",
"->",
"None",
":",
"cd_id",
"=",
"rev_reg_id2cred_def_id",
"(",
"rr_id",
")",
"directory",
"=",
"join",
"(",
"base_dir",
",",
"cd_id",
")",
"... | Create symbolic link to tails file named tails_hash for rev reg id rr_id.
:param rr_id: rev reg id
:param tails_hash: hash of tails file, serving as file name | [
"Create",
"symbolic",
"link",
"to",
"tails",
"file",
"named",
"tails_hash",
"for",
"rev",
"reg",
"id",
"rr_id",
"."
] | python | train | 32.933333 |
nchopin/particles | particles/hmm.py | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/hmm.py#L244-L261 | def sample(self, N=1):
"""Sample N trajectories from the posterior.
Note
----
Performs the forward step in case it has not been performed.
"""
if not self.filt:
self.forward()
paths = np.empty((len(self.filt), N), np.int)
paths[-1, ... | [
"def",
"sample",
"(",
"self",
",",
"N",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"filt",
":",
"self",
".",
"forward",
"(",
")",
"paths",
"=",
"np",
".",
"empty",
"(",
"(",
"len",
"(",
"self",
".",
"filt",
")",
",",
"N",
")",
",",
"np",... | Sample N trajectories from the posterior.
Note
----
Performs the forward step in case it has not been performed. | [
"Sample",
"N",
"trajectories",
"from",
"the",
"posterior",
".",
"Note",
"----",
"Performs",
"the",
"forward",
"step",
"in",
"case",
"it",
"has",
"not",
"been",
"performed",
"."
] | python | train | 36.055556 |
realitix/vulkan | generator/generate.py | https://github.com/realitix/vulkan/blob/07285387092aaa61d2d71fa2913d60a73f022cbe/generator/generate.py#L325-L445 | def model_functions(vk, model):
"""Fill the model with functions"""
def get_vk_extension_functions():
names = set()
for extension in get_extensions_filtered(vk):
for req in extension['require']:
if 'command' not in req:
continue
fo... | [
"def",
"model_functions",
"(",
"vk",
",",
"model",
")",
":",
"def",
"get_vk_extension_functions",
"(",
")",
":",
"names",
"=",
"set",
"(",
")",
"for",
"extension",
"in",
"get_extensions_filtered",
"(",
"vk",
")",
":",
"for",
"req",
"in",
"extension",
"[",
... | Fill the model with functions | [
"Fill",
"the",
"model",
"with",
"functions"
] | python | train | 34.727273 |
raiden-network/raiden | raiden/network/transport/udp/udp_transport.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L489-L504 | def maybe_sendraw(self, host_port: Tuple[int, int], messagedata: bytes):
""" Send message to recipient if the transport is running. """
# Don't sleep if timeout is zero, otherwise a context-switch is done
# and the message is delayed, increasing its latency
sleep_timeout = self.throttle... | [
"def",
"maybe_sendraw",
"(",
"self",
",",
"host_port",
":",
"Tuple",
"[",
"int",
",",
"int",
"]",
",",
"messagedata",
":",
"bytes",
")",
":",
"# Don't sleep if timeout is zero, otherwise a context-switch is done",
"# and the message is delayed, increasing its latency",
"sle... | Send message to recipient if the transport is running. | [
"Send",
"message",
"to",
"recipient",
"if",
"the",
"transport",
"is",
"running",
"."
] | python | train | 42.6875 |
sibirrer/lenstronomy | lenstronomy/Cosmo/lens_cosmo.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Cosmo/lens_cosmo.py#L257-L265 | def D_s(self, H_0, Om0, Ode0=None):
"""
angular diameter to source
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
"""
lensCosmo = self._get_cosom(H_0, Om0, Ode0)
return lensCosmo.D_s | [
"def",
"D_s",
"(",
"self",
",",
"H_0",
",",
"Om0",
",",
"Ode0",
"=",
"None",
")",
":",
"lensCosmo",
"=",
"self",
".",
"_get_cosom",
"(",
"H_0",
",",
"Om0",
",",
"Ode0",
")",
"return",
"lensCosmo",
".",
"D_s"
] | angular diameter to source
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc] | [
"angular",
"diameter",
"to",
"source",
":",
"param",
"H_0",
":",
"Hubble",
"parameter",
"[",
"km",
"/",
"s",
"/",
"Mpc",
"]",
":",
"param",
"Om0",
":",
"normalized",
"matter",
"density",
"at",
"present",
"time",
":",
"return",
":",
"float",
"[",
"Mpc",... | python | train | 34 |
ardydedase/apiwrapper | apiwrapper/apiwrapper.py | https://github.com/ardydedase/apiwrapper/blob/dd477e9f6fc5706b7a29c61a466cd63427d7c517/apiwrapper/apiwrapper.py#L252-L268 | def _default_poll_callback(self, poll_resp):
"""
Checks the condition in poll response to determine if it is complete
and no subsequent poll requests should be done.
"""
if poll_resp.parsed is None:
return False
success_list = ['UpdatesComplete', True, 'COMPLE... | [
"def",
"_default_poll_callback",
"(",
"self",
",",
"poll_resp",
")",
":",
"if",
"poll_resp",
".",
"parsed",
"is",
"None",
":",
"return",
"False",
"success_list",
"=",
"[",
"'UpdatesComplete'",
",",
"True",
",",
"'COMPLETE'",
"]",
"status",
"=",
"None",
"if",... | Checks the condition in poll response to determine if it is complete
and no subsequent poll requests should be done. | [
"Checks",
"the",
"condition",
"in",
"poll",
"response",
"to",
"determine",
"if",
"it",
"is",
"complete",
"and",
"no",
"subsequent",
"poll",
"requests",
"should",
"be",
"done",
"."
] | python | valid | 41.941176 |
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3615-L3691 | def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the ang... | [
"def",
"sc",
"(",
"simulated_array",
",",
"observed_array",
",",
"replace_nan",
"=",
"None",
",",
"replace_inf",
"=",
"None",
",",
"remove_neg",
"=",
"False",
",",
"remove_zero",
"=",
"False",
")",
":",
"# Treats data",
"simulated_array",
",",
"observed_array",
... | Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Para... | [
"Compute",
"the",
"Spectral",
"Correlation",
"(",
"SC",
")",
"."
] | python | train | 36.272727 |
MycroftAI/adapt | adapt/tools/text/tokenizer.py | https://github.com/MycroftAI/adapt/blob/334f23248b8e09fb9d84a88398424ec5bd3bae4c/adapt/tools/text/tokenizer.py#L38-L82 | def tokenize(self, string):
"""Used to parce a string into tokens
This function is to take in a string and return a list of tokens
Args:
string(str): This is a string of words or a sentance to be parsed into tokens
Returns:
list: a list of tokens from the strin... | [
"def",
"tokenize",
"(",
"self",
",",
"string",
")",
":",
"s",
"=",
"string",
"s",
"=",
"re",
".",
"sub",
"(",
"'\\t'",
",",
"\" \"",
",",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"\"(\"",
"+",
"regex_separator",
"+",
"\")\"",
",",
"\" \\g<1> \"... | Used to parce a string into tokens
This function is to take in a string and return a list of tokens
Args:
string(str): This is a string of words or a sentance to be parsed into tokens
Returns:
list: a list of tokens from the string passed in.
Notes:
... | [
"Used",
"to",
"parce",
"a",
"string",
"into",
"tokens"
] | python | train | 38.488889 |
boundlessgeo/gsconfig | src/geoserver/catalog.py | https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L194-L225 | def delete(self, config_object, purge=None, recurse=False):
"""
send a delete request
XXX [more here]
"""
rest_url = config_object.href
params = []
# purge deletes the SLD from disk when a style is deleted
if purge:
params.append("purge=" + st... | [
"def",
"delete",
"(",
"self",
",",
"config_object",
",",
"purge",
"=",
"None",
",",
"recurse",
"=",
"False",
")",
":",
"rest_url",
"=",
"config_object",
".",
"href",
"params",
"=",
"[",
"]",
"# purge deletes the SLD from disk when a style is deleted",
"if",
"pur... | send a delete request
XXX [more here] | [
"send",
"a",
"delete",
"request",
"XXX",
"[",
"more",
"here",
"]"
] | python | valid | 30.125 |
genialis/resolwe | resolwe/elastic/viewsets.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/viewsets.py#L131-L155 | def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatche... | [
"def",
"filter_search",
"(",
"self",
",",
"search",
")",
":",
"builder",
"=",
"QueryBuilder",
"(",
"self",
".",
"filtering_fields",
",",
"self",
".",
"filtering_map",
",",
"self",
")",
"search",
",",
"unmatched",
"=",
"builder",
".",
"build",
"(",
"search"... | Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object | [
"Filter",
"given",
"search",
"by",
"the",
"filter",
"parameter",
"given",
"in",
"request",
"."
] | python | train | 31.24 |
latchset/jwcrypto | jwcrypto/jwk.py | https://github.com/latchset/jwcrypto/blob/961df898dc08f63fe3d900f2002618740bc66b4a/jwcrypto/jwk.py#L566-L573 | def has_public(self):
"""Whether this JWK has an asymmetric Public key."""
if self.is_symmetric:
return False
reg = JWKValuesRegistry[self._params['kty']]
for value in reg:
if reg[value].public and value in self._key:
return True | [
"def",
"has_public",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_symmetric",
":",
"return",
"False",
"reg",
"=",
"JWKValuesRegistry",
"[",
"self",
".",
"_params",
"[",
"'kty'",
"]",
"]",
"for",
"value",
"in",
"reg",
":",
"if",
"reg",
"[",
"value",
... | Whether this JWK has an asymmetric Public key. | [
"Whether",
"this",
"JWK",
"has",
"an",
"asymmetric",
"Public",
"key",
"."
] | python | train | 36.75 |
iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualtile.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualtile.py#L58-L84 | def FindByName(cls, name):
"""Find an installed VirtualTile by name.
This function searches for installed virtual tiles
using the pkg_resources entry_point `iotile.virtual_tile`.
If name is a path ending in .py, it is assumed to point to
a module on disk and loaded directly rat... | [
"def",
"FindByName",
"(",
"cls",
",",
"name",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'.py'",
")",
":",
"return",
"cls",
".",
"LoadFromFile",
"(",
"name",
")",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_name",
",",
"tile",
"in",
"reg"... | Find an installed VirtualTile by name.
This function searches for installed virtual tiles
using the pkg_resources entry_point `iotile.virtual_tile`.
If name is a path ending in .py, it is assumed to point to
a module on disk and loaded directly rather than using
pkg_resources.
... | [
"Find",
"an",
"installed",
"VirtualTile",
"by",
"name",
"."
] | python | train | 33.555556 |
woolfson-group/isambard | isambard/ampal/pdb_parser.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/pdb_parser.py#L200-L224 | def proc_line_coordinate(self, line):
"""Extracts data from columns in ATOM/HETATM record."""
pdb_atom_col_dict = global_settings['ampal']['pdb_atom_col_dict']
at_type = line[0:6].strip() # 0
at_ser = int(line[6:11].strip()) # 1
at_name = line[12:16].strip() # 2
alt_lo... | [
"def",
"proc_line_coordinate",
"(",
"self",
",",
"line",
")",
":",
"pdb_atom_col_dict",
"=",
"global_settings",
"[",
"'ampal'",
"]",
"[",
"'pdb_atom_col_dict'",
"]",
"at_type",
"=",
"line",
"[",
"0",
":",
"6",
"]",
".",
"strip",
"(",
")",
"# 0",
"at_ser",
... | Extracts data from columns in ATOM/HETATM record. | [
"Extracts",
"data",
"from",
"columns",
"in",
"ATOM",
"/",
"HETATM",
"record",
"."
] | python | train | 49.28 |
chrisspen/weka | weka/arff.py | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L559-L584 | def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
"""
Write an arff structure to a string.
"""
assert not (schema_only and data_only), 'Make up your mind.'
assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s'... | [
"def",
"write",
"(",
"self",
",",
"fout",
"=",
"None",
",",
"fmt",
"=",
"SPARSE",
",",
"schema_only",
"=",
"False",
",",
"data_only",
"=",
"False",
")",
":",
"assert",
"not",
"(",
"schema_only",
"and",
"data_only",
")",
",",
"'Make up your mind.'",
"asse... | Write an arff structure to a string. | [
"Write",
"an",
"arff",
"structure",
"to",
"a",
"string",
"."
] | python | train | 36.576923 |
Dallinger/Dallinger | dallinger/mturk.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L349-L392 | def create_hit(
self,
title,
description,
keywords,
reward,
duration_hours,
lifetime_days,
ad_url,
notification_url,
approve_requirement,
max_assignments,
us_only,
blacklist=None,
annotation=None,
):
... | [
"def",
"create_hit",
"(",
"self",
",",
"title",
",",
"description",
",",
"keywords",
",",
"reward",
",",
"duration_hours",
",",
"lifetime_days",
",",
"ad_url",
",",
"notification_url",
",",
"approve_requirement",
",",
"max_assignments",
",",
"us_only",
",",
"bla... | Create the actual HIT and return a dict with its useful properties. | [
"Create",
"the",
"actual",
"HIT",
"and",
"return",
"a",
"dict",
"with",
"its",
"useful",
"properties",
"."
] | python | train | 34.068182 |
MisterWil/skybellpy | skybellpy/__init__.py | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L161-L200 | def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.AC... | [
"def",
"send_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"json_data",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
"and",
"url",
... | Send requests to Skybell. | [
"Send",
"requests",
"to",
"Skybell",
"."
] | python | train | 35.725 |
dask/dask-ml | dask_ml/model_selection/utils.py | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/utils.py#L141-L149 | def add_warning(self, key, *args, **kwargs):
"""Add a warning to be triggered when the specified key is read
Parameters
----------
key : any hashable object
The key
"""
self._deprecations[key] = (args, kwargs) | [
"def",
"add_warning",
"(",
"self",
",",
"key",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_deprecations",
"[",
"key",
"]",
"=",
"(",
"args",
",",
"kwargs",
")"
] | Add a warning to be triggered when the specified key is read
Parameters
----------
key : any hashable object
The key | [
"Add",
"a",
"warning",
"to",
"be",
"triggered",
"when",
"the",
"specified",
"key",
"is",
"read"
] | python | train | 29.111111 |
O365/python-o365 | O365/excel.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/excel.py#L1186-L1208 | def get_columns(self, *, top=None, skip=None):
"""
Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip
"""
url = self.build_url(self._endpoints.get('get_columns'))
params = {}
if top is... | [
"def",
"get_columns",
"(",
"self",
",",
"*",
",",
"top",
"=",
"None",
",",
"skip",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_columns'",
")",
")",
"params",
"=",
"{",
"}",
"... | Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip | [
"Return",
"the",
"columns",
"of",
"this",
"table",
":",
"param",
"int",
"top",
":",
"specify",
"n",
"columns",
"to",
"retrieve",
":",
"param",
"int",
"skip",
":",
"specify",
"n",
"columns",
"to",
"skip"
] | python | train | 32 |
ArtoLabs/SimpleSteem | simplesteem/util.py | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L157-L168 | def sp_to_rshares(self, sp, voting_power=10000, vote_pct=10000):
""" Obtain the r-shares
:param number sp: Steem Power
:param int voting_power: voting power (100% = 10000)
:param int vote_pct: voting participation (100% = 10000)
"""
vesting_shares = int(self.s... | [
"def",
"sp_to_rshares",
"(",
"self",
",",
"sp",
",",
"voting_power",
"=",
"10000",
",",
"vote_pct",
"=",
"10000",
")",
":",
"vesting_shares",
"=",
"int",
"(",
"self",
".",
"sp_to_vests",
"(",
"sp",
")",
"*",
"1e6",
")",
"used_power",
"=",
"int",
"(",
... | Obtain the r-shares
:param number sp: Steem Power
:param int voting_power: voting power (100% = 10000)
:param int vote_pct: voting participation (100% = 10000) | [
"Obtain",
"the",
"r",
"-",
"shares",
":",
"param",
"number",
"sp",
":",
"Steem",
"Power",
":",
"param",
"int",
"voting_power",
":",
"voting",
"power",
"(",
"100%",
"=",
"10000",
")",
":",
"param",
"int",
"vote_pct",
":",
"voting",
"participation",
"(",
... | python | train | 53.5 |
rstoneback/pysat | pysat/utils.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/utils.py#L526-L563 | def nan_circstd(samples, high=2.0*np.pi, low=0.0, axis=None):
"""NaN insensitive version of scipy's circular standard deviation routine
Parameters
-----------
samples : array_like
Input array
low : float or int
Lower boundary for circular standard deviation range (default=0)
hig... | [
"def",
"nan_circstd",
"(",
"samples",
",",
"high",
"=",
"2.0",
"*",
"np",
".",
"pi",
",",
"low",
"=",
"0.0",
",",
"axis",
"=",
"None",
")",
":",
"samples",
"=",
"np",
".",
"asarray",
"(",
"samples",
")",
"samples",
"=",
"samples",
"[",
"~",
"np",... | NaN insensitive version of scipy's circular standard deviation routine
Parameters
-----------
samples : array_like
Input array
low : float or int
Lower boundary for circular standard deviation range (default=0)
high: float or int
Upper boundary for circular standard deviatio... | [
"NaN",
"insensitive",
"version",
"of",
"scipy",
"s",
"circular",
"standard",
"deviation",
"routine"
] | python | train | 32 |
cloudera/cm_api | python/src/cm_api/endpoints/external_accounts.py | https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/external_accounts.py#L107-L116 | def update_external_account(resource_root, account):
"""
Update an external account
@param resource_root: The root Resource object.
@param account: Account to update, account name must be specified.
@return: An ApiExternalAccount object, representing the updated external account
"""
return call(resource_r... | [
"def",
"update_external_account",
"(",
"resource_root",
",",
"account",
")",
":",
"return",
"call",
"(",
"resource_root",
".",
"put",
",",
"EXTERNAL_ACCOUNT_PATH",
"%",
"(",
"\"update\"",
",",
")",
",",
"ApiExternalAccount",
",",
"False",
",",
"data",
"=",
"ac... | Update an external account
@param resource_root: The root Resource object.
@param account: Account to update, account name must be specified.
@return: An ApiExternalAccount object, representing the updated external account | [
"Update",
"an",
"external",
"account"
] | python | train | 40.9 |
saltstack/salt | salt/modules/launchctl_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L128-L148 | def _service_by_name(name):
'''
Return the service info for a service by label, filename or path
'''
services = _available_services()
name = name.lower()
if name in services:
# Match on label
return services[name]
for service in six.itervalues(services):
if service[... | [
"def",
"_service_by_name",
"(",
"name",
")",
":",
"services",
"=",
"_available_services",
"(",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"in",
"services",
":",
"# Match on label",
"return",
"services",
"[",
"name",
"]",
"for",
"servic... | Return the service info for a service by label, filename or path | [
"Return",
"the",
"service",
"info",
"for",
"a",
"service",
"by",
"label",
"filename",
"or",
"path"
] | python | train | 26.904762 |
openeemeter/eemeter | eemeter/transform.py | https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/transform.py#L141-L164 | def day_counts(index):
"""Days between DatetimeIndex values as a :any:`pandas.Series`.
Parameters
----------
index : :any:`pandas.DatetimeIndex`
The index for which to get day counts.
Returns
-------
day_counts : :any:`pandas.Series`
A :any:`pandas.Series` with counts of da... | [
"def",
"day_counts",
"(",
"index",
")",
":",
"# dont affect the original data",
"index",
"=",
"index",
".",
"copy",
"(",
")",
"if",
"len",
"(",
"index",
")",
"==",
"0",
":",
"return",
"pd",
".",
"Series",
"(",
"[",
"]",
",",
"index",
"=",
"index",
")... | Days between DatetimeIndex values as a :any:`pandas.Series`.
Parameters
----------
index : :any:`pandas.DatetimeIndex`
The index for which to get day counts.
Returns
-------
day_counts : :any:`pandas.Series`
A :any:`pandas.Series` with counts of days between periods. Counts are... | [
"Days",
"between",
"DatetimeIndex",
"values",
"as",
"a",
":",
"any",
":",
"pandas",
".",
"Series",
"."
] | python | train | 29.125 |
jobovy/galpy | galpy/potential/planarPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/planarPotential.py#L767-L806 | def RZToplanarPotential(RZPot):
"""
NAME:
RZToplanarPotential
PURPOSE:
convert an RZPotential to a planarPotential in the mid-plane (z=0)
INPUT:
RZPot - RZPotential instance or list of such instances (existing planarPotential instances are just copied to the output)
OUTPUT... | [
"def",
"RZToplanarPotential",
"(",
"RZPot",
")",
":",
"RZPot",
"=",
"flatten",
"(",
"RZPot",
")",
"if",
"isinstance",
"(",
"RZPot",
",",
"list",
")",
":",
"out",
"=",
"[",
"]",
"for",
"pot",
"in",
"RZPot",
":",
"if",
"isinstance",
"(",
"pot",
",",
... | NAME:
RZToplanarPotential
PURPOSE:
convert an RZPotential to a planarPotential in the mid-plane (z=0)
INPUT:
RZPot - RZPotential instance or list of such instances (existing planarPotential instances are just copied to the output)
OUTPUT:
planarPotential instance(s)
H... | [
"NAME",
":"
] | python | train | 30.525 |
ethereum/py-evm | eth/db/chain.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L441-L449 | def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Memoizable version of `get_block_transactions`
"""
for encoded_transaction in self._get_block_transaction_data(... | [
"def",
"_get_block_transactions",
"(",
"self",
",",
"transaction_root",
":",
"Hash32",
",",
"transaction_class",
":",
"Type",
"[",
"'BaseTransaction'",
"]",
")",
"->",
"Iterable",
"[",
"'BaseTransaction'",
"]",
":",
"for",
"encoded_transaction",
"in",
"self",
".",... | Memoizable version of `get_block_transactions` | [
"Memoizable",
"version",
"of",
"get_block_transactions"
] | python | train | 46 |
vertexproject/synapse | synapse/lib/encoding.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/encoding.py#L44-L70 | def decode(name, byts, **opts):
'''
Decode the given byts with the named decoder.
If name is a comma separated list of decoders,
loop through and do them all.
Example:
byts = s_encoding.decode('base64',byts)
Note: Decoder names may also be prefixed with +
to *encode* for tha... | [
"def",
"decode",
"(",
"name",
",",
"byts",
",",
"*",
"*",
"opts",
")",
":",
"for",
"name",
"in",
"name",
".",
"split",
"(",
"','",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'+'",
")",
":",
"byts",
"=",
"encode",
"(",
"name",
"[",
"1",
... | Decode the given byts with the named decoder.
If name is a comma separated list of decoders,
loop through and do them all.
Example:
byts = s_encoding.decode('base64',byts)
Note: Decoder names may also be prefixed with +
to *encode* for that name/layer. | [
"Decode",
"the",
"given",
"byts",
"with",
"the",
"named",
"decoder",
".",
"If",
"name",
"is",
"a",
"comma",
"separated",
"list",
"of",
"decoders",
"loop",
"through",
"and",
"do",
"them",
"all",
"."
] | python | train | 22.777778 |
jxtech/wechatpy | wechatpy/client/api/device.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/device.py#L78-L94 | def get_qrcode_url(self, ticket, data=None):
"""
通过 ticket 换取二维码地址
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4
:param ticket: 二维码 ticket
:param data: 额外数据
:return: 二维码地址
"""
url = 'https://we.qq.com/d/{ticket}'.format(ticket=tic... | [
"def",
"get_qrcode_url",
"(",
"self",
",",
"ticket",
",",
"data",
"=",
"None",
")",
":",
"url",
"=",
"'https://we.qq.com/d/{ticket}'",
".",
"format",
"(",
"ticket",
"=",
"ticket",
")",
"if",
"data",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"dict",... | 通过 ticket 换取二维码地址
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4
:param ticket: 二维码 ticket
:param data: 额外数据
:return: 二维码地址 | [
"通过",
"ticket",
"换取二维码地址",
"详情请参考",
"https",
":",
"//",
"iot",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki",
"/",
"new",
"/",
"index",
".",
"html?page",
"=",
"3",
"-",
"4",
"-",
"4"
] | python | train | 33.411765 |
tcalmant/python-javaobj | javaobj/core.py | https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L637-L753 | def do_classdesc(self, parent=None, ident=0):
"""
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
"""
# TC_CLASSDESC className serialVersionUID newHandle classDescInfo
# classDescInfo:
#... | [
"def",
"do_classdesc",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"ident",
"=",
"0",
")",
":",
"# TC_CLASSDESC className serialVersionUID newHandle classDescInfo",
"# classDescInfo:",
"# classDescFlags fields classAnnotation superClassDesc",
"# classDescFlags:",
"# (byte) ... | Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object | [
"Handles",
"a",
"TC_CLASSDESC",
"opcode"
] | python | train | 35.008547 |
SmokinCaterpillar/pypet | pypet/naturalnaming.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L3092-L3112 | def f_get_default(self, name, default=None, fast_access=True, with_links=True,
shortcuts=True, max_depth=None, auto_load=False):
""" Similar to `f_get`, but returns the default value if `name` is not found in the
trajectory.
This function uses the `f_get` method and will return th... | [
"def",
"f_get_default",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"fast_access",
"=",
"True",
",",
"with_links",
"=",
"True",
",",
"shortcuts",
"=",
"True",
",",
"max_depth",
"=",
"None",
",",
"auto_load",
"=",
"False",
")",
":",
"try... | Similar to `f_get`, but returns the default value if `name` is not found in the
trajectory.
This function uses the `f_get` method and will return the default value
in case `f_get` raises an AttributeError or a DataNotInStorageError.
Other errors are not handled.
In contrast to ... | [
"Similar",
"to",
"f_get",
"but",
"returns",
"the",
"default",
"value",
"if",
"name",
"is",
"not",
"found",
"in",
"the",
"trajectory",
"."
] | python | test | 41.142857 |
PythonCharmers/python-future | src/future/backports/email/utils.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L247-L254 | def unquote(str):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str | [
"def",
"unquote",
"(",
"str",
")",
":",
"if",
"len",
"(",
"str",
")",
">",
"1",
":",
"if",
"str",
".",
"startswith",
"(",
"'\"'",
")",
"and",
"str",
".",
"endswith",
"(",
"'\"'",
")",
":",
"return",
"str",
"[",
"1",
":",
"-",
"1",
"]",
".",
... | Remove quotes from a string. | [
"Remove",
"quotes",
"from",
"a",
"string",
"."
] | python | train | 36.625 |
twilio/twilio-python | twilio/rest/sync/v1/service/sync_list/sync_list_permission.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py#L333-L348 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListPermissionContext for this SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"SyncListPermissionContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListPermissionContext for this SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncLi... | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train | 43.875 |
scot-dev/scot | scot/ooapi.py | https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L403-L420 | def optimize_var(self):
""" Optimize the VAR model's hyperparameters (such as regularization).
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain source ac... | [
"def",
"optimize_var",
"(",
"self",
")",
":",
"if",
"self",
".",
"activations_",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"VAR fitting requires source activations (run do_mvarica first)\"",
")",
"self",
".",
"var_",
".",
"optimize",
"(",
"self",
".",
"ac... | Optimize the VAR model's hyperparameters (such as regularization).
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain source activations. | [
"Optimize",
"the",
"VAR",
"model",
"s",
"hyperparameters",
"(",
"such",
"as",
"regularization",
")",
"."
] | python | train | 30.611111 |
saltstack/salt | salt/returners/multi_returner.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L101-L109 | def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(returner_)]())
return ret | [
"def",
"get_jids",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"ret",
".",
"update",
"(",
"_mminion",
"(",
")",
".",
"returners",
"[",
"'{0}.get_jids'",
".",
"format",
"(",
"returner_",
")",
... | Return all job data from all returners | [
"Return",
"all",
"job",
"data",
"from",
"all",
"returners"
] | python | train | 23.888889 |
PMEAL/OpenPNM | openpnm/network/DelaunayVoronoiDual.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/network/DelaunayVoronoiDual.py#L156-L221 | def _trim_external_pores(self, shape):
r'''
'''
# Find all pores within the domain
Ps = topotools.isoutside(coords=self['pore.coords'], shape=shape)
self['pore.external'] = False
self['pore.external'][Ps] = True
# Find which internal pores are delaunay
Ps... | [
"def",
"_trim_external_pores",
"(",
"self",
",",
"shape",
")",
":",
"# Find all pores within the domain",
"Ps",
"=",
"topotools",
".",
"isoutside",
"(",
"coords",
"=",
"self",
"[",
"'pore.coords'",
"]",
",",
"shape",
"=",
"shape",
")",
"self",
"[",
"'pore.exte... | r''' | [
"r"
] | python | train | 39.666667 |
impact27/registrator | registrator/image.py | https://github.com/impact27/registrator/blob/04c099d83e0466207dc5b2e40d9b03db020d4dad/registrator/image.py#L562-L596 | def dft_optsize_same(im0, im1):
"""Resize 2 image same size for optimal DFT and computes it
Parameters
----------
im0: 2d array
First image
im1: 2d array
Second image
Returns
-------
dft0: 2d array
The dft of the first image
dft1: 2d array
The dft of... | [
"def",
"dft_optsize_same",
"(",
"im0",
",",
"im1",
")",
":",
"im0",
"=",
"np",
".",
"asarray",
"(",
"im0",
")",
"im1",
"=",
"np",
".",
"asarray",
"(",
"im1",
")",
"# save shape",
"shape0",
"=",
"im0",
".",
"shape",
"shape1",
"=",
"im1",
".",
"shape... | Resize 2 image same size for optimal DFT and computes it
Parameters
----------
im0: 2d array
First image
im1: 2d array
Second image
Returns
-------
dft0: 2d array
The dft of the first image
dft1: 2d array
The dft of the second image
Notes
-----
... | [
"Resize",
"2",
"image",
"same",
"size",
"for",
"optimal",
"DFT",
"and",
"computes",
"it"
] | python | train | 23.342857 |
Qiskit/qiskit-terra | qiskit/qasm/qasmparser.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/qasmparser.py#L154-L179 | def verify_reg(self, obj, object_type):
"""Verify a register."""
# How to verify:
# types must match
# indexes must be checked
if obj.name not in self.global_symtab:
raise QasmError('Cannot find definition for', object_type, "'"
+ obj... | [
"def",
"verify_reg",
"(",
"self",
",",
"obj",
",",
"object_type",
")",
":",
"# How to verify:",
"# types must match",
"# indexes must be checked",
"if",
"obj",
".",
"name",
"not",
"in",
"self",
".",
"global_symtab",
":",
"raise",
"QasmError",
"(",
"'Cannot f... | Verify a register. | [
"Verify",
"a",
"register",
"."
] | python | test | 44.115385 |
hozn/stravalib | stravalib/client.py | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L966-L1059 | def get_segment_leaderboard(self, segment_id, gender=None, age_group=None, weight_class=None,
following=None, club_id=None, timeframe=None, top_results_limit=None,
page=None, context_entries = None):
"""
Gets the leaderboard for a segment.
... | [
"def",
"get_segment_leaderboard",
"(",
"self",
",",
"segment_id",
",",
"gender",
"=",
"None",
",",
"age_group",
"=",
"None",
",",
"weight_class",
"=",
"None",
",",
"following",
"=",
"None",
",",
"club_id",
"=",
"None",
",",
"timeframe",
"=",
"None",
",",
... | Gets the leaderboard for a segment.
http://strava.github.io/api/v3/segments/#leaderboard
Note that by default Strava will return the top 10 results, and if the current user has ridden
that segment, the current user's result along with the two results above in rank and the two
results b... | [
"Gets",
"the",
"leaderboard",
"for",
"a",
"segment",
"."
] | python | train | 47.425532 |
genialis/genesis-pyapi | genesis/utils.py | https://github.com/genialis/genesis-pyapi/blob/dfe9bcc8b332a8b9873db4ab9994b0cc10eb209a/genesis/utils.py#L36-L58 | def iterate_schema(fields, schema, path=None):
"""Recursively iterate over all schema sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
:path schema: Field path
:path schema: string
"""
fo... | [
"def",
"iterate_schema",
"(",
"fields",
",",
"schema",
",",
"path",
"=",
"None",
")",
":",
"for",
"field_schema",
"in",
"schema",
":",
"name",
"=",
"field_schema",
"[",
"'name'",
"]",
"if",
"'group'",
"in",
"field_schema",
":",
"for",
"rvals",
"in",
"ite... | Recursively iterate over all schema sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
:path schema: Field path
:path schema: string | [
"Recursively",
"iterate",
"over",
"all",
"schema",
"sub",
"-",
"fields",
"."
] | python | test | 36.521739 |
opencobra/memote | memote/experimental/checks.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/experimental/checks.py#L27-L31 | def check_partial(func, *args, **kwargs):
"""Create a partial to be used by goodtables."""
new_func = partial(func, *args, **kwargs)
new_func.check = func.check
return new_func | [
"def",
"check_partial",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"new_func",
"=",
"partial",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"new_func",
".",
"check",
"=",
"func",
".",
"check",
"return",
"new_f... | Create a partial to be used by goodtables. | [
"Create",
"a",
"partial",
"to",
"be",
"used",
"by",
"goodtables",
"."
] | python | train | 37.6 |
dcwatson/bbcode | bbcode.py | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L222-L229 | def _replace(self, data, replacements):
"""
Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result.
"""
for find, repl in replacements:
data = data.replace(find, repl)
return data | [
"def",
"_replace",
"(",
"self",
",",
"data",
",",
"replacements",
")",
":",
"for",
"find",
",",
"repl",
"in",
"replacements",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"find",
",",
"repl",
")",
"return",
"data"
] | Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result. | [
"Given",
"a",
"list",
"of",
"2",
"-",
"tuples",
"(",
"find",
"repl",
")",
"this",
"function",
"performs",
"all",
"replacements",
"on",
"the",
"input",
"and",
"returns",
"the",
"result",
"."
] | python | train | 36.375 |
pytroll/satpy | satpy/scene.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/scene.py#L623-L666 | def aggregate(self, dataset_ids=None, boundary='exact', side='left', func='mean', **dim_kwargs):
"""Create an aggregated version of the Scene.
Args:
dataset_ids (iterable): DatasetIDs to include in the returned
`Scene`. Defaults to all datasets.
... | [
"def",
"aggregate",
"(",
"self",
",",
"dataset_ids",
"=",
"None",
",",
"boundary",
"=",
"'exact'",
",",
"side",
"=",
"'left'",
",",
"func",
"=",
"'mean'",
",",
"*",
"*",
"dim_kwargs",
")",
":",
"new_scn",
"=",
"self",
".",
"copy",
"(",
"datasets",
"=... | Create an aggregated version of the Scene.
Args:
dataset_ids (iterable): DatasetIDs to include in the returned
`Scene`. Defaults to all datasets.
func (string): Function to apply on each aggregation window. One of
'mean', 's... | [
"Create",
"an",
"aggregated",
"version",
"of",
"the",
"Scene",
"."
] | python | train | 41.545455 |
cebel/pyctd | src/pyctd/manager/database.py | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/database.py#L131-L136 | def drop_all(self):
"""Drops all tables in the database"""
log.info('dropping tables in %s', self.engine.url)
self.session.commit()
models.Base.metadata.drop_all(self.engine)
self.session.commit() | [
"def",
"drop_all",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'dropping tables in %s'",
",",
"self",
".",
"engine",
".",
"url",
")",
"self",
".",
"session",
".",
"commit",
"(",
")",
"models",
".",
"Base",
".",
"metadata",
".",
"drop_all",
"(",
... | Drops all tables in the database | [
"Drops",
"all",
"tables",
"in",
"the",
"database"
] | python | train | 38.5 |
joshspeagle/dynesty | dynesty/bounding.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L1115-L1130 | def logvol_prefactor(n, p=2.):
"""
Returns the ln(volume constant) for an `n`-dimensional sphere with an
:math:`L^p` norm. The constant is defined as::
lnf = n * ln(2.) + n * LogGamma(1./p + 1) - LogGamma(n/p + 1.)
By default the `p=2.` norm is used (i.e. the standard Euclidean norm).
"""... | [
"def",
"logvol_prefactor",
"(",
"n",
",",
"p",
"=",
"2.",
")",
":",
"p",
"*=",
"1.",
"# convert to float in case user inputs an integer",
"lnf",
"=",
"(",
"n",
"*",
"np",
".",
"log",
"(",
"2.",
")",
"+",
"n",
"*",
"special",
".",
"gammaln",
"(",
"1.",
... | Returns the ln(volume constant) for an `n`-dimensional sphere with an
:math:`L^p` norm. The constant is defined as::
lnf = n * ln(2.) + n * LogGamma(1./p + 1) - LogGamma(n/p + 1.)
By default the `p=2.` norm is used (i.e. the standard Euclidean norm). | [
"Returns",
"the",
"ln",
"(",
"volume",
"constant",
")",
"for",
"an",
"n",
"-",
"dimensional",
"sphere",
"with",
"an",
":",
"math",
":",
"L^p",
"norm",
".",
"The",
"constant",
"is",
"defined",
"as",
"::"
] | python | train | 30.1875 |
FPGAwars/apio | apio/resources.py | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/resources.py#L112-L136 | def list_boards(self):
"""Return a list with all the supported boards"""
# Print table
click.echo('\nSupported boards:\n')
BOARDLIST_TPL = ('{board:25} {fpga:20} {type:<5} {size:<5} {pack:<10}')
terminal_width, _ = click.get_terminal_size()
click.echo('-' * terminal_wi... | [
"def",
"list_boards",
"(",
"self",
")",
":",
"# Print table",
"click",
".",
"echo",
"(",
"'\\nSupported boards:\\n'",
")",
"BOARDLIST_TPL",
"=",
"(",
"'{board:25} {fpga:20} {type:<5} {size:<5} {pack:<10}'",
")",
"terminal_width",
",",
"_",
"=",
"click",
".",
"get_term... | Return a list with all the supported boards | [
"Return",
"a",
"list",
"with",
"all",
"the",
"supported",
"boards"
] | python | train | 36.92 |
jtauber/sebastian | sebastian/core/transforms.py | https://github.com/jtauber/sebastian/blob/4e460c3aeab332b45c74fe78e65e76ec87d5cfa8/sebastian/core/transforms.py#L8-L24 | def transform_sequence(f):
"""
A decorator to take a function operating on a point and
turn it into a function returning a callable operating on a sequence.
The functions passed to this decorator must define a kwarg called "point",
or have point be the last positional argument
"""
@wraps(f)
... | [
"def",
"transform_sequence",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#The arguments here are the arguments passed to the transform,",
"#ie, there will be no \"point\" argument",
"#Send a ... | A decorator to take a function operating on a point and
turn it into a function returning a callable operating on a sequence.
The functions passed to this decorator must define a kwarg called "point",
or have point be the last positional argument | [
"A",
"decorator",
"to",
"take",
"a",
"function",
"operating",
"on",
"a",
"point",
"and",
"turn",
"it",
"into",
"a",
"function",
"returning",
"a",
"callable",
"operating",
"on",
"a",
"sequence",
".",
"The",
"functions",
"passed",
"to",
"this",
"decorator",
... | python | train | 38 |
ff0000/scarlet | scarlet/cms/item.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L341-L386 | def save_form(self, form):
"""
Save a valid form. If there is a parent attribute,
this will make sure that the parent object is added
to the saved object. Either as a relationship before
saving or in the case of many to many relations after
saving. Any forced instance val... | [
"def",
"save_form",
"(",
"self",
",",
"form",
")",
":",
"# Add any force_instance_values",
"force",
"=",
"self",
".",
"get_force_instance_values",
"(",
")",
"if",
"force",
":",
"for",
"k",
",",
"v",
"in",
"force",
".",
"items",
"(",
")",
":",
"setattr",
... | Save a valid form. If there is a parent attribute,
this will make sure that the parent object is added
to the saved object. Either as a relationship before
saving or in the case of many to many relations after
saving. Any forced instance values are set as well.
Returns the saved... | [
"Save",
"a",
"valid",
"form",
".",
"If",
"there",
"is",
"a",
"parent",
"attribute",
"this",
"will",
"make",
"sure",
"that",
"the",
"parent",
"object",
"is",
"added",
"to",
"the",
"saved",
"object",
".",
"Either",
"as",
"a",
"relationship",
"before",
"sav... | python | train | 33.717391 |
rsmuc/health_monitoring_plugins | health_monitoring_plugins/raritan.py | https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/raritan.py#L68-L77 | def real_value(value, digit):
"""
function to calculate the real value
we need to devide the value by the digit
e.g.
value = 100
digit = 2
return: "1.0"
"""
return str(float(value) / math.pow(10, float(digit))) | [
"def",
"real_value",
"(",
"value",
",",
"digit",
")",
":",
"return",
"str",
"(",
"float",
"(",
"value",
")",
"/",
"math",
".",
"pow",
"(",
"10",
",",
"float",
"(",
"digit",
")",
")",
")"
] | function to calculate the real value
we need to devide the value by the digit
e.g.
value = 100
digit = 2
return: "1.0" | [
"function",
"to",
"calculate",
"the",
"real",
"value",
"we",
"need",
"to",
"devide",
"the",
"value",
"by",
"the",
"digit",
"e",
".",
"g",
".",
"value",
"=",
"100",
"digit",
"=",
"2",
"return",
":",
"1",
".",
"0"
] | python | train | 27.3 |
scivision/sciencedates | sciencedates/__init__.py | https://github.com/scivision/sciencedates/blob/a713389e027b42d26875cf227450a5d7c6696000/sciencedates/__init__.py#L40-L72 | def yeardoy2datetime(yeardate: int,
utsec: Union[float, int] = None) -> datetime.datetime:
"""
Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-t... | [
"def",
"yeardoy2datetime",
"(",
"yeardate",
":",
"int",
",",
"utsec",
":",
"Union",
"[",
"float",
",",
"int",
"]",
"=",
"None",
")",
"->",
"datetime",
".",
"datetime",
":",
"if",
"isinstance",
"(",
"yeardate",
",",
"(",
"tuple",
",",
"list",
",",
"np... | Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date | [
"Inputs",
":",
"yd",
":",
"yyyyddd",
"four",
"digit",
"year",
"3",
"digit",
"day",
"of",
"year",
"(",
"INTEGER",
"7",
"digits",
")"
] | python | train | 31 |
wglass/lighthouse | lighthouse/haproxy/balancer.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/haproxy/balancer.py#L98-L149 | def apply_config(self, config):
"""
Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas.
"""
self.haproxy_config_path = config["config_file"]
global_stanza =... | [
"def",
"apply_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"haproxy_config_path",
"=",
"config",
"[",
"\"config_file\"",
"]",
"global_stanza",
"=",
"Stanza",
"(",
"\"global\"",
")",
"global_stanza",
".",
"add_lines",
"(",
"config",
".",
"get",
... | Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas. | [
"Constructs",
"HAProxyConfig",
"and",
"HAProxyControl",
"instances",
"based",
"on",
"the",
"contents",
"of",
"the",
"config",
"."
] | python | train | 35.519231 |
totalgood/twip | twip/nlp.py | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/nlp.py#L297-L312 | def make_named_stemmer(stem=None, min_len=3):
"""Construct a callable object and a string sufficient to reconstruct it later (unpickling)
>>> make_named_stemmer('str_lower')
('str_lower', <function str_lower at ...>)
>>> make_named_stemmer('Lancaster')
('lancaster', <Stemmer object at ...>)
"""... | [
"def",
"make_named_stemmer",
"(",
"stem",
"=",
"None",
",",
"min_len",
"=",
"3",
")",
":",
"name",
",",
"stem",
"=",
"stringify",
"(",
"stem",
")",
",",
"make_stemmer",
"(",
"stem",
"=",
"stem",
",",
"min_len",
"=",
"min_len",
")",
"if",
"hasattr",
"... | Construct a callable object and a string sufficient to reconstruct it later (unpickling)
>>> make_named_stemmer('str_lower')
('str_lower', <function str_lower at ...>)
>>> make_named_stemmer('Lancaster')
('lancaster', <Stemmer object at ...>) | [
"Construct",
"a",
"callable",
"object",
"and",
"a",
"string",
"sufficient",
"to",
"reconstruct",
"it",
"later",
"(",
"unpickling",
")"
] | python | train | 39.8125 |
libyal/dtfabric | dtfabric/data_types.py | https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/data_types.py#L398-L409 | def AddMemberDefinition(self, member_definition):
"""Adds a member definition.
Args:
member_definition (DataTypeDefinition): member data type definition.
"""
self._byte_size = None
self.members.append(member_definition)
if self.sections:
section_definition = self.sections[-1]
... | [
"def",
"AddMemberDefinition",
"(",
"self",
",",
"member_definition",
")",
":",
"self",
".",
"_byte_size",
"=",
"None",
"self",
".",
"members",
".",
"append",
"(",
"member_definition",
")",
"if",
"self",
".",
"sections",
":",
"section_definition",
"=",
"self",
... | Adds a member definition.
Args:
member_definition (DataTypeDefinition): member data type definition. | [
"Adds",
"a",
"member",
"definition",
"."
] | python | train | 30.166667 |
scivision/histutils | histutils/__init__.py | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L116-L140 | def dir2fn(ofn, ifn, suffix) -> Union[None, Path]:
"""
ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5
"""
if not ofn: # no output file desired
return None
ofn = Path(ofn).expanduse... | [
"def",
"dir2fn",
"(",
"ofn",
",",
"ifn",
",",
"suffix",
")",
"->",
"Union",
"[",
"None",
",",
"Path",
"]",
":",
"if",
"not",
"ofn",
":",
"# no output file desired",
"return",
"None",
"ofn",
"=",
"Path",
"(",
"ofn",
")",
".",
"expanduser",
"(",
")",
... | ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5 | [
"ofn",
"=",
"filename",
"or",
"output",
"directory",
"to",
"create",
"filename",
"based",
"on",
"ifn",
"ifn",
"=",
"input",
"filename",
"(",
"don",
"t",
"overwrite!",
")",
"suffix",
"=",
"desired",
"file",
"extension",
"e",
".",
"g",
".",
".",
"h5"
] | python | train | 31.72 |
dls-controls/pymalcolm | malcolm/modules/builtin/controllers/statefulcontroller.py | https://github.com/dls-controls/pymalcolm/blob/80ea667e4da26365a6cebc0249f52fdc744bd983/malcolm/modules/builtin/controllers/statefulcontroller.py#L97-L127 | def transition(self, state, message=""):
"""Change to a new state if the transition is allowed
Args:
state (str): State to transition to
message (str): Message if the transition is to a fault state
"""
with self.changes_squashed:
initial_state = self.... | [
"def",
"transition",
"(",
"self",
",",
"state",
",",
"message",
"=",
"\"\"",
")",
":",
"with",
"self",
".",
"changes_squashed",
":",
"initial_state",
"=",
"self",
".",
"state",
".",
"value",
"if",
"self",
".",
"state_set",
".",
"transition_allowed",
"(",
... | Change to a new state if the transition is allowed
Args:
state (str): State to transition to
message (str): Message if the transition is to a fault state | [
"Change",
"to",
"a",
"new",
"state",
"if",
"the",
"transition",
"is",
"allowed"
] | python | train | 45.258065 |
getnikola/coil | coil/web.py | https://github.com/getnikola/coil/blob/80ef1827460b0691cf2c98351a14d88e235c9899/coil/web.py#L627-L667 | def index():
"""Show the index with all posts.
:param int all: Whether or not should show all posts
"""
context = {'postform': NewPostForm(),
'pageform': NewPageForm(),
'delform': DeleteForm()}
n = request.args.get('all')
if n is None:
wants_now = None
... | [
"def",
"index",
"(",
")",
":",
"context",
"=",
"{",
"'postform'",
":",
"NewPostForm",
"(",
")",
",",
"'pageform'",
":",
"NewPageForm",
"(",
")",
",",
"'delform'",
":",
"DeleteForm",
"(",
")",
"}",
"n",
"=",
"request",
".",
"args",
".",
"get",
"(",
... | Show the index with all posts.
:param int all: Whether or not should show all posts | [
"Show",
"the",
"index",
"with",
"all",
"posts",
"."
] | python | train | 25.804878 |
zeaphoo/reston | reston/core/dvm.py | https://github.com/zeaphoo/reston/blob/96502487b2259572df55237c9526f92627465088/reston/core/dvm.py#L7970-L7987 | def get_method_by_idx(self, idx):
"""
Return a specific method by using an index
:param idx: the index of the method
:type idx: int
:rtype: None or an :class:`EncodedMethod` object
"""
if self.__cached_methods_idx == None:
self.__cached_method... | [
"def",
"get_method_by_idx",
"(",
"self",
",",
"idx",
")",
":",
"if",
"self",
".",
"__cached_methods_idx",
"==",
"None",
":",
"self",
".",
"__cached_methods_idx",
"=",
"{",
"}",
"for",
"i",
"in",
"self",
".",
"classes",
".",
"class_def",
":",
"for",
"j",
... | Return a specific method by using an index
:param idx: the index of the method
:type idx: int
:rtype: None or an :class:`EncodedMethod` object | [
"Return",
"a",
"specific",
"method",
"by",
"using",
"an",
"index",
":",
"param",
"idx",
":",
"the",
"index",
"of",
"the",
"method",
":",
"type",
"idx",
":",
"int"
] | python | train | 32.388889 |
UDST/urbansim | urbansim/models/dcm.py | https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/dcm.py#L1205-L1211 | def alts_columns_used(self):
"""
Columns from the alternatives table that are used for filtering.
"""
return list(tz.unique(tz.concat(
m.alts_columns_used() for m in self.models.values()))) | [
"def",
"alts_columns_used",
"(",
"self",
")",
":",
"return",
"list",
"(",
"tz",
".",
"unique",
"(",
"tz",
".",
"concat",
"(",
"m",
".",
"alts_columns_used",
"(",
")",
"for",
"m",
"in",
"self",
".",
"models",
".",
"values",
"(",
")",
")",
")",
")"
] | Columns from the alternatives table that are used for filtering. | [
"Columns",
"from",
"the",
"alternatives",
"table",
"that",
"are",
"used",
"for",
"filtering",
"."
] | python | train | 32.571429 |
numenta/nupic | src/nupic/algorithms/spatial_pooler.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1552-L1581 | def _inhibitColumns(self, overlaps):
"""
Performs inhibition. This method calculates the necessary values needed to
actually perform inhibition and then delegates the task of picking the
active columns to helper functions.
Parameters:
----------------------------
:param overlaps: an array c... | [
"def",
"_inhibitColumns",
"(",
"self",
",",
"overlaps",
")",
":",
"# determine how many columns should be selected in the inhibition phase.",
"# This can be specified by either setting the 'numActiveColumnsPerInhArea'",
"# parameter or the 'localAreaDensity' parameter when initializing the class... | Performs inhibition. This method calculates the necessary values needed to
actually perform inhibition and then delegates the task of picking the
active columns to helper functions.
Parameters:
----------------------------
:param overlaps: an array containing the overlap score for each column.
... | [
"Performs",
"inhibition",
".",
"This",
"method",
"calculates",
"the",
"necessary",
"values",
"needed",
"to",
"actually",
"perform",
"inhibition",
"and",
"then",
"delegates",
"the",
"task",
"of",
"picking",
"the",
"active",
"columns",
"to",
"helper",
"functions",
... | python | valid | 46.866667 |
ambitioninc/django-entity-event | entity_event/models.py | https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L926-L988 | def create_event(self, actors=None, ignore_duplicates=False, **kwargs):
"""
Create events with actors.
This method can be used in place of ``Event.objects.create``
to create events, and the appropriate actors. It takes all the
same keywords as ``Event.objects.create`` for the ev... | [
"def",
"create_event",
"(",
"self",
",",
"actors",
"=",
"None",
",",
"ignore_duplicates",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'actors'",
"]",
"=",
"actors",
"kwargs",
"[",
"'ignore_duplicates'",
"]",
"=",
"ignore_duplicates",
"... | Create events with actors.
This method can be used in place of ``Event.objects.create``
to create events, and the appropriate actors. It takes all the
same keywords as ``Event.objects.create`` for the event
creation, but additionally takes a list of actors, and can be
told to no... | [
"Create",
"events",
"with",
"actors",
"."
] | python | train | 43.174603 |
gmr/helper | helper/config.py | https://github.com/gmr/helper/blob/fe8e45fc8eabf619429b2940c682c252ee33c082/helper/config.py#L316-L332 | def _remove_debug_handlers(self):
"""Remove any handlers with an attribute of debug_only that is True and
remove the references to said handlers from any loggers that are
referencing them.
"""
remove = list()
for handler in self.config[self.HANDLERS]:
if self... | [
"def",
"_remove_debug_handlers",
"(",
"self",
")",
":",
"remove",
"=",
"list",
"(",
")",
"for",
"handler",
"in",
"self",
".",
"config",
"[",
"self",
".",
"HANDLERS",
"]",
":",
"if",
"self",
".",
"config",
"[",
"self",
".",
"HANDLERS",
"]",
"[",
"hand... | Remove any handlers with an attribute of debug_only that is True and
remove the references to said handlers from any loggers that are
referencing them. | [
"Remove",
"any",
"handlers",
"with",
"an",
"attribute",
"of",
"debug_only",
"that",
"is",
"True",
"and",
"remove",
"the",
"references",
"to",
"said",
"handlers",
"from",
"any",
"loggers",
"that",
"are",
"referencing",
"them",
"."
] | python | train | 43.529412 |
Guake/guake | guake/gsettings.py | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L115-L124 | def tabbar_toggled(self, settings, key, user_data):
"""If the gconf var use_tabbar be changed, this method will be
called and will show/hide the tabbar.
"""
if settings.get_boolean(key):
for n in self.guake.notebook_manager.iter_notebooks():
n.set_property("sh... | [
"def",
"tabbar_toggled",
"(",
"self",
",",
"settings",
",",
"key",
",",
"user_data",
")",
":",
"if",
"settings",
".",
"get_boolean",
"(",
"key",
")",
":",
"for",
"n",
"in",
"self",
".",
"guake",
".",
"notebook_manager",
".",
"iter_notebooks",
"(",
")",
... | If the gconf var use_tabbar be changed, this method will be
called and will show/hide the tabbar. | [
"If",
"the",
"gconf",
"var",
"use_tabbar",
"be",
"changed",
"this",
"method",
"will",
"be",
"called",
"and",
"will",
"show",
"/",
"hide",
"the",
"tabbar",
"."
] | python | train | 45.8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.