repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
Crunch-io/crunch-cube | src/cr/cube/dimension.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L113-L118 | def _raw_dimensions(self):
"""Sequence of _RawDimension objects wrapping each dimension dict."""
return tuple(
_RawDimension(dimension_dict, self._dimension_dicts)
for dimension_dict in self._dimension_dicts
) | [
"def",
"_raw_dimensions",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"_RawDimension",
"(",
"dimension_dict",
",",
"self",
".",
"_dimension_dicts",
")",
"for",
"dimension_dict",
"in",
"self",
".",
"_dimension_dicts",
")"
] | Sequence of _RawDimension objects wrapping each dimension dict. | [
"Sequence",
"of",
"_RawDimension",
"objects",
"wrapping",
"each",
"dimension",
"dict",
"."
] | python | train |
niccokunzmann/hanging_threads | hanging_threads.py | https://github.com/niccokunzmann/hanging_threads/blob/167f4faa9ef7bf44866d9cda75d30606acb3c416/hanging_threads.py#L51-L66 | def start_monitoring(seconds_frozen=SECONDS_FROZEN,
test_interval=TEST_INTERVAL):
"""Start monitoring for hanging threads.
seconds_frozen - How much time should thread hang to activate
printing stack trace - default(10)
tests_interval - Sleep time of monitoring thread (in millisec... | [
"def",
"start_monitoring",
"(",
"seconds_frozen",
"=",
"SECONDS_FROZEN",
",",
"test_interval",
"=",
"TEST_INTERVAL",
")",
":",
"thread",
"=",
"StoppableThread",
"(",
"target",
"=",
"monitor",
",",
"args",
"=",
"(",
"seconds_frozen",
",",
"test_interval",
")",
")... | Start monitoring for hanging threads.
seconds_frozen - How much time should thread hang to activate
printing stack trace - default(10)
tests_interval - Sleep time of monitoring thread (in milliseconds)
- default(100) | [
"Start",
"monitoring",
"for",
"hanging",
"threads",
"."
] | python | train |
Dallinger/Dallinger | dallinger/models.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L332-L340 | def json_data(self):
"""Return json description of a question."""
return {
"number": self.number,
"type": self.type,
"participant_id": self.participant_id,
"question": self.question,
"response": self.response,
} | [
"def",
"json_data",
"(",
"self",
")",
":",
"return",
"{",
"\"number\"",
":",
"self",
".",
"number",
",",
"\"type\"",
":",
"self",
".",
"type",
",",
"\"participant_id\"",
":",
"self",
".",
"participant_id",
",",
"\"question\"",
":",
"self",
".",
"question",... | Return json description of a question. | [
"Return",
"json",
"description",
"of",
"a",
"question",
"."
] | python | train |
fastai/fastai | fastai/core.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L119-L122 | def camel2snake(name:str)->str:
"Change `name` from camel to snake style."
s1 = re.sub(_camel_re1, r'\1_\2', name)
return re.sub(_camel_re2, r'\1_\2', s1).lower() | [
"def",
"camel2snake",
"(",
"name",
":",
"str",
")",
"->",
"str",
":",
"s1",
"=",
"re",
".",
"sub",
"(",
"_camel_re1",
",",
"r'\\1_\\2'",
",",
"name",
")",
"return",
"re",
".",
"sub",
"(",
"_camel_re2",
",",
"r'\\1_\\2'",
",",
"s1",
")",
".",
"lower... | Change `name` from camel to snake style. | [
"Change",
"name",
"from",
"camel",
"to",
"snake",
"style",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L763-L784 | def create_partition(self, org_name, part_name, dci_id, vrf_prof,
service_node_ip=None, desc=None):
"""Create partition on the DCNM.
:param org_name: name of organization to be created
:param part_name: name of partition to be created
:param dci_id: DCI ID
... | [
"def",
"create_partition",
"(",
"self",
",",
"org_name",
",",
"part_name",
",",
"dci_id",
",",
"vrf_prof",
",",
"service_node_ip",
"=",
"None",
",",
"desc",
"=",
"None",
")",
":",
"desc",
"=",
"desc",
"or",
"org_name",
"res",
"=",
"self",
".",
"_create_o... | Create partition on the DCNM.
:param org_name: name of organization to be created
:param part_name: name of partition to be created
:param dci_id: DCI ID
:vrf_prof: VRF profile for the partition
:param service_node_ip: Specifies the Default route IP address.
:param desc:... | [
"Create",
"partition",
"on",
"the",
"DCNM",
"."
] | python | train |
qualisys/qualisys_python_sdk | qtm/qrt.py | https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L56-L61 | async def qtm_version(self):
"""Get the QTM version.
"""
return await asyncio.wait_for(
self._protocol.send_command("qtmversion"), timeout=self._timeout
) | [
"async",
"def",
"qtm_version",
"(",
"self",
")",
":",
"return",
"await",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"_protocol",
".",
"send_command",
"(",
"\"qtmversion\"",
")",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")"
] | Get the QTM version. | [
"Get",
"the",
"QTM",
"version",
"."
] | python | valid |
AguaClara/aguaclara | aguaclara/research/peristaltic_pump.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/peristaltic_pump.py#L104-L123 | def flow_rate(vol_per_rev, rpm):
"""Return the flow rate from a pump given the volume of fluid pumped per
revolution and the desired pump speed.
:param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:param rpm: Desired pump speed in revolu... | [
"def",
"flow_rate",
"(",
"vol_per_rev",
",",
"rpm",
")",
":",
"return",
"(",
"vol_per_rev",
"*",
"rpm",
")",
".",
"to",
"(",
"u",
".",
"mL",
"/",
"u",
".",
"s",
")"
] | Return the flow rate from a pump given the volume of fluid pumped per
revolution and the desired pump speed.
:param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:param rpm: Desired pump speed in revolutions per minute
:type rpm: float
... | [
"Return",
"the",
"flow",
"rate",
"from",
"a",
"pump",
"given",
"the",
"volume",
"of",
"fluid",
"pumped",
"per",
"revolution",
"and",
"the",
"desired",
"pump",
"speed",
"."
] | python | train |
lowandrew/OLCTools | spadespipeline/sistr.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/sistr.py#L59-L95 | def report(self):
"""Creates sistr reports"""
# Initialise strings to store report data
header = '\t'.join(self.headers) + '\n'
data = ''
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
# Each strain is a fresh row
... | [
"def",
"report",
"(",
"self",
")",
":",
"# Initialise strings to store report data",
"header",
"=",
"'\\t'",
".",
"join",
"(",
"self",
".",
"headers",
")",
"+",
"'\\n'",
"data",
"=",
"''",
"for",
"sample",
"in",
"self",
".",
"metadata",
":",
"if",
"sample"... | Creates sistr reports | [
"Creates",
"sistr",
"reports"
] | python | train |
ArchiveTeam/wpull | wpull/protocol/ftp/client.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L362-L382 | def _open_data_stream(self):
'''Open the data stream connection.
Coroutine.
'''
@asyncio.coroutine
def connection_factory(address: Tuple[int, int]):
self._data_connection = yield from self._acquire_connection(address[0], address[1])
return self._data_conn... | [
"def",
"_open_data_stream",
"(",
"self",
")",
":",
"@",
"asyncio",
".",
"coroutine",
"def",
"connection_factory",
"(",
"address",
":",
"Tuple",
"[",
"int",
",",
"int",
"]",
")",
":",
"self",
".",
"_data_connection",
"=",
"yield",
"from",
"self",
".",
"_a... | Open the data stream connection.
Coroutine. | [
"Open",
"the",
"data",
"stream",
"connection",
"."
] | python | train |
MAVENSDC/cdflib | cdflib/cdfwrite.py | https://github.com/MAVENSDC/cdflib/blob/d237c60e5db67db0f92d96054209c25c4042465c/cdflib/cdfwrite.py#L1193-L1214 | def _use_vxrentry(self, f, VXRoffset, recStart, recEnd, offset):
'''
Adds a VVR pointer to a VXR
'''
# Select the next unused entry in a VXR for a VVR/CVVR
f.seek(VXRoffset+20)
# num entries
numEntries = int.from_bytes(f.read(4), 'big', signed=True)
# used... | [
"def",
"_use_vxrentry",
"(",
"self",
",",
"f",
",",
"VXRoffset",
",",
"recStart",
",",
"recEnd",
",",
"offset",
")",
":",
"# Select the next unused entry in a VXR for a VVR/CVVR",
"f",
".",
"seek",
"(",
"VXRoffset",
"+",
"20",
")",
"# num entries",
"numEntries",
... | Adds a VVR pointer to a VXR | [
"Adds",
"a",
"VVR",
"pointer",
"to",
"a",
"VXR"
] | python | train |
Jaymon/dsnparse | dsnparse.py | https://github.com/Jaymon/dsnparse/blob/2e4e1be8cc9d2dd0f6138c881b06677a6e80b029/dsnparse.py#L197-L210 | def setdefault(self, key, val):
"""
set a default value for key
this is different than dict's setdefault because it will set default either
if the key doesn't exist, or if the value at the key evaluates to False, so
an empty string or a None value will also be updated
:... | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"key",
",",
"None",
")",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"val",
")"
] | set a default value for key
this is different than dict's setdefault because it will set default either
if the key doesn't exist, or if the value at the key evaluates to False, so
an empty string or a None value will also be updated
:param key: string, the attribute to update
:... | [
"set",
"a",
"default",
"value",
"for",
"key"
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/akkar_2014.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/akkar_2014.py#L385-L393 | def _compute_logarithmic_distance_term(self, C, mag, dists):
"""
Compute and return fourth term in equations (2a)
and (2b), page 20.
"""
return (
(C['a4'] + C['a5'] * (mag - self.c1)) *
np.log(np.sqrt(dists.rhypo ** 2 + C['a6'] ** 2))
) | [
"def",
"_compute_logarithmic_distance_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"dists",
")",
":",
"return",
"(",
"(",
"C",
"[",
"'a4'",
"]",
"+",
"C",
"[",
"'a5'",
"]",
"*",
"(",
"mag",
"-",
"self",
".",
"c1",
")",
")",
"*",
"np",
".",
"l... | Compute and return fourth term in equations (2a)
and (2b), page 20. | [
"Compute",
"and",
"return",
"fourth",
"term",
"in",
"equations",
"(",
"2a",
")",
"and",
"(",
"2b",
")",
"page",
"20",
"."
] | python | train |
waqasbhatti/astrobase | astrobase/periodbase/zgls.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/zgls.py#L161-L265 | def generalized_lsp_value_withtau(times, mags, errs, omega):
'''Generalized LSP value for a single omega.
This uses tau to provide an arbitrary time-reference point.
The relations used are::
P(w) = (1/YY) * (YC*YC/CC + YS*YS/SS)
where: YC, YS, CC, and SS are all calculated at T
... | [
"def",
"generalized_lsp_value_withtau",
"(",
"times",
",",
"mags",
",",
"errs",
",",
"omega",
")",
":",
"one_over_errs2",
"=",
"1.0",
"/",
"(",
"errs",
"*",
"errs",
")",
"W",
"=",
"npsum",
"(",
"one_over_errs2",
")",
"wi",
"=",
"one_over_errs2",
"/",
"W"... | Generalized LSP value for a single omega.
This uses tau to provide an arbitrary time-reference point.
The relations used are::
P(w) = (1/YY) * (YC*YC/CC + YS*YS/SS)
where: YC, YS, CC, and SS are all calculated at T
and where: tan 2omegaT = 2*CS/(CC - SS)
and where:
... | [
"Generalized",
"LSP",
"value",
"for",
"a",
"single",
"omega",
"."
] | python | valid |
EUDAT-B2SAFE/B2HANDLE | b2handle/handleclient.py | https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L934-L973 | def search_handle(self, URL=None, prefix=None, **key_value_pairs):
'''
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, th... | [
"def",
"search_handle",
"(",
"self",
",",
"URL",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"*",
"*",
"key_value_pairs",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'search_handle...'",
")",
"list_of_handles",
"=",
"self",
".",
"__searcher",
".",
"search_ha... | Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`.
... | [
"Search",
"for",
"handles",
"containing",
"the",
"specified",
"key",
"with",
"the",
"specified",
"value",
".",
"The",
"search",
"terms",
"are",
"passed",
"on",
"to",
"the",
"reverse",
"lookup",
"servlet",
"as",
"-",
"is",
".",
"The",
"servlet",
"is",
"supp... | python | train |
serge-sans-paille/pythran | pythran/conversion.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/conversion.py#L34-L65 | def size_container_folding(value):
"""
Convert value to ast expression if size is not too big.
Converter for sized container.
"""
if len(value) < MAX_LEN:
if isinstance(value, list):
return ast.List([to_ast(elt) for elt in value], ast.Load())
elif isinstance(value, tuple... | [
"def",
"size_container_folding",
"(",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"<",
"MAX_LEN",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"ast",
".",
"List",
"(",
"[",
"to_ast",
"(",
"elt",
")",
"for",
"elt",
... | Convert value to ast expression if size is not too big.
Converter for sized container. | [
"Convert",
"value",
"to",
"ast",
"expression",
"if",
"size",
"is",
"not",
"too",
"big",
"."
] | python | train |
ewiger/mlab | src/mlab/awmstools.py | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1037-L1051 | def some(predicate, *seqs):
"""
>>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False
"""
try:
if len(seqs) == 1: return ifilter(bool,imap(predicate... | [
"def",
"some",
"(",
"predicate",
",",
"*",
"seqs",
")",
":",
"try",
":",
"if",
"len",
"(",
"seqs",
")",
"==",
"1",
":",
"return",
"ifilter",
"(",
"bool",
",",
"imap",
"(",
"predicate",
",",
"seqs",
"[",
"0",
"]",
")",
")",
".",
"next",
"(",
"... | >>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False | [
">>>",
"some",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"False",
"None",
"]",
")",
"False",
">>>",
"some",
"(",
"lambda",
"x",
":",
"x",
"[",
"None",
"0",
"2",
"3",
"]",
")",
"2",
">>>",
"some",
"(",
"operator",
".",
"eq",
"[",
"0",
"1",
"2"... | python | train |
mwouts/jupytext | jupytext/jupytext.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/jupytext.py#L45-L90 | def reads(self, s, **_):
"""Read a notebook represented as text"""
if self.fmt.get('format_name') == 'pandoc':
return md_to_notebook(s)
lines = s.splitlines()
cells = []
metadata, jupyter_md, header_cell, pos = header_to_metadata_and_cell(lines,
... | [
"def",
"reads",
"(",
"self",
",",
"s",
",",
"*",
"*",
"_",
")",
":",
"if",
"self",
".",
"fmt",
".",
"get",
"(",
"'format_name'",
")",
"==",
"'pandoc'",
":",
"return",
"md_to_notebook",
"(",
"s",
")",
"lines",
"=",
"s",
".",
"splitlines",
"(",
")"... | Read a notebook represented as text | [
"Read",
"a",
"notebook",
"represented",
"as",
"text"
] | python | train |
gem/oq-engine | openquake/commonlib/readinput.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L1328-L1372 | def get_input_files(oqparam, hazard=False):
"""
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: input path names in a specific order
"""
fnames = [] # files entering in the checksum
for key in oqparam.inputs:
fname = oqparam.input... | [
"def",
"get_input_files",
"(",
"oqparam",
",",
"hazard",
"=",
"False",
")",
":",
"fnames",
"=",
"[",
"]",
"# files entering in the checksum",
"for",
"key",
"in",
"oqparam",
".",
"inputs",
":",
"fname",
"=",
"oqparam",
".",
"inputs",
"[",
"key",
"]",
"if",
... | :param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: input path names in a specific order | [
":",
"param",
"oqparam",
":",
"an",
"OqParam",
"instance",
":",
"param",
"hazard",
":",
"if",
"True",
"consider",
"only",
"the",
"hazard",
"files",
":",
"returns",
":",
"input",
"path",
"names",
"in",
"a",
"specific",
"order"
] | python | train |
rhgrant10/Groupy | groupy/api/memberships.py | https://github.com/rhgrant10/Groupy/blob/ffd8cac57586fa1c218e3b4bfaa531142c3be766/groupy/api/memberships.py#L66-L82 | def check(self, results_id):
"""Check for results of a membership request.
:param str results_id: the ID of a membership request
:return: successfully created memberships
:rtype: :class:`list`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raise... | [
"def",
"check",
"(",
"self",
",",
"results_id",
")",
":",
"path",
"=",
"'results/{}'",
".",
"format",
"(",
"results_id",
")",
"url",
"=",
"utils",
".",
"urljoin",
"(",
"self",
".",
"url",
",",
"path",
")",
"response",
"=",
"self",
".",
"session",
"."... | Check for results of a membership request.
:param str results_id: the ID of a membership request
:return: successfully created memberships
:rtype: :class:`list`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raises groupy.exceptions.ResultsExpired: if t... | [
"Check",
"for",
"results",
"of",
"a",
"membership",
"request",
"."
] | python | train |
xzased/lvm2py | lvm2py/vg.py | https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L197-L204 | def is_exported(self):
"""
Returns True if the VG is exported, False otherwise.
"""
self.open()
exp = lvm_vg_is_exported(self.handle)
self.close()
return bool(exp) | [
"def",
"is_exported",
"(",
"self",
")",
":",
"self",
".",
"open",
"(",
")",
"exp",
"=",
"lvm_vg_is_exported",
"(",
"self",
".",
"handle",
")",
"self",
".",
"close",
"(",
")",
"return",
"bool",
"(",
"exp",
")"
] | Returns True if the VG is exported, False otherwise. | [
"Returns",
"True",
"if",
"the",
"VG",
"is",
"exported",
"False",
"otherwise",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/fiesta.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/fiesta.py#L355-L364 | def dump_BSE_data_in_GW_run(self, BSE_dump=True):
"""
:param BSE_dump: boolean
:return: set the "do_bse" variable to one in cell.in
"""
if BSE_dump:
self.BSE_TDDFT_options.update(do_bse=1, do_tddft=0)
else:
self.BSE_TDDFT_options.update(do_bse=0, ... | [
"def",
"dump_BSE_data_in_GW_run",
"(",
"self",
",",
"BSE_dump",
"=",
"True",
")",
":",
"if",
"BSE_dump",
":",
"self",
".",
"BSE_TDDFT_options",
".",
"update",
"(",
"do_bse",
"=",
"1",
",",
"do_tddft",
"=",
"0",
")",
"else",
":",
"self",
".",
"BSE_TDDFT_o... | :param BSE_dump: boolean
:return: set the "do_bse" variable to one in cell.in | [
":",
"param",
"BSE_dump",
":",
"boolean",
":",
"return",
":",
"set",
"the",
"do_bse",
"variable",
"to",
"one",
"in",
"cell",
".",
"in"
] | python | train |
adrn/gala | gala/coordinates/quaternion.py | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/quaternion.py#L112-L137 | def random(cls):
"""
Randomly sample a Quaternion from a distribution uniform in
3D rotation angles.
https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf
Returns
-------
q : :class:`gala.coordinates.Quaternion`
... | [
"def",
"random",
"(",
"cls",
")",
":",
"s",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
")",
"s1",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"s",
")",
"s2",
"=",
"np",
".",
"sqrt",
"(",
"s",
")",
"t1",
"=",
"np",
".",
"random",
".",
"unif... | Randomly sample a Quaternion from a distribution uniform in
3D rotation angles.
https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf
Returns
-------
q : :class:`gala.coordinates.Quaternion`
A randomly sampled ``Quaternion`` ins... | [
"Randomly",
"sample",
"a",
"Quaternion",
"from",
"a",
"distribution",
"uniform",
"in",
"3D",
"rotation",
"angles",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/scaleway.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L91-L124 | def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in... | [
"def",
"list_nodes",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called with -f or --function.'",
")",
"items",
"=",
"query",
"(",
"method",
"=",
"'servers'",
")",
... | Return a list of the BareMetal servers that are on the provider. | [
"Return",
"a",
"list",
"of",
"the",
"BareMetal",
"servers",
"that",
"are",
"on",
"the",
"provider",
"."
] | python | train |
gunthercox/ChatterBot | chatterbot/utils.py | https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/utils.py#L6-L17 | def import_module(dotted_path):
"""
Imports the specified module based on the
dot notated import path for the module.
"""
import importlib
module_parts = dotted_path.split('.')
module_path = '.'.join(module_parts[:-1])
module = importlib.import_module(module_path)
return getattr(mo... | [
"def",
"import_module",
"(",
"dotted_path",
")",
":",
"import",
"importlib",
"module_parts",
"=",
"dotted_path",
".",
"split",
"(",
"'.'",
")",
"module_path",
"=",
"'.'",
".",
"join",
"(",
"module_parts",
"[",
":",
"-",
"1",
"]",
")",
"module",
"=",
"imp... | Imports the specified module based on the
dot notated import path for the module. | [
"Imports",
"the",
"specified",
"module",
"based",
"on",
"the",
"dot",
"notated",
"import",
"path",
"for",
"the",
"module",
"."
] | python | train |
ui/django-thumbnails | thumbnails/post_processors.py | https://github.com/ui/django-thumbnails/blob/5cef55e7f167060458709ed760dd43981124796a/thumbnails/post_processors.py#L31-L79 | def optimize(thumbnail_file, jpg_command=None, png_command=None,
gif_command=None):
"""
A post processing function to optimize file size. Accepts commands
to optimize JPG, PNG and GIF images as arguments. Example:
THUMBNAILS = {
# Other options...
'POST_PROCESSORS': [
... | [
"def",
"optimize",
"(",
"thumbnail_file",
",",
"jpg_command",
"=",
"None",
",",
"png_command",
"=",
"None",
",",
"gif_command",
"=",
"None",
")",
":",
"temp_dir",
"=",
"get_or_create_temp_dir",
"(",
")",
"thumbnail_filename",
"=",
"os",
".",
"path",
".",
"jo... | A post processing function to optimize file size. Accepts commands
to optimize JPG, PNG and GIF images as arguments. Example:
THUMBNAILS = {
# Other options...
'POST_PROCESSORS': [
{
'processor': 'thumbnails.post_processors.optimize',
'png_command': '... | [
"A",
"post",
"processing",
"function",
"to",
"optimize",
"file",
"size",
".",
"Accepts",
"commands",
"to",
"optimize",
"JPG",
"PNG",
"and",
"GIF",
"images",
"as",
"arguments",
".",
"Example",
":"
] | python | test |
Azure/azure-sdk-for-python | azure-servicebus/azure/servicebus/aio/async_receive_handler.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/aio/async_receive_handler.py#L513-L537 | async def get_session_state(self):
"""Get the session state.
Returns None if no state has been set.
:rtype: str
Example:
.. literalinclude:: ../examples/async_examples/test_examples_async.py
:start-after: [START set_session_state]
:end-befor... | [
"async",
"def",
"get_session_state",
"(",
"self",
")",
":",
"await",
"self",
".",
"_can_run",
"(",
")",
"response",
"=",
"await",
"self",
".",
"_mgmt_request_response",
"(",
"REQUEST_RESPONSE_GET_SESSION_STATE_OPERATION",
",",
"{",
"'session-id'",
":",
"self",
"."... | Get the session state.
Returns None if no state has been set.
:rtype: str
Example:
.. literalinclude:: ../examples/async_examples/test_examples_async.py
:start-after: [START set_session_state]
:end-before: [END set_session_state]
:la... | [
"Get",
"the",
"session",
"state",
"."
] | python | test |
sparklingpandas/sparklingpandas | sparklingpandas/groupby.py | https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/groupby.py#L129-L134 | def ngroups(self):
"""Number of groups."""
if self._can_use_new_school():
return self._grouped_spark_sql.count()
self._prep_pandas_groupby()
return self._mergedRDD.count() | [
"def",
"ngroups",
"(",
"self",
")",
":",
"if",
"self",
".",
"_can_use_new_school",
"(",
")",
":",
"return",
"self",
".",
"_grouped_spark_sql",
".",
"count",
"(",
")",
"self",
".",
"_prep_pandas_groupby",
"(",
")",
"return",
"self",
".",
"_mergedRDD",
".",
... | Number of groups. | [
"Number",
"of",
"groups",
"."
] | python | train |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L220-L227 | def set_itunes_closed_captioned(self):
"""Parses isClosedCaptioned from itunes tags and sets value"""
try:
self.itunes_closed_captioned = self.soup.find(
'itunes:isclosedcaptioned').string
self.itunes_closed_captioned = self.itunes_closed_captioned.lower()
... | [
"def",
"set_itunes_closed_captioned",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_closed_captioned",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:isclosedcaptioned'",
")",
".",
"string",
"self",
".",
"itunes_closed_captioned",
"=",
"self",
".... | Parses isClosedCaptioned from itunes tags and sets value | [
"Parses",
"isClosedCaptioned",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | python | train |
pirate/mesh-networking | examples/mesh-botnet/shell_tools.py | https://github.com/pirate/mesh-networking/blob/e8da35d2ecded6930cf2180605bf28479ee555c7/examples/mesh-botnet/shell_tools.py#L41-L86 | def run_shell(cmd, timeout=60, verbose=False):
"""run a shell command and return the output, verbose enables live command output via yield"""
retcode = None
try:
p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, executable='/bin/bash')
continue_running = True
except Exception as e:
... | [
"def",
"run_shell",
"(",
"cmd",
",",
"timeout",
"=",
"60",
",",
"verbose",
"=",
"False",
")",
":",
"retcode",
"=",
"None",
"try",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"STDO... | run a shell command and return the output, verbose enables live command output via yield | [
"run",
"a",
"shell",
"command",
"and",
"return",
"the",
"output",
"verbose",
"enables",
"live",
"command",
"output",
"via",
"yield"
] | python | train |
rbarrois/aionotify | aionotify/aioutils.py | https://github.com/rbarrois/aionotify/blob/6cfa35b26a2660f77f29a92d3efb7d1dde685b43/aionotify/aioutils.py#L60-L63 | def pause_reading(self):
"""Public API: pause reading the transport."""
self._loop.remove_reader(self._fileno)
self._active = False | [
"def",
"pause_reading",
"(",
"self",
")",
":",
"self",
".",
"_loop",
".",
"remove_reader",
"(",
"self",
".",
"_fileno",
")",
"self",
".",
"_active",
"=",
"False"
] | Public API: pause reading the transport. | [
"Public",
"API",
":",
"pause",
"reading",
"the",
"transport",
"."
] | python | test |
Iotic-Labs/py-IoticAgent | src/IoticAgent/IOT/ThingMeta.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/ThingMeta.py#L48-L63 | def get_location(self):
"""Gets the current geo location of your Thing
Returns tuple of `(lat, lon)` in `float` or `(None, None)` if location is not set for this Thing
"""
lat = None
lon = None
# note: always picks from first triple
for _, _, o in self._graph.tri... | [
"def",
"get_location",
"(",
"self",
")",
":",
"lat",
"=",
"None",
"lon",
"=",
"None",
"# note: always picks from first triple",
"for",
"_",
",",
"_",
",",
"o",
"in",
"self",
".",
"_graph",
".",
"triples",
"(",
"(",
"None",
",",
"GEO_NS",
".",
"lat",
",... | Gets the current geo location of your Thing
Returns tuple of `(lat, lon)` in `float` or `(None, None)` if location is not set for this Thing | [
"Gets",
"the",
"current",
"geo",
"location",
"of",
"your",
"Thing"
] | python | train |
finklabs/metrics | metrics/position.py | https://github.com/finklabs/metrics/blob/fd9974af498831664b9ae8e8f3834e1ec2e8a699/metrics/position.py#L112-L132 | def process_token(self, tok):
"""count lines and track position of classes and functions"""
if tok[0] == Token.Text:
count = tok[1].count('\n')
if count:
self._line += count # adjust linecount
if self._detector.process(tok):
pass # works bee... | [
"def",
"process_token",
"(",
"self",
",",
"tok",
")",
":",
"if",
"tok",
"[",
"0",
"]",
"==",
"Token",
".",
"Text",
":",
"count",
"=",
"tok",
"[",
"1",
"]",
".",
"count",
"(",
"'\\n'",
")",
"if",
"count",
":",
"self",
".",
"_line",
"+=",
"count"... | count lines and track position of classes and functions | [
"count",
"lines",
"and",
"track",
"position",
"of",
"classes",
"and",
"functions"
] | python | train |
ecordell/pymacaroons | pymacaroons/serializers/binary_serializer.py | https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/binary_serializer.py#L301-L311 | def _encode_uvarint(data, n):
''' Encodes integer into variable-length format into data.'''
if n < 0:
raise ValueError('only support positive integer')
while True:
this_byte = n & 0x7f
n >>= 7
if n == 0:
data.append(this_byte)
break
data.append... | [
"def",
"_encode_uvarint",
"(",
"data",
",",
"n",
")",
":",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'only support positive integer'",
")",
"while",
"True",
":",
"this_byte",
"=",
"n",
"&",
"0x7f",
"n",
">>=",
"7",
"if",
"n",
"==",
"0",
... | Encodes integer into variable-length format into data. | [
"Encodes",
"integer",
"into",
"variable",
"-",
"length",
"format",
"into",
"data",
"."
] | python | train |
angr/angr | angr/analyses/cfg/cfg_base.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_base.py#L507-L527 | def _should_skip_region(self, region_start):
"""
Some regions usually do not contain any executable code, but are still marked as executable. We should skip
those regions by default.
:param int region_start: Address of the beginning of the region.
:return: True/F... | [
"def",
"_should_skip_region",
"(",
"self",
",",
"region_start",
")",
":",
"obj",
"=",
"self",
".",
"project",
".",
"loader",
".",
"find_object_containing",
"(",
"region_start",
",",
"membership_check",
"=",
"False",
")",
"if",
"obj",
"is",
"None",
":",
"retu... | Some regions usually do not contain any executable code, but are still marked as executable. We should skip
those regions by default.
:param int region_start: Address of the beginning of the region.
:return: True/False
:rtype: bool | [
"Some",
"regions",
"usually",
"do",
"not",
"contain",
"any",
"executable",
"code",
"but",
"are",
"still",
"marked",
"as",
"executable",
".",
"We",
"should",
"skip",
"those",
"regions",
"by",
"default",
"."
] | python | train |
mitsei/dlkit | dlkit/services/authorization.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/authorization.py#L430-L438 | def use_comparative_vault_view(self):
"""Pass through to provider AuthorizationVaultSession.use_comparative_vault_view"""
self._vault_view = COMPARATIVE
# self._get_provider_session('authorization_vault_session') # To make sure the session is tracked
for session in self._get_provider_ses... | [
"def",
"use_comparative_vault_view",
"(",
"self",
")",
":",
"self",
".",
"_vault_view",
"=",
"COMPARATIVE",
"# self._get_provider_session('authorization_vault_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
"... | Pass through to provider AuthorizationVaultSession.use_comparative_vault_view | [
"Pass",
"through",
"to",
"provider",
"AuthorizationVaultSession",
".",
"use_comparative_vault_view"
] | python | train |
batiste/django-page-cms | pages/models.py | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/models.py#L465-L478 | def slug(self, language=None, fallback=True):
"""
Return the slug of the page depending on the given language.
:param language: wanted language, if not defined default is used.
:param fallback: if ``True``, the slug will also be searched in other \
languages.
"""
... | [
"def",
"slug",
"(",
"self",
",",
"language",
"=",
"None",
",",
"fallback",
"=",
"True",
")",
":",
"slug",
"=",
"self",
".",
"get_content",
"(",
"language",
",",
"'slug'",
",",
"language_fallback",
"=",
"fallback",
")",
"if",
"slug",
"==",
"''",
":",
... | Return the slug of the page depending on the given language.
:param language: wanted language, if not defined default is used.
:param fallback: if ``True``, the slug will also be searched in other \
languages. | [
"Return",
"the",
"slug",
"of",
"the",
"page",
"depending",
"on",
"the",
"given",
"language",
"."
] | python | train |
XuShaohua/bcloud | bcloud/App.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/App.py#L492-L496 | def update_clipboard(self, text):
'''将文本复制到系统剪贴板里面'''
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(text, -1)
self.toast(_('{0} copied to clipboard'.format(text))) | [
"def",
"update_clipboard",
"(",
"self",
",",
"text",
")",
":",
"clipboard",
"=",
"Gtk",
".",
"Clipboard",
".",
"get",
"(",
"Gdk",
".",
"SELECTION_CLIPBOARD",
")",
"clipboard",
".",
"set_text",
"(",
"text",
",",
"-",
"1",
")",
"self",
".",
"toast",
"(",... | 将文本复制到系统剪贴板里面 | [
"将文本复制到系统剪贴板里面"
] | python | train |
saltstack/salt | salt/modules/apf.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apf.py#L57-L66 | def _status_apf():
'''
Return True if apf is running otherwise return False
'''
status = 0
table = iptc.Table(iptc.Table.FILTER)
for chain in table.chains:
if 'sanity' in chain.name.lower():
status = 1
return True if status else False | [
"def",
"_status_apf",
"(",
")",
":",
"status",
"=",
"0",
"table",
"=",
"iptc",
".",
"Table",
"(",
"iptc",
".",
"Table",
".",
"FILTER",
")",
"for",
"chain",
"in",
"table",
".",
"chains",
":",
"if",
"'sanity'",
"in",
"chain",
".",
"name",
".",
"lower... | Return True if apf is running otherwise return False | [
"Return",
"True",
"if",
"apf",
"is",
"running",
"otherwise",
"return",
"False"
] | python | train |
ella/ella | ella/core/templatetags/core.py | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L332-L345 | def do_render(parser, token):
"""
Renders a rich-text field using defined markup.
Example::
{% render some_var %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise template.TemplateSyntaxError()
return RenderNode(bits[1]) | [
"def",
"do_render",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
")",
"return",
"RenderNode",
"(",
"bi... | Renders a rich-text field using defined markup.
Example::
{% render some_var %} | [
"Renders",
"a",
"rich",
"-",
"text",
"field",
"using",
"defined",
"markup",
"."
] | python | train |
BetterWorks/django-anonymizer | anonymizer/replacers.py | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L166-L170 | def zip_code(anon, obj, field, val):
"""
Returns a randomly generated US zip code (not necessarily valid, but will look like one).
"""
return anon.faker.zipcode(field=field) | [
"def",
"zip_code",
"(",
"anon",
",",
"obj",
",",
"field",
",",
"val",
")",
":",
"return",
"anon",
".",
"faker",
".",
"zipcode",
"(",
"field",
"=",
"field",
")"
] | Returns a randomly generated US zip code (not necessarily valid, but will look like one). | [
"Returns",
"a",
"randomly",
"generated",
"US",
"zip",
"code",
"(",
"not",
"necessarily",
"valid",
"but",
"will",
"look",
"like",
"one",
")",
"."
] | python | train |
sony/nnabla | python/src/nnabla/parameter.py | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parameter.py#L179-L245 | def get_parameter_or_create(name, shape=None, initializer=None, need_grad=True,
as_need_grad=None):
"""
Returns an existing parameter variable with the provided name.
If a variable with the provided name does not exist,
a new variable with the provided name is returned.
... | [
"def",
"get_parameter_or_create",
"(",
"name",
",",
"shape",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"need_grad",
"=",
"True",
",",
"as_need_grad",
"=",
"None",
")",
":",
"names",
"=",
"name",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",... | Returns an existing parameter variable with the provided name.
If a variable with the provided name does not exist,
a new variable with the provided name is returned.
Args:
name(str): The name under the current scope. If it already exists, the name is queried from the
parameter manager.
... | [
"Returns",
"an",
"existing",
"parameter",
"variable",
"with",
"the",
"provided",
"name",
".",
"If",
"a",
"variable",
"with",
"the",
"provided",
"name",
"does",
"not",
"exist",
"a",
"new",
"variable",
"with",
"the",
"provided",
"name",
"is",
"returned",
"."
] | python | train |
wkentaro/fcn | fcn/trainer.py | https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/trainer.py#L91-L149 | def validate(self, n_viz=9):
"""Validate current model using validation dataset.
Parameters
----------
n_viz: int
Number fo visualization.
Returns
-------
log: dict
Log values.
"""
iter_valid = copy.copy(self.iter_valid)
... | [
"def",
"validate",
"(",
"self",
",",
"n_viz",
"=",
"9",
")",
":",
"iter_valid",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"iter_valid",
")",
"losses",
",",
"lbl_trues",
",",
"lbl_preds",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"vizs",
"=",... | Validate current model using validation dataset.
Parameters
----------
n_viz: int
Number fo visualization.
Returns
-------
log: dict
Log values. | [
"Validate",
"current",
"model",
"using",
"validation",
"dataset",
"."
] | python | train |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L1274-L1294 | def list_benchmarks(self,
index = None,
doc_type = None,
params = {},
cb = None,
**kwargs
):
"""
View the progress of long-running benchmarks.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/sea... | [
"def",
"list_benchmarks",
"(",
"self",
",",
"index",
"=",
"None",
",",
"doc_type",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"cb",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"mk_url",
"(",
"*",
"[",
"index",
... | View the progress of long-running benchmarks.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
string to perform the operation on all indices
:arg doc_type: The name ... | [
"View",
"the",
"progress",
"of",
"long",
"-",
"running",
"benchmarks",
".",
"<http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"master",
"/",
"search",
"-",
"benchmark",
".",... | python | train |
NiklasRosenstein/myo-python | myo/_device_listener.py | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/_device_listener.py#L218-L242 | def wait_for_single_device(self, timeout=None, interval=0.5):
"""
Waits until a Myo is was paired **and** connected with the Hub and returns
it. If the *timeout* is exceeded, returns None. This function will not
return a Myo that is only paired but not connected.
# Parameters
timeout: The maxim... | [
"def",
"wait_for_single_device",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"interval",
"=",
"0.5",
")",
":",
"timer",
"=",
"TimeoutManager",
"(",
"timeout",
")",
"with",
"self",
".",
"_cond",
":",
"# As long as there are no Myo's connected, wait until we",
"#... | Waits until a Myo is was paired **and** connected with the Hub and returns
it. If the *timeout* is exceeded, returns None. This function will not
return a Myo that is only paired but not connected.
# Parameters
timeout: The maximum time to wait for a device.
interval: The interval at which the func... | [
"Waits",
"until",
"a",
"Myo",
"is",
"was",
"paired",
"**",
"and",
"**",
"connected",
"with",
"the",
"Hub",
"and",
"returns",
"it",
".",
"If",
"the",
"*",
"timeout",
"*",
"is",
"exceeded",
"returns",
"None",
".",
"This",
"function",
"will",
"not",
"retu... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/ultratb.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/ultratb.py#L391-L400 | def color_toggle(self):
"""Toggle between the currently active color scheme and NoColor."""
if self.color_scheme_table.active_scheme_name == 'NoColor':
self.color_scheme_table.set_active_scheme(self.old_scheme)
self.Colors = self.color_scheme_table.active_colors
else:
... | [
"def",
"color_toggle",
"(",
"self",
")",
":",
"if",
"self",
".",
"color_scheme_table",
".",
"active_scheme_name",
"==",
"'NoColor'",
":",
"self",
".",
"color_scheme_table",
".",
"set_active_scheme",
"(",
"self",
".",
"old_scheme",
")",
"self",
".",
"Colors",
"... | Toggle between the currently active color scheme and NoColor. | [
"Toggle",
"between",
"the",
"currently",
"active",
"color",
"scheme",
"and",
"NoColor",
"."
] | python | test |
GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L579-L590 | def acpi_shutdown(self, acpi_shutdown):
"""
Sets either this QEMU VM can be ACPI shutdown.
:param acpi_shutdown: boolean
"""
if acpi_shutdown:
log.info('QEMU VM "{name}" [{id}] has enabled ACPI shutdown'.format(name=self._name, id=self._id))
else:
... | [
"def",
"acpi_shutdown",
"(",
"self",
",",
"acpi_shutdown",
")",
":",
"if",
"acpi_shutdown",
":",
"log",
".",
"info",
"(",
"'QEMU VM \"{name}\" [{id}] has enabled ACPI shutdown'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"id",
"=",
"self",
".... | Sets either this QEMU VM can be ACPI shutdown.
:param acpi_shutdown: boolean | [
"Sets",
"either",
"this",
"QEMU",
"VM",
"can",
"be",
"ACPI",
"shutdown",
"."
] | python | train |
praekelt/panya-music | music/importer.py | https://github.com/praekelt/panya-music/blob/9300b1866bc33178e721b6de4771ba866bfc4b11/music/importer.py#L38-L47 | def lookup_track(self, track):
"""
Looks up Django Track object for provided raw importing track object.
"""
tracks = Track.objects.filter(title__iexact=track.title)
for track_obj in tracks:
for contributor in track_obj.get_primary_contributors(permitted=False):
... | [
"def",
"lookup_track",
"(",
"self",
",",
"track",
")",
":",
"tracks",
"=",
"Track",
".",
"objects",
".",
"filter",
"(",
"title__iexact",
"=",
"track",
".",
"title",
")",
"for",
"track_obj",
"in",
"tracks",
":",
"for",
"contributor",
"in",
"track_obj",
".... | Looks up Django Track object for provided raw importing track object. | [
"Looks",
"up",
"Django",
"Track",
"object",
"for",
"provided",
"raw",
"importing",
"track",
"object",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/LensModel/Profiles/spp.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/Profiles/spp.py#L123-L132 | def mass_3d(self, r, rho0, gamma):
"""
mass enclosed a 3d sphere or radius r
:param r:
:param a:
:param s:
:return:
"""
mass_3d = 4 * np.pi * rho0 /(-gamma + 3) * r ** (-gamma + 3)
return mass_3d | [
"def",
"mass_3d",
"(",
"self",
",",
"r",
",",
"rho0",
",",
"gamma",
")",
":",
"mass_3d",
"=",
"4",
"*",
"np",
".",
"pi",
"*",
"rho0",
"/",
"(",
"-",
"gamma",
"+",
"3",
")",
"*",
"r",
"**",
"(",
"-",
"gamma",
"+",
"3",
")",
"return",
"mass_3... | mass enclosed a 3d sphere or radius r
:param r:
:param a:
:param s:
:return: | [
"mass",
"enclosed",
"a",
"3d",
"sphere",
"or",
"radius",
"r",
":",
"param",
"r",
":",
":",
"param",
"a",
":",
":",
"param",
"s",
":",
":",
"return",
":"
] | python | train |
cloudant/python-cloudant | src/cloudant/design_document.py | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L425-L441 | def delete_view(self, view_name):
"""
Removes an existing MapReduce view definition from the locally cached
DesignDocument View dictionary. To delete a JSON query index
use :func:`~cloudant.database.CloudantDatabase.delete_query_index`
instead. A CloudantException is raised if ... | [
"def",
"delete_view",
"(",
"self",
",",
"view_name",
")",
":",
"view",
"=",
"self",
".",
"get_view",
"(",
"view_name",
")",
"if",
"view",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"view",
",",
"QueryIndexView",
")",
":",
"raise",
"CloudantDes... | Removes an existing MapReduce view definition from the locally cached
DesignDocument View dictionary. To delete a JSON query index
use :func:`~cloudant.database.CloudantDatabase.delete_query_index`
instead. A CloudantException is raised if an attempt to delete a
QueryIndexView (JSON qu... | [
"Removes",
"an",
"existing",
"MapReduce",
"view",
"definition",
"from",
"the",
"locally",
"cached",
"DesignDocument",
"View",
"dictionary",
".",
"To",
"delete",
"a",
"JSON",
"query",
"index",
"use",
":",
"func",
":",
"~cloudant",
".",
"database",
".",
"Cloudan... | python | train |
materialsproject/pymatgen | pymatgen/analysis/reaction_calculator.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/reaction_calculator.py#L160-L165 | def reactants(self):
"""
List of reactants
"""
return [self._all_comp[i] for i in range(len(self._all_comp))
if self._coeffs[i] < 0] | [
"def",
"reactants",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_all_comp",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_all_comp",
")",
")",
"if",
"self",
".",
"_coeffs",
"[",
"i",
"]",
"<",
"0",
"]"
] | List of reactants | [
"List",
"of",
"reactants"
] | python | train |
ets-labs/python-domain-models | domain_models/views.py | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L54-L73 | def check_include_exclude(attributes):
"""Check __include__ and __exclude__ attributes.
:type attributes: dict
"""
include = attributes.get('__include__', tuple())
exclude = attributes.get('__exclude__', tuple())
if not isinstance(include, tuple):
raise Type... | [
"def",
"check_include_exclude",
"(",
"attributes",
")",
":",
"include",
"=",
"attributes",
".",
"get",
"(",
"'__include__'",
",",
"tuple",
"(",
")",
")",
"exclude",
"=",
"attributes",
".",
"get",
"(",
"'__exclude__'",
",",
"tuple",
"(",
")",
")",
"if",
"... | Check __include__ and __exclude__ attributes.
:type attributes: dict | [
"Check",
"__include__",
"and",
"__exclude__",
"attributes",
"."
] | python | train |
guma44/GEOparse | GEOparse/GEOTypes.py | https://github.com/guma44/GEOparse/blob/7ee8d5b8678d780382a6bf884afa69d2033f5ca0/GEOparse/GEOTypes.py#L637-L649 | def _get_object_as_soft(self):
"""Return object as SOFT formatted string."""
soft = []
if self.database is not None:
soft.append(self.database._get_object_as_soft())
soft += ["^%s = %s" % (self.geotype, self.name),
self._get_metadata_as_string()]
for ... | [
"def",
"_get_object_as_soft",
"(",
"self",
")",
":",
"soft",
"=",
"[",
"]",
"if",
"self",
".",
"database",
"is",
"not",
"None",
":",
"soft",
".",
"append",
"(",
"self",
".",
"database",
".",
"_get_object_as_soft",
"(",
")",
")",
"soft",
"+=",
"[",
"\... | Return object as SOFT formatted string. | [
"Return",
"object",
"as",
"SOFT",
"formatted",
"string",
"."
] | python | train |
Clinical-Genomics/scout | scout/server/blueprints/variants/views.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/variants/views.py#L455-L459 | def acmg():
"""Calculate an ACMG classification from submitted criteria."""
criteria = request.args.getlist('criterion')
classification = get_acmg(criteria)
return jsonify(dict(classification=classification)) | [
"def",
"acmg",
"(",
")",
":",
"criteria",
"=",
"request",
".",
"args",
".",
"getlist",
"(",
"'criterion'",
")",
"classification",
"=",
"get_acmg",
"(",
"criteria",
")",
"return",
"jsonify",
"(",
"dict",
"(",
"classification",
"=",
"classification",
")",
")... | Calculate an ACMG classification from submitted criteria. | [
"Calculate",
"an",
"ACMG",
"classification",
"from",
"submitted",
"criteria",
"."
] | python | test |
WoLpH/python-statsd | statsd/client.py | https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L96-L102 | def get_raw(self, name=None):
'''Shortcut for getting a :class:`~statsd.raw.Raw` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
'''
return self.get_client(name=name, class_=statsd.Raw) | [
"def",
"get_raw",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_client",
"(",
"name",
"=",
"name",
",",
"class_",
"=",
"statsd",
".",
"Raw",
")"
] | Shortcut for getting a :class:`~statsd.raw.Raw` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str | [
"Shortcut",
"for",
"getting",
"a",
":",
"class",
":",
"~statsd",
".",
"raw",
".",
"Raw",
"instance"
] | python | train |
robotools/fontParts | Lib/fontParts/base/contour.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/contour.py#L534-L551 | def appendSegment(self, type=None, points=None, smooth=False, segment=None):
"""
Append a segment to the contour.
"""
if segment is not None:
if type is not None:
type = segment.type
if points is None:
points = [(point.x, point.y) f... | [
"def",
"appendSegment",
"(",
"self",
",",
"type",
"=",
"None",
",",
"points",
"=",
"None",
",",
"smooth",
"=",
"False",
",",
"segment",
"=",
"None",
")",
":",
"if",
"segment",
"is",
"not",
"None",
":",
"if",
"type",
"is",
"not",
"None",
":",
"type"... | Append a segment to the contour. | [
"Append",
"a",
"segment",
"to",
"the",
"contour",
"."
] | python | train |
mathandy/svgpathtools | svgpathtools/bezier.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/bezier.py#L236-L239 | def interval_intersection_width(a, b, c, d):
"""returns the width of the intersection of intervals [a,b] and [c,d]
(thinking of these as intervals on the real number line)"""
return max(0, min(b, d) - max(a, c)) | [
"def",
"interval_intersection_width",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
")",
":",
"return",
"max",
"(",
"0",
",",
"min",
"(",
"b",
",",
"d",
")",
"-",
"max",
"(",
"a",
",",
"c",
")",
")"
] | returns the width of the intersection of intervals [a,b] and [c,d]
(thinking of these as intervals on the real number line) | [
"returns",
"the",
"width",
"of",
"the",
"intersection",
"of",
"intervals",
"[",
"a",
"b",
"]",
"and",
"[",
"c",
"d",
"]",
"(",
"thinking",
"of",
"these",
"as",
"intervals",
"on",
"the",
"real",
"number",
"line",
")"
] | python | train |
airspeed-velocity/asv | asv/benchmark.py | https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L303-L342 | def get_source_code(items):
"""
Extract source code of given items, and concatenate and dedent it.
"""
sources = []
prev_class_name = None
for func in items:
try:
lines, lineno = inspect.getsourcelines(func)
except TypeError:
continue
if not line... | [
"def",
"get_source_code",
"(",
"items",
")",
":",
"sources",
"=",
"[",
"]",
"prev_class_name",
"=",
"None",
"for",
"func",
"in",
"items",
":",
"try",
":",
"lines",
",",
"lineno",
"=",
"inspect",
".",
"getsourcelines",
"(",
"func",
")",
"except",
"TypeErr... | Extract source code of given items, and concatenate and dedent it. | [
"Extract",
"source",
"code",
"of",
"given",
"items",
"and",
"concatenate",
"and",
"dedent",
"it",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/image.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/image.py#L121-L142 | def monochrome(I, color, vmin=None, vmax=None):
"""Turns a intensity array to a monochrome 'image' by replacing each intensity by a scaled 'color'
Values in I between vmin and vmax get scaled between 0 and 1, and values outside this range are clipped to this.
Example
>>> I = np.arange(16.).reshape(4,... | [
"def",
"monochrome",
"(",
"I",
",",
"color",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"if",
"vmin",
"is",
"None",
":",
"vmin",
"=",
"np",
".",
"nanmin",
"(",
"I",
")",
"if",
"vmax",
"is",
"None",
":",
"vmax",
"=",
"np",
"... | Turns a intensity array to a monochrome 'image' by replacing each intensity by a scaled 'color'
Values in I between vmin and vmax get scaled between 0 and 1, and values outside this range are clipped to this.
Example
>>> I = np.arange(16.).reshape(4,4)
>>> color = (0, 0, 1) # red
>>> rgb = vx.ima... | [
"Turns",
"a",
"intensity",
"array",
"to",
"a",
"monochrome",
"image",
"by",
"replacing",
"each",
"intensity",
"by",
"a",
"scaled",
"color"
] | python | test |
AmesCornish/buttersink | buttersink/Store.py | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L84-L88 | def listContents(self):
""" Return list of volumes or diffs in this Store's selected directory. """
vols = list(self.listVolumes())
vols.sort(key=lambda v: self.getSendPath(v))
return [vol.display(self, detail="line") for vol in vols] | [
"def",
"listContents",
"(",
"self",
")",
":",
"vols",
"=",
"list",
"(",
"self",
".",
"listVolumes",
"(",
")",
")",
"vols",
".",
"sort",
"(",
"key",
"=",
"lambda",
"v",
":",
"self",
".",
"getSendPath",
"(",
"v",
")",
")",
"return",
"[",
"vol",
"."... | Return list of volumes or diffs in this Store's selected directory. | [
"Return",
"list",
"of",
"volumes",
"or",
"diffs",
"in",
"this",
"Store",
"s",
"selected",
"directory",
"."
] | python | train |
otto-torino/django-baton | baton/views.py | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L19-L36 | def get(self, request):
""" Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console
"""
self.app_list = site.get_app_list(request)
self.apps_dict = self.c... | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"app_list",
"=",
"site",
".",
"get_app_list",
"(",
"request",
")",
"self",
".",
"apps_dict",
"=",
"self",
".",
"create_app_list_dict",
"(",
")",
"# no menu provided",
"items",
"=",
"get_conf... | Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console | [
"Returns",
"a",
"json",
"representing",
"the",
"menu",
"voices",
"in",
"a",
"format",
"eaten",
"by",
"the",
"js",
"menu",
".",
"Raised",
"ImproperlyConfigured",
"exceptions",
"can",
"be",
"viewed",
"in",
"the",
"browser",
"console"
] | python | train |
ggaughan/pipe2py | pipe2py/lib/pprint2.py | https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/lib/pprint2.py#L55-L68 | def str_args(args):
"""formats a list of function arguments prettily not as code
(kwargs are tuples (argname, argvalue)
"""
res = []
for x in args:
if isinstance(x, tuple) and len(x) == 2:
key, value = x
if value and str_arg(value):
res += ["%s=%s" % ... | [
"def",
"str_args",
"(",
"args",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"args",
":",
"if",
"isinstance",
"(",
"x",
",",
"tuple",
")",
"and",
"len",
"(",
"x",
")",
"==",
"2",
":",
"key",
",",
"value",
"=",
"x",
"if",
"value",
"and",
... | formats a list of function arguments prettily not as code
(kwargs are tuples (argname, argvalue) | [
"formats",
"a",
"list",
"of",
"function",
"arguments",
"prettily",
"not",
"as",
"code"
] | python | train |
tanghaibao/jcvi | jcvi/apps/phylo.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L318-L337 | def build_ml_phyml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with PhyML
"""
phy_file = op.join(work_dir, "work", "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
phyml_cl = PhymlCommandline(cmd=PHYML_BIN("phyml"), input=... | [
"def",
"build_ml_phyml",
"(",
"alignment",
",",
"outfile",
",",
"work_dir",
"=",
"\".\"",
",",
"*",
"*",
"kwargs",
")",
":",
"phy_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"work\"",
",",
"\"aln.phy\"",
")",
"AlignIO",
".",
"write",
"(",
"a... | build maximum likelihood tree of DNA seqs with PhyML | [
"build",
"maximum",
"likelihood",
"tree",
"of",
"DNA",
"seqs",
"with",
"PhyML"
] | python | train |
PmagPy/PmagPy | pmagpy/convert_2_magic.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/convert_2_magic.py#L3045-L3244 | def iodp_dscr_lore(dscr_file,dscr_ex_file="", dir_path=".", input_dir_path="",volume=7,noave=False,\
meas_file="measurements.txt", offline_meas_file="",spec_file="specimens.txt"):
"""
Convert IODP discrete measurement files in MagIC file(s). This program
assumes that you have created the speci... | [
"def",
"iodp_dscr_lore",
"(",
"dscr_file",
",",
"dscr_ex_file",
"=",
"\"\"",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"volume",
"=",
"7",
",",
"noave",
"=",
"False",
",",
"meas_file",
"=",
"\"measurements.txt\"",
",",
"offline_... | Convert IODP discrete measurement files in MagIC file(s). This program
assumes that you have created the specimens, samples, sites and location
files using convert_2_magic.iodp_samples_csv from files downloaded from the LIMS online
repository and that all samples are in that file.
If there are offline ... | [
"Convert",
"IODP",
"discrete",
"measurement",
"files",
"in",
"MagIC",
"file",
"(",
"s",
")",
".",
"This",
"program",
"assumes",
"that",
"you",
"have",
"created",
"the",
"specimens",
"samples",
"sites",
"and",
"location",
"files",
"using",
"convert_2_magic",
".... | python | train |
gwpy/gwpy | gwpy/plot/axes.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/plot/axes.py#L402-L492 | def tile(self, x, y, w, h, color=None,
anchor='center', edgecolors='face', linewidth=0.8,
**kwargs):
"""Plot rectanguler tiles based onto these `Axes`.
``x`` and ``y`` give the anchor point for each tile, with
``w`` and ``h`` giving the extent in the X and Y axis respe... | [
"def",
"tile",
"(",
"self",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"color",
"=",
"None",
",",
"anchor",
"=",
"'center'",
",",
"edgecolors",
"=",
"'face'",
",",
"linewidth",
"=",
"0.8",
",",
"*",
"*",
"kwargs",
")",
":",
"# get color and sort"... | Plot rectanguler tiles based onto these `Axes`.
``x`` and ``y`` give the anchor point for each tile, with
``w`` and ``h`` giving the extent in the X and Y axis respectively.
Parameters
----------
x, y, w, h : `array_like`, shape (n, )
Input data
color : `ar... | [
"Plot",
"rectanguler",
"tiles",
"based",
"onto",
"these",
"Axes",
"."
] | python | train |
numenta/nupic | src/nupic/regions/record_sensor.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/record_sensor.py#L620-L629 | def writeToProto(self, proto):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.writeToProto`.
"""
self.encoder.write(proto.encoder)
if self.disabledEncoder is not None:
self.disabledEncoder.write(proto.disabledEncoder)
proto.topDownMode = int(self.topDownMode)
proto.verbo... | [
"def",
"writeToProto",
"(",
"self",
",",
"proto",
")",
":",
"self",
".",
"encoder",
".",
"write",
"(",
"proto",
".",
"encoder",
")",
"if",
"self",
".",
"disabledEncoder",
"is",
"not",
"None",
":",
"self",
".",
"disabledEncoder",
".",
"write",
"(",
"pro... | Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.writeToProto`. | [
"Overrides",
":",
"meth",
":",
"nupic",
".",
"bindings",
".",
"regions",
".",
"PyRegion",
".",
"PyRegion",
".",
"writeToProto",
"."
] | python | valid |
blockcypher/blockcypher-python | blockcypher/api.py | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L673-L678 | def get_block_hash(block_height, coin_symbol='btc', api_key=None):
'''
Takes a block_height and returns the block_hash
'''
return get_block_overview(block_representation=block_height,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['hash'] | [
"def",
"get_block_hash",
"(",
"block_height",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_block_overview",
"(",
"block_representation",
"=",
"block_height",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
"txn_limit",
"=",
... | Takes a block_height and returns the block_hash | [
"Takes",
"a",
"block_height",
"and",
"returns",
"the",
"block_hash"
] | python | train |
Iotic-Labs/py-IoticAgent | src/IoticAgent/Core/Client.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1446-L1455 | def __handle_low_seq_resend(self, msg, req):
"""special error case - low sequence number (update sequence number & resend if applicable). Returns True if
a resend was scheduled, False otherwise. MUST be called within self.__requests lock."""
if msg[M_TYPE] == E_FAILED and msg[M_PAYLOAD][P_COD... | [
"def",
"__handle_low_seq_resend",
"(",
"self",
",",
"msg",
",",
"req",
")",
":",
"if",
"msg",
"[",
"M_TYPE",
"]",
"==",
"E_FAILED",
"and",
"msg",
"[",
"M_PAYLOAD",
"]",
"[",
"P_CODE",
"]",
"==",
"E_FAILED_CODE_LOWSEQNUM",
":",
"with",
"self",
".",
"__seq... | special error case - low sequence number (update sequence number & resend if applicable). Returns True if
a resend was scheduled, False otherwise. MUST be called within self.__requests lock. | [
"special",
"error",
"case",
"-",
"low",
"sequence",
"number",
"(",
"update",
"sequence",
"number",
"&",
"resend",
"if",
"applicable",
")",
".",
"Returns",
"True",
"if",
"a",
"resend",
"was",
"scheduled",
"False",
"otherwise",
".",
"MUST",
"be",
"called",
"... | python | train |
Blueqat/Blueqat | examples/maxcut_qaoa.py | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/examples/maxcut_qaoa.py#L3-L22 | def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True):
"""Setup QAOA.
:param n_step: The number of step of QAOA
:param n_sample: The number of sampling time of each measurement in VQE.
If None, use calculated ideal value.
:param edges: The edges list of the gra... | [
"def",
"maxcut_qaoa",
"(",
"n_step",
",",
"edges",
",",
"minimizer",
"=",
"None",
",",
"sampler",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"sampler",
"=",
"sampler",
"or",
"vqe",
".",
"non_sampling_sampler",
"minimizer",
"=",
"minimizer",
"or",
... | Setup QAOA.
:param n_step: The number of step of QAOA
:param n_sample: The number of sampling time of each measurement in VQE.
If None, use calculated ideal value.
:param edges: The edges list of the graph.
:returns Vqe object | [
"Setup",
"QAOA",
"."
] | python | train |
sci-bots/serial-device | serial_device/or_event.py | https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/or_event.py#L39-L70 | def OrEvent(*events):
'''
Parameters
----------
events : list(threading.Event)
List of events.
Returns
-------
threading.Event
Event that is set when **at least one** of the events in :data:`events`
is set.
'''
or_event = threading.Event()
def changed():... | [
"def",
"OrEvent",
"(",
"*",
"events",
")",
":",
"or_event",
"=",
"threading",
".",
"Event",
"(",
")",
"def",
"changed",
"(",
")",
":",
"'''\n Set ``or_event`` if any of the specified events have been set.\n '''",
"bools",
"=",
"[",
"event_i",
".",
"is_... | Parameters
----------
events : list(threading.Event)
List of events.
Returns
-------
threading.Event
Event that is set when **at least one** of the events in :data:`events`
is set. | [
"Parameters",
"----------",
"events",
":",
"list",
"(",
"threading",
".",
"Event",
")",
"List",
"of",
"events",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/defects/utils.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/defects/utils.py#L1222-L1240 | def sort_sites_by_integrated_chg(self, r=0.4):
"""
Get the average charge density around each local minima in the charge density
and store the result in _extrema_df
Args:
r (float): radius of sphere around each site to evaluate the average
"""
if self.extrema... | [
"def",
"sort_sites_by_integrated_chg",
"(",
"self",
",",
"r",
"=",
"0.4",
")",
":",
"if",
"self",
".",
"extrema_type",
"is",
"None",
":",
"self",
".",
"get_local_extrema",
"(",
")",
"int_den",
"=",
"[",
"]",
"for",
"isite",
"in",
"self",
".",
"extrema_co... | Get the average charge density around each local minima in the charge density
and store the result in _extrema_df
Args:
r (float): radius of sphere around each site to evaluate the average | [
"Get",
"the",
"average",
"charge",
"density",
"around",
"each",
"local",
"minima",
"in",
"the",
"charge",
"density",
"and",
"store",
"the",
"result",
"in",
"_extrema_df",
"Args",
":",
"r",
"(",
"float",
")",
":",
"radius",
"of",
"sphere",
"around",
"each",... | python | train |
nfcpy/nfcpy | src/nfc/clf/device.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L496-L526 | def send_cmd_recv_rsp(self, target, data, timeout):
"""Exchange data with a remote Target
Sends command *data* to the remote *target* discovered in the
most recent call to one of the sense_xxx() methods. Note that
*target* becomes invalid with any call to mute(), sense_xxx()
or ... | [
"def",
"send_cmd_recv_rsp",
"(",
"self",
",",
"target",
",",
"data",
",",
"timeout",
")",
":",
"fname",
"=",
"\"send_cmd_recv_rsp\"",
"cname",
"=",
"self",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"self",
".",
"__class__",
".",
"__name__",
"ra... | Exchange data with a remote Target
Sends command *data* to the remote *target* discovered in the
most recent call to one of the sense_xxx() methods. Note that
*target* becomes invalid with any call to mute(), sense_xxx()
or listen_xxx()
Arguments:
target (nfc.clf.Rem... | [
"Exchange",
"data",
"with",
"a",
"remote",
"Target"
] | python | train |
openid/python-openid | openid/extensions/ax.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L149-L179 | def toTypeURIs(namespace_map, alias_list_s):
"""Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.messa... | [
"def",
"toTypeURIs",
"(",
"namespace_map",
",",
"alias_list_s",
")",
":",
"uris",
"=",
"[",
"]",
"if",
"alias_list_s",
":",
"for",
"alias",
"in",
"alias_list_s",
".",
"split",
"(",
"','",
")",
":",
"type_uri",
"=",
"namespace_map",
".",
"getNamespaceURI",
... | Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.message.NamespaceMap
@param alias_list_s: The string... | [
"Given",
"a",
"namespace",
"mapping",
"and",
"a",
"string",
"containing",
"a",
"comma",
"-",
"separated",
"list",
"of",
"namespace",
"aliases",
"return",
"a",
"list",
"of",
"type",
"URIs",
"that",
"correspond",
"to",
"those",
"aliases",
"."
] | python | train |
eavanvalkenburg/brunt-api | brunt/brunt.py | https://github.com/eavanvalkenburg/brunt-api/blob/c6bae43f56e0fd8f79b7af67d524611dd104dafa/brunt/brunt.py#L29-L72 | def request(self, data, request_type: RequestTypes):
""" internal request method
:param session: session object from the Requests package
:param data: internal data of your API call
:param request: the type of request, based on the RequestType enum
:returns: dict with s... | [
"def",
"request",
"(",
"self",
",",
"data",
",",
"request_type",
":",
"RequestTypes",
")",
":",
"#prepare the URL to send the request to",
"url",
"=",
"data",
"[",
"'host'",
"]",
"+",
"data",
"[",
"'path'",
"]",
"#fixed header content",
"headers",
"=",
"self",
... | internal request method
:param session: session object from the Requests package
:param data: internal data of your API call
:param request: the type of request, based on the RequestType enum
:returns: dict with sessionid for a login and the dict of the things for the other cal... | [
"internal",
"request",
"method",
":",
"param",
"session",
":",
"session",
"object",
"from",
"the",
"Requests",
"package",
":",
"param",
"data",
":",
"internal",
"data",
"of",
"your",
"API",
"call",
":",
"param",
"request",
":",
"the",
"type",
"of",
"reques... | python | train |
gitpython-developers/GitPython | git/remote.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/remote.py#L526-L554 | def urls(self):
""":return: Iterator yielding all configured URL targets on a remote as strings"""
try:
remote_details = self.repo.git.remote("get-url", "--all", self.name)
for line in remote_details.split('\n'):
yield line
except GitCommandError as ex:
... | [
"def",
"urls",
"(",
"self",
")",
":",
"try",
":",
"remote_details",
"=",
"self",
".",
"repo",
".",
"git",
".",
"remote",
"(",
"\"get-url\"",
",",
"\"--all\"",
",",
"self",
".",
"name",
")",
"for",
"line",
"in",
"remote_details",
".",
"split",
"(",
"'... | :return: Iterator yielding all configured URL targets on a remote as strings | [
":",
"return",
":",
"Iterator",
"yielding",
"all",
"configured",
"URL",
"targets",
"on",
"a",
"remote",
"as",
"strings"
] | python | train |
vbwagner/ctypescrypto | ctypescrypto/cms.py | https://github.com/vbwagner/ctypescrypto/blob/33c32904cf5e04901f87f90e2499634b8feecd3e/ctypescrypto/cms.py#L183-L206 | def verify(self, store, flags, data=None, certs=None):
"""
Verifies signature under CMS message using trusted cert store
@param store - X509Store object with trusted certs
@param flags - OR-ed combination of flag consants
@param data - message data, if messge has detached signa... | [
"def",
"verify",
"(",
"self",
",",
"store",
",",
"flags",
",",
"data",
"=",
"None",
",",
"certs",
"=",
"None",
")",
":",
"bio",
"=",
"None",
"if",
"data",
"!=",
"None",
":",
"bio_obj",
"=",
"Membio",
"(",
"data",
")",
"bio",
"=",
"bio_obj",
".",
... | Verifies signature under CMS message using trusted cert store
@param store - X509Store object with trusted certs
@param flags - OR-ed combination of flag consants
@param data - message data, if messge has detached signature
param certs - list of certificates to use during verification
... | [
"Verifies",
"signature",
"under",
"CMS",
"message",
"using",
"trusted",
"cert",
"store"
] | python | train |
arneb/django-messages | django_messages/templatetags/inbox.py | https://github.com/arneb/django-messages/blob/8e4b8e6660740e6f716ea4a7f4d77221baf166c5/django_messages/templatetags/inbox.py#L19-L42 | def do_print_inbox_count(parser, token):
"""
A templatetag to show the unread-count for a logged in user.
Returns the number of unread messages in the user's inbox.
Usage::
{% load inbox %}
{% inbox_count %}
{# or assign the value to a variable: #}
{% inbox_count as my... | [
"def",
"do_print_inbox_count",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">",
"1",
":",
"if",
"len",
"(",
"bits",
")",
"!=",
"3",
":",
"raise",
"TemplateSynt... | A templatetag to show the unread-count for a logged in user.
Returns the number of unread messages in the user's inbox.
Usage::
{% load inbox %}
{% inbox_count %}
{# or assign the value to a variable: #}
{% inbox_count as my_var %}
{{ my_var }} | [
"A",
"templatetag",
"to",
"show",
"the",
"unread",
"-",
"count",
"for",
"a",
"logged",
"in",
"user",
".",
"Returns",
"the",
"number",
"of",
"unread",
"messages",
"in",
"the",
"user",
"s",
"inbox",
".",
"Usage",
"::"
] | python | train |
python-fedex-devs/python-fedex | fedex/services/document_service.py | https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/document_service.py#L41-L52 | def _prepare_wsdl_objects(self):
"""
This is the data that will be used to create your shipment. Create
the data structure and get it ready for the WSDL request.
"""
self.UploadDocumentsRequest = self.client.factory.create('UploadDocumentsRequest')
... | [
"def",
"_prepare_wsdl_objects",
"(",
"self",
")",
":",
"self",
".",
"UploadDocumentsRequest",
"=",
"self",
".",
"client",
".",
"factory",
".",
"create",
"(",
"'UploadDocumentsRequest'",
")",
"self",
".",
"OriginCountryCode",
"=",
"None",
"self",
".",
"Destinatio... | This is the data that will be used to create your shipment. Create
the data structure and get it ready for the WSDL request. | [
"This",
"is",
"the",
"data",
"that",
"will",
"be",
"used",
"to",
"create",
"your",
"shipment",
".",
"Create",
"the",
"data",
"structure",
"and",
"get",
"it",
"ready",
"for",
"the",
"WSDL",
"request",
"."
] | python | train |
oanda/v20-python | src/v20/account.py | https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/account.py#L248-L376 | def from_dict(data, ctx):
"""
Instantiate a new Account from a dict (generally from loading a JSON
response). The data used to instantiate the Account is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately.
"""
data = dat... | [
"def",
"from_dict",
"(",
"data",
",",
"ctx",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'balance'",
")",
"is",
"not",
"None",
":",
"data",
"[",
"'balance'",
"]",
"=",
"ctx",
".",
"convert_decimal_number",
... | Instantiate a new Account from a dict (generally from loading a JSON
response). The data used to instantiate the Account is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately. | [
"Instantiate",
"a",
"new",
"Account",
"from",
"a",
"dict",
"(",
"generally",
"from",
"loading",
"a",
"JSON",
"response",
")",
".",
"The",
"data",
"used",
"to",
"instantiate",
"the",
"Account",
"is",
"a",
"shallow",
"copy",
"of",
"the",
"dict",
"passed",
... | python | train |
mishbahr/django-connected | connected_accounts/providers/base.py | https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L88-L94 | def get_redirect_url(self, request, callback, parameters=None):
"""Build authentication redirect url."""
args = self.get_redirect_args(request, callback=callback)
additional = parameters or {}
args.update(additional)
params = urlencode(args)
return '{0}?{1}'.format(self.a... | [
"def",
"get_redirect_url",
"(",
"self",
",",
"request",
",",
"callback",
",",
"parameters",
"=",
"None",
")",
":",
"args",
"=",
"self",
".",
"get_redirect_args",
"(",
"request",
",",
"callback",
"=",
"callback",
")",
"additional",
"=",
"parameters",
"or",
... | Build authentication redirect url. | [
"Build",
"authentication",
"redirect",
"url",
"."
] | python | train |
Scifabric/pybossa-client | pbclient/__init__.py | https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L674-L689 | def update_result(result):
"""Update a result for a given result ID.
:param result: PYBOSSA result
"""
try:
result_id = result.id
result = _forbidden_attributes(result)
res = _pybossa_req('put', 'result', result_id, payload=result.data)
if res.get('id'):
ret... | [
"def",
"update_result",
"(",
"result",
")",
":",
"try",
":",
"result_id",
"=",
"result",
".",
"id",
"result",
"=",
"_forbidden_attributes",
"(",
"result",
")",
"res",
"=",
"_pybossa_req",
"(",
"'put'",
",",
"'result'",
",",
"result_id",
",",
"payload",
"="... | Update a result for a given result ID.
:param result: PYBOSSA result | [
"Update",
"a",
"result",
"for",
"a",
"given",
"result",
"ID",
"."
] | python | valid |
mdgoldberg/sportsref | sportsref/nfl/teams.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nfl/teams.py#L297-L308 | def def_coordinator(self, year):
"""Returns the coach ID for the team's DC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the DC.
"""
try:
dc_anchor = self._year_info_pq(year, 'Defensive Coordinator')('a')
... | [
"def",
"def_coordinator",
"(",
"self",
",",
"year",
")",
":",
"try",
":",
"dc_anchor",
"=",
"self",
".",
"_year_info_pq",
"(",
"year",
",",
"'Defensive Coordinator'",
")",
"(",
"'a'",
")",
"if",
"dc_anchor",
":",
"return",
"dc_anchor",
".",
"attr",
"[",
... | Returns the coach ID for the team's DC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the DC. | [
"Returns",
"the",
"coach",
"ID",
"for",
"the",
"team",
"s",
"DC",
"in",
"a",
"given",
"year",
"."
] | python | test |
KelSolaar/Umbra | umbra/ui/widgets/basic_QPlainTextEdit.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/basic_QPlainTextEdit.py#L799-L849 | def replace(self, pattern, replacement_pattern, **kwargs):
"""
Replaces current given pattern occurence in the document with the replacement pattern.
Usage::
>>> script_editor = Umbra.components_manager.get_interface("factory.script_editor")
True
>>> codeEdi... | [
"def",
"replace",
"(",
"self",
",",
"pattern",
",",
"replacement_pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"settings",
"=",
"foundations",
".",
"data_structures",
".",
"Structure",
"(",
"*",
"*",
"{",
"\"case_sensitive\"",
":",
"False",
",",
"\"regular_ex... | Replaces current given pattern occurence in the document with the replacement pattern.
Usage::
>>> script_editor = Umbra.components_manager.get_interface("factory.script_editor")
True
>>> codeEditor = script_editor.get_current_editor()
True
>>> codeE... | [
"Replaces",
"current",
"given",
"pattern",
"occurence",
"in",
"the",
"document",
"with",
"the",
"replacement",
"pattern",
"."
] | python | train |
limix/limix-core | limix_core/mean/linear.py | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/linear.py#L567-L572 | def getParams(self):
""" get params """
rv = np.array([])
if self.n_terms>0:
rv = np.concatenate([np.reshape(self.B[term_i],self.B[term_i].size, order='F') for term_i in range(self.n_terms)])
return rv | [
"def",
"getParams",
"(",
"self",
")",
":",
"rv",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"self",
".",
"n_terms",
">",
"0",
":",
"rv",
"=",
"np",
".",
"concatenate",
"(",
"[",
"np",
".",
"reshape",
"(",
"self",
".",
"B",
"[",
"term_... | get params | [
"get",
"params"
] | python | train |
ambitioninc/rabbitmq-admin | rabbitmq_admin/api.py | https://github.com/ambitioninc/rabbitmq-admin/blob/ff65054115f19991da153f0e4f4e45e526545fea/rabbitmq_admin/api.py#L32-L45 | def get_node(self, name, memory=False, binary=False):
"""
An individual node in the RabbitMQ cluster. Set "memory=true" to get
memory statistics, and "binary=true" to get a breakdown of binary
memory use (may be expensive if there are many small binaries in the
system).
"... | [
"def",
"get_node",
"(",
"self",
",",
"name",
",",
"memory",
"=",
"False",
",",
"binary",
"=",
"False",
")",
":",
"return",
"self",
".",
"_api_get",
"(",
"url",
"=",
"'/api/nodes/{0}'",
".",
"format",
"(",
"name",
")",
",",
"params",
"=",
"dict",
"(",... | An individual node in the RabbitMQ cluster. Set "memory=true" to get
memory statistics, and "binary=true" to get a breakdown of binary
memory use (may be expensive if there are many small binaries in the
system). | [
"An",
"individual",
"node",
"in",
"the",
"RabbitMQ",
"cluster",
".",
"Set",
"memory",
"=",
"true",
"to",
"get",
"memory",
"statistics",
"and",
"binary",
"=",
"true",
"to",
"get",
"a",
"breakdown",
"of",
"binary",
"memory",
"use",
"(",
"may",
"be",
"expen... | python | train |
google/grr | grr/server/grr_response_server/gui/wsgiapp.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/wsgiapp.py#L65-L70 | def StoreCSRFCookie(user, response):
"""Decorator for WSGI handler that inserts CSRF cookie into response."""
csrf_token = GenerateCSRFToken(user, None)
response.set_cookie(
"csrftoken", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds) | [
"def",
"StoreCSRFCookie",
"(",
"user",
",",
"response",
")",
":",
"csrf_token",
"=",
"GenerateCSRFToken",
"(",
"user",
",",
"None",
")",
"response",
".",
"set_cookie",
"(",
"\"csrftoken\"",
",",
"csrf_token",
",",
"max_age",
"=",
"CSRF_TOKEN_DURATION",
".",
"s... | Decorator for WSGI handler that inserts CSRF cookie into response. | [
"Decorator",
"for",
"WSGI",
"handler",
"that",
"inserts",
"CSRF",
"cookie",
"into",
"response",
"."
] | python | train |
edx/edx-enterprise | integrated_channels/integrated_channel/management/commands/transmit_learner_data.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/management/commands/transmit_learner_data.py#L40-L53 | def handle(self, *args, **options):
"""
Transmit the learner data for the EnterpriseCustomer(s) to the active integration channels.
"""
# Ensure that we were given an api_user name, and that User exists.
api_username = options['api_user']
try:
User.objects.get... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# Ensure that we were given an api_user name, and that User exists.",
"api_username",
"=",
"options",
"[",
"'api_user'",
"]",
"try",
":",
"User",
".",
"objects",
".",
"get",
"("... | Transmit the learner data for the EnterpriseCustomer(s) to the active integration channels. | [
"Transmit",
"the",
"learner",
"data",
"for",
"the",
"EnterpriseCustomer",
"(",
"s",
")",
"to",
"the",
"active",
"integration",
"channels",
"."
] | python | valid |
Azure/azure-sdk-for-python | azure-keyvault/azure/keyvault/http_bearer_challenge_cache/__init__.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-keyvault/azure/keyvault/http_bearer_challenge_cache/__init__.py#L16-L31 | def get_challenge_for_url(url):
""" Gets the challenge for the cached URL.
:param url: the URL the challenge is cached for.
:rtype: HttpBearerChallenge """
if not url:
raise ValueError('URL cannot be None')
url = parse.urlparse(url)
_lock.acquire()
val = _cache.get(url.netloc)
... | [
"def",
"get_challenge_for_url",
"(",
"url",
")",
":",
"if",
"not",
"url",
":",
"raise",
"ValueError",
"(",
"'URL cannot be None'",
")",
"url",
"=",
"parse",
".",
"urlparse",
"(",
"url",
")",
"_lock",
".",
"acquire",
"(",
")",
"val",
"=",
"_cache",
".",
... | Gets the challenge for the cached URL.
:param url: the URL the challenge is cached for.
:rtype: HttpBearerChallenge | [
"Gets",
"the",
"challenge",
"for",
"the",
"cached",
"URL",
".",
":",
"param",
"url",
":",
"the",
"URL",
"the",
"challenge",
"is",
"cached",
"for",
".",
":",
"rtype",
":",
"HttpBearerChallenge"
] | python | test |
cirruscluster/cirruscluster | cirruscluster/ami/builder.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ami/builder.py#L53-L61 | def GetAmi(ec2, ami_spec):
""" Get the boto ami object given a AmiSpecification object. """
images = ec2.get_all_images(owners=[ami_spec.owner_id] )
requested_image = None
for image in images:
if image.name == ami_spec.ami_name:
requested_image = image
break
return requested_i... | [
"def",
"GetAmi",
"(",
"ec2",
",",
"ami_spec",
")",
":",
"images",
"=",
"ec2",
".",
"get_all_images",
"(",
"owners",
"=",
"[",
"ami_spec",
".",
"owner_id",
"]",
")",
"requested_image",
"=",
"None",
"for",
"image",
"in",
"images",
":",
"if",
"image",
"."... | Get the boto ami object given a AmiSpecification object. | [
"Get",
"the",
"boto",
"ami",
"object",
"given",
"a",
"AmiSpecification",
"object",
"."
] | python | train |
jsommers/switchyard | switchyard/lib/openflow/openflow10.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/openflow/openflow10.py#L1212-L1226 | def _unpack_actions(raw):
'''
deserialize 1 or more actions; return a list of
Action* objects
'''
actions = []
while len(raw) > 0:
atype, alen = struct.unpack('!HH', raw[:4])
atype = OpenflowActionType(atype)
action = _ActionClassMap.get(atype)()
action.from_byte... | [
"def",
"_unpack_actions",
"(",
"raw",
")",
":",
"actions",
"=",
"[",
"]",
"while",
"len",
"(",
"raw",
")",
">",
"0",
":",
"atype",
",",
"alen",
"=",
"struct",
".",
"unpack",
"(",
"'!HH'",
",",
"raw",
"[",
":",
"4",
"]",
")",
"atype",
"=",
"Open... | deserialize 1 or more actions; return a list of
Action* objects | [
"deserialize",
"1",
"or",
"more",
"actions",
";",
"return",
"a",
"list",
"of",
"Action",
"*",
"objects"
] | python | train |
madedotcom/photon-pump | photonpump/connection.py | https://github.com/madedotcom/photon-pump/blob/ff0736c9cacd43c1f783c9668eefb53d03a3a93e/photonpump/connection.py#L788-L840 | async def get_all(
self,
direction: msg.StreamDirection = msg.StreamDirection.Forward,
from_position: Optional[Union[msg.Position, msg._PositionSentinel]] = None,
max_count: int = 100,
resolve_links: bool = True,
require_master: bool = False,
correlation_id: uuid.... | [
"async",
"def",
"get_all",
"(",
"self",
",",
"direction",
":",
"msg",
".",
"StreamDirection",
"=",
"msg",
".",
"StreamDirection",
".",
"Forward",
",",
"from_position",
":",
"Optional",
"[",
"Union",
"[",
"msg",
".",
"Position",
",",
"msg",
".",
"_PositionS... | Read a range of events from the whole database.
Args:
direction (optional): Controls whether to read events forward or backward.
defaults to Forward.
from_position (optional): The position to read from.
defaults to the beginning of the stream when direction i... | [
"Read",
"a",
"range",
"of",
"events",
"from",
"the",
"whole",
"database",
"."
] | python | train |
welchbj/sublemon | demos/from_the_readme.py | https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/demos/from_the_readme.py#L23-L29 | async def one(s: Sublemon):
"""Spin up some subprocesses, sleep, and echo a message for this coro."""
shell_cmds = [
'sleep 1 && echo subprocess 1 in coroutine one',
'sleep 1 && echo subprocess 2 in coroutine one']
async for line in s.iter_lines(*shell_cmds):
print(line) | [
"async",
"def",
"one",
"(",
"s",
":",
"Sublemon",
")",
":",
"shell_cmds",
"=",
"[",
"'sleep 1 && echo subprocess 1 in coroutine one'",
",",
"'sleep 1 && echo subprocess 2 in coroutine one'",
"]",
"async",
"for",
"line",
"in",
"s",
".",
"iter_lines",
"(",
"*",
"shell... | Spin up some subprocesses, sleep, and echo a message for this coro. | [
"Spin",
"up",
"some",
"subprocesses",
"sleep",
"and",
"echo",
"a",
"message",
"for",
"this",
"coro",
"."
] | python | train |
Raynes/quarantine | quarantine/cdc.py | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L32-L36 | def list_exes(self):
"""List the installed executables by this project."""
return [path.join(self.env_bin, f)
for f
in os.listdir(self.env_bin)] | [
"def",
"list_exes",
"(",
"self",
")",
":",
"return",
"[",
"path",
".",
"join",
"(",
"self",
".",
"env_bin",
",",
"f",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"env_bin",
")",
"]"
] | List the installed executables by this project. | [
"List",
"the",
"installed",
"executables",
"by",
"this",
"project",
"."
] | python | train |
rueckstiess/mtools | mtools/mlaunch/mlaunch.py | https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mlaunch/mlaunch.py#L1290-L1298 | def is_running(self, port):
"""Return True if a host on a specific port is running."""
try:
con = self.client('localhost:%s' % port)
con.admin.command('ping')
return True
except (AutoReconnect, ConnectionFailure, OperationFailure):
# Catch Operatio... | [
"def",
"is_running",
"(",
"self",
",",
"port",
")",
":",
"try",
":",
"con",
"=",
"self",
".",
"client",
"(",
"'localhost:%s'",
"%",
"port",
")",
"con",
".",
"admin",
".",
"command",
"(",
"'ping'",
")",
"return",
"True",
"except",
"(",
"AutoReconnect",
... | Return True if a host on a specific port is running. | [
"Return",
"True",
"if",
"a",
"host",
"on",
"a",
"specific",
"port",
"is",
"running",
"."
] | python | train |
bpannier/simpletr64 | simpletr64/devicetr64.py | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/devicetr64.py#L644-L668 | def _loadDeviceDefinitions(self, urlOfXMLDefinition, xml):
"""Internal call to parse the XML of the device definition.
:param urlOfXMLDefinition: the URL to the XML device defintions
:param xml: the XML content to parse
"""
# extract the base path of the given XML to make sure ... | [
"def",
"_loadDeviceDefinitions",
"(",
"self",
",",
"urlOfXMLDefinition",
",",
"xml",
")",
":",
"# extract the base path of the given XML to make sure any relative URL later will be created correctly",
"url",
"=",
"urlparse",
"(",
"urlOfXMLDefinition",
")",
"baseURIPath",
"=",
"... | Internal call to parse the XML of the device definition.
:param urlOfXMLDefinition: the URL to the XML device defintions
:param xml: the XML content to parse | [
"Internal",
"call",
"to",
"parse",
"the",
"XML",
"of",
"the",
"device",
"definition",
"."
] | python | train |
fastai/fastai | fastai/callback.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L364-L367 | def annealing_cos(start:Number, end:Number, pct:float)->Number:
"Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0."
cos_out = np.cos(np.pi * pct) + 1
return end + (start-end)/2 * cos_out | [
"def",
"annealing_cos",
"(",
"start",
":",
"Number",
",",
"end",
":",
"Number",
",",
"pct",
":",
"float",
")",
"->",
"Number",
":",
"cos_out",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"pi",
"*",
"pct",
")",
"+",
"1",
"return",
"end",
"+",
"(",
"s... | Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0. | [
"Cosine",
"anneal",
"from",
"start",
"to",
"end",
"as",
"pct",
"goes",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | python | train |
napalm-automation/napalm-logs | napalm_logs/device.py | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/device.py#L140-L186 | def _parse(self, msg_dict):
'''
Parse a syslog message and check what OpenConfig object should
be generated.
'''
error_present = False
# log.debug('Matching the message:')
# log.debug(msg_dict)
for message in self.compiled_messages:
# log.debug... | [
"def",
"_parse",
"(",
"self",
",",
"msg_dict",
")",
":",
"error_present",
"=",
"False",
"# log.debug('Matching the message:')",
"# log.debug(msg_dict)",
"for",
"message",
"in",
"self",
".",
"compiled_messages",
":",
"# log.debug('Matching using:')",
"# log.debug(message)",
... | Parse a syslog message and check what OpenConfig object should
be generated. | [
"Parse",
"a",
"syslog",
"message",
"and",
"check",
"what",
"OpenConfig",
"object",
"should",
"be",
"generated",
"."
] | python | train |
cds-astro/mocpy | mocpy/abstract_moc.py | https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L527-L564 | def serialize(self, format='fits', optional_kw_dict=None):
"""
Serializes the MOC into a specific format.
Possible formats are FITS, JSON and STRING
Parameters
----------
format : str
'fits' by default. The other possible choice is 'json' or 'str'.
o... | [
"def",
"serialize",
"(",
"self",
",",
"format",
"=",
"'fits'",
",",
"optional_kw_dict",
"=",
"None",
")",
":",
"formats",
"=",
"(",
"'fits'",
",",
"'json'",
",",
"'str'",
")",
"if",
"format",
"not",
"in",
"formats",
":",
"raise",
"ValueError",
"(",
"'f... | Serializes the MOC into a specific format.
Possible formats are FITS, JSON and STRING
Parameters
----------
format : str
'fits' by default. The other possible choice is 'json' or 'str'.
optional_kw_dict : dict
Optional keywords arguments added to the FIT... | [
"Serializes",
"the",
"MOC",
"into",
"a",
"specific",
"format",
"."
] | python | train |
appstore-zencore/daemon-application | src/daemon_application/base.py | https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L141-L151 | def daemon_stop(pidfile, sig=None):
"""Stop application.
"""
logger.debug("stop daemon application pidfile={pidfile}.".format(pidfile=pidfile))
pid = load_pid(pidfile)
logger.debug("load pid={pid}".format(pid=pid))
if not pid:
six.print_("Application is not running or crashed...", file=o... | [
"def",
"daemon_stop",
"(",
"pidfile",
",",
"sig",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"stop daemon application pidfile={pidfile}.\"",
".",
"format",
"(",
"pidfile",
"=",
"pidfile",
")",
")",
"pid",
"=",
"load_pid",
"(",
"pidfile",
")",
"log... | Stop application. | [
"Stop",
"application",
"."
] | python | train |
resync/resync | resync/resource_container.py | https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/resource_container.py#L114-L120 | def link(self, rel):
"""Look for link with specified rel, return else None."""
for link in self.ln:
if ('rel' in link and
link['rel'] == rel):
return(link)
return(None) | [
"def",
"link",
"(",
"self",
",",
"rel",
")",
":",
"for",
"link",
"in",
"self",
".",
"ln",
":",
"if",
"(",
"'rel'",
"in",
"link",
"and",
"link",
"[",
"'rel'",
"]",
"==",
"rel",
")",
":",
"return",
"(",
"link",
")",
"return",
"(",
"None",
")"
] | Look for link with specified rel, return else None. | [
"Look",
"for",
"link",
"with",
"specified",
"rel",
"return",
"else",
"None",
"."
] | python | train |
cggh/scikit-allel | allel/model/ndarray.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L2522-L2527 | def distinct_frequencies(self):
"""Return frequencies for each distinct haplotype."""
c = self.distinct_counts()
n = self.shape[1]
return c / n | [
"def",
"distinct_frequencies",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"distinct_counts",
"(",
")",
"n",
"=",
"self",
".",
"shape",
"[",
"1",
"]",
"return",
"c",
"/",
"n"
] | Return frequencies for each distinct haplotype. | [
"Return",
"frequencies",
"for",
"each",
"distinct",
"haplotype",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.