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 |
|---|---|---|---|---|---|---|---|---|---|
Aluriak/tergraw | tergraw/view.py | https://github.com/Aluriak/tergraw/blob/7f73cd286a77611e9c73f50b1e43be4f6643ac9f/tergraw/view.py#L32-L40 | def next_unwrittable_on_row(view, coords):
"""Return position of the next (in row) letter that is unwrittable"""
x, y = coords
maxx = max(view.keys(), key=itemgetter(0))[0]
for offset in range(x + 1, maxx):
letter = view[offset, y]
if letter not in REWRITABLE_LETTERS:
return ... | [
"def",
"next_unwrittable_on_row",
"(",
"view",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"coords",
"maxx",
"=",
"max",
"(",
"view",
".",
"keys",
"(",
")",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
"[",
"0",
"]",
"for",
"offset",
"in",... | Return position of the next (in row) letter that is unwrittable | [
"Return",
"position",
"of",
"the",
"next",
"(",
"in",
"row",
")",
"letter",
"that",
"is",
"unwrittable"
] | python | train | 37.111111 |
riga/law | law/decorator.py | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/decorator.py#L170-L248 | def notify(fn, opts, task, *args, **kwargs):
""" notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
wrapped task vi... | [
"def",
"notify",
"(",
"fn",
",",
"opts",
",",
"task",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_task",
"=",
"get_task",
"(",
"task",
")",
"# get notification transports",
"transports",
"=",
"[",
"]",
"for",
"param_name",
",",
"param",
"in"... | notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
wrapped task via adding :py:class:`law.NotifyParameter` parameters. ... | [
"notify",
"(",
"on_success",
"=",
"True",
"on_failure",
"=",
"True",
"**",
"kwargs",
")",
"Wraps",
"a",
"bound",
"method",
"of",
"a",
"task",
"and",
"guards",
"its",
"execution",
".",
"Information",
"about",
"the",
"execution",
"(",
"task",
"name",
"durati... | python | train | 37.607595 |
cdeboever3/cdpybio | cdpybio/pysamext.py | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/pysamext.py#L105-L150 | def _pos_nt(pr, pos, stranded=False):
"""
Given a pileup read and a position, return the base that is covered by the
read at the given position if the position is covered.
Parameters
----------
pr : pysam.calignmentfile.PileupRead
Region of type chrom:start-end, chrom:start-end:strand, ... | [
"def",
"_pos_nt",
"(",
"pr",
",",
"pos",
",",
"stranded",
"=",
"False",
")",
":",
"nt",
"=",
"None",
"bases",
"=",
"dict",
"(",
"zip",
"(",
"pr",
".",
"alignment",
".",
"get_reference_positions",
"(",
")",
",",
"list",
"(",
"pr",
".",
"alignment",
... | Given a pileup read and a position, return the base that is covered by the
read at the given position if the position is covered.
Parameters
----------
pr : pysam.calignmentfile.PileupRead
Region of type chrom:start-end, chrom:start-end:strand, or [chrom,
pos : int
Zero-based p... | [
"Given",
"a",
"pileup",
"read",
"and",
"a",
"position",
"return",
"the",
"base",
"that",
"is",
"covered",
"by",
"the",
"read",
"at",
"the",
"given",
"position",
"if",
"the",
"position",
"is",
"covered",
"."
] | python | train | 34.152174 |
Erotemic/utool | utool/util_list.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L361-L382 | def search_list(text_list, pattern, flags=0):
"""
CommandLine:
python -m utool.util_list --test-search_list
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> text_list = ['ham', 'jam', 'eggs', 'spam']
>>> pattern = '.am'
>>> flags = 0
>>> (vali... | [
"def",
"search_list",
"(",
"text_list",
",",
"pattern",
",",
"flags",
"=",
"0",
")",
":",
"import",
"re",
"import",
"utool",
"as",
"ut",
"match_list",
"=",
"[",
"re",
".",
"search",
"(",
"pattern",
",",
"text",
",",
"flags",
"=",
"flags",
")",
"for",... | CommandLine:
python -m utool.util_list --test-search_list
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> text_list = ['ham', 'jam', 'eggs', 'spam']
>>> pattern = '.am'
>>> flags = 0
>>> (valid_index_list, valid_match_list) = ut.search_list(text_list... | [
"CommandLine",
":",
"python",
"-",
"m",
"utool",
".",
"util_list",
"--",
"test",
"-",
"search_list"
] | python | train | 35.727273 |
dragnet-org/dragnet | dragnet/util.py | https://github.com/dragnet-org/dragnet/blob/532c9d9f28e5b1b57f3cabc708218d3863a16322/dragnet/util.py#L20-L63 | def dameraulevenshtein(seq1, seq2):
"""Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with strings, any sequences of
... | [
"def",
"dameraulevenshtein",
"(",
"seq1",
",",
"seq2",
")",
":",
"# codesnippet:D0DE4716-B6E6-4161-9219-2903BF8F547F",
"# Conceptually, this is based on a len(seq1) + 1 * len(seq2) + 1 matrix.",
"# However, only the current and two previous rows are needed at once,",
"# so we only store those.... | Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with strings, any sequences of
comparable objects will work.
Transpos... | [
"Calculate",
"the",
"Damerau",
"-",
"Levenshtein",
"distance",
"between",
"sequences",
"."
] | python | train | 42.295455 |
IceflowRE/unidown | unidown/core/manager.py | https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/core/manager.py#L17-L56 | def init(main_dir: Path, logfile_path: Path, log_level: str):
"""
Initialize the _downloader. TODO.
:param main_dir: main directory
:type main_dir: ~pathlib.Path
:param logfile_path: logfile path
:type logfile_path: ~pathlib.Path
:param log_level: logging level
:type log_level: str
... | [
"def",
"init",
"(",
"main_dir",
":",
"Path",
",",
"logfile_path",
":",
"Path",
",",
"log_level",
":",
"str",
")",
":",
"dynamic_data",
".",
"reset",
"(",
")",
"dynamic_data",
".",
"init_dirs",
"(",
"main_dir",
",",
"logfile_path",
")",
"dynamic_data",
".",... | Initialize the _downloader. TODO.
:param main_dir: main directory
:type main_dir: ~pathlib.Path
:param logfile_path: logfile path
:type logfile_path: ~pathlib.Path
:param log_level: logging level
:type log_level: str | [
"Initialize",
"the",
"_downloader",
".",
"TODO",
"."
] | python | train | 43.675 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py#L163-L175 | def fwdl_status_output_fwdl_entries_blade_app(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_entries = ET.SubElement(output, ... | [
"def",
"fwdl_status_output_fwdl_entries_blade_app",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fwdl_status",
"=",
"ET",
".",
"Element",
"(",
"\"fwdl_status\"",
")",
"config",
"=",
"fwdl_status"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 40.307692 |
pvlib/pvlib-python | pvlib/pvsystem.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L893-L952 | def ashraeiam(aoi, b=0.05):
'''
Determine the incidence angle modifier using the ASHRAE transmission
model.
ashraeiam calculates the incidence angle modifier as developed in
[1], and adopted by ASHRAE (American Society of Heating,
Refrigeration, and Air Conditioning Engineers) [2]. The model ha... | [
"def",
"ashraeiam",
"(",
"aoi",
",",
"b",
"=",
"0.05",
")",
":",
"iam",
"=",
"1",
"-",
"b",
"*",
"(",
"(",
"1",
"/",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"aoi",
")",
")",
"-",
"1",
")",
")",
"aoi_gte_90",
"=",
"np",
".",
"ful... | Determine the incidence angle modifier using the ASHRAE transmission
model.
ashraeiam calculates the incidence angle modifier as developed in
[1], and adopted by ASHRAE (American Society of Heating,
Refrigeration, and Air Conditioning Engineers) [2]. The model has
been used by model programs such a... | [
"Determine",
"the",
"incidence",
"angle",
"modifier",
"using",
"the",
"ASHRAE",
"transmission",
"model",
"."
] | python | train | 30.666667 |
elastic/elasticsearch-py | elasticsearch/client/xpack/ml.py | https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ml.py#L400-L410 | def get_filters(self, filter_id=None, params=None):
"""
`<>`_
:arg filter_id: The ID of the filter to fetch
:arg from_: skips a number of filters
:arg size: specifies a max number of filters to get
"""
return self.transport.perform_request(
"GET", _ma... | [
"def",
"get_filters",
"(",
"self",
",",
"filter_id",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"GET\"",
",",
"_make_path",
"(",
"\"_ml\"",
",",
"\"filters\"",
",",
"filter_id",
")"... | `<>`_
:arg filter_id: The ID of the filter to fetch
:arg from_: skips a number of filters
:arg size: specifies a max number of filters to get | [
"<",
">",
"_"
] | python | train | 33.727273 |
drj11/pypng | code/png.py | https://github.com/drj11/pypng/blob/b8220ca9f58e4c5bc1d507e713744fcb8c049225/code/png.py#L273-L293 | def check_sizes(size, width, height):
"""
Check that these arguments, if supplied, are consistent.
Return a (width, height) pair.
"""
if not size:
return width, height
if len(size) != 2:
raise ProtocolError(
"size argument should be a pair (width, height)")
if w... | [
"def",
"check_sizes",
"(",
"size",
",",
"width",
",",
"height",
")",
":",
"if",
"not",
"size",
":",
"return",
"width",
",",
"height",
"if",
"len",
"(",
"size",
")",
"!=",
"2",
":",
"raise",
"ProtocolError",
"(",
"\"size argument should be a pair (width, heig... | Check that these arguments, if supplied, are consistent.
Return a (width, height) pair. | [
"Check",
"that",
"these",
"arguments",
"if",
"supplied",
"are",
"consistent",
".",
"Return",
"a",
"(",
"width",
"height",
")",
"pair",
"."
] | python | train | 32.238095 |
phn/lineid_plot | lineid_plot/lineid_plot.py | https://github.com/phn/lineid_plot/blob/7c7a1af53fe439b3a7c5a57f01680575837fb978/lineid_plot/lineid_plot.py#L222-L230 | def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1),
ax_dim=(0.85, 0.65)):
"""Create fig and axes if needed and layout axes in fig."""
# Axes location in figure.
if not fig:
fig = plt.figure()
ax = fig.add_axes([ax_lower[0], ax_lower[1], ax_dim[0], ax_dim[1]])
ax.plot... | [
"def",
"prepare_axes",
"(",
"wave",
",",
"flux",
",",
"fig",
"=",
"None",
",",
"ax_lower",
"=",
"(",
"0.1",
",",
"0.1",
")",
",",
"ax_dim",
"=",
"(",
"0.85",
",",
"0.65",
")",
")",
":",
"# Axes location in figure.",
"if",
"not",
"fig",
":",
"fig",
... | Create fig and axes if needed and layout axes in fig. | [
"Create",
"fig",
"and",
"axes",
"if",
"needed",
"and",
"layout",
"axes",
"in",
"fig",
"."
] | python | train | 38.111111 |
tensorflow/cleverhans | cleverhans/attacks/spsa.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L584-L610 | def parallel_apply_transformations(x, transforms, black_border_size=0):
"""
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
"""
transforms = tf.convert_to_tensor(transforms, dtype=tf.float32)
x ... | [
"def",
"parallel_apply_transformations",
"(",
"x",
",",
"transforms",
",",
"black_border_size",
"=",
"0",
")",
":",
"transforms",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"transforms",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"x",
"=",
"_apply_black_bord... | Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images | [
"Apply",
"image",
"transformations",
"in",
"parallel",
".",
":",
"param",
"transforms",
":",
"TODO",
":",
"param",
"black_border_size",
":",
"int",
"size",
"of",
"black",
"border",
"to",
"apply",
"Returns",
":",
"Transformed",
"images"
] | python | train | 31.888889 |
vmware/pyvmomi | pyVim/connect.py | https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVim/connect.py#L650-L686 | def __VersionIsSupported(desiredVersion, serviceVersionDescription):
"""
Private method that returns true if the service version description document
indicates that the desired version is supported
@param desiredVersion: The version we want to see if the server supports
(eg. vim.v... | [
"def",
"__VersionIsSupported",
"(",
"desiredVersion",
",",
"serviceVersionDescription",
")",
":",
"root",
"=",
"serviceVersionDescription",
"if",
"root",
".",
"tag",
"==",
"'namespaces'",
":",
"# serviceVersionDescription appears to be a vimServiceVersions.xml document",
"if",
... | Private method that returns true if the service version description document
indicates that the desired version is supported
@param desiredVersion: The version we want to see if the server supports
(eg. vim.version.version2.
@type desiredVersion: string
@param serviceVersionDescr... | [
"Private",
"method",
"that",
"returns",
"true",
"if",
"the",
"service",
"version",
"description",
"document",
"indicates",
"that",
"the",
"desired",
"version",
"is",
"supported"
] | python | train | 44.837838 |
ansible/ansible-runner | ansible_runner/runner.py | https://github.com/ansible/ansible-runner/blob/8ce485480a5d0b602428d9d64a752e06fb46cdb8/ansible_runner/runner.py#L313-L319 | def host_events(self, host):
'''
Given a host name, this will return all task events executed on that host
'''
all_host_events = filter(lambda x: 'event_data' in x and 'host' in x['event_data'] and x['event_data']['host'] == host,
self.events)
ret... | [
"def",
"host_events",
"(",
"self",
",",
"host",
")",
":",
"all_host_events",
"=",
"filter",
"(",
"lambda",
"x",
":",
"'event_data'",
"in",
"x",
"and",
"'host'",
"in",
"x",
"[",
"'event_data'",
"]",
"and",
"x",
"[",
"'event_data'",
"]",
"[",
"'host'",
"... | Given a host name, this will return all task events executed on that host | [
"Given",
"a",
"host",
"name",
"this",
"will",
"return",
"all",
"task",
"events",
"executed",
"on",
"that",
"host"
] | python | train | 47.571429 |
saltstack/salt | salt/modules/boto_sqs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sqs.py#L107-L126 | def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a queue exists.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.exists myqueue region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
... | [
"def",
"exists",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"="... | Check to see if a queue exists.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.exists myqueue region=us-east-1 | [
"Check",
"to",
"see",
"if",
"a",
"queue",
"exists",
"."
] | python | train | 32 |
has2k1/mizani | mizani/utils.py | https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L239-L254 | def is_close_to_int(x):
"""
Check if value is close to an integer
Parameters
----------
x : float
Numeric value to check
Returns
-------
out : bool
"""
if not np.isfinite(x):
return False
return abs(x - nearest_int(x)) < 1e-10 | [
"def",
"is_close_to_int",
"(",
"x",
")",
":",
"if",
"not",
"np",
".",
"isfinite",
"(",
"x",
")",
":",
"return",
"False",
"return",
"abs",
"(",
"x",
"-",
"nearest_int",
"(",
"x",
")",
")",
"<",
"1e-10"
] | Check if value is close to an integer
Parameters
----------
x : float
Numeric value to check
Returns
-------
out : bool | [
"Check",
"if",
"value",
"is",
"close",
"to",
"an",
"integer"
] | python | valid | 17.0625 |
Pelagicore/qface | qface/helper/qtcpp.py | https://github.com/Pelagicore/qface/blob/7f60e91e3a91a7cb04cfacbc9ce80f43df444853/qface/helper/qtcpp.py#L154-L158 | def close_ns(symbol):
'''generates a closing names statement from a symbol'''
closing = ' '.join(['}' for x in symbol.module.name_parts])
name = '::'.join(symbol.module.name_parts)
return '{0} // namespace {1}'.format(closing, name) | [
"def",
"close_ns",
"(",
"symbol",
")",
":",
"closing",
"=",
"' '",
".",
"join",
"(",
"[",
"'}'",
"for",
"x",
"in",
"symbol",
".",
"module",
".",
"name_parts",
"]",
")",
"name",
"=",
"'::'",
".",
"join",
"(",
"symbol",
".",
"module",
".",
"name_part... | generates a closing names statement from a symbol | [
"generates",
"a",
"closing",
"names",
"statement",
"from",
"a",
"symbol"
] | python | train | 52 |
alphatwirl/alphatwirl | alphatwirl/concurrently/WorkingArea.py | https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/WorkingArea.py#L62-L73 | def open(self):
"""Open the working area
Returns
-------
None
"""
self.path = self._prepare_dir(self.topdir)
self._copy_executable(area_path=self.path)
self._save_logging_levels(area_path=self.path)
self._put_python_modules(modules=self.python_mo... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"path",
"=",
"self",
".",
"_prepare_dir",
"(",
"self",
".",
"topdir",
")",
"self",
".",
"_copy_executable",
"(",
"area_path",
"=",
"self",
".",
"path",
")",
"self",
".",
"_save_logging_levels",
"(",
"a... | Open the working area
Returns
-------
None | [
"Open",
"the",
"working",
"area"
] | python | valid | 28 |
quantmind/pulsar | pulsar/apps/wsgi/route.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/route.py#L331-L349 | def match(self, path):
'''Match a path and return ``None`` if no matching, otherwise
a dictionary of matched variables with values. If there is more
to be match in the path, the remaining string is placed in the
``__remaining__`` key of the dictionary.'''
match = self._regex.sear... | [
"def",
"match",
"(",
"self",
",",
"path",
")",
":",
"match",
"=",
"self",
".",
"_regex",
".",
"search",
"(",
"path",
")",
"if",
"match",
"is",
"not",
"None",
":",
"remaining",
"=",
"path",
"[",
"match",
".",
"end",
"(",
")",
":",
"]",
"groups",
... | Match a path and return ``None`` if no matching, otherwise
a dictionary of matched variables with values. If there is more
to be match in the path, the remaining string is placed in the
``__remaining__`` key of the dictionary. | [
"Match",
"a",
"path",
"and",
"return",
"None",
"if",
"no",
"matching",
"otherwise",
"a",
"dictionary",
"of",
"matched",
"variables",
"with",
"values",
".",
"If",
"there",
"is",
"more",
"to",
"be",
"match",
"in",
"the",
"path",
"the",
"remaining",
"string",... | python | train | 41.421053 |
saltstack/salt | salt/beacons/status.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/status.py#L119-L168 | def beacon(config):
'''
Return status for requested information
'''
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
if not config:
config = [{
'loadavg': ['all'],
'cpustats': ['all'],
'meminfo': ['all'],
'vmstats': ['all']... | [
"def",
"beacon",
"(",
"config",
")",
":",
"log",
".",
"debug",
"(",
"config",
")",
"ctime",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"if",
"not",
"config",
":",
"config",
"=",
"[",
"{",
"'loadavg'",
":"... | Return status for requested information | [
"Return",
"status",
"for",
"requested",
"information"
] | python | train | 30.66 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L28561-L28571 | def on_recording_change(self, enable):
"""Triggered when recording settings have changed.
in enable of type bool
TODO
"""
if not isinstance(enable, bool):
raise TypeError("enable can only be an instance of type bool")
self._call("onRecordingChange",
... | [
"def",
"on_recording_change",
"(",
"self",
",",
"enable",
")",
":",
"if",
"not",
"isinstance",
"(",
"enable",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"enable can only be an instance of type bool\"",
")",
"self",
".",
"_call",
"(",
"\"onRecordingChange\... | Triggered when recording settings have changed.
in enable of type bool
TODO | [
"Triggered",
"when",
"recording",
"settings",
"have",
"changed",
"."
] | python | train | 31 |
firecat53/urlscan | urlscan/urlchoose.py | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L357-L371 | def _digits(self):
""" 0-9 """
self.number += self.key
try:
if self.compact is False:
self.top.body.focus_position = \
self.items.index(self.items_com[max(int(self.number) - 1, 0)])
else:
self.top.body.focus_position = \... | [
"def",
"_digits",
"(",
"self",
")",
":",
"self",
".",
"number",
"+=",
"self",
".",
"key",
"try",
":",
"if",
"self",
".",
"compact",
"is",
"False",
":",
"self",
".",
"top",
".",
"body",
".",
"focus_position",
"=",
"self",
".",
"items",
".",
"index",... | 0-9 | [
"0",
"-",
"9"
] | python | train | 42.8 |
ECRL/ecabc | ecabc/abc.py | https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L114-L138 | def add_value(self, value_type, value_min, value_max):
'''Add a tunable value to the ABC (fitness function must be
configured to handle it)
Args:
value_type (string): type of the value, 'int' or 'float'
value_min (int or float): minimum bound for the value
va... | [
"def",
"add_value",
"(",
"self",
",",
"value_type",
",",
"value_min",
",",
"value_max",
")",
":",
"if",
"len",
"(",
"self",
".",
"_employers",
")",
">",
"0",
":",
"self",
".",
"_logger",
".",
"log",
"(",
"'warn'",
",",
"'Adding a value after employers have... | Add a tunable value to the ABC (fitness function must be
configured to handle it)
Args:
value_type (string): type of the value, 'int' or 'float'
value_min (int or float): minimum bound for the value
value_max (int or float): maximum bound for the value
Retur... | [
"Add",
"a",
"tunable",
"value",
"to",
"the",
"ABC",
"(",
"fitness",
"function",
"must",
"be",
"configured",
"to",
"handle",
"it",
")"
] | python | train | 33.4 |
aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/MQTTLib.py | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/MQTTLib.py#L1392-L1421 | def createShadowHandlerWithName(self, shadowName, isPersistentSubscribe):
"""
**Description**
Create a device shadow handler using the specified shadow name and isPersistentSubscribe.
**Syntax**
.. code:: python
# Create a device shadow handler for shadow named "Bot... | [
"def",
"createShadowHandlerWithName",
"(",
"self",
",",
"shadowName",
",",
"isPersistentSubscribe",
")",
":",
"# Create and return a deviceShadow instance",
"return",
"deviceShadow",
".",
"deviceShadow",
"(",
"shadowName",
",",
"isPersistentSubscribe",
",",
"self",
".",
"... | **Description**
Create a device shadow handler using the specified shadow name and isPersistentSubscribe.
**Syntax**
.. code:: python
# Create a device shadow handler for shadow named "Bot1", using persistent subscription
Bot1Shadow = myAWSIoTMQTTShadowClient.createShadow... | [
"**",
"Description",
"**"
] | python | train | 41.5 |
coldfix/udiskie | udiskie/mount.py | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L109-L126 | async def browse(self, device):
"""
Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not... | [
"async",
"def",
"browse",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"device",
".",
"is_mounted",
":",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"\"not browsing {0}: not moun... | Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched. | [
"Launch",
"file",
"manager",
"on",
"the",
"mount",
"path",
"of",
"the",
"specified",
"device",
"."
] | python | train | 41.777778 |
calmjs/calmjs | src/calmjs/base.py | https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L59-L75 | def _get_exec_binary(binary, kw):
"""
On win32, the subprocess module can only reliably resolve the
target binary if it's actually a binary; as for a Node.js script
it seems to only work iff shell=True was specified, presenting
a security risk. Resolve the target manually through which will
acc... | [
"def",
"_get_exec_binary",
"(",
"binary",
",",
"kw",
")",
":",
"binary",
"=",
"which",
"(",
"binary",
",",
"path",
"=",
"kw",
".",
"get",
"(",
"'env'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'PATH'",
")",
")",
"if",
"binary",
"is",
"None",
":",
... | On win32, the subprocess module can only reliably resolve the
target binary if it's actually a binary; as for a Node.js script
it seems to only work iff shell=True was specified, presenting
a security risk. Resolve the target manually through which will
account for that.
The kw argument is the key... | [
"On",
"win32",
"the",
"subprocess",
"module",
"can",
"only",
"reliably",
"resolve",
"the",
"target",
"binary",
"if",
"it",
"s",
"actually",
"a",
"binary",
";",
"as",
"for",
"a",
"Node",
".",
"js",
"script",
"it",
"seems",
"to",
"only",
"work",
"iff",
"... | python | train | 38.882353 |
openid/JWTConnect-Python-CryptoJWT | src/cryptojwt/jwk/__init__.py | https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/__init__.py#L124-L152 | def verify(self):
"""
Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False
"""
for param in self.longs:
item = getattr(self, para... | [
"def",
"verify",
"(",
"self",
")",
":",
"for",
"param",
"in",
"self",
".",
"longs",
":",
"item",
"=",
"getattr",
"(",
"self",
",",
"param",
")",
"if",
"not",
"item",
"or",
"isinstance",
"(",
"item",
",",
"str",
")",
":",
"continue",
"if",
"isinstan... | Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False | [
"Verify",
"that",
"the",
"information",
"gathered",
"from",
"the",
"on",
"-",
"the",
"-",
"wire",
"representation",
"is",
"of",
"the",
"right",
"type",
".",
"This",
"is",
"supposed",
"to",
"be",
"run",
"before",
"the",
"info",
"is",
"deserialized",
"."
] | python | train | 30.310345 |
saltstack/salt | salt/states/zone.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L842-L988 | def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
di... | [
"def",
"present",
"(",
"name",
",",
"brand",
",",
"zonepath",
",",
"properties",
"=",
"None",
",",
"resources",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'com... | Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resource... | [
"Ensure",
"a",
"zone",
"with",
"certain",
"properties",
"and",
"resources"
] | python | train | 41.755102 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L10003-L10027 | def global_position_int_cov_send(self, time_boot_ms, time_utc, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance, force_mavlink1=False):
'''
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-u... | [
"def",
"global_position_int_cov_send",
"(",
"self",
",",
"time_boot_ms",
",",
"time_utc",
",",
"estimator_type",
",",
"lat",
",",
"lon",
",",
"alt",
",",
"relative_alt",
",",
"vx",
",",
"vy",
",",
"vz",
",",
"covariance",
",",
"force_mavlink1",
"=",
"False",... | The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It is
designed as scaled integer message since the
resolution of float is not sufficient. NOTE: This
message is intended for onboard netwo... | [
"The",
"filtered",
"global",
"position",
"(",
"e",
".",
"g",
".",
"fused",
"GPS",
"and",
"accelerometers",
")",
".",
"The",
"position",
"is",
"in",
"GPS",
"-",
"frame",
"(",
"right",
"-",
"handed",
"Z",
"-",
"up",
")",
".",
"It",
"is",
"designed",
... | python | train | 86.76 |
iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L795-L806 | def _parse_return(cls, result):
"""Extract the result, return value and context from a result object
"""
return_value = None
success = result['result']
context = result['context']
if 'return_value' in result:
return_value = result['return_value']
re... | [
"def",
"_parse_return",
"(",
"cls",
",",
"result",
")",
":",
"return_value",
"=",
"None",
"success",
"=",
"result",
"[",
"'result'",
"]",
"context",
"=",
"result",
"[",
"'context'",
"]",
"if",
"'return_value'",
"in",
"result",
":",
"return_value",
"=",
"re... | Extract the result, return value and context from a result object | [
"Extract",
"the",
"result",
"return",
"value",
"and",
"context",
"from",
"a",
"result",
"object"
] | python | train | 28.666667 |
bretth/woven | woven/deployment.py | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/deployment.py#L63-L88 | def _stage_local_files(local_dir, local_files={}):
"""
Either ``local_files`` and/or ``context`` should be supplied.
Will stage a ``local_files`` dictionary of path:filename pairs where path
is relative to ``local_dir`` into a local tmp staging directory.
Returns a path to the temporary lo... | [
"def",
"_stage_local_files",
"(",
"local_dir",
",",
"local_files",
"=",
"{",
"}",
")",
":",
"staging_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"mkdtemp",
"(",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"local_dir",
")",
... | Either ``local_files`` and/or ``context`` should be supplied.
Will stage a ``local_files`` dictionary of path:filename pairs where path
is relative to ``local_dir`` into a local tmp staging directory.
Returns a path to the temporary local staging directory | [
"Either",
"local_files",
"and",
"/",
"or",
"context",
"should",
"be",
"supplied",
".",
"Will",
"stage",
"a",
"local_files",
"dictionary",
"of",
"path",
":",
"filename",
"pairs",
"where",
"path",
"is",
"relative",
"to",
"local_dir",
"into",
"a",
"local",
"tmp... | python | train | 41.884615 |
ssato/python-anyconfig | src/anyconfig/backend/base.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L618-L630 | def load_from_string(self, content, container, **options):
"""
Load configuration data from given string 'content'.
:param content: Configuration string
:param container: callble to make a container object
:param options: keyword options passed to '_load_from_string_fn'
... | [
"def",
"load_from_string",
"(",
"self",
",",
"content",
",",
"container",
",",
"*",
"*",
"options",
")",
":",
"return",
"load_with_fn",
"(",
"self",
".",
"_load_from_string_fn",
",",
"content",
",",
"container",
",",
"allow_primitives",
"=",
"self",
".",
"al... | Load configuration data from given string 'content'.
:param content: Configuration string
:param container: callble to make a container object
:param options: keyword options passed to '_load_from_string_fn'
:return: container object holding the configuration data | [
"Load",
"configuration",
"data",
"from",
"given",
"string",
"content",
"."
] | python | train | 43.153846 |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L847-L851 | def notifications_get(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /notifications/get API method.
"""
return DXHTTPRequest('/notifications/get', input_params, always_retry=always_retry, **kwargs) | [
"def",
"notifications_get",
"(",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/notifications/get'",
",",
"input_params",
",",
"always_retry",
"=",
"always_retry",
",",
"*"... | Invokes the /notifications/get API method. | [
"Invokes",
"the",
"/",
"notifications",
"/",
"get",
"API",
"method",
"."
] | python | train | 45 |
genialis/resolwe | resolwe/flow/views/mixins.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/mixins.py#L121-L137 | def slug_exists(self, request):
"""Check if given url slug exists.
Check if slug given in query parameter ``name`` exists. Return
``True`` if slug already exists and ``False`` otherwise.
"""
if not request.user.is_authenticated:
return Response(status=status.HTTP_40... | [
"def",
"slug_exists",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
":",
"return",
"Response",
"(",
"status",
"=",
"status",
".",
"HTTP_401_UNAUTHORIZED",
")",
"if",
"'name'",
"not",
"in",
"request",
"... | Check if given url slug exists.
Check if slug given in query parameter ``name`` exists. Return
``True`` if slug already exists and ``False`` otherwise. | [
"Check",
"if",
"given",
"url",
"slug",
"exists",
"."
] | python | train | 39.647059 |
HHammond/PrettyPandas | prettypandas/summarizer.py | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L202-L226 | def style(self):
"""Add summaries and convert to Pandas Styler"""
row_titles = [a.title for a in self._cleaned_summary_rows]
col_titles = [a.title for a in self._cleaned_summary_cols]
row_ix = pd.IndexSlice[row_titles, :]
col_ix = pd.IndexSlice[:, col_titles]
def handle_... | [
"def",
"style",
"(",
"self",
")",
":",
"row_titles",
"=",
"[",
"a",
".",
"title",
"for",
"a",
"in",
"self",
".",
"_cleaned_summary_rows",
"]",
"col_titles",
"=",
"[",
"a",
".",
"title",
"for",
"a",
"in",
"self",
".",
"_cleaned_summary_cols",
"]",
"row_... | Add summaries and convert to Pandas Styler | [
"Add",
"summaries",
"and",
"convert",
"to",
"Pandas",
"Styler"
] | python | train | 31.76 |
rtfd/sphinx-autoapi | autoapi/mappers/python/mapper.py | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L201-L216 | def load(self, patterns, dirs, ignore=None):
"""Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module
"""
for dir_ in dirs:
dir_root = dir_
... | [
"def",
"load",
"(",
"self",
",",
"patterns",
",",
"dirs",
",",
"ignore",
"=",
"None",
")",
":",
"for",
"dir_",
"in",
"dirs",
":",
"dir_root",
"=",
"dir_",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_",
... | Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module | [
"Load",
"objects",
"from",
"the",
"filesystem",
"into",
"the",
"paths",
"dictionary"
] | python | train | 45.3125 |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1651-L1658 | def get_model(self):
"""
Get a model if the formula was previously satisfied.
"""
if self.lingeling and self.status == True:
model = pysolvers.lingeling_model(self.lingeling)
return model if model != None else [] | [
"def",
"get_model",
"(",
"self",
")",
":",
"if",
"self",
".",
"lingeling",
"and",
"self",
".",
"status",
"==",
"True",
":",
"model",
"=",
"pysolvers",
".",
"lingeling_model",
"(",
"self",
".",
"lingeling",
")",
"return",
"model",
"if",
"model",
"!=",
"... | Get a model if the formula was previously satisfied. | [
"Get",
"a",
"model",
"if",
"the",
"formula",
"was",
"previously",
"satisfied",
"."
] | python | train | 33.25 |
spyder-ide/spyder | spyder/utils/external/binaryornot/check.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/binaryornot/check.py#L28-L43 | def is_binary(filename):
"""
:param filename: File to check.
:returns: True if it's a binary file, otherwise False.
"""
logger.debug('is_binary: %(filename)r', locals())
# Check if the file extension is in a list of known binary types
binary_extensions = ['pyc', 'iso', 'zip', 'pdf']
for... | [
"def",
"is_binary",
"(",
"filename",
")",
":",
"logger",
".",
"debug",
"(",
"'is_binary: %(filename)r'",
",",
"locals",
"(",
")",
")",
"# Check if the file extension is in a list of known binary types",
"binary_extensions",
"=",
"[",
"'pyc'",
",",
"'iso'",
",",
"'zip'... | :param filename: File to check.
:returns: True if it's a binary file, otherwise False. | [
":",
"param",
"filename",
":",
"File",
"to",
"check",
".",
":",
"returns",
":",
"True",
"if",
"it",
"s",
"a",
"binary",
"file",
"otherwise",
"False",
"."
] | python | train | 32.5 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/fireball.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/fireball.py#L70-L92 | def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the remote host '''
vvv("EXEC COMMAND %s" % cmd)
if self.runner.sudo and sudoable:
raise errors.AnsibleError("fireball does not use sudo, but runs as whoever it was initiate... | [
"def",
"exec_command",
"(",
"self",
",",
"cmd",
",",
"tmp_path",
",",
"sudo_user",
",",
"sudoable",
"=",
"False",
",",
"executable",
"=",
"'/bin/sh'",
")",
":",
"vvv",
"(",
"\"EXEC COMMAND %s\"",
"%",
"cmd",
")",
"if",
"self",
".",
"runner",
".",
"sudo",... | run a command on the remote host | [
"run",
"a",
"command",
"on",
"the",
"remote",
"host"
] | python | train | 36.782609 |
Opentrons/opentrons | api/src/opentrons/protocol_api/contexts.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L1438-L1447 | def hw_pipette(self) -> Dict[str, Any]:
""" View the information returned by the hardware API directly.
:raises: a :py:class:`.types.PipetteNotAttachedError` if the pipette is
no longer attached (should not happen).
"""
pipette = self._hw_manager.hardware.attached_instr... | [
"def",
"hw_pipette",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"pipette",
"=",
"self",
".",
"_hw_manager",
".",
"hardware",
".",
"attached_instruments",
"[",
"self",
".",
"_mount",
"]",
"if",
"pipette",
"is",
"None",
":",
"raise... | View the information returned by the hardware API directly.
:raises: a :py:class:`.types.PipetteNotAttachedError` if the pipette is
no longer attached (should not happen). | [
"View",
"the",
"information",
"returned",
"by",
"the",
"hardware",
"API",
"directly",
"."
] | python | train | 42.9 |
deeplook/svglib | svglib/svglib.py | https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L1231-L1267 | def applyTransformOnGroup(self, transform, group):
"""Apply an SVG transformation to a RL Group shape.
The transformation is the value of an SVG transform attribute
like transform="scale(1, -1) translate(10, 30)".
rotate(<angle> [<cx> <cy>]) is equivalent to:
translate(<cx> <... | [
"def",
"applyTransformOnGroup",
"(",
"self",
",",
"transform",
",",
"group",
")",
":",
"tr",
"=",
"self",
".",
"attrConverter",
".",
"convertTransform",
"(",
"transform",
")",
"for",
"op",
",",
"values",
"in",
"tr",
":",
"if",
"op",
"==",
"\"scale\"",
":... | Apply an SVG transformation to a RL Group shape.
The transformation is the value of an SVG transform attribute
like transform="scale(1, -1) translate(10, 30)".
rotate(<angle> [<cx> <cy>]) is equivalent to:
translate(<cx> <cy>) rotate(<angle>) translate(-<cx> -<cy>) | [
"Apply",
"an",
"SVG",
"transformation",
"to",
"a",
"RL",
"Group",
"shape",
"."
] | python | train | 40.945946 |
skorokithakis/shortuuid | shortuuid/main.py | https://github.com/skorokithakis/shortuuid/blob/4da632a986c3a43f75c7df64f27a90bbf7ff8039/shortuuid/main.py#L9-L22 | def int_to_string(number, alphabet, padding=None):
"""
Convert a number to a string, using the given alphabet.
The output has the most significant digit first.
"""
output = ""
alpha_len = len(alphabet)
while number:
number, digit = divmod(number, alpha_len)
output += alphabet... | [
"def",
"int_to_string",
"(",
"number",
",",
"alphabet",
",",
"padding",
"=",
"None",
")",
":",
"output",
"=",
"\"\"",
"alpha_len",
"=",
"len",
"(",
"alphabet",
")",
"while",
"number",
":",
"number",
",",
"digit",
"=",
"divmod",
"(",
"number",
",",
"alp... | Convert a number to a string, using the given alphabet.
The output has the most significant digit first. | [
"Convert",
"a",
"number",
"to",
"a",
"string",
"using",
"the",
"given",
"alphabet",
".",
"The",
"output",
"has",
"the",
"most",
"significant",
"digit",
"first",
"."
] | python | train | 32.428571 |
jaraco/jaraco.packaging | jaraco/packaging/sphinx.py | https://github.com/jaraco/jaraco.packaging/blob/c84fd1282b222bc262a2bab7a2e668c947472f46/jaraco/packaging/sphinx.py#L18-L37 | def load_config_from_setup(app):
"""
Replace values in app.config from package metadata
"""
# for now, assume project root is one level up
root = os.path.join(app.confdir, '..')
setup_script = os.path.join(root, 'setup.py')
fields = ['--name', '--version', '--url', '--author']
dist_info_... | [
"def",
"load_config_from_setup",
"(",
"app",
")",
":",
"# for now, assume project root is one level up",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app",
".",
"confdir",
",",
"'..'",
")",
"setup_script",
"=",
"os",
".",
"path",
".",
"join",
"(",
"roo... | Replace values in app.config from package metadata | [
"Replace",
"values",
"in",
"app",
".",
"config",
"from",
"package",
"metadata"
] | python | train | 36.15 |
lionheart/django-pyodbc | django_pyodbc/operations.py | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L330-L385 | def sql_flush(self, style, tables, sequences, allow_cascade=False):
"""
Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
... | [
"def",
"sql_flush",
"(",
"self",
",",
"style",
",",
"tables",
",",
"sequences",
",",
"allow_cascade",
"=",
"False",
")",
":",
"if",
"tables",
":",
"# Cannot use TRUNCATE on tables that are referenced by a FOREIGN KEY",
"# So must use the much slower DELETE",
"from",
"djan... | Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color. | [
"Returns",
"a",
"list",
"of",
"SQL",
"statements",
"required",
"to",
"remove",
"all",
"data",
"from",
"the",
"given",
"database",
"tables",
"(",
"without",
"actually",
"removing",
"the",
"tables",
"themselves",
")",
"."
] | python | train | 48.732143 |
limodou/uliweb | uliweb/contrib/model_config/__init__.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/model_config/__init__.py#L69-L100 | def get_model_fields(model, add_reserver_flag=True):
"""
Creating fields suit for model_config , id will be skipped.
"""
import uliweb.orm as orm
fields = []
m = {'type':'type_name', 'hint':'hint',
'default':'default', 'required':'required'}
m1 = {'index':'index', 'unique':'unique'... | [
"def",
"get_model_fields",
"(",
"model",
",",
"add_reserver_flag",
"=",
"True",
")",
":",
"import",
"uliweb",
".",
"orm",
"as",
"orm",
"fields",
"=",
"[",
"]",
"m",
"=",
"{",
"'type'",
":",
"'type_name'",
",",
"'hint'",
":",
"'hint'",
",",
"'default'",
... | Creating fields suit for model_config , id will be skipped. | [
"Creating",
"fields",
"suit",
"for",
"model_config",
"id",
"will",
"be",
"skipped",
"."
] | python | train | 38.21875 |
ff0000/scarlet | scarlet/cms/list.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/list.py#L159-L169 | def get_formset_class(self, **kwargs):
"""
Returns the formset for the queryset,
if a form class is available.
"""
form_class = self.get_formset_form_class()
if form_class:
kwargs['formfield_callback'] = self.formfield_for_dbfield
return model_form... | [
"def",
"get_formset_class",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"form_class",
"=",
"self",
".",
"get_formset_form_class",
"(",
")",
"if",
"form_class",
":",
"kwargs",
"[",
"'formfield_callback'",
"]",
"=",
"self",
".",
"formfield_for_dbfield",
"ret... | Returns the formset for the queryset,
if a form class is available. | [
"Returns",
"the",
"formset",
"for",
"the",
"queryset",
"if",
"a",
"form",
"class",
"is",
"available",
"."
] | python | train | 40.909091 |
basvandenbroek/gcloud_taskqueue | gcloud_taskqueue/taskqueue.py | https://github.com/basvandenbroek/gcloud_taskqueue/blob/b147b57f7c0ad9e8030ee9797d6526a448aa5007/gcloud_taskqueue/taskqueue.py#L51-L61 | def get_items_from_response(self, response):
"""Yield :class:`.taskqueue.task.Task` items from response.
:type response: dict
:param response: The JSON API response for a page of tasks.
"""
for item in response.get('items', []):
id = item.get('id')
task =... | [
"def",
"get_items_from_response",
"(",
"self",
",",
"response",
")",
":",
"for",
"item",
"in",
"response",
".",
"get",
"(",
"'items'",
",",
"[",
"]",
")",
":",
"id",
"=",
"item",
".",
"get",
"(",
"'id'",
")",
"task",
"=",
"Task",
"(",
"id",
",",
... | Yield :class:`.taskqueue.task.Task` items from response.
:type response: dict
:param response: The JSON API response for a page of tasks. | [
"Yield",
":",
"class",
":",
".",
"taskqueue",
".",
"task",
".",
"Task",
"items",
"from",
"response",
"."
] | python | train | 37 |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L718-L754 | def send_until(self,
send,
regexps,
not_there=False,
shutit_pexpect_child=None,
cadence=5,
retries=100,
echo=None,
note=None,
debug_command=None,
pause_point_on... | [
"def",
"send_until",
"(",
"self",
",",
"send",
",",
"regexps",
",",
"not_there",
"=",
"False",
",",
"shutit_pexpect_child",
"=",
"None",
",",
"cadence",
"=",
"5",
",",
"retries",
"=",
"100",
",",
"echo",
"=",
"None",
",",
"note",
"=",
"None",
",",
"d... | Send string on a regular cadence until a string is either seen, or the timeout is triggered.
@param send: See send()
@param regexps: List of regexps to wait for.
@param not_there: If True, wait until this a regexp is not seen in the output. If False
... | [
"Send",
"string",
"on",
"a",
"regular",
"cadence",
"until",
"a",
"string",
"is",
"either",
"seen",
"or",
"the",
"timeout",
"is",
"triggered",
"."
] | python | train | 49.324324 |
etgalloway/fullqualname | fullqualname.py | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L9-L45 | def fullqualname_py3(obj):
"""Fully qualified name for objects in Python 3."""
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py3(obj)
elif type(obj).__name__ == 'function':
return _fullqualname_function_py3(obj)
elif type(obj).__name__ in ['memb... | [
"def",
"fullqualname_py3",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'builtin_function_or_method'",
":",
"return",
"_fullqualname_builtin_py3",
"(",
"obj",
")",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'func... | Fully qualified name for objects in Python 3. | [
"Fully",
"qualified",
"name",
"for",
"objects",
"in",
"Python",
"3",
"."
] | python | train | 26.783784 |
daler/trackhub | trackhub/upload.py | https://github.com/daler/trackhub/blob/e4655f79177822529f80b923df117e38e28df702/trackhub/upload.py#L122-L176 | def stage(x, staging):
"""
Stage an object to the `staging` directory.
If the object is a Track and is one of the types that needs an index file
(bam, vcfTabix), then the index file will be staged as well.
Returns a list of the linknames created.
"""
linknames = []
# Objects that don'... | [
"def",
"stage",
"(",
"x",
",",
"staging",
")",
":",
"linknames",
"=",
"[",
"]",
"# Objects that don't represent a file shouldn't be staged",
"non_file_objects",
"=",
"(",
"track",
".",
"ViewTrack",
",",
"track",
".",
"CompositeTrack",
",",
"track",
".",
"Aggregate... | Stage an object to the `staging` directory.
If the object is a Track and is one of the types that needs an index file
(bam, vcfTabix), then the index file will be staged as well.
Returns a list of the linknames created. | [
"Stage",
"an",
"object",
"to",
"the",
"staging",
"directory",
"."
] | python | train | 28.727273 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/optoanalysis.py | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/optoanalysis.py#L3183-L3230 | def arrange_plots_on_one_canvas(FigureAxTupleArray, title='', SubtitleArray = [], show_fig=True):
"""
Arranges plots, given in an array of tuples consisting of fig and axs,
onto a subplot-figure consisting of 2 horizontal times the lenght of the
passed (fig,axs)-array divided by 2 vertical subplots
... | [
"def",
"arrange_plots_on_one_canvas",
"(",
"FigureAxTupleArray",
",",
"title",
"=",
"''",
",",
"SubtitleArray",
"=",
"[",
"]",
",",
"show_fig",
"=",
"True",
")",
":",
"if",
"SubtitleArray",
"==",
"[",
"]",
":",
"SubtitleArray",
"=",
"[",
"\"Plot {}\"",
".",
... | Arranges plots, given in an array of tuples consisting of fig and axs,
onto a subplot-figure consisting of 2 horizontal times the lenght of the
passed (fig,axs)-array divided by 2 vertical subplots
Parameters
----------
FigureAxTupleArray : array-like
array of Tuples(fig, axs) outputted f... | [
"Arranges",
"plots",
"given",
"in",
"an",
"array",
"of",
"tuples",
"consisting",
"of",
"fig",
"and",
"axs",
"onto",
"a",
"subplot",
"-",
"figure",
"consisting",
"of",
"2",
"horizontal",
"times",
"the",
"lenght",
"of",
"the",
"passed",
"(",
"fig",
"axs",
... | python | train | 42.333333 |
saltstack/salt | salt/cloud/clouds/nova.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/nova.py#L1395-L1411 | def floating_ip_create(kwargs, call=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
if call != 'function':
raise SaltCloudSystemExit(
'The floating_ip_create action must be called with -f or --function'
)
if 'pool' not in kwargs:
log.error('... | [
"def",
"floating_ip_create",
"(",
"kwargs",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The floating_ip_create action must be called with -f or --function'",
")",
"if",
"'pool'",
"not",
"in",
"kwarg... | Allocate a floating IP
.. versionadded:: 2016.3.0 | [
"Allocate",
"a",
"floating",
"IP"
] | python | train | 24.529412 |
Karaage-Cluster/karaage | karaage/common/trace.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/common/trace.py#L305-L355 | def set_formatter(name, func):
"""Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance method.
* class argument - the... | [
"def",
"set_formatter",
"(",
"name",
",",
"func",
")",
":",
"if",
"name",
"in",
"(",
"'self'",
",",
"'instance'",
",",
"'this'",
")",
":",
"global",
"af_self",
"af_self",
"=",
"_formatter_self",
"if",
"func",
"is",
"None",
"else",
"func",
"elif",
"name",... | Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance method.
* class argument - the class object bound to a class method.... | [
"Replace",
"the",
"formatter",
"function",
"used",
"by",
"the",
"trace",
"decorator",
"to",
"handle",
"formatting",
"a",
"specific",
"kind",
"of",
"argument",
".",
"There",
"are",
"several",
"kinds",
"of",
"arguments",
"that",
"trace",
"discriminates",
"between"... | python | train | 47.039216 |
openstack/python-monascaclient | monascaclient/v2_0/shell.py | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L867-L918 | def do_alarm_definition_list(mc, args):
'''List alarm definitions for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.severity:
if not _validate_severity(arg... | [
"def",
"do_alarm_definition_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"name",
":",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"args",
".",
"dimensions",
":",
"fields",
"[",
"'dimensions'",
... | List alarm definitions for this tenant. | [
"List",
"alarm",
"definitions",
"for",
"this",
"tenant",
"."
] | python | train | 41.980769 |
niccokunzmann/hanging_threads | hanging_threads.py | https://github.com/niccokunzmann/hanging_threads/blob/167f4faa9ef7bf44866d9cda75d30606acb3c416/hanging_threads.py#L145-L164 | def frame2string(frame):
"""Return info about frame.
Keyword arg:
frame
Return string in format:
File {file name}, line {line number}, in
{name of parent of code object} {newline}
Line from file at line number
"""
lineno = frame.f_lineno # or f_lasti
co = frame.f_code
... | [
"def",
"frame2string",
"(",
"frame",
")",
":",
"lineno",
"=",
"frame",
".",
"f_lineno",
"# or f_lasti",
"co",
"=",
"frame",
".",
"f_code",
"filename",
"=",
"co",
".",
"co_filename",
"name",
"=",
"co",
".",
"co_name",
"s",
"=",
"'\\tFile \"{0}\", line {1}, in... | Return info about frame.
Keyword arg:
frame
Return string in format:
File {file name}, line {line number}, in
{name of parent of code object} {newline}
Line from file at line number | [
"Return",
"info",
"about",
"frame",
"."
] | python | train | 26.35 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L4394-L4397 | def views_preview(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#previewing-views"
api_path = "/api/v2/views/preview.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"views_preview",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/views/preview.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
"*... | https://developer.zendesk.com/rest_api/docs/core/views#previewing-views | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"views#previewing",
"-",
"views"
] | python | train | 59.5 |
warrenspe/hconf | hconf/subparsers/yaml_.py | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/subparsers/yaml_.py#L32-L52 | def parse(self, configManager, config):
"""
Parse configuration options out of a YAML configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options popula... | [
"def",
"parse",
"(",
"self",
",",
"configManager",
",",
"config",
")",
":",
"configFile",
"=",
"self",
".",
"_getConfigFile",
"(",
"config",
")",
"if",
"not",
"configFile",
":",
"return",
"dict",
"(",
")",
"yamlConfigs",
"=",
"yaml",
".",
"load",
"(",
... | Parse configuration options out of a YAML configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options populated thus far.
Outputs: A dictionary of new configur... | [
"Parse",
"configuration",
"options",
"out",
"of",
"a",
"YAML",
"configuration",
"file",
"."
] | python | train | 38.333333 |
PGower/PyCanvas | pycanvas/apis/appointment_groups.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/appointment_groups.py#L291-L314 | def list_user_participants(self, id, registration_status=None):
"""
List user participants.
List users that are (or may be) participating in this appointment group.
Refer to the Users API for the response fields. Returns no results for
appointment groups with the "Group" p... | [
"def",
"list_user_participants",
"(",
"self",
",",
"id",
",",
"registration_status",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"id\"",
"]",
"="... | List user participants.
List users that are (or may be) participating in this appointment group.
Refer to the Users API for the response fields. Returns no results for
appointment groups with the "Group" participant_type. | [
"List",
"user",
"participants",
".",
"List",
"users",
"that",
"are",
"(",
"or",
"may",
"be",
")",
"participating",
"in",
"this",
"appointment",
"group",
".",
"Refer",
"to",
"the",
"Users",
"API",
"for",
"the",
"response",
"fields",
".",
"Returns",
"no",
... | python | train | 45.708333 |
Qiskit/qiskit-terra | qiskit/quantum_info/operators/channel/chi.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/chi.py#L136-L169 | def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(s... | [
"def",
"compose",
"(",
"self",
",",
"other",
",",
"qargs",
"=",
"None",
",",
"front",
"=",
"False",
")",
":",
"if",
"qargs",
"is",
"not",
"None",
":",
"return",
"Chi",
"(",
"SuperOp",
"(",
"self",
")",
".",
"compose",
"(",
"other",
",",
"qargs",
... | Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compose in rev... | [
"Return",
"the",
"composition",
"channel",
"self∘other",
"."
] | python | test | 42.235294 |
williamgilpin/pypdb | pypdb/pypdb.py | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1164-L1212 | def list_types(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the... | [
"def",
"list_types",
"(",
"pdb_list",
",",
"sleep_time",
"=",
".1",
")",
":",
"if",
"len",
"(",
"pdb_list",
")",
"*",
"sleep_time",
">",
"30",
":",
"warnings",
".",
"warn",
"(",
"\"Because of API limitations, this function\\\n will take at least \"",
"+",
"... | Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary a... | [
"Given",
"a",
"list",
"of",
"PDB",
"IDs",
"look",
"up",
"their",
"associated",
"structure",
"type"
] | python | train | 30.55102 |
cakebread/yolk | yolk/plugins/__init__.py | https://github.com/cakebread/yolk/blob/ee8c9f529a542d9c5eff4fe69b9c7906c802e4d8/yolk/plugins/__init__.py#L89-L109 | def load_plugins(builtin=True, others=True):
"""Load plugins, either builtin, others, or both.
"""
for entry_point in pkg_resources.iter_entry_points('yolk.plugins'):
#LOG.debug("load plugin %s" % entry_point)
try:
plugin = entry_point.load()
except KeyboardInterrupt:
... | [
"def",
"load_plugins",
"(",
"builtin",
"=",
"True",
",",
"others",
"=",
"True",
")",
":",
"for",
"entry_point",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'yolk.plugins'",
")",
":",
"#LOG.debug(\"load plugin %s\" % entry_point)",
"try",
":",
"plugin",
... | Load plugins, either builtin, others, or both. | [
"Load",
"plugins",
"either",
"builtin",
"others",
"or",
"both",
"."
] | python | train | 37.285714 |
materialsproject/pymatgen | pymatgen/electronic_structure/plotter.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/plotter.py#L576-L589 | def save_plot(self, filename, img_format="eps", ylim=None,
zero_to_efermi=True, smooth=False):
"""
Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-... | [
"def",
"save_plot",
"(",
"self",
",",
"filename",
",",
"img_format",
"=",
"\"eps\"",
",",
"ylim",
"=",
"None",
",",
"zero_to_efermi",
"=",
"True",
",",
"smooth",
"=",
"False",
")",
":",
"plt",
"=",
"self",
".",
"get_plot",
"(",
"ylim",
"=",
"ylim",
"... | Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits. | [
"Save",
"matplotlib",
"plot",
"to",
"a",
"file",
"."
] | python | train | 36.642857 |
titusjan/argos | argos/application.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L391-L397 | def execute(self):
""" Executes all main windows by starting the Qt main application
"""
logger.info("Starting Argos event loop...")
exitCode = self.qApplication.exec_()
logger.info("Argos event loop finished with exit code: {}".format(exitCode))
return exitCode | [
"def",
"execute",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Starting Argos event loop...\"",
")",
"exitCode",
"=",
"self",
".",
"qApplication",
".",
"exec_",
"(",
")",
"logger",
".",
"info",
"(",
"\"Argos event loop finished with exit code: {}\"",
".",... | Executes all main windows by starting the Qt main application | [
"Executes",
"all",
"main",
"windows",
"by",
"starting",
"the",
"Qt",
"main",
"application"
] | python | train | 43.428571 |
limpyd/redis-limpyd | limpyd/fields.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/fields.py#L223-L234 | def proxy_set(self, value):
"""
A helper to easily call the proxy_setter of the field
"""
setter = getattr(self, self.proxy_setter)
if isinstance(value, (list, tuple, set)):
result = setter(*value)
elif isinstance(value, dict):
result = setter(**va... | [
"def",
"proxy_set",
"(",
"self",
",",
"value",
")",
":",
"setter",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"proxy_setter",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"result",
"=",
"sett... | A helper to easily call the proxy_setter of the field | [
"A",
"helper",
"to",
"easily",
"call",
"the",
"proxy_setter",
"of",
"the",
"field"
] | python | train | 32 |
pantsbuild/pants | src/python/pants/reporting/json_reporter.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/json_reporter.py#L88-L101 | def do_handle_log(self, workunit, level, *msg_elements):
"""Implementation of Reporter callback."""
entry_info = {
'level': self._log_level_str[level],
'messages': self._render_messages(*msg_elements),
}
root_id = str(workunit.root().id)
current_stack = self._root_id_to_workunit_stack[... | [
"def",
"do_handle_log",
"(",
"self",
",",
"workunit",
",",
"level",
",",
"*",
"msg_elements",
")",
":",
"entry_info",
"=",
"{",
"'level'",
":",
"self",
".",
"_log_level_str",
"[",
"level",
"]",
",",
"'messages'",
":",
"self",
".",
"_render_messages",
"(",
... | Implementation of Reporter callback. | [
"Implementation",
"of",
"Reporter",
"callback",
"."
] | python | train | 33.357143 |
mistio/mist.client | src/mistclient/__init__.py | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/__init__.py#L119-L131 | def _list_clouds(self):
"""
Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances
"""
req = self.request(self.uri + '/clouds')
clouds = req.get().json()
if clouds:
for cloud in clouds:
s... | [
"def",
"_list_clouds",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"uri",
"+",
"'/clouds'",
")",
"clouds",
"=",
"req",
".",
"get",
"(",
")",
".",
"json",
"(",
")",
"if",
"clouds",
":",
"for",
"cloud",
"in",
"cloud... | Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances | [
"Request",
"a",
"list",
"of",
"all",
"added",
"clouds",
"."
] | python | train | 30.538462 |
edwards-lab/libGWAS | libgwas/snp_boundary_check.py | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/snp_boundary_check.py#L128-L138 | def NoExclusions(self):
"""Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive.
... | [
"def",
"NoExclusions",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"start_bounds",
")",
"+",
"len",
"(",
"self",
".",
"target_rs",
")",
"+",
"len",
"(",
"self",
".",
"ignored_rs",
")",
"==",
"0",
":",
"return",
"BoundaryCheck",
".",
"chrom"... | Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive. | [
"Determine",
"that",
"there",
"are",
"no",
"exclusion",
"criterion",
"in",
"play"
] | python | train | 42.181818 |
pybel/pybel-tools | src/pybel_tools/integration/overlay.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/integration/overlay.py#L58-L86 | def overlay_type_data(graph: BELGraph,
data: Mapping[str, float],
func: str,
namespace: str,
label: Optional[str] = None,
overwrite: bool = False,
impute: Optional[float] = None,
... | [
"def",
"overlay_type_data",
"(",
"graph",
":",
"BELGraph",
",",
"data",
":",
"Mapping",
"[",
"str",
",",
"float",
"]",
",",
"func",
":",
"str",
",",
"namespace",
":",
"str",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"overwrite... | Overlay tabular data on the network for data that comes from an data set with identifiers that lack
namespaces.
For example, if you want to overlay differential gene expression data from a table, that table
probably has HGNC identifiers, but no specific annotations that they are in the HGNC namespace or
... | [
"Overlay",
"tabular",
"data",
"on",
"the",
"network",
"for",
"data",
"that",
"comes",
"from",
"an",
"data",
"set",
"with",
"identifiers",
"that",
"lack",
"namespaces",
"."
] | python | valid | 45.862069 |
brantai/python-rightscale | rightscale/commands.py | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/commands.py#L63-L113 | def run_script_on_server(
script_name,
server_name,
inputs=None,
timeout_s=10,
output=sys.stdout
):
"""
Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
... | [
"def",
"run_script_on_server",
"(",
"script_name",
",",
"server_name",
",",
"inputs",
"=",
"None",
",",
"timeout_s",
"=",
"10",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"api",
"=",
"get_api",
"(",
")",
"script",
"=",
"find_by_name",
"(",
"api"... | Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
'my cool bob lol script',
'some server',
inputs={'BOB': 'blah blah', 'LOL': 'fubar'},
)
Sample output::
... | [
"Runs",
"a",
"RightScript",
"and",
"polls",
"for",
"status",
"."
] | python | train | 30.72549 |
hyperledger/indy-sdk | wrappers/python/indy/did.py | https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/did.py#L368-L405 | async def set_endpoint_for_did(wallet_handle: int,
did: str,
address: str,
transport_key: str) -> None:
"""
Set/replaces endpoint information for the given DID.
:param wallet_handle: Wallet handle (created by open_... | [
"async",
"def",
"set_endpoint_for_did",
"(",
"wallet_handle",
":",
"int",
",",
"did",
":",
"str",
",",
"address",
":",
"str",
",",
"transport_key",
":",
"str",
")",
"->",
"None",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"log... | Set/replaces endpoint information for the given DID.
:param wallet_handle: Wallet handle (created by open_wallet).
:param did: The DID to resolve endpoint.
:param address: The DIDs endpoint address.
:param transport_key: The DIDs transport key (ver key, key id).
:return: Error code | [
"Set",
"/",
"replaces",
"endpoint",
"information",
"for",
"the",
"given",
"DID",
"."
] | python | train | 36.736842 |
google/grr | grr/core/grr_response_core/lib/fingerprint.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/fingerprint.py#L241-L261 | def EvalGeneric(self, hashers=None):
"""Causes the entire file to be hashed by the given hash functions.
This sets up a 'finger' for fingerprinting, where the entire file
is passed through a pre-defined (or user defined) set of hash functions.
Args:
hashers: An iterable of hash classes (e.g. out... | [
"def",
"EvalGeneric",
"(",
"self",
",",
"hashers",
"=",
"None",
")",
":",
"if",
"hashers",
"is",
"None",
":",
"hashers",
"=",
"Fingerprinter",
".",
"GENERIC_HASH_CLASSES",
"hashfuncs",
"=",
"[",
"x",
"(",
")",
"for",
"x",
"in",
"hashers",
"]",
"finger",
... | Causes the entire file to be hashed by the given hash functions.
This sets up a 'finger' for fingerprinting, where the entire file
is passed through a pre-defined (or user defined) set of hash functions.
Args:
hashers: An iterable of hash classes (e.g. out of hashlib) which will
be in... | [
"Causes",
"the",
"entire",
"file",
"to",
"be",
"hashed",
"by",
"the",
"given",
"hash",
"functions",
"."
] | python | train | 40.714286 |
secure-systems-lab/securesystemslib | securesystemslib/ecdsa_keys.py | https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/ecdsa_keys.py#L161-L240 | def create_signature(public_key, private_key, data, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy ... | [
"def",
"create_signature",
"(",
"public_key",
",",
"private_key",
",",
"data",
",",
"scheme",
"=",
"'ecdsa-sha2-nistp256'",
")",
":",
"# Do 'public_key' and 'private_key' have the correct format?",
"# This check will ensure that the arguments conform to",
"# 'securesystemslib.formats... | <Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> signature, scheme = create_signature(public, private, data, requested_scheme)
... | [
"<Purpose",
">",
"Return",
"a",
"(",
"signature",
"scheme",
")",
"tuple",
"."
] | python | train | 35.1125 |
SmokinCaterpillar/pypet | pypet/brian2/parameter.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/brian2/parameter.py#L201-L207 | def _supports(self, data):
""" Simply checks if data is supported """
if isinstance(data, Quantity):
return True
elif super(Brian2Result, self)._supports(data):
return True
return False | [
"def",
"_supports",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"Quantity",
")",
":",
"return",
"True",
"elif",
"super",
"(",
"Brian2Result",
",",
"self",
")",
".",
"_supports",
"(",
"data",
")",
":",
"return",
"True",
"... | Simply checks if data is supported | [
"Simply",
"checks",
"if",
"data",
"is",
"supported"
] | python | test | 33.571429 |
secdev/scapy | scapy/contrib/macsec.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/macsec.py#L123-L136 | def encap(self, pkt):
"""encapsulate a frame using this Secure Association"""
if pkt.name != Ether().name:
raise TypeError('cannot encapsulate packet in MACsec, must be Ethernet') # noqa: E501
hdr = copy.deepcopy(pkt)
payload = hdr.payload
del hdr.payload
tag... | [
"def",
"encap",
"(",
"self",
",",
"pkt",
")",
":",
"if",
"pkt",
".",
"name",
"!=",
"Ether",
"(",
")",
".",
"name",
":",
"raise",
"TypeError",
"(",
"'cannot encapsulate packet in MACsec, must be Ethernet'",
")",
"# noqa: E501",
"hdr",
"=",
"copy",
".",
"deepc... | encapsulate a frame using this Secure Association | [
"encapsulate",
"a",
"frame",
"using",
"this",
"Secure",
"Association"
] | python | train | 44.142857 |
gmr/tinman | tinman/utils.py | https://github.com/gmr/tinman/blob/98f0acd15a228d752caa1864cdf02aaa3d492a9f/tinman/utils.py#L29-L38 | def import_namespaced_class(path):
"""Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str path: The object path
:rtype: class
"""
parts = path.split('.')
return getattr(importlib.import_module('.'.join(parts[0:-1])), p... | [
"def",
"import_namespaced_class",
"(",
"path",
")",
":",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"return",
"getattr",
"(",
"importlib",
".",
"import_module",
"(",
"'.'",
".",
"join",
"(",
"parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
... | Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str path: The object path
:rtype: class | [
"Pass",
"in",
"a",
"string",
"in",
"the",
"format",
"of",
"foo",
".",
"Bar",
"foo",
".",
"bar",
".",
"Baz",
"foo",
".",
"bar",
".",
"baz",
".",
"Qux",
"and",
"it",
"will",
"return",
"a",
"handle",
"to",
"the",
"class"
] | python | train | 32 |
airspeed-velocity/asv | asv/extern/asizeof.py | https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L726-L734 | def _len_frame(obj):
'''Length of a frame object.
'''
c = getattr(obj, 'f_code', None)
if c:
n = _len_code(c)
else:
n = 0
return n | [
"def",
"_len_frame",
"(",
"obj",
")",
":",
"c",
"=",
"getattr",
"(",
"obj",
",",
"'f_code'",
",",
"None",
")",
"if",
"c",
":",
"n",
"=",
"_len_code",
"(",
"c",
")",
"else",
":",
"n",
"=",
"0",
"return",
"n"
] | Length of a frame object. | [
"Length",
"of",
"a",
"frame",
"object",
"."
] | python | train | 17.777778 |
SmokinCaterpillar/pypet | pypet/trajectory.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/trajectory.py#L788-L809 | def _prepare_experiment(self):
"""Called by the environment to make some initial configurations before performing the
individual runs.
Checks if all parameters marked for presetting were preset. If not raises a
DefaultReplacementError.
Locks all parameters.
Removal of ... | [
"def",
"_prepare_experiment",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_changed_default_parameters",
")",
":",
"raise",
"pex",
".",
"PresettingError",
"(",
"'The following parameters were supposed to replace a '",
"'default value, but it was never tried to '",
... | Called by the environment to make some initial configurations before performing the
individual runs.
Checks if all parameters marked for presetting were preset. If not raises a
DefaultReplacementError.
Locks all parameters.
Removal of potential results of previous runs in case... | [
"Called",
"by",
"the",
"environment",
"to",
"make",
"some",
"initial",
"configurations",
"before",
"performing",
"the",
"individual",
"runs",
"."
] | python | test | 39 |
python-openxml/python-docx | docx/text/parfmt.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/text/parfmt.py#L145-L158 | def line_spacing_rule(self):
"""
A member of the :ref:`WdLineSpacing` enumeration indicating how the
value of :attr:`line_spacing` should be interpreted. Assigning any of
the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
:attr:`ONE_POINT_FIVE` will cause the val... | [
"def",
"line_spacing_rule",
"(",
"self",
")",
":",
"pPr",
"=",
"self",
".",
"_element",
".",
"pPr",
"if",
"pPr",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"_line_spacing_rule",
"(",
"pPr",
".",
"spacing_line",
",",
"pPr",
".",
"spacing_... | A member of the :ref:`WdLineSpacing` enumeration indicating how the
value of :attr:`line_spacing` should be interpreted. Assigning any of
the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
:attr:`ONE_POINT_FIVE` will cause the value of :attr:`line_spacing`
to be updated ... | [
"A",
"member",
"of",
"the",
":",
"ref",
":",
"WdLineSpacing",
"enumeration",
"indicating",
"how",
"the",
"value",
"of",
":",
"attr",
":",
"line_spacing",
"should",
"be",
"interpreted",
".",
"Assigning",
"any",
"of",
"the",
":",
"ref",
":",
"WdLineSpacing",
... | python | train | 42.214286 |
emilydolson/avida-spatial-tools | avidaspatial/visualizations.py | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/visualizations.py#L425-L458 | def color_array_by_hue_mix(value, palette):
"""
Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap.
"""
if int(value, 2) > 0:
# Convert bi... | [
"def",
"color_array_by_hue_mix",
"(",
"value",
",",
"palette",
")",
":",
"if",
"int",
"(",
"value",
",",
"2",
")",
">",
"0",
":",
"# Convert bits to list and reverse order to avoid issues with",
"# differing lengths",
"int_list",
"=",
"[",
"int",
"(",
"i",
")",
... | Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap. | [
"Figure",
"out",
"the",
"appropriate",
"color",
"for",
"a",
"binary",
"string",
"value",
"by",
"averaging",
"the",
"colors",
"corresponding",
"the",
"indices",
"of",
"each",
"one",
"that",
"it",
"contains",
".",
"Makes",
"for",
"visualizations",
"that",
"intui... | python | train | 31.029412 |
abarto/pandas-drf-tools | pandas_drf_tools/generics.py | https://github.com/abarto/pandas-drf-tools/blob/ec754ac75327e6ee5a1efd256a572a9a531e4d28/pandas_drf_tools/generics.py#L132-L141 | def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
self._paginator = self.pagination_class()
... | [
"def",
"paginator",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_paginator'",
")",
":",
"if",
"self",
".",
"pagination_class",
"is",
"None",
":",
"self",
".",
"_paginator",
"=",
"None",
"else",
":",
"self",
".",
"_paginator",
"="... | The paginator instance associated with the view, or `None`. | [
"The",
"paginator",
"instance",
"associated",
"with",
"the",
"view",
"or",
"None",
"."
] | python | valid | 33.9 |
heuer/cablemap | cablemap.core/cablemap/core/models.py | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/models.py#L182-L199 | def wl_uris(self):
"""\
Returns cable IRIs to WikiLeaks (mirrors).
"""
def year_month(d):
date, time = d.split()
return date.split('-')[:2]
if not self.created:
raise ValueError('The "created" property must be provided')
year, month = y... | [
"def",
"wl_uris",
"(",
"self",
")",
":",
"def",
"year_month",
"(",
"d",
")",
":",
"date",
",",
"time",
"=",
"d",
".",
"split",
"(",
")",
"return",
"date",
".",
"split",
"(",
"'-'",
")",
"[",
":",
"2",
"]",
"if",
"not",
"self",
".",
"created",
... | \
Returns cable IRIs to WikiLeaks (mirrors). | [
"\\",
"Returns",
"cable",
"IRIs",
"to",
"WikiLeaks",
"(",
"mirrors",
")",
"."
] | python | train | 32.5 |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L321-L333 | def num_rows(self):
"""
Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.summary()['num_vertices']
elif self._is_edge_frame():
ret... | [
"def",
"num_rows",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_vertex_frame",
"(",
")",
":",
"return",
"self",
".",
"__graph__",
".",
"summary",
"(",
")",
"[",
"'num_vertices'",
"]",
"elif",
"self",
".",
"_is_edge_frame",
"(",
")",
":",
"return",
"s... | Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame. | [
"Returns",
"the",
"number",
"of",
"rows",
"."
] | python | train | 26.846154 |
Azure/Azure-MachineLearning-ClientLibrary-Python | azureml/__init__.py | https://github.com/Azure/Azure-MachineLearning-ClientLibrary-Python/blob/d1211b289747671898eb063013e0dc53d3c80acd/azureml/__init__.py#L621-L628 | def read_as_text(self):
'''Read and return the dataset contents as text.'''
return self.workspace._rest.read_intermediate_dataset_contents_text(
self.workspace.workspace_id,
self.experiment.experiment_id,
self.node_id,
self.port_name
) | [
"def",
"read_as_text",
"(",
"self",
")",
":",
"return",
"self",
".",
"workspace",
".",
"_rest",
".",
"read_intermediate_dataset_contents_text",
"(",
"self",
".",
"workspace",
".",
"workspace_id",
",",
"self",
".",
"experiment",
".",
"experiment_id",
",",
"self",... | Read and return the dataset contents as text. | [
"Read",
"and",
"return",
"the",
"dataset",
"contents",
"as",
"text",
"."
] | python | test | 37.5 |
javipalanca/spade | spade/behaviour.py | https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L287-L299 | async def send(self, msg: Message):
"""
Sends a message.
Args:
msg (spade.message.Message): the message to be sent.
"""
if not msg.sender:
msg.sender = str(self.agent.jid)
logger.debug(f"Adding agent's jid as sender to message: {msg}")
... | [
"async",
"def",
"send",
"(",
"self",
",",
"msg",
":",
"Message",
")",
":",
"if",
"not",
"msg",
".",
"sender",
":",
"msg",
".",
"sender",
"=",
"str",
"(",
"self",
".",
"agent",
".",
"jid",
")",
"logger",
".",
"debug",
"(",
"f\"Adding agent's jid as se... | Sends a message.
Args:
msg (spade.message.Message): the message to be sent. | [
"Sends",
"a",
"message",
"."
] | python | train | 33.307692 |
shoebot/shoebot | lib/graph/style.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L29-L41 | def create(self, stylename, **kwargs):
""" Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
"""
if stylename == "default":
self[stylename] = style(stylename, self._ctx, **kwargs)
... | [
"def",
"create",
"(",
"self",
",",
"stylename",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"stylename",
"==",
"\"default\"",
":",
"self",
"[",
"stylename",
"]",
"=",
"style",
"(",
"stylename",
",",
"self",
".",
"_ctx",
",",
"*",
"*",
"kwargs",
")",
"... | Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter. | [
"Creates",
"a",
"new",
"style",
"which",
"inherits",
"from",
"the",
"default",
"style",
"or",
"any",
"other",
"style",
"which",
"name",
"is",
"supplied",
"to",
"the",
"optional",
"template",
"parameter",
"."
] | python | valid | 43.923077 |
array-split/array_split | array_split/logging.py | https://github.com/array-split/array_split/blob/e07abe3001209394dde809f7e6f505f9f49a1c26/array_split/logging.py#L69-L98 | def emit(self, record):
"""
Mostly copy-paste from :obj:`logging.StreamHandler`.
"""
try:
msg = self.format(record)
if record.levelno < self.splitLevel:
stream = self.outStream
else:
stream = self.errStream
f... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"msg",
"=",
"self",
".",
"format",
"(",
"record",
")",
"if",
"record",
".",
"levelno",
"<",
"self",
".",
"splitLevel",
":",
"stream",
"=",
"self",
".",
"outStream",
"else",
":",
"stre... | Mostly copy-paste from :obj:`logging.StreamHandler`. | [
"Mostly",
"copy",
"-",
"paste",
"from",
":",
"obj",
":",
"logging",
".",
"StreamHandler",
"."
] | python | train | 32.966667 |
mitsei/dlkit | dlkit/json_/learning/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/sessions.py#L881-L903 | def alias_objective(self, objective_id, alias_id):
"""Adds an ``Id`` to an ``Objective`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Objective`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer... | [
"def",
"alias_objective",
"(",
"self",
",",
"objective_id",
",",
"alias_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.alias_resources_template",
"self",
".",
"_alias_id",
"(",
"primary_id",
"=",
"objective_id",
",",
"equivalent_id",
... | Adds an ``Id`` to an ``Objective`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Objective`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another objective, it is
reassigned to the given o... | [
"Adds",
"an",
"Id",
"to",
"an",
"Objective",
"for",
"the",
"purpose",
"of",
"creating",
"compatibility",
"."
] | python | train | 48.478261 |
fmfn/BayesianOptimization | bayes_opt/util.py | https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/util.py#L159-L171 | def ensure_rng(random_state=None):
"""
Creates a random number generator based on an optional seed. This can be
an integer or another random state for a seeded rng, or None for an
unseeded rng.
"""
if random_state is None:
random_state = np.random.RandomState()
elif isinstance(rando... | [
"def",
"ensure_rng",
"(",
"random_state",
"=",
"None",
")",
":",
"if",
"random_state",
"is",
"None",
":",
"random_state",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
")",
"elif",
"isinstance",
"(",
"random_state",
",",
"int",
")",
":",
"random_state... | Creates a random number generator based on an optional seed. This can be
an integer or another random state for a seeded rng, or None for an
unseeded rng. | [
"Creates",
"a",
"random",
"number",
"generator",
"based",
"on",
"an",
"optional",
"seed",
".",
"This",
"can",
"be",
"an",
"integer",
"or",
"another",
"random",
"state",
"for",
"a",
"seeded",
"rng",
"or",
"None",
"for",
"an",
"unseeded",
"rng",
"."
] | python | train | 36.769231 |
persandstrom/python-vasttrafik | vasttrafik/__main__.py | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/__main__.py#L43-L57 | def print_table(document, *columns):
""" Print json document as table """
headers = []
for _, header in columns:
headers.append(header)
table = []
for element in document:
row = []
for item, _ in columns:
if item in element:
row.append(element[item... | [
"def",
"print_table",
"(",
"document",
",",
"*",
"columns",
")",
":",
"headers",
"=",
"[",
"]",
"for",
"_",
",",
"header",
"in",
"columns",
":",
"headers",
".",
"append",
"(",
"header",
")",
"table",
"=",
"[",
"]",
"for",
"element",
"in",
"document",... | Print json document as table | [
"Print",
"json",
"document",
"as",
"table"
] | python | train | 28.666667 |
saltstack/salt | salt/modules/github.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1426-L1462 | def remove_team_repo(repo_name, team_name, profile="github"):
'''
Removes a repository from a team with team_name.
repo_name
The name of the repository to remove.
team_name
The name of the team of which to remove the repository.
profile
The name of the profile configuratio... | [
"def",
"remove_team_repo",
"(",
"repo_name",
",",
"team_name",
",",
"profile",
"=",
"\"github\"",
")",
":",
"team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"team",
":",
"log",
".",
"error",
"(",
"'Team %s does n... | Removes a repository from a team with team_name.
repo_name
The name of the repository to remove.
team_name
The name of the team of which to remove the repository.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. code-block:: b... | [
"Removes",
"a",
"repository",
"from",
"a",
"team",
"with",
"team_name",
"."
] | python | train | 29.864865 |
DataONEorg/d1_python | lib_common/src/d1_common/cert/subject_info.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/cert/subject_info.py#L378-L392 | def _trim_tree(state):
"""Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed ... | [
"def",
"_trim_tree",
"(",
"state",
")",
":",
"for",
"n",
"in",
"list",
"(",
"state",
".",
"tree",
".",
"leaf_node_gen",
")",
":",
"if",
"n",
".",
"type_str",
"==",
"TYPE_NODE_TAG",
":",
"n",
".",
"parent",
".",
"child_list",
".",
"remove",
"(",
"n",
... | Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed here.
- Removing a leaf n... | [
"Trim",
"empty",
"leaf",
"nodes",
"from",
"the",
"tree",
"."
] | python | train | 42.8 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L480-L506 | def start(self):
"""
Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_response",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"command execution already started\"",
")",
"request",
"=",
"aioxmpp",
".",
"IQ",
"(",
"type_",
"=",
"aioxmpp",
".",
"IQType",
... | Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`response` and related attributes get ... | [
"Initiate",
"the",
"session",
"by",
"starting",
"to",
"execute",
"the",
"command",
"with",
"the",
"peer",
"."
] | python | train | 30.407407 |
jonathansick/paperweight | paperweight/gitio.py | https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/gitio.py#L67-L84 | def absolute_git_root_dir(fpath=""):
"""Absolute path to the git root directory containing a given file or
directory.
"""
if len(fpath) == 0:
dirname_str = os.getcwd()
else:
dirname_str = os.path.dirname(fpath)
dirname_str = os.path.abspath(dirname_str)
dirnames = dirname_str... | [
"def",
"absolute_git_root_dir",
"(",
"fpath",
"=",
"\"\"",
")",
":",
"if",
"len",
"(",
"fpath",
")",
"==",
"0",
":",
"dirname_str",
"=",
"os",
".",
"getcwd",
"(",
")",
"else",
":",
"dirname_str",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fpath",
... | Absolute path to the git root directory containing a given file or
directory. | [
"Absolute",
"path",
"to",
"the",
"git",
"root",
"directory",
"containing",
"a",
"given",
"file",
"or",
"directory",
"."
] | python | train | 33.388889 |
antoniobotelho/py-business-calendar | business_calendar/business_calendar.py | https://github.com/antoniobotelho/py-business-calendar/blob/92365fbddd043e41e33b01f1ddd9dd6a5094c031/business_calendar/business_calendar.py#L238-L277 | def adjust(self, date, mode):
"""
Adjust the date to the closest work date.
Args:
date (date, datetime or str): Date to be adjusted.
mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING.
Note:
If date is already a business date than it i... | [
"def",
"adjust",
"(",
"self",
",",
"date",
",",
"mode",
")",
":",
"date",
"=",
"parsefun",
"(",
"date",
")",
"if",
"self",
".",
"isbusday",
"(",
"date",
")",
":",
"return",
"date",
"if",
"mode",
"==",
"FOLLOWING",
":",
"dateadj",
"=",
"self",
".",
... | Adjust the date to the closest work date.
Args:
date (date, datetime or str): Date to be adjusted.
mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING.
Note:
If date is already a business date than it is returned unchanged.
How to use the ad... | [
"Adjust",
"the",
"date",
"to",
"the",
"closest",
"work",
"date",
".",
"Args",
":",
"date",
"(",
"date",
"datetime",
"or",
"str",
")",
":",
"Date",
"to",
"be",
"adjusted",
".",
"mode",
"(",
"integer",
")",
":",
"FOLLOWING",
"PREVIOUS",
"or",
"MODIFIEDFO... | python | train | 33.35 |
dixudx/rtcclient | rtcclient/client.py | https://github.com/dixudx/rtcclient/blob/1721dd0b047478f5bdd6359b07a2c503cfafd86f/rtcclient/client.py#L881-L928 | def getWorkitem(self, workitem_id, returned_properties=None):
"""Get :class:`rtcclient.workitem.Workitem` object by its id/number
:param workitem_id: the workitem id/number
(integer or equivalent string)
:param returned_properties: the returned properties that you want.
... | [
"def",
"getWorkitem",
"(",
"self",
",",
"workitem_id",
",",
"returned_properties",
"=",
"None",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"workitem_id",
",",
"bool",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid Workitem id\"",
")",
"if",
"isinstance",... | Get :class:`rtcclient.workitem.Workitem` object by its id/number
:param workitem_id: the workitem id/number
(integer or equivalent string)
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
... | [
"Get",
":",
"class",
":",
"rtcclient",
".",
"workitem",
".",
"Workitem",
"object",
"by",
"its",
"id",
"/",
"number"
] | python | train | 42 |
msmbuilder/msmbuilder | msmbuilder/decomposition/tica.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/tica.py#L470-L489 | def summarize(self):
"""Some summary information."""
# force shrinkage to be calculated
self.covariance_
return """time-structure based Independent Components Analysis (tICA)
-----------------------------------------------------------
n_components : {n_components}
shrinkage ... | [
"def",
"summarize",
"(",
"self",
")",
":",
"# force shrinkage to be calculated",
"self",
".",
"covariance_",
"return",
"\"\"\"time-structure based Independent Components Analysis (tICA)\n-----------------------------------------------------------\nn_components : {n_components}\nshrinkag... | Some summary information. | [
"Some",
"summary",
"information",
"."
] | python | train | 34.1 |
projectshift/shift-boiler | boiler/user/user_service.py | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L49-L71 | def init(self, app):
"""
Initialise from flask app
This gets configuration values from a flask application.
:param app: flask.Flask
:return: boiler.user.user_servce.UserService
"""
cfg = app.config
self.welcome_message = cfg.get('USER_SEND_WELCOME_MESSAGE'... | [
"def",
"init",
"(",
"self",
",",
"app",
")",
":",
"cfg",
"=",
"app",
".",
"config",
"self",
".",
"welcome_message",
"=",
"cfg",
".",
"get",
"(",
"'USER_SEND_WELCOME_MESSAGE'",
")",
"self",
".",
"require_confirmation",
"=",
"cfg",
".",
"get",
"(",
"'USER_... | Initialise from flask app
This gets configuration values from a flask application.
:param app: flask.Flask
:return: boiler.user.user_servce.UserService | [
"Initialise",
"from",
"flask",
"app",
"This",
"gets",
"configuration",
"values",
"from",
"a",
"flask",
"application",
".",
":",
"param",
"app",
":",
"flask",
".",
"Flask",
":",
"return",
":",
"boiler",
".",
"user",
".",
"user_servce",
".",
"UserService"
] | python | train | 37.347826 |
consbio/ncdjango | ncdjango/interfaces/arcgis_extended/utils.py | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis_extended/utils.py#L8-L43 | def get_renderer_from_definition(config):
"""Returns a renderer object based on the configuration (as a dictionary)"""
options = config.get('options', {})
try:
renderer_type = config['type']
renderer_colors = [(float(x[0]), hex_to_color(x[1])) for x in config['colors']]
fill_value ... | [
"def",
"get_renderer_from_definition",
"(",
"config",
")",
":",
"options",
"=",
"config",
".",
"get",
"(",
"'options'",
",",
"{",
"}",
")",
"try",
":",
"renderer_type",
"=",
"config",
"[",
"'type'",
"]",
"renderer_colors",
"=",
"[",
"(",
"float",
"(",
"x... | Returns a renderer object based on the configuration (as a dictionary) | [
"Returns",
"a",
"renderer",
"object",
"based",
"on",
"the",
"configuration",
"(",
"as",
"a",
"dictionary",
")"
] | python | train | 36.388889 |
futurecolors/django-geoip | django_geoip/management/ipgeobase.py | https://github.com/futurecolors/django-geoip/blob/f9eee4bcad40508089b184434b79826f842d7bd0/django_geoip/management/ipgeobase.py#L105-L126 | def _process_cities_file(self, file, city_country_mapping):
""" Iterate over cities info and extract useful data """
data = {'all_regions': list(), 'regions': list(), 'cities': list(), 'city_region_mapping': dict()}
allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
for geo_info in... | [
"def",
"_process_cities_file",
"(",
"self",
",",
"file",
",",
"city_country_mapping",
")",
":",
"data",
"=",
"{",
"'all_regions'",
":",
"list",
"(",
")",
",",
"'regions'",
":",
"list",
"(",
")",
",",
"'cities'",
":",
"list",
"(",
")",
",",
"'city_region_... | Iterate over cities info and extract useful data | [
"Iterate",
"over",
"cities",
"info",
"and",
"extract",
"useful",
"data"
] | python | train | 59.363636 |
PMEAL/OpenPNM | openpnm/core/ModelsMixin.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/core/ModelsMixin.py#L307-L335 | def remove_model(self, propname=None, mode=['model', 'data']):
r"""
Removes model and data from object.
Parameters
----------
propname : string or list of strings
The property or list of properties to remove
mode : list of strings
Controls what i... | [
"def",
"remove_model",
"(",
"self",
",",
"propname",
"=",
"None",
",",
"mode",
"=",
"[",
"'model'",
",",
"'data'",
"]",
")",
":",
"if",
"type",
"(",
"propname",
")",
"is",
"str",
":",
"propname",
"=",
"[",
"propname",
"]",
"for",
"item",
"in",
"pro... | r"""
Removes model and data from object.
Parameters
----------
propname : string or list of strings
The property or list of properties to remove
mode : list of strings
Controls what is removed. Options are:
*'model'* : Removes the model but... | [
"r",
"Removes",
"model",
"and",
"data",
"from",
"object",
"."
] | python | train | 29.413793 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.