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 |
|---|---|---|---|---|---|---|---|---|
KnorrFG/pyparadigm | pyparadigm/extras.py | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L26-L31 | def apply_color_map(name: str, mat: np.ndarray = None):
"""returns an RGB matrix scaled by a matplotlib color map"""
def apply_map(mat):
return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)
return apply_map if mat is None else apply_map(mat) | [
"def",
"apply_color_map",
"(",
"name",
":",
"str",
",",
"mat",
":",
"np",
".",
"ndarray",
"=",
"None",
")",
":",
"def",
"apply_map",
"(",
"mat",
")",
":",
"return",
"(",
"cm",
".",
"get_cmap",
"(",
"name",
")",
"(",
"_normalize",
"(",
"mat",
")",
... | returns an RGB matrix scaled by a matplotlib color map | [
"returns",
"an",
"RGB",
"matrix",
"scaled",
"by",
"a",
"matplotlib",
"color",
"map"
] | python | train |
infothrill/python-dyndnsc | dyndnsc/core.py | https://github.com/infothrill/python-dyndnsc/blob/2196d48aa6098da9835a7611fbdb0b5f0fbf51e4/dyndnsc/core.py#L85-L113 | def has_state_changed(self):
"""
Detect changes in offline detector and real DNS value.
Detect a change either in the offline detector or a
difference between the real DNS value and what the online
detector last got.
This is efficient, since it only generates minimal dns... | [
"def",
"has_state_changed",
"(",
"self",
")",
":",
"self",
".",
"lastcheck",
"=",
"time",
".",
"time",
"(",
")",
"# prefer offline state change detection:",
"if",
"self",
".",
"detector",
".",
"can_detect_offline",
"(",
")",
":",
"self",
".",
"detector",
".",
... | Detect changes in offline detector and real DNS value.
Detect a change either in the offline detector or a
difference between the real DNS value and what the online
detector last got.
This is efficient, since it only generates minimal dns traffic
for online detectors and no traf... | [
"Detect",
"changes",
"in",
"offline",
"detector",
"and",
"real",
"DNS",
"value",
"."
] | python | train |
Dallinger/Dallinger | dallinger/recruiters.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L128-L141 | def open_recruitment(self, n=1):
"""Return initial experiment URL list, plus instructions
for finding subsequent recruitment events in experiemnt logs.
"""
logger.info("Opening CLI recruitment for {} participants".format(n))
recruitments = self.recruit(n)
message = (
... | [
"def",
"open_recruitment",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"logger",
".",
"info",
"(",
"\"Opening CLI recruitment for {} participants\"",
".",
"format",
"(",
"n",
")",
")",
"recruitments",
"=",
"self",
".",
"recruit",
"(",
"n",
")",
"message",
"... | Return initial experiment URL list, plus instructions
for finding subsequent recruitment events in experiemnt logs. | [
"Return",
"initial",
"experiment",
"URL",
"list",
"plus",
"instructions",
"for",
"finding",
"subsequent",
"recruitment",
"events",
"in",
"experiemnt",
"logs",
"."
] | python | train |
edx/ease | ease/grade.py | https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/grade.py#L167-L188 | def get_confidence_value(algorithm,model,grader_feats,score, scores):
"""
Determines a confidence in a certain score, given proper input parameters
algorithm- from util_functions.AlgorithmTypes
model - a trained model
grader_feats - a row of features used by the model for classification/regression
... | [
"def",
"get_confidence_value",
"(",
"algorithm",
",",
"model",
",",
"grader_feats",
",",
"score",
",",
"scores",
")",
":",
"min_score",
"=",
"min",
"(",
"numpy",
".",
"asarray",
"(",
"scores",
")",
")",
"max_score",
"=",
"max",
"(",
"numpy",
".",
"asarra... | Determines a confidence in a certain score, given proper input parameters
algorithm- from util_functions.AlgorithmTypes
model - a trained model
grader_feats - a row of features used by the model for classification/regression
score - The score assigned to the submission by a prior model | [
"Determines",
"a",
"confidence",
"in",
"a",
"certain",
"score",
"given",
"proper",
"input",
"parameters",
"algorithm",
"-",
"from",
"util_functions",
".",
"AlgorithmTypes",
"model",
"-",
"a",
"trained",
"model",
"grader_feats",
"-",
"a",
"row",
"of",
"features",... | python | valid |
ibm-watson-iot/iot-python | src/wiotp/sdk/api/mgmt/extensions.py | https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/mgmt/extensions.py#L50-L62 | def delete(self, bundleId):
"""
Delete a device management extension package
It accepts bundleId (string) as parameters
In case of failure it throws APIException
"""
url = "api/v0002/mgmt/custom/bundle/%s" % (bundleId)
r = self._apiClient.delete(url)
if r... | [
"def",
"delete",
"(",
"self",
",",
"bundleId",
")",
":",
"url",
"=",
"\"api/v0002/mgmt/custom/bundle/%s\"",
"%",
"(",
"bundleId",
")",
"r",
"=",
"self",
".",
"_apiClient",
".",
"delete",
"(",
"url",
")",
"if",
"r",
".",
"status_code",
"==",
"204",
":",
... | Delete a device management extension package
It accepts bundleId (string) as parameters
In case of failure it throws APIException | [
"Delete",
"a",
"device",
"management",
"extension",
"package",
"It",
"accepts",
"bundleId",
"(",
"string",
")",
"as",
"parameters",
"In",
"case",
"of",
"failure",
"it",
"throws",
"APIException"
] | python | test |
seleniumbase/SeleniumBase | seleniumbase/core/tour_helper.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/core/tour_helper.py#L26-L54 | def activate_bootstrap(driver):
""" Allows you to use Bootstrap Tours with SeleniumBase
http://bootstraptour.com/
"""
bootstrap_tour_css = constants.BootstrapTour.MIN_CSS
bootstrap_tour_js = constants.BootstrapTour.MIN_JS
verify_script = ("""// Verify Bootstrap Tour activated
... | [
"def",
"activate_bootstrap",
"(",
"driver",
")",
":",
"bootstrap_tour_css",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_CSS",
"bootstrap_tour_js",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_JS",
"verify_script",
"=",
"(",
"\"\"\"// Verify Bootstrap Tour act... | Allows you to use Bootstrap Tours with SeleniumBase
http://bootstraptour.com/ | [
"Allows",
"you",
"to",
"use",
"Bootstrap",
"Tours",
"with",
"SeleniumBase",
"http",
":",
"//",
"bootstraptour",
".",
"com",
"/"
] | python | train |
vals/umis | umis/umis.py | https://github.com/vals/umis/blob/e8adb8486d9e9134ab8a6cad9811a7e74dcc4a2c/umis/umis.py#L1360-L1392 | def subset_bamfile(sam, barcodes):
"""
Subset a SAM/BAM file, keeping only alignments from given
cellular barcodes
"""
from pysam import AlignmentFile
start_time = time.time()
sam_file = open_bamfile(sam)
out_file = AlignmentFile("-", "wh", template=sam_file)
track = sam_file.fetch... | [
"def",
"subset_bamfile",
"(",
"sam",
",",
"barcodes",
")",
":",
"from",
"pysam",
"import",
"AlignmentFile",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"sam_file",
"=",
"open_bamfile",
"(",
"sam",
")",
"out_file",
"=",
"AlignmentFile",
"(",
"\"-\"",
... | Subset a SAM/BAM file, keeping only alignments from given
cellular barcodes | [
"Subset",
"a",
"SAM",
"/",
"BAM",
"file",
"keeping",
"only",
"alignments",
"from",
"given",
"cellular",
"barcodes"
] | python | train |
alexhayes/django-toolkit | django_toolkit/date_util.py | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L33-L48 | def business_days(start, stop):
"""
Return business days between two inclusive dates - ignoring public holidays.
Note that start must be less than stop or else 0 is returned.
@param start: Start date
@param stop: Stop date
@return int
"""
dates=rrule.rruleset()
# Get dates ... | [
"def",
"business_days",
"(",
"start",
",",
"stop",
")",
":",
"dates",
"=",
"rrule",
".",
"rruleset",
"(",
")",
"# Get dates between start/stop (which are inclusive)",
"dates",
".",
"rrule",
"(",
"rrule",
".",
"rrule",
"(",
"rrule",
".",
"DAILY",
",",
"dtstart"... | Return business days between two inclusive dates - ignoring public holidays.
Note that start must be less than stop or else 0 is returned.
@param start: Start date
@param stop: Stop date
@return int | [
"Return",
"business",
"days",
"between",
"two",
"inclusive",
"dates",
"-",
"ignoring",
"public",
"holidays",
".",
"Note",
"that",
"start",
"must",
"be",
"less",
"than",
"stop",
"or",
"else",
"0",
"is",
"returned",
"."
] | python | train |
UCBerkeleySETI/blimpy | blimpy/filterbank.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/filterbank.py#L747-L773 | def plot_kurtosis(self, f_start=None, f_stop=None, if_id=0, **kwargs):
""" Plot kurtosis
Args:
f_start (float): start frequency, in MHz
f_stop (float): stop frequency, in MHz
kwargs: keyword args to be passed to matplotlib imshow()
"""
ax = plt.gca()... | [
"def",
"plot_kurtosis",
"(",
"self",
",",
"f_start",
"=",
"None",
",",
"f_stop",
"=",
"None",
",",
"if_id",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"plot_f",
",",
"plot_data",
"=",
"self",
".",
"grab_d... | Plot kurtosis
Args:
f_start (float): start frequency, in MHz
f_stop (float): stop frequency, in MHz
kwargs: keyword args to be passed to matplotlib imshow() | [
"Plot",
"kurtosis"
] | python | test |
Fuyukai/ConfigMaster | configmaster/ConfigFile.py | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigFile.py#L155-L164 | def reload(self):
"""
Automatically reloads the config file.
This is just an alias for self.load()."""
if not self.fd.closed: self.fd.close()
self.fd = open(self.fd.name, 'r')
self.load() | [
"def",
"reload",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"fd",
".",
"closed",
":",
"self",
".",
"fd",
".",
"close",
"(",
")",
"self",
".",
"fd",
"=",
"open",
"(",
"self",
".",
"fd",
".",
"name",
",",
"'r'",
")",
"self",
".",
"load",
... | Automatically reloads the config file.
This is just an alias for self.load(). | [
"Automatically",
"reloads",
"the",
"config",
"file",
"."
] | python | train |
google/grr | grr/core/grr_response_core/lib/rdfvalues/structs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/structs.py#L262-L275 | def _SerializeEntries(entries):
"""Serializes given triplets of python and wire values and a descriptor."""
output = []
for python_format, wire_format, type_descriptor in entries:
if wire_format is None or (python_format and
type_descriptor.IsDirty(python_format)):
wire_... | [
"def",
"_SerializeEntries",
"(",
"entries",
")",
":",
"output",
"=",
"[",
"]",
"for",
"python_format",
",",
"wire_format",
",",
"type_descriptor",
"in",
"entries",
":",
"if",
"wire_format",
"is",
"None",
"or",
"(",
"python_format",
"and",
"type_descriptor",
".... | Serializes given triplets of python and wire values and a descriptor. | [
"Serializes",
"given",
"triplets",
"of",
"python",
"and",
"wire",
"values",
"and",
"a",
"descriptor",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L130-L139 | def copy(src, dst):
"""Copy data and mode bits ("cp src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copymode(src, dst) | [
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dst",
")",
":",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
")",
"copyfile",
... | Copy data and mode bits ("cp src dst").
The destination may be a directory. | [
"Copy",
"data",
"and",
"mode",
"bits",
"(",
"cp",
"src",
"dst",
")",
"."
] | python | train |
streamlink/streamlink | src/streamlink/plugins/euronews.py | https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugins/euronews.py#L50-L60 | def _get_streams(self):
"""
Find the streams for euronews
:return:
"""
match = self._url_re.match(self.url).groupdict()
if match.get("path") == "live":
return self._get_live_streams(match)
else:
return self._get_vod_stream() | [
"def",
"_get_streams",
"(",
"self",
")",
":",
"match",
"=",
"self",
".",
"_url_re",
".",
"match",
"(",
"self",
".",
"url",
")",
".",
"groupdict",
"(",
")",
"if",
"match",
".",
"get",
"(",
"\"path\"",
")",
"==",
"\"live\"",
":",
"return",
"self",
".... | Find the streams for euronews
:return: | [
"Find",
"the",
"streams",
"for",
"euronews",
":",
"return",
":"
] | python | test |
bitesofcode/projexui | projexui/widgets/xchartwidget/xchartscene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartscene.py#L488-L582 | def rebuildGrid( self ):
"""
Rebuilds the ruler data.
"""
vruler = self.verticalRuler()
hruler = self.horizontalRuler()
rect = self._buildData['grid_rect']
# process the vertical ruler
h_lines = []
h_alt = [... | [
"def",
"rebuildGrid",
"(",
"self",
")",
":",
"vruler",
"=",
"self",
".",
"verticalRuler",
"(",
")",
"hruler",
"=",
"self",
".",
"horizontalRuler",
"(",
")",
"rect",
"=",
"self",
".",
"_buildData",
"[",
"'grid_rect'",
"]",
"# process the vertical ruler\r",
"h... | Rebuilds the ruler data. | [
"Rebuilds",
"the",
"ruler",
"data",
"."
] | python | train |
syrusakbary/promise | promise/dataloader.py | https://github.com/syrusakbary/promise/blob/d80d791fcc86c89713dac57b55e56c0a9024f153/promise/dataloader.py#L80-L109 | def load(self, key=None):
# type: (Hashable) -> Promise
"""
Loads a key, returning a `Promise` for the value represented by that key.
"""
if key is None:
raise TypeError(
(
"The loader.load() function must be called with a value,"
... | [
"def",
"load",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"# type: (Hashable) -> Promise",
"if",
"key",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"(",
"\"The loader.load() function must be called with a value,\"",
"+",
"\"but got: {}.\"",
")",
".",
"format"... | Loads a key, returning a `Promise` for the value represented by that key. | [
"Loads",
"a",
"key",
"returning",
"a",
"Promise",
"for",
"the",
"value",
"represented",
"by",
"that",
"key",
"."
] | python | train |
openstax/cnx-archive | cnxarchive/database.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L449-L480 | def republish_module_trigger(plpy, td):
"""Trigger called from postgres database when republishing a module.
When a module is republished, the versions of the collections that it is
part of will need to be updated (a minor update).
e.g. there is a collection c1 v2.1, which contains module m1 v3
... | [
"def",
"republish_module_trigger",
"(",
"plpy",
",",
"td",
")",
":",
"# Is this an insert from legacy? Legacy always supplies the version.",
"is_legacy_publication",
"=",
"td",
"[",
"'new'",
"]",
"[",
"'version'",
"]",
"is",
"not",
"None",
"if",
"not",
"is_legacy_public... | Trigger called from postgres database when republishing a module.
When a module is republished, the versions of the collections that it is
part of will need to be updated (a minor update).
e.g. there is a collection c1 v2.1, which contains module m1 v3
m1 is updated, we have a new row in the modules... | [
"Trigger",
"called",
"from",
"postgres",
"database",
"when",
"republishing",
"a",
"module",
"."
] | python | train |
Hackerfleet/hfos | hfos/component.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/component.py#L250-L253 | def unregister(self):
"""Removes the unique name from the systems unique name list"""
self.names.remove(self.uniquename)
super(ConfigurableMeta, self).unregister() | [
"def",
"unregister",
"(",
"self",
")",
":",
"self",
".",
"names",
".",
"remove",
"(",
"self",
".",
"uniquename",
")",
"super",
"(",
"ConfigurableMeta",
",",
"self",
")",
".",
"unregister",
"(",
")"
] | Removes the unique name from the systems unique name list | [
"Removes",
"the",
"unique",
"name",
"from",
"the",
"systems",
"unique",
"name",
"list"
] | python | train |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L139-L152 | def _handle_failed_response(self, response):
"""
Handle the failed response and check for rate limit exceeded
If rate limit exceeded it runs the rate_limit_exceeded function which you should overwrite
:param response: requests.Response
:type response: requests.Reponse
:r... | [
"def",
"_handle_failed_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"too_many_requests",
":",
"return",
"self",
".",
"rate_limit_exceeded",
"(",
"response",
")",
"else",
":",
"res... | Handle the failed response and check for rate limit exceeded
If rate limit exceeded it runs the rate_limit_exceeded function which you should overwrite
:param response: requests.Response
:type response: requests.Reponse
:return: None
:rtype: None | [
"Handle",
"the",
"failed",
"response",
"and",
"check",
"for",
"rate",
"limit",
"exceeded",
"If",
"rate",
"limit",
"exceeded",
"it",
"runs",
"the",
"rate_limit_exceeded",
"function",
"which",
"you",
"should",
"overwrite"
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_radio_group.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_radio_group.py#L69-L84 | def on_checked_changed(self, group, checked_id):
""" Set the checked property based on the checked state
of all the children
"""
d = self.declaration
if checked_id < 0:
with self.widget.clearCheck.suppressed():
d.checked = None
ret... | [
"def",
"on_checked_changed",
"(",
"self",
",",
"group",
",",
"checked_id",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"if",
"checked_id",
"<",
"0",
":",
"with",
"self",
".",
"widget",
".",
"clearCheck",
".",
"suppressed",
"(",
")",
":",
"d",
".",
... | Set the checked property based on the checked state
of all the children | [
"Set",
"the",
"checked",
"property",
"based",
"on",
"the",
"checked",
"state",
"of",
"all",
"the",
"children"
] | python | train |
NoviceLive/intellicoder | intellicoder/transformers.py | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/transformers.py#L80-L91 | def transform_sources(self, sources, with_string=False):
"""Get the defintions of needed strings and functions
after replacement.
"""
modules = {}
updater = partial(
self.replace_source, modules=modules, prefix='string_')
for filename in sources:
u... | [
"def",
"transform_sources",
"(",
"self",
",",
"sources",
",",
"with_string",
"=",
"False",
")",
":",
"modules",
"=",
"{",
"}",
"updater",
"=",
"partial",
"(",
"self",
".",
"replace_source",
",",
"modules",
"=",
"modules",
",",
"prefix",
"=",
"'string_'",
... | Get the defintions of needed strings and functions
after replacement. | [
"Get",
"the",
"defintions",
"of",
"needed",
"strings",
"and",
"functions",
"after",
"replacement",
"."
] | python | train |
praekelt/django-profile | profile/utils.py | https://github.com/praekelt/django-profile/blob/52a3d3f7e776742c5333f8fab67b5af3cdbc878b/profile/utils.py#L4-L16 | def get_profile_model():
"""
Returns configured user profile model or None if not found
"""
auth_profile_module = getattr(settings, 'AUTH_PROFILE_MODULE', None)
profile_model = None
if auth_profile_module:
# get the profile model. TODO: super flacky, refactor
app_label, model = a... | [
"def",
"get_profile_model",
"(",
")",
":",
"auth_profile_module",
"=",
"getattr",
"(",
"settings",
",",
"'AUTH_PROFILE_MODULE'",
",",
"None",
")",
"profile_model",
"=",
"None",
"if",
"auth_profile_module",
":",
"# get the profile model. TODO: super flacky, refactor",
"app... | Returns configured user profile model or None if not found | [
"Returns",
"configured",
"user",
"profile",
"model",
"or",
"None",
"if",
"not",
"found"
] | python | train |
mbj4668/pyang | pyang/translators/dsdl.py | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/dsdl.py#L548-L555 | def qname(self, stmt):
"""Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping.
"""
if self.gg_level: return stmt.arg
return self.prefix_stack[-1] + ":" + stmt.arg | [
"def",
"qname",
"(",
"self",
",",
"stmt",
")",
":",
"if",
"self",
".",
"gg_level",
":",
"return",
"stmt",
".",
"arg",
"return",
"self",
".",
"prefix_stack",
"[",
"-",
"1",
"]",
"+",
"\":\"",
"+",
"stmt",
".",
"arg"
] | Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping. | [
"Return",
"(",
"prefixed",
")",
"node",
"name",
"of",
"stmt",
"."
] | python | train |
openstack/stacktach-stackdistiller | stackdistiller/distiller.py | https://github.com/openstack/stacktach-stackdistiller/blob/38cc32994cc5411c3f7c76f31ef3ea8b3245e871/stackdistiller/distiller.py#L259-L271 | def _extract_when(body):
"""Extract the generated datetime from the notification."""
# NOTE: I am keeping the logic the same as it was in openstack
# code, However, *ALL* notifications should have a 'timestamp'
# field, it's part of the notification envelope spec. If this was
# ... | [
"def",
"_extract_when",
"(",
"body",
")",
":",
"# NOTE: I am keeping the logic the same as it was in openstack",
"# code, However, *ALL* notifications should have a 'timestamp'",
"# field, it's part of the notification envelope spec. If this was",
"# put here because some openstack project is gene... | Extract the generated datetime from the notification. | [
"Extract",
"the",
"generated",
"datetime",
"from",
"the",
"notification",
"."
] | python | train |
has2k1/plotnine | plotnine/facets/facet.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet.py#L352-L364 | def make_axes(self, figure, layout, coordinates):
"""
Create and return Matplotlib axes
"""
axs = self._create_subplots(figure, layout)
# Used for labelling the x and y axes, the first and
# last axes according to how MPL creates them.
self.first_ax = figure.axes... | [
"def",
"make_axes",
"(",
"self",
",",
"figure",
",",
"layout",
",",
"coordinates",
")",
":",
"axs",
"=",
"self",
".",
"_create_subplots",
"(",
"figure",
",",
"layout",
")",
"# Used for labelling the x and y axes, the first and",
"# last axes according to how MPL creates... | Create and return Matplotlib axes | [
"Create",
"and",
"return",
"Matplotlib",
"axes"
] | python | train |
quandyfactory/dicttoxml | dicttoxml.py | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L257-L321 | def convert_list(items, ids, parent, attr_type, item_func, cdata):
"""Converts a list into an XML string."""
LOG.info('Inside convert_list()')
output = []
addline = output.append
item_name = item_func(parent)
if ids:
this_id = get_unique_id(parent)
for i, item in enumerate(items):... | [
"def",
"convert_list",
"(",
"items",
",",
"ids",
",",
"parent",
",",
"attr_type",
",",
"item_func",
",",
"cdata",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside convert_list()'",
")",
"output",
"=",
"[",
"]",
"addline",
"=",
"output",
".",
"append",
"item_n... | Converts a list into an XML string. | [
"Converts",
"a",
"list",
"into",
"an",
"XML",
"string",
"."
] | python | train |
saltstack/salt | salt/engines/libvirt_events.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L156-L175 | def _get_libvirt_enum_string(prefix, value):
'''
Convert the libvirt enum integer value into a human readable string.
:param prefix: start of the libvirt attribute to look for.
:param value: integer to convert to string
'''
attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.s... | [
"def",
"_get_libvirt_enum_string",
"(",
"prefix",
",",
"value",
")",
":",
"attributes",
"=",
"[",
"attr",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"for",
"attr",
"in",
"libvirt",
".",
"__dict__",
"if",
"attr",
".",
"startswith",
"(",
"prefix",
")",
"]... | Convert the libvirt enum integer value into a human readable string.
:param prefix: start of the libvirt attribute to look for.
:param value: integer to convert to string | [
"Convert",
"the",
"libvirt",
"enum",
"integer",
"value",
"into",
"a",
"human",
"readable",
"string",
"."
] | python | train |
Yipit/elasticfun | elasticfun/queryset.py | https://github.com/Yipit/elasticfun/blob/dc85b93d49818d09c26fb3a5015fdb25535bd2d7/elasticfun/queryset.py#L32-L50 | def search(self, query, index='default', **kwargs):
"""
kwargs supported are the parameters listed at:
http://www.elasticsearch.org/guide/reference/api/search/request-body/
Namely: timeout, from, size and search_type.
IMPORTANT: prepend ALL keys with "es_" as pyelasticsearch ... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"index",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Looking up the index",
"if",
"index",
"not",
"in",
"self",
".",
"conf",
".",
"indexes",
":",
"self",
".",
"raise_improperly_configured",
"(",
... | kwargs supported are the parameters listed at:
http://www.elasticsearch.org/guide/reference/api/search/request-body/
Namely: timeout, from, size and search_type.
IMPORTANT: prepend ALL keys with "es_" as pyelasticsearch requires this | [
"kwargs",
"supported",
"are",
"the",
"parameters",
"listed",
"at",
":",
"http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"reference",
"/",
"api",
"/",
"search",
"/",
"request",
"-",
"body",
"/",
"Namely",
":",
"timeout",
"... | python | train |
jciskey/pygraph | pygraph/functions/spanning_tree.py | https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/functions/spanning_tree.py#L65-L101 | def kruskal_mst(graph):
"""Implements Kruskal's Algorithm for finding minimum spanning trees.
Assumes a non-empty, connected graph.
"""
edges_accepted = 0
ds = DisjointSet()
pq = PriorityQueue()
accepted_edges = []
label_lookup = {}
nodes = graph.get_all_node_ids()
num_vertices ... | [
"def",
"kruskal_mst",
"(",
"graph",
")",
":",
"edges_accepted",
"=",
"0",
"ds",
"=",
"DisjointSet",
"(",
")",
"pq",
"=",
"PriorityQueue",
"(",
")",
"accepted_edges",
"=",
"[",
"]",
"label_lookup",
"=",
"{",
"}",
"nodes",
"=",
"graph",
".",
"get_all_node_... | Implements Kruskal's Algorithm for finding minimum spanning trees.
Assumes a non-empty, connected graph. | [
"Implements",
"Kruskal",
"s",
"Algorithm",
"for",
"finding",
"minimum",
"spanning",
"trees",
".",
"Assumes",
"a",
"non",
"-",
"empty",
"connected",
"graph",
"."
] | python | train |
veeti/decent | decent/validators.py | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L50-L61 | def Msg(validator, message):
"""
Wraps the given validator callable, replacing any error messages raised.
"""
@wraps(Msg)
def built(value):
try:
return validator(value)
except Error as e:
e.message = message
raise e
return built | [
"def",
"Msg",
"(",
"validator",
",",
"message",
")",
":",
"@",
"wraps",
"(",
"Msg",
")",
"def",
"built",
"(",
"value",
")",
":",
"try",
":",
"return",
"validator",
"(",
"value",
")",
"except",
"Error",
"as",
"e",
":",
"e",
".",
"message",
"=",
"m... | Wraps the given validator callable, replacing any error messages raised. | [
"Wraps",
"the",
"given",
"validator",
"callable",
"replacing",
"any",
"error",
"messages",
"raised",
"."
] | python | train |
housecanary/hc-api-python | housecanary/excel/__init__.py | https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/__init__.py#L18-L28 | def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys):
"""Creates an Excel file containing data returned by the Analytics API
Args:
data: Analytics API data as a list of dicts
output_file_name: File name for output Excel file (use .xlsx extension).
""... | [
"def",
"export_analytics_data_to_excel",
"(",
"data",
",",
"output_file_name",
",",
"result_info_key",
",",
"identifier_keys",
")",
":",
"workbook",
"=",
"create_excel_workbook",
"(",
"data",
",",
"result_info_key",
",",
"identifier_keys",
")",
"workbook",
".",
"save"... | Creates an Excel file containing data returned by the Analytics API
Args:
data: Analytics API data as a list of dicts
output_file_name: File name for output Excel file (use .xlsx extension). | [
"Creates",
"an",
"Excel",
"file",
"containing",
"data",
"returned",
"by",
"the",
"Analytics",
"API"
] | python | train |
frictionlessdata/goodtables-py | goodtables/inspector.py | https://github.com/frictionlessdata/goodtables-py/blob/3e7d6891d2f4e342dfafbe0e951e204ccc252a44/goodtables/inspector.py#L330-L340 | def _clean_empty(d):
"""Remove None values from a dict."""
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (_clean_empty(v) for v in d) if v is not None]
return {
k: v for k, v in
((k, _clean_empty(v)) for k, v in d.items())
... | [
"def",
"_clean_empty",
"(",
"d",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"(",
"dict",
",",
"list",
")",
")",
":",
"return",
"d",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"return",
"[",
"v",
"for",
"v",
"in",
"(",
"_clean... | Remove None values from a dict. | [
"Remove",
"None",
"values",
"from",
"a",
"dict",
"."
] | python | train |
chaoss/grimoirelab-manuscripts | manuscripts/report.py | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/report.py#L753-L767 | def create_data_figs(self):
"""
Generate the data and figs files for the report
:return:
"""
logger.info("Generating the report data and figs from %s to %s",
self.start, self.end)
for section in self.sections():
logger.info("Generating %... | [
"def",
"create_data_figs",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Generating the report data and figs from %s to %s\"",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
")",
"for",
"section",
"in",
"self",
".",
"sections",
"(",
")",
":",
"l... | Generate the data and figs files for the report
:return: | [
"Generate",
"the",
"data",
"and",
"figs",
"files",
"for",
"the",
"report"
] | python | train |
google/grr | grr/server/grr_response_server/gui/api_auth_manager.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_auth_manager.py#L71-L83 | def _CreateRouter(self, router_cls, params=None):
"""Creates a router with a given name and params."""
if not router_cls.params_type and params:
raise ApiCallRouterDoesNotExpectParameters(
"%s is not configurable" % router_cls)
rdf_params = None
if router_cls.params_type:
rdf_para... | [
"def",
"_CreateRouter",
"(",
"self",
",",
"router_cls",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"router_cls",
".",
"params_type",
"and",
"params",
":",
"raise",
"ApiCallRouterDoesNotExpectParameters",
"(",
"\"%s is not configurable\"",
"%",
"router_cls",
... | Creates a router with a given name and params. | [
"Creates",
"a",
"router",
"with",
"a",
"given",
"name",
"and",
"params",
"."
] | python | train |
shoebot/shoebot | lib/cornu/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/cornu/__init__.py#L272-L288 | def draw_cornu_flat(x0, y0, t0, t1, s0, c0, flip, cs, ss, cmd):
""" Raph Levien's code draws fast LINETO segments.
"""
for j in range(0, 100):
t = j * .01
s, c = eval_cornu(t0 + t * (t1 - t0))
s *= flip
s -= s0
c -= c0
#print '%', c, s
x = c ... | [
"def",
"draw_cornu_flat",
"(",
"x0",
",",
"y0",
",",
"t0",
",",
"t1",
",",
"s0",
",",
"c0",
",",
"flip",
",",
"cs",
",",
"ss",
",",
"cmd",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"100",
")",
":",
"t",
"=",
"j",
"*",
".01",
"s"... | Raph Levien's code draws fast LINETO segments. | [
"Raph",
"Levien",
"s",
"code",
"draws",
"fast",
"LINETO",
"segments",
"."
] | python | valid |
mikedh/trimesh | trimesh/graph.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/graph.py#L136-L186 | def face_adjacency_radius(mesh):
"""
Compute an approximate radius between adjacent faces.
Parameters
--------------
mesh : trimesh.Trimesh
Returns
-------------
radii : (len(self.face_adjacency),) float
Approximate radius between faces
Parallel faces will have a value ... | [
"def",
"face_adjacency_radius",
"(",
"mesh",
")",
":",
"# solve for the radius of the adjacent faces",
"# distance",
"# R = ------------------",
"# 2 * sin(theta / 2)",
"nonzero",
"=",
"mesh",
".",
"face_adjacency_angles",
">",
"np",
".",
"radians",
"(",
".01",
... | Compute an approximate radius between adjacent faces.
Parameters
--------------
mesh : trimesh.Trimesh
Returns
-------------
radii : (len(self.face_adjacency),) float
Approximate radius between faces
Parallel faces will have a value of np.inf
span : (len(self.face_adjacenc... | [
"Compute",
"an",
"approximate",
"radius",
"between",
"adjacent",
"faces",
"."
] | python | train |
abw333/dominoes | dominoes/search.py | https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/search.py#L5-L38 | def make_moves(game, player=dominoes.players.identity):
'''
For each of a Game object's valid moves, yields
a tuple containing the move and the Game object
obtained by playing the move on the original Game
object. The original Game object will be modified.
:param Game game: the game to make mov... | [
"def",
"make_moves",
"(",
"game",
",",
"player",
"=",
"dominoes",
".",
"players",
".",
"identity",
")",
":",
"# game is over - do not yield anything",
"if",
"game",
".",
"result",
"is",
"not",
"None",
":",
"return",
"# determine the order in which to make moves",
"p... | For each of a Game object's valid moves, yields
a tuple containing the move and the Game object
obtained by playing the move on the original Game
object. The original Game object will be modified.
:param Game game: the game to make moves on
:param callable player: a player to call on the
... | [
"For",
"each",
"of",
"a",
"Game",
"object",
"s",
"valid",
"moves",
"yields",
"a",
"tuple",
"containing",
"the",
"move",
"and",
"the",
"Game",
"object",
"obtained",
"by",
"playing",
"the",
"move",
"on",
"the",
"original",
"Game",
"object",
".",
"The",
"or... | python | train |
thiagopbueno/pyrddl | pyrddl/parser.py | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L273-L276 | def p_domain_block(self, p):
'''domain_block : DOMAIN IDENT LCURLY req_section domain_list RCURLY'''
d = Domain(p[2], p[4], p[5])
p[0] = ('domain', d) | [
"def",
"p_domain_block",
"(",
"self",
",",
"p",
")",
":",
"d",
"=",
"Domain",
"(",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"4",
"]",
",",
"p",
"[",
"5",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"(",
"'domain'",
",",
"d",
")"
] | domain_block : DOMAIN IDENT LCURLY req_section domain_list RCURLY | [
"domain_block",
":",
"DOMAIN",
"IDENT",
"LCURLY",
"req_section",
"domain_list",
"RCURLY"
] | python | train |
sp4ke/howto | howto/howto.py | https://github.com/sp4ke/howto/blob/2588144a587be5138d45ca9db0ce6ab125fa7d0c/howto/howto.py#L78-L84 | def cli_run():
"""docstring for argparse"""
parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')
parser.add_argument('query', help="What's the problem ?", type=str, nargs='+')
parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')
... | [
"def",
"cli_run",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Stupidly simple code answers from StackOverflow'",
")",
"parser",
".",
"add_argument",
"(",
"'query'",
",",
"help",
"=",
"\"What's the problem ?\"",
",",
"t... | docstring for argparse | [
"docstring",
"for",
"argparse"
] | python | test |
wummel/linkchecker | linkcheck/containers.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/containers.py#L60-L64 | def pop (self, key):
"""Remove key from dict and return value."""
if key in self._keys:
self._keys.remove(key)
super(ListDict, self).pop(key) | [
"def",
"pop",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_keys",
":",
"self",
".",
"_keys",
".",
"remove",
"(",
"key",
")",
"super",
"(",
"ListDict",
",",
"self",
")",
".",
"pop",
"(",
"key",
")"
] | Remove key from dict and return value. | [
"Remove",
"key",
"from",
"dict",
"and",
"return",
"value",
"."
] | python | train |
sighingnow/parsec.py | src/parsec/__init__.py | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L165-L174 | def choice(self, other):
'''(|) This combinator implements choice. The parser p | q first applies p.
If it succeeds, the value of p is returned.
If p fails **without consuming any input**, parser q is tried.
NOTICE: without backtrack.'''
@Parser
def choice_parser(text, in... | [
"def",
"choice",
"(",
"self",
",",
"other",
")",
":",
"@",
"Parser",
"def",
"choice_parser",
"(",
"text",
",",
"index",
")",
":",
"res",
"=",
"self",
"(",
"text",
",",
"index",
")",
"return",
"res",
"if",
"res",
".",
"status",
"or",
"res",
".",
"... | (|) This combinator implements choice. The parser p | q first applies p.
If it succeeds, the value of p is returned.
If p fails **without consuming any input**, parser q is tried.
NOTICE: without backtrack. | [
"(",
"|",
")",
"This",
"combinator",
"implements",
"choice",
".",
"The",
"parser",
"p",
"|",
"q",
"first",
"applies",
"p",
".",
"If",
"it",
"succeeds",
"the",
"value",
"of",
"p",
"is",
"returned",
".",
"If",
"p",
"fails",
"**",
"without",
"consuming",
... | python | train |
apache/incubator-mxnet | example/ssd/config/utils.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/config/utils.py#L78-L90 | def zip_namedtuple(nt_list):
""" accept list of namedtuple, return a dict of zipped fields """
if not nt_list:
return dict()
if not isinstance(nt_list, list):
nt_list = [nt_list]
for nt in nt_list:
assert type(nt) == type(nt_list[0])
ret = {k : [v] for k, v in nt_list[0]._asd... | [
"def",
"zip_namedtuple",
"(",
"nt_list",
")",
":",
"if",
"not",
"nt_list",
":",
"return",
"dict",
"(",
")",
"if",
"not",
"isinstance",
"(",
"nt_list",
",",
"list",
")",
":",
"nt_list",
"=",
"[",
"nt_list",
"]",
"for",
"nt",
"in",
"nt_list",
":",
"ass... | accept list of namedtuple, return a dict of zipped fields | [
"accept",
"list",
"of",
"namedtuple",
"return",
"a",
"dict",
"of",
"zipped",
"fields"
] | python | train |
terrycain/aioboto3 | aioboto3/s3/inject.py | https://github.com/terrycain/aioboto3/blob/0fd192175461f7bb192f3ed9a872591caf8474ac/aioboto3/s3/inject.py#L206-L219 | async def upload_file(self, Filename, Bucket, Key, ExtraArgs=None, Callback=None, Config=None):
"""Upload a file to an S3 object.
Usage::
import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')
Similar behavior as S3Transfer's u... | [
"async",
"def",
"upload_file",
"(",
"self",
",",
"Filename",
",",
"Bucket",
",",
"Key",
",",
"ExtraArgs",
"=",
"None",
",",
"Callback",
"=",
"None",
",",
"Config",
"=",
"None",
")",
":",
"with",
"open",
"(",
"Filename",
",",
"'rb'",
")",
"as",
"open_... | Upload a file to an S3 object.
Usage::
import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')
Similar behavior as S3Transfer's upload_file() method,
except that parameters are capitalized. | [
"Upload",
"a",
"file",
"to",
"an",
"S3",
"object",
"."
] | python | train |
serge-sans-paille/pythran | setup.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/setup.py#L75-L95 | def copy_pkg(self, pkg, src_only=False):
"Install boost deps from the third_party directory"
if getattr(self, 'no_' + pkg) is None:
print('Copying boost dependencies')
to_copy = pkg,
else:
return
src = os.path.join('third_party', *to_copy)
#... | [
"def",
"copy_pkg",
"(",
"self",
",",
"pkg",
",",
"src_only",
"=",
"False",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'no_'",
"+",
"pkg",
")",
"is",
"None",
":",
"print",
"(",
"'Copying boost dependencies'",
")",
"to_copy",
"=",
"pkg",
",",
"else",
... | Install boost deps from the third_party directory | [
"Install",
"boost",
"deps",
"from",
"the",
"third_party",
"directory"
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L476-L489 | def overlay_gateway_enable_statistics_vlan_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
... | [
"def",
"overlay_gateway_enable_statistics_vlan_action",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
nschloe/orthopy | orthopy/disk/orth.py | https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/disk/orth.py#L9-L89 | def tree(X, n, symbolic=False):
"""Evaluates the entire tree of orthogonal polynomials on the unit disk.
The return value is a list of arrays, where `out[k]` hosts the `2*k+1`
values of the `k`th level of the tree
(0, 0)
(0, 1) (1, 1)
(0, 2) (1, 2) (2, 2)
... .... | [
"def",
"tree",
"(",
"X",
",",
"n",
",",
"symbolic",
"=",
"False",
")",
":",
"frac",
"=",
"sympy",
".",
"Rational",
"if",
"symbolic",
"else",
"lambda",
"x",
",",
"y",
":",
"x",
"/",
"y",
"sqrt",
"=",
"sympy",
".",
"sqrt",
"if",
"symbolic",
"else",... | Evaluates the entire tree of orthogonal polynomials on the unit disk.
The return value is a list of arrays, where `out[k]` hosts the `2*k+1`
values of the `k`th level of the tree
(0, 0)
(0, 1) (1, 1)
(0, 2) (1, 2) (2, 2)
... ... ... | [
"Evaluates",
"the",
"entire",
"tree",
"of",
"orthogonal",
"polynomials",
"on",
"the",
"unit",
"disk",
"."
] | python | train |
aouyar/PyMunin | pymunin/__init__.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/__init__.py#L768-L791 | def run(self):
"""Implements main entry point for plugin execution."""
if len(self._argv) > 1 and len(self._argv[1]) > 0:
oper = self._argv[1]
else:
oper = 'fetch'
if oper == 'fetch':
ret = self.fetch()
elif oper == 'config':
ret = ... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_argv",
")",
">",
"1",
"and",
"len",
"(",
"self",
".",
"_argv",
"[",
"1",
"]",
")",
">",
"0",
":",
"oper",
"=",
"self",
".",
"_argv",
"[",
"1",
"]",
"else",
":",
"oper",
... | Implements main entry point for plugin execution. | [
"Implements",
"main",
"entry",
"point",
"for",
"plugin",
"execution",
"."
] | python | train |
mrcagney/gtfstk | gtfstk/miscellany.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L808-L891 | def restrict_to_polygon(feed: "Feed", polygon: Polygon) -> "Feed":
"""
Build a new feed by restricting this one to only the trips
that have at least one stop intersecting the given Shapely polygon,
then restricting stops, routes, stop times, etc. to those
associated with that subset of trips.
Re... | [
"def",
"restrict_to_polygon",
"(",
"feed",
":",
"\"Feed\"",
",",
"polygon",
":",
"Polygon",
")",
"->",
"\"Feed\"",
":",
"# Initialize the new feed as the old feed.",
"# Restrict its DataFrames below.",
"feed",
"=",
"feed",
".",
"copy",
"(",
")",
"# Get IDs of stops with... | Build a new feed by restricting this one to only the trips
that have at least one stop intersecting the given Shapely polygon,
then restricting stops, routes, stop times, etc. to those
associated with that subset of trips.
Return the resulting feed.
Requires GeoPandas.
Assume the following fee... | [
"Build",
"a",
"new",
"feed",
"by",
"restricting",
"this",
"one",
"to",
"only",
"the",
"trips",
"that",
"have",
"at",
"least",
"one",
"stop",
"intersecting",
"the",
"given",
"Shapely",
"polygon",
"then",
"restricting",
"stops",
"routes",
"stop",
"times",
"etc... | python | train |
Erotemic/utool | utool/Printable.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Printable.py#L96-L118 | def printableType(val, name=None, parent=None):
"""
Tries to make a nice type string for a value.
Can also pass in a Printable parent object
"""
import numpy as np
if parent is not None and hasattr(parent, 'customPrintableType'):
# Hack for non - trivial preference types
_typestr... | [
"def",
"printableType",
"(",
"val",
",",
"name",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"parent",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"parent",
",",
"'customPrintableType'",
")",
":",
"# Hack for n... | Tries to make a nice type string for a value.
Can also pass in a Printable parent object | [
"Tries",
"to",
"make",
"a",
"nice",
"type",
"string",
"for",
"a",
"value",
".",
"Can",
"also",
"pass",
"in",
"a",
"Printable",
"parent",
"object"
] | python | train |
pyopenapi/pyswagger | pyswagger/scanner/v1_2/validate.py | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L115-L122 | def _validate_granttype(self, path, obj, _):
""" make sure either implicit or authorization_code is defined """
errs = []
if not obj.implicit and not obj.authorization_code:
errs.append('Either implicit or authorization_code should be defined.')
return path, obj.__class__._... | [
"def",
"_validate_granttype",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"not",
"obj",
".",
"implicit",
"and",
"not",
"obj",
".",
"authorization_code",
":",
"errs",
".",
"append",
"(",
"'Either implicit or auth... | make sure either implicit or authorization_code is defined | [
"make",
"sure",
"either",
"implicit",
"or",
"authorization_code",
"is",
"defined"
] | python | train |
IAMconsortium/pyam | pyam/core.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L749-L801 | def aggregate_region(self, variable, region='World', subregions=None,
components=None, append=False):
"""Compute the aggregate of timeseries over a number of regions
including variable components only defined at the `region` level
Parameters
----------
v... | [
"def",
"aggregate_region",
"(",
"self",
",",
"variable",
",",
"region",
"=",
"'World'",
",",
"subregions",
"=",
"None",
",",
"components",
"=",
"None",
",",
"append",
"=",
"False",
")",
":",
"# default subregions to all regions other than `region`",
"if",
"subregi... | Compute the aggregate of timeseries over a number of regions
including variable components only defined at the `region` level
Parameters
----------
variable: str
variable for which the aggregate should be computed
region: str, default 'World'
dimension
... | [
"Compute",
"the",
"aggregate",
"of",
"timeseries",
"over",
"a",
"number",
"of",
"regions",
"including",
"variable",
"components",
"only",
"defined",
"at",
"the",
"region",
"level"
] | python | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/zip.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/zip.py#L94-L130 | def unzip_from_uri(uri, layer_zip_path, unzip_output_dir, progressbar_label):
"""
Download the LayerVersion Zip to the Layer Pkg Cache
Parameters
----------
uri str
Uri to download from
layer_zip_path str
Path to where the content from the uri should be downloaded to
unzip_o... | [
"def",
"unzip_from_uri",
"(",
"uri",
",",
"layer_zip_path",
",",
"unzip_output_dir",
",",
"progressbar_label",
")",
":",
"try",
":",
"get_request",
"=",
"requests",
".",
"get",
"(",
"uri",
",",
"stream",
"=",
"True",
",",
"verify",
"=",
"os",
".",
"environ... | Download the LayerVersion Zip to the Layer Pkg Cache
Parameters
----------
uri str
Uri to download from
layer_zip_path str
Path to where the content from the uri should be downloaded to
unzip_output_dir str
Path to unzip the zip to
progressbar_label str
Label to ... | [
"Download",
"the",
"LayerVersion",
"Zip",
"to",
"the",
"Layer",
"Pkg",
"Cache"
] | python | train |
d0c-s4vage/pfp | pfp/bitwrap.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L70-L80 | def is_eof(self):
"""Return if the stream has reached EOF or not
without discarding any unflushed bits
:returns: True/False
"""
pos = self._stream.tell()
byte = self._stream.read(1)
self._stream.seek(pos, 0)
return utils.binary(byte) == utils.binary("") | [
"def",
"is_eof",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"_stream",
".",
"tell",
"(",
")",
"byte",
"=",
"self",
".",
"_stream",
".",
"read",
"(",
"1",
")",
"self",
".",
"_stream",
".",
"seek",
"(",
"pos",
",",
"0",
")",
"return",
"utils... | Return if the stream has reached EOF or not
without discarding any unflushed bits
:returns: True/False | [
"Return",
"if",
"the",
"stream",
"has",
"reached",
"EOF",
"or",
"not",
"without",
"discarding",
"any",
"unflushed",
"bits"
] | python | train |
GNS3/gns3-server | gns3server/controller/__init__.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L580-L586 | def _project_auto_open(self):
"""
Auto open the project with auto open enable
"""
for project in self._projects.values():
if project.auto_open:
yield from project.open() | [
"def",
"_project_auto_open",
"(",
"self",
")",
":",
"for",
"project",
"in",
"self",
".",
"_projects",
".",
"values",
"(",
")",
":",
"if",
"project",
".",
"auto_open",
":",
"yield",
"from",
"project",
".",
"open",
"(",
")"
] | Auto open the project with auto open enable | [
"Auto",
"open",
"the",
"project",
"with",
"auto",
"open",
"enable"
] | python | train |
DLR-RM/RAFCON | source/rafcon/core/states/container_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1047-L1070 | def change_state_type(self, state, new_state_class):
""" Changes the type of the state to another type
:param state: the state to be changed
:param new_state_class: the new type of the state
:return: the new state having the new state type
:rtype: :py:class:`rafcon.core.states.s... | [
"def",
"change_state_type",
"(",
"self",
",",
"state",
",",
"new_state_class",
")",
":",
"from",
"rafcon",
".",
"gui",
".",
"helpers",
".",
"state",
"import",
"create_new_state_from_state_with_type",
"state_id",
"=",
"state",
".",
"state_id",
"if",
"state_id",
"... | Changes the type of the state to another type
:param state: the state to be changed
:param new_state_class: the new type of the state
:return: the new state having the new state type
:rtype: :py:class:`rafcon.core.states.state.State`
:raises exceptions.ValueError: if the state d... | [
"Changes",
"the",
"type",
"of",
"the",
"state",
"to",
"another",
"type"
] | python | train |
tdryer/hangups | hangups/conversation.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L874-L906 | async def _get_or_fetch_conversation(self, conv_id):
"""Get a cached conversation or fetch a missing conversation.
Args:
conv_id: string, conversation identifier
Raises:
NetworkError: If the request to fetch the conversation fails.
Returns:
:class:`... | [
"async",
"def",
"_get_or_fetch_conversation",
"(",
"self",
",",
"conv_id",
")",
":",
"conv",
"=",
"self",
".",
"_conv_dict",
".",
"get",
"(",
"conv_id",
",",
"None",
")",
"if",
"conv",
"is",
"None",
":",
"logger",
".",
"info",
"(",
"'Fetching unknown conve... | Get a cached conversation or fetch a missing conversation.
Args:
conv_id: string, conversation identifier
Raises:
NetworkError: If the request to fetch the conversation fails.
Returns:
:class:`.Conversation` with matching ID. | [
"Get",
"a",
"cached",
"conversation",
"or",
"fetch",
"a",
"missing",
"conversation",
"."
] | python | valid |
openvax/mhcnames | mhcnames/class2.py | https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/class2.py#L21-L39 | def infer_alpha_chain(beta):
"""
Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain.
"""
if beta.gene.startswith("DRB"):
return AlleleName(species="HLA", gene="DRA1", allele_family="01", allele_code="01")
elif beta.gene.startswith("DPB"):
... | [
"def",
"infer_alpha_chain",
"(",
"beta",
")",
":",
"if",
"beta",
".",
"gene",
".",
"startswith",
"(",
"\"DRB\"",
")",
":",
"return",
"AlleleName",
"(",
"species",
"=",
"\"HLA\"",
",",
"gene",
"=",
"\"DRA1\"",
",",
"allele_family",
"=",
"\"01\"",
",",
"al... | Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain. | [
"Given",
"a",
"parsed",
"beta",
"chain",
"of",
"a",
"class",
"II",
"MHC",
"infer",
"the",
"most",
"frequent",
"corresponding",
"alpha",
"chain",
"."
] | python | train |
allenai/allennlp | allennlp/common/util.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L177-L206 | def prepare_environment(params: Params):
"""
Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
yo... | [
"def",
"prepare_environment",
"(",
"params",
":",
"Params",
")",
":",
"seed",
"=",
"params",
".",
"pop_int",
"(",
"\"random_seed\"",
",",
"13370",
")",
"numpy_seed",
"=",
"params",
".",
"pop_int",
"(",
"\"numpy_seed\"",
",",
"1337",
")",
"torch_seed",
"=",
... | Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
your experiments should be reasonably reproducible. If ... | [
"Sets",
"random",
"seeds",
"for",
"reproducible",
"experiments",
".",
"This",
"may",
"not",
"work",
"as",
"expected",
"if",
"you",
"use",
"this",
"from",
"within",
"a",
"python",
"project",
"in",
"which",
"you",
"have",
"already",
"imported",
"Pytorch",
".",... | python | train |
Qiskit/qiskit-terra | qiskit/compiler/transpiler.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/compiler/transpiler.py#L153-L178 | def _transpile_circuit(circuit_config_tuple):
"""Select a PassManager and run a single circuit through it.
Args:
circuit_config_tuple (tuple):
circuit (QuantumCircuit): circuit to transpile
transpile_config (TranspileConfig): configuration dictating how to transpile
Returns... | [
"def",
"_transpile_circuit",
"(",
"circuit_config_tuple",
")",
":",
"circuit",
",",
"transpile_config",
"=",
"circuit_config_tuple",
"# if the pass manager is not already selected, choose an appropriate one.",
"if",
"transpile_config",
".",
"pass_manager",
":",
"pass_manager",
"=... | Select a PassManager and run a single circuit through it.
Args:
circuit_config_tuple (tuple):
circuit (QuantumCircuit): circuit to transpile
transpile_config (TranspileConfig): configuration dictating how to transpile
Returns:
QuantumCircuit: transpiled circuit | [
"Select",
"a",
"PassManager",
"and",
"run",
"a",
"single",
"circuit",
"through",
"it",
"."
] | python | test |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L230-L257 | def _queue_dag(self, name, *, data=None):
""" Add a new dag to the queue.
If the stop workflow flag is set, no new dag can be queued.
Args:
name (str): The name of the dag that should be queued.
data (MultiTaskData): The data that should be passed on to the new dag.
... | [
"def",
"_queue_dag",
"(",
"self",
",",
"name",
",",
"*",
",",
"data",
"=",
"None",
")",
":",
"if",
"self",
".",
"_stop_workflow",
":",
"return",
"None",
"if",
"name",
"not",
"in",
"self",
".",
"_dags_blueprint",
":",
"raise",
"DagNameUnknown",
"(",
")"... | Add a new dag to the queue.
If the stop workflow flag is set, no new dag can be queued.
Args:
name (str): The name of the dag that should be queued.
data (MultiTaskData): The data that should be passed on to the new dag.
Raises:
DagNameUnknown: If the speci... | [
"Add",
"a",
"new",
"dag",
"to",
"the",
"queue",
"."
] | python | train |
rhayes777/PyAutoFit | autofit/tools/pipeline.py | https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/tools/pipeline.py#L74-L97 | def from_phase(self, phase_name):
"""
Returns the result of a previous phase by its name
Parameters
----------
phase_name: str
The name of a previous phase
Returns
-------
result: Result
The result of that phase
Raises
... | [
"def",
"from_phase",
"(",
"self",
",",
"phase_name",
")",
":",
"try",
":",
"return",
"self",
".",
"__result_dict",
"[",
"phase_name",
"]",
"except",
"KeyError",
":",
"raise",
"exc",
".",
"PipelineException",
"(",
"\"No previous phase named {} found in results ({})\"... | Returns the result of a previous phase by its name
Parameters
----------
phase_name: str
The name of a previous phase
Returns
-------
result: Result
The result of that phase
Raises
------
exc.PipelineException
... | [
"Returns",
"the",
"result",
"of",
"a",
"previous",
"phase",
"by",
"its",
"name"
] | python | train |
drslump/pyshould | pyshould/dsl.py | https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/dsl.py#L51-L57 | def none_of(value, *args):
""" None of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationNone(value) | [
"def",
"none_of",
"(",
"value",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
":",
"value",
"=",
"(",
"value",
",",
")",
"+",
"args",
"return",
"ExpectationNone",
"(",
"value",
")"
] | None of the items in value should match | [
"None",
"of",
"the",
"items",
"in",
"value",
"should",
"match"
] | python | train |
ContinuumIO/flask-ldap-login | flask_ldap_login/__init__.py | https://github.com/ContinuumIO/flask-ldap-login/blob/09a08be45f861823cb08f95883ee1e092a618c37/flask_ldap_login/__init__.py#L146-L154 | def attrlist(self):
'Transform the KEY_MAP paramiter into an attrlist for ldap filters'
keymap = self.config.get('KEY_MAP')
if keymap:
# https://github.com/ContinuumIO/flask-ldap-login/issues/11
# https://continuumsupport.zendesk.com/agent/tickets/393
return [... | [
"def",
"attrlist",
"(",
"self",
")",
":",
"keymap",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'KEY_MAP'",
")",
"if",
"keymap",
":",
"# https://github.com/ContinuumIO/flask-ldap-login/issues/11",
"# https://continuumsupport.zendesk.com/agent/tickets/393",
"return",
"["... | Transform the KEY_MAP paramiter into an attrlist for ldap filters | [
"Transform",
"the",
"KEY_MAP",
"paramiter",
"into",
"an",
"attrlist",
"for",
"ldap",
"filters"
] | python | train |
fermiPy/fermipy | fermipy/jobs/file_archive.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L96-L119 | def latch_file_info(self, args):
"""Extract the file paths from a set of arguments
"""
self.file_dict.clear()
for key, val in self.file_args.items():
try:
file_path = args[key]
if file_path is None:
continue
... | [
"def",
"latch_file_info",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"file_dict",
".",
"clear",
"(",
")",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_args",
".",
"items",
"(",
")",
":",
"try",
":",
"file_path",
"=",
"args",
"[",
"key",... | Extract the file paths from a set of arguments | [
"Extract",
"the",
"file",
"paths",
"from",
"a",
"set",
"of",
"arguments"
] | python | train |
scopus-api/scopus | scopus/abstract_citations.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_citations.py#L28-L35 | def cc(self):
"""List of tuples of yearly number of citations
for specified years."""
_years = range(self._start, self._end+1)
try:
return list(zip(_years, [d.get('$') for d in self._citeInfoMatrix['cc']]))
except AttributeError: # No citations
return lis... | [
"def",
"cc",
"(",
"self",
")",
":",
"_years",
"=",
"range",
"(",
"self",
".",
"_start",
",",
"self",
".",
"_end",
"+",
"1",
")",
"try",
":",
"return",
"list",
"(",
"zip",
"(",
"_years",
",",
"[",
"d",
".",
"get",
"(",
"'$'",
")",
"for",
"d",
... | List of tuples of yearly number of citations
for specified years. | [
"List",
"of",
"tuples",
"of",
"yearly",
"number",
"of",
"citations",
"for",
"specified",
"years",
"."
] | python | train |
PMEAL/OpenPNM | openpnm/core/Base.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/core/Base.py#L702-L770 | def pores(self, labels='all', mode='or', asmask=False):
r"""
Returns pore indicies where given labels exist, according to the logic
specified by the ``mode`` argument.
Parameters
----------
labels : string or list of strings
The label(s) whose pores locations... | [
"def",
"pores",
"(",
"self",
",",
"labels",
"=",
"'all'",
",",
"mode",
"=",
"'or'",
",",
"asmask",
"=",
"False",
")",
":",
"ind",
"=",
"self",
".",
"_get_indices",
"(",
"element",
"=",
"'pore'",
",",
"labels",
"=",
"labels",
",",
"mode",
"=",
"mode... | r"""
Returns pore indicies where given labels exist, according to the logic
specified by the ``mode`` argument.
Parameters
----------
labels : string or list of strings
The label(s) whose pores locations are requested. This argument
also accepts '*' for ... | [
"r",
"Returns",
"pore",
"indicies",
"where",
"given",
"labels",
"exist",
"according",
"to",
"the",
"logic",
"specified",
"by",
"the",
"mode",
"argument",
"."
] | python | train |
s-m-i-t-a/railroad | railroad/guard.py | https://github.com/s-m-i-t-a/railroad/blob/ddb4afa018b8523b5d8c3a86e55388d1ea0ab37c/railroad/guard.py#L36-L56 | def guard(params, guardian, error_class=GuardError, message=''):
'''
A guard function - check parameters
with guardian function on decorated function
:param tuple or string params: guarded function parameter/s
:param function guardian: verifying the conditions for the selected parameter
:param ... | [
"def",
"guard",
"(",
"params",
",",
"guardian",
",",
"error_class",
"=",
"GuardError",
",",
"message",
"=",
"''",
")",
":",
"params",
"=",
"[",
"params",
"]",
"if",
"isinstance",
"(",
"params",
",",
"string_types",
")",
"else",
"params",
"def",
"guard_de... | A guard function - check parameters
with guardian function on decorated function
:param tuple or string params: guarded function parameter/s
:param function guardian: verifying the conditions for the selected parameter
:param Exception error_class: raised class when guardian return false
:param str... | [
"A",
"guard",
"function",
"-",
"check",
"parameters",
"with",
"guardian",
"function",
"on",
"decorated",
"function"
] | python | train |
thomasdelaet/python-velbus | velbus/messages/write_module_address_and_serial_number.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/write_module_address_and_serial_number.py#L31-L45 | def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_firmware_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 6)
self.set_attributes(priority, address, rtr)
self.module_ty... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_firmware_priority",
"(",
"priority",
")",
"self",
".",
"needs_no_rtr",
"(",
"r... | :return: None | [
":",
"return",
":",
"None"
] | python | train |
mmp2/megaman | megaman/geometry/geometry.py | https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/geometry/geometry.py#L154-L182 | def compute_adjacency_matrix(self, copy=False, **kwargs):
"""
This function will compute the adjacency matrix.
In order to acquire the existing adjacency matrix use
self.adjacency_matrix as comptute_adjacency_matrix() will re-compute
the adjacency matrix.
Parameters
... | [
"def",
"compute_adjacency_matrix",
"(",
"self",
",",
"copy",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"X",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"distance_error_msg",
")",
"kwds",
"=",
"self",
".",
"adjacency_kwds",
".... | This function will compute the adjacency matrix.
In order to acquire the existing adjacency matrix use
self.adjacency_matrix as comptute_adjacency_matrix() will re-compute
the adjacency matrix.
Parameters
----------
copy : boolean, whether to return a copied version of t... | [
"This",
"function",
"will",
"compute",
"the",
"adjacency",
"matrix",
".",
"In",
"order",
"to",
"acquire",
"the",
"existing",
"adjacency",
"matrix",
"use",
"self",
".",
"adjacency_matrix",
"as",
"comptute_adjacency_matrix",
"()",
"will",
"re",
"-",
"compute",
"th... | python | train |
hyperledger/sawtooth-core | validator/sawtooth_validator/execution/execution_context.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/execution/execution_context.py#L198-L212 | def get_all_if_set(self):
"""Return all the addresses and opaque values set in the context.
Useful in the squash method.
Returns:
(dict of str to bytes): The addresses and bytes that have
been set in the context.
"""
with self._lock:
resu... | [
"def",
"get_all_if_set",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"results",
"=",
"{",
"}",
"for",
"add",
",",
"fut",
"in",
"self",
".",
"_state",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"_contains_and_set",
"(",
"add",
")"... | Return all the addresses and opaque values set in the context.
Useful in the squash method.
Returns:
(dict of str to bytes): The addresses and bytes that have
been set in the context. | [
"Return",
"all",
"the",
"addresses",
"and",
"opaque",
"values",
"set",
"in",
"the",
"context",
".",
"Useful",
"in",
"the",
"squash",
"method",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/vasp/inputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/inputs.py#L1081-L1116 | def automatic_gamma_density(structure, kppa):
"""
Returns an automatic Kpoint object based on a structure and a kpoint
density. Uses Gamma centered meshes always. For GW.
Algorithm:
Uses a simple approach scaling the number of divisions along each
reciprocal latt... | [
"def",
"automatic_gamma_density",
"(",
"structure",
",",
"kppa",
")",
":",
"latt",
"=",
"structure",
".",
"lattice",
"lengths",
"=",
"latt",
".",
"abc",
"ngrid",
"=",
"kppa",
"/",
"structure",
".",
"num_sites",
"mult",
"=",
"(",
"ngrid",
"*",
"lengths",
... | Returns an automatic Kpoint object based on a structure and a kpoint
density. Uses Gamma centered meshes always. For GW.
Algorithm:
Uses a simple approach scaling the number of divisions along each
reciprocal lattice vector proportional to its length.
Args:
... | [
"Returns",
"an",
"automatic",
"Kpoint",
"object",
"based",
"on",
"a",
"structure",
"and",
"a",
"kpoint",
"density",
".",
"Uses",
"Gamma",
"centered",
"meshes",
"always",
".",
"For",
"GW",
"."
] | python | train |
QuantEcon/QuantEcon.py | quantecon/markov/core.py | https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/markov/core.py#L441-L527 | def simulate_indices(self, ts_length, init=None, num_reps=None,
random_state=None):
"""
Simulate time series of state transitions, where state indices
are returned.
Parameters
----------
ts_length : scalar(int)
Length of each simulati... | [
"def",
"simulate_indices",
"(",
"self",
",",
"ts_length",
",",
"init",
"=",
"None",
",",
"num_reps",
"=",
"None",
",",
"random_state",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"dim",
"=",
"1",
"# Dimension o... | Simulate time series of state transitions, where state indices
are returned.
Parameters
----------
ts_length : scalar(int)
Length of each simulation.
init : int or array_like(int, ndim=1), optional
Initial state(s). If None, the initial state is randomly... | [
"Simulate",
"time",
"series",
"of",
"state",
"transitions",
"where",
"state",
"indices",
"are",
"returned",
"."
] | python | train |
tjcsl/cslbot | cslbot/helpers/handler.py | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L186-L213 | def send(self, target, nick, msg, msgtype, ignore_length=False, filters=None):
"""Send a message.
Records the message in the log.
"""
if not isinstance(msg, str):
raise Exception("Trying to send a %s to irc, only strings allowed." % type(msg).__name__)
if filters is... | [
"def",
"send",
"(",
"self",
",",
"target",
",",
"nick",
",",
"msg",
",",
"msgtype",
",",
"ignore_length",
"=",
"False",
",",
"filters",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"str",
")",
":",
"raise",
"Exception",
"(",
"... | Send a message.
Records the message in the log. | [
"Send",
"a",
"message",
"."
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/mask_flags.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/mask_flags.py#L50-L64 | def parse_helpfull_output(help_output, regex=FLAG_HELP_RE_PY):
"""Parses the output of --helpfull.
Args:
help_output: str, the full output of --helpfull.
Returns:
A set of flags that are valid flags.
"""
valid_flags = set()
for _, no_prefix, flag_name in regex.findall(help_outp... | [
"def",
"parse_helpfull_output",
"(",
"help_output",
",",
"regex",
"=",
"FLAG_HELP_RE_PY",
")",
":",
"valid_flags",
"=",
"set",
"(",
")",
"for",
"_",
",",
"no_prefix",
",",
"flag_name",
"in",
"regex",
".",
"findall",
"(",
"help_output",
")",
":",
"valid_flags... | Parses the output of --helpfull.
Args:
help_output: str, the full output of --helpfull.
Returns:
A set of flags that are valid flags. | [
"Parses",
"the",
"output",
"of",
"--",
"helpfull",
"."
] | python | train |
evhub/coconut | coconut/compiler/compiler.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/compiler.py#L457-L469 | def adjust(self, ln):
"""Converts a parsing line number into an original line number."""
adj_ln = ln
need_unskipped = 0
for i in self.skips:
if i <= ln:
need_unskipped += 1
elif adj_ln + need_unskipped < i:
break
else:
... | [
"def",
"adjust",
"(",
"self",
",",
"ln",
")",
":",
"adj_ln",
"=",
"ln",
"need_unskipped",
"=",
"0",
"for",
"i",
"in",
"self",
".",
"skips",
":",
"if",
"i",
"<=",
"ln",
":",
"need_unskipped",
"+=",
"1",
"elif",
"adj_ln",
"+",
"need_unskipped",
"<",
... | Converts a parsing line number into an original line number. | [
"Converts",
"a",
"parsing",
"line",
"number",
"into",
"an",
"original",
"line",
"number",
"."
] | python | train |
quantopian/alphalens | alphalens/plotting.py | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L192-L245 | def plot_ic_ts(ic, ax=None):
"""
Plots Spearman Rank Information Coefficient and IC moving
average for a given factor.
Parameters
----------
ic : pd.DataFrame
DataFrame indexed by date, with IC for each forward return.
ax : matplotlib.Axes, optional
Axes upon which to plot.
... | [
"def",
"plot_ic_ts",
"(",
"ic",
",",
"ax",
"=",
"None",
")",
":",
"ic",
"=",
"ic",
".",
"copy",
"(",
")",
"num_plots",
"=",
"len",
"(",
"ic",
".",
"columns",
")",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"("... | Plots Spearman Rank Information Coefficient and IC moving
average for a given factor.
Parameters
----------
ic : pd.DataFrame
DataFrame indexed by date, with IC for each forward return.
ax : matplotlib.Axes, optional
Axes upon which to plot.
Returns
-------
ax : matplot... | [
"Plots",
"Spearman",
"Rank",
"Information",
"Coefficient",
"and",
"IC",
"moving",
"average",
"for",
"a",
"given",
"factor",
"."
] | python | train |
RRZE-HPC/kerncraft | kerncraft/iaca.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/iaca.py#L251-L284 | def userselect_block(blocks, default=None, debug=False):
"""Let user interactively select block."""
print("Blocks found in assembly file:")
print(" block | OPs | pck. | AVX || Registers | ZMM | YMM | XMM | GP ||ptr.inc|\n"
"----------------+-----+------+-----++--------... | [
"def",
"userselect_block",
"(",
"blocks",
",",
"default",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"print",
"(",
"\"Blocks found in assembly file:\"",
")",
"print",
"(",
"\" block | OPs | pck. | AVX || Registers | ZMM | YMM | XMM | GP ||... | Let user interactively select block. | [
"Let",
"user",
"interactively",
"select",
"block",
"."
] | python | test |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L86-L99 | def readTupleQuotes(self, symbol, start, end):
''' read quotes as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Quote).filter(and_(Quote.symbol == symbol,
... | [
"def",
"readTupleQuotes",
"(",
"self",
",",
"symbol",
",",
"start",
",",
"end",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"sys",
".",
"maxint",
"session",
"=",
"self",
".",
"getReadSession",
"(",
")",
"(",
")",
"try",
":",
"rows",
"=",
... | read quotes as tuple | [
"read",
"quotes",
"as",
"tuple"
] | python | train |
aaugustin/websockets | src/websockets/client.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/client.py#L223-L309 | async def handshake(
self,
wsuri: WebSocketURI,
origin: Optional[Origin] = None,
available_extensions: Optional[Sequence[ClientExtensionFactory]] = None,
available_subprotocols: Optional[Sequence[Subprotocol]] = None,
extra_headers: Optional[HeadersLike] = None,
) -> ... | [
"async",
"def",
"handshake",
"(",
"self",
",",
"wsuri",
":",
"WebSocketURI",
",",
"origin",
":",
"Optional",
"[",
"Origin",
"]",
"=",
"None",
",",
"available_extensions",
":",
"Optional",
"[",
"Sequence",
"[",
"ClientExtensionFactory",
"]",
"]",
"=",
"None",... | Perform the client side of the opening handshake.
If provided, ``origin`` sets the Origin HTTP header.
If provided, ``available_extensions`` is a list of supported
extensions in the order in which they should be used.
If provided, ``available_subprotocols`` is a list of supported
... | [
"Perform",
"the",
"client",
"side",
"of",
"the",
"opening",
"handshake",
"."
] | python | train |
shoebot/shoebot | lib/graph/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L241-L257 | def copy(self, empty=False):
""" Create a copy of the graph (by default with nodes and edges).
"""
g = graph(self.layout.n, self.distance, self.layout.type)
g.layout = self.layout.copy(g)
g.styles = self.styles.copy(g)
g.events = self.events.copy(g)
... | [
"def",
"copy",
"(",
"self",
",",
"empty",
"=",
"False",
")",
":",
"g",
"=",
"graph",
"(",
"self",
".",
"layout",
".",
"n",
",",
"self",
".",
"distance",
",",
"self",
".",
"layout",
".",
"type",
")",
"g",
".",
"layout",
"=",
"self",
".",
"layout... | Create a copy of the graph (by default with nodes and edges). | [
"Create",
"a",
"copy",
"of",
"the",
"graph",
"(",
"by",
"default",
"with",
"nodes",
"and",
"edges",
")",
"."
] | python | valid |
JohnDoee/thomas | thomas/__main__.py | https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/__main__.py#L15-L42 | def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer i... | [
"def",
"query_yes_no",
"(",
"question",
",",
"default",
"=",
"\"yes\"",
")",
":",
"valid",
"=",
"{",
"\"yes\"",
":",
"True",
",",
"\"y\"",
":",
"True",
",",
"\"ye\"",
":",
"True",
",",
"\"no\"",
":",
"False",
",",
"\"n\"",
":",
"False",
"}",
"if",
... | Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return v... | [
"Ask",
"a",
"yes",
"/",
"no",
"question",
"via",
"raw_input",
"()",
"and",
"return",
"their",
"answer",
".",
"question",
"is",
"a",
"string",
"that",
"is",
"presented",
"to",
"the",
"user",
".",
"default",
"is",
"the",
"presumed",
"answer",
"if",
"the",
... | python | train |
waqasbhatti/astrobase | astrobase/hatsurveys/hatlc.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1303-L1369 | def describe_lcc_csv(lcdict, returndesc=False):
'''
This describes the LCC CSV format light curve file.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str instead of ju... | [
"def",
"describe_lcc_csv",
"(",
"lcdict",
",",
"returndesc",
"=",
"False",
")",
":",
"metadata_lines",
"=",
"[",
"]",
"coldef_lines",
"=",
"[",
"]",
"if",
"'lcformat'",
"in",
"lcdict",
"and",
"'lcc-csv'",
"in",
"lcdict",
"[",
"'lcformat'",
"]",
".",
"lower... | This describes the LCC CSV format light curve file.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str instead of just
printing it to stdout.
Returns
-------
... | [
"This",
"describes",
"the",
"LCC",
"CSV",
"format",
"light",
"curve",
"file",
"."
] | python | valid |
pinterest/pymemcache | pymemcache/client/base.py | https://github.com/pinterest/pymemcache/blob/f3a348f4ce2248cce8b398e93e08d984fb9100e5/pymemcache/client/base.py#L585-L608 | def decr(self, key, value, noreply=False):
"""
The memcached "decr" command.
Args:
key: str, see class docs for details.
value: int, the amount by which to increment the value.
noreply: optional bool, False to wait for the reply (the default).
Returns:
... | [
"def",
"decr",
"(",
"self",
",",
"key",
",",
"value",
",",
"noreply",
"=",
"False",
")",
":",
"key",
"=",
"self",
".",
"check_key",
"(",
"key",
")",
"cmd",
"=",
"b'decr '",
"+",
"key",
"+",
"b' '",
"+",
"six",
".",
"text_type",
"(",
"value",
")",... | The memcached "decr" command.
Args:
key: str, see class docs for details.
value: int, the amount by which to increment the value.
noreply: optional bool, False to wait for the reply (the default).
Returns:
If noreply is True, always returns None. Otherwise retur... | [
"The",
"memcached",
"decr",
"command",
"."
] | python | train |
Murali-group/halp | halp/utilities/directed_statistics.py | https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_statistics.py#L240-L256 | def _F_hyperedge_head_cardinality(H, F):
"""Returns the result of a function F applied to the set of cardinalities
of hyperedge heads in the hypergraph.
:param H: the hypergraph whose head cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities i... | [
"def",
"_F_hyperedge_head_cardinality",
"(",
"H",
",",
"F",
")",
":",
"if",
"not",
"isinstance",
"(",
"H",
",",
"DirectedHypergraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Algorithm only applicable to directed hypergraphs\"",
")",
"return",
"F",
"(",
"[",
"len",... | Returns the result of a function F applied to the set of cardinalities
of hyperedge heads in the hypergraph.
:param H: the hypergraph whose head cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities in the
hypergraph.
:returns: resu... | [
"Returns",
"the",
"result",
"of",
"a",
"function",
"F",
"applied",
"to",
"the",
"set",
"of",
"cardinalities",
"of",
"hyperedge",
"heads",
"in",
"the",
"hypergraph",
"."
] | python | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L533-L573 | def extract_patch_images(f, which_set):
"""Extracts a dict of the "patch images" for ILSVRC2010.
Parameters
----------
f : str or file-like object
The filename or file-handle to the patch images TAR file.
which_set : str
Which set of images to extract. One of 'train', 'valid', 'test... | [
"def",
"extract_patch_images",
"(",
"f",
",",
"which_set",
")",
":",
"if",
"which_set",
"not",
"in",
"(",
"'train'",
",",
"'valid'",
",",
"'test'",
")",
":",
"raise",
"ValueError",
"(",
"'which_set must be one of train, valid, or test'",
")",
"which_set",
"=",
"... | Extracts a dict of the "patch images" for ILSVRC2010.
Parameters
----------
f : str or file-like object
The filename or file-handle to the patch images TAR file.
which_set : str
Which set of images to extract. One of 'train', 'valid', 'test'.
Returns
-------
dict
A ... | [
"Extracts",
"a",
"dict",
"of",
"the",
"patch",
"images",
"for",
"ILSVRC2010",
"."
] | python | train |
gwastro/pycbc | pycbc/frame/frame.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/frame.py#L142-L246 | def read_frame(location, channels, start_time=None,
end_time=None, duration=None, check_integrity=True,
sieve=None):
"""Read time series from frame data.
Using the `location`, which can either be a frame file ".gwf" or a
frame cache ".gwf", read in the data for the given chann... | [
"def",
"read_frame",
"(",
"location",
",",
"channels",
",",
"start_time",
"=",
"None",
",",
"end_time",
"=",
"None",
",",
"duration",
"=",
"None",
",",
"check_integrity",
"=",
"True",
",",
"sieve",
"=",
"None",
")",
":",
"if",
"end_time",
"and",
"duratio... | Read time series from frame data.
Using the `location`, which can either be a frame file ".gwf" or a
frame cache ".gwf", read in the data for the given channel(s) and output
as a TimeSeries or list of TimeSeries.
Parameters
----------
location : string
A source of gravitational wave fr... | [
"Read",
"time",
"series",
"from",
"frame",
"data",
"."
] | python | train |
saltstack/salt | salt/modules/pcs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L214-L235 | def cluster_node_add(node, extra_args=None):
'''
Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_node_add... | [
"def",
"cluster_node_add",
"(",
"node",
",",
"extra_args",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
",",
"'cluster'",
",",
"'node'",
",",
"'add'",
"]",
"cmd",
"+=",
"[",
"node",
"]",
"if",
"isinstance",
"(",
"extra_args",
",",
"(",
"list",
",... | Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_node_add node=node2.example.org | [
"Add",
"a",
"node",
"to",
"the",
"pacemaker",
"cluster",
"via",
"pcs",
"command"
] | python | train |
fermiPy/fermipy | fermipy/utils.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L1068-L1075 | def val_to_edge(edges, x):
"""Convert axis coordinate to bin index."""
edges = np.array(edges)
w = edges[1:] - edges[:-1]
w = np.insert(w, 0, w[0])
ibin = np.digitize(np.array(x, ndmin=1), edges - 0.5 * w) - 1
ibin[ibin < 0] = 0
return ibin | [
"def",
"val_to_edge",
"(",
"edges",
",",
"x",
")",
":",
"edges",
"=",
"np",
".",
"array",
"(",
"edges",
")",
"w",
"=",
"edges",
"[",
"1",
":",
"]",
"-",
"edges",
"[",
":",
"-",
"1",
"]",
"w",
"=",
"np",
".",
"insert",
"(",
"w",
",",
"0",
... | Convert axis coordinate to bin index. | [
"Convert",
"axis",
"coordinate",
"to",
"bin",
"index",
"."
] | python | train |
docker/docker-py | docker/models/containers.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/models/containers.py#L349-L360 | def rename(self, name):
"""
Rename this container. Similar to the ``docker rename`` command.
Args:
name (str): New name for the container
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self.c... | [
"def",
"rename",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"client",
".",
"api",
".",
"rename",
"(",
"self",
".",
"id",
",",
"name",
")"
] | Rename this container. Similar to the ``docker rename`` command.
Args:
name (str): New name for the container
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. | [
"Rename",
"this",
"container",
".",
"Similar",
"to",
"the",
"docker",
"rename",
"command",
"."
] | python | train |
alex-kostirin/pyatomac | atomac/ldtpd/menu.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/menu.py#L93-L114 | def menuitemenabled(self, window_name, object_name):
"""
Verify a menu item is enabled
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either ful... | [
"def",
"menuitemenabled",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"try",
":",
"menu_handle",
"=",
"self",
".",
"_get_menu_handle",
"(",
"window_name",
",",
"object_name",
",",
"False",
")",
"if",
"menu_handle",
".",
"AXEnabled",
":",
"... | Verify a menu item is enabled
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob. Or menu heirarchy... | [
"Verify",
"a",
"menu",
"item",
"is",
"enabled"
] | python | valid |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L4006-L4096 | def sort_values(self, by=None, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last'):
"""
Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
... | [
"def",
"sort_values",
"(",
"self",
",",
"by",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"ascending",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"kind",
"=",
"'quicksort'",
",",
"na_position",
"=",
"'last'",
")",
":",
"raise",
"NotImplementedError",
... | Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
ascending : bool or list of bool, default True
Sort ascending vs. descending. Specify list for multiple sort
orders.... | [
"Sort",
"by",
"the",
"values",
"along",
"either",
"axis",
"."
] | python | train |
fastai/fastai | fastai/callbacks/tensorboard.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L387-L392 | def write(self)->None:
"Writes original, generated and real(target) images to Tensorboard."
orig_images, gen_images, real_images = self._get_image_tensors()
self._write_images(name='orig images', images=orig_images)
self._write_images(name='gen images', images=gen_images)
self._... | [
"def",
"write",
"(",
"self",
")",
"->",
"None",
":",
"orig_images",
",",
"gen_images",
",",
"real_images",
"=",
"self",
".",
"_get_image_tensors",
"(",
")",
"self",
".",
"_write_images",
"(",
"name",
"=",
"'orig images'",
",",
"images",
"=",
"orig_images",
... | Writes original, generated and real(target) images to Tensorboard. | [
"Writes",
"original",
"generated",
"and",
"real",
"(",
"target",
")",
"images",
"to",
"Tensorboard",
"."
] | python | train |
biolink/ontobio | ontobio/sim/api/interfaces.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/sim/api/interfaces.py#L44-L55 | def filtered_search(self,
id_list: Iterable,
negated_classes: Iterable,
limit: Optional[int],
taxon_filter: Optional,
category_filter: Optional,
method: Optional) -> SimResult:
"""
Given an input iterable of classe... | [
"def",
"filtered_search",
"(",
"self",
",",
"id_list",
":",
"Iterable",
",",
"negated_classes",
":",
"Iterable",
",",
"limit",
":",
"Optional",
"[",
"int",
"]",
",",
"taxon_filter",
":",
"Optional",
",",
"category_filter",
":",
"Optional",
",",
"method",
":"... | Given an input iterable of classes or individuals,
provides a ranking of similar profiles | [
"Given",
"an",
"input",
"iterable",
"of",
"classes",
"or",
"individuals",
"provides",
"a",
"ranking",
"of",
"similar",
"profiles"
] | python | train |
internetarchive/brozzler | brozzler/ydl.py | https://github.com/internetarchive/brozzler/blob/411b3f266a38b9bb942021c0121ebd8e5ca66447/brozzler/ydl.py#L357-L387 | def do_youtube_dl(worker, site, page):
'''
Runs youtube-dl configured for `worker` and `site` to download videos from
`page`.
Args:
worker (brozzler.BrozzlerWorker): the calling brozzler worker
site (brozzler.Site): the site we are brozzling
page (brozzler.Page): the page we are... | [
"def",
"do_youtube_dl",
"(",
"worker",
",",
"site",
",",
"page",
")",
":",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
"prefix",
"=",
"'brzl-ydl-'",
")",
"as",
"tempdir",
":",
"ydl",
"=",
"_build_youtube_dl",
"(",
"worker",
",",
"tempdir",
",",
"si... | Runs youtube-dl configured for `worker` and `site` to download videos from
`page`.
Args:
worker (brozzler.BrozzlerWorker): the calling brozzler worker
site (brozzler.Site): the site we are brozzling
page (brozzler.Page): the page we are brozzling
Returns:
tuple with two ent... | [
"Runs",
"youtube",
"-",
"dl",
"configured",
"for",
"worker",
"and",
"site",
"to",
"download",
"videos",
"from",
"page",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/internal/nest_util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L76-L79 | def expand_as_args(args):
"""Returns `True` if `args` should be expanded as `*args`."""
return (isinstance(args, collections.Sequence) and
not _is_namedtuple(args) and not _force_leaf(args)) | [
"def",
"expand_as_args",
"(",
"args",
")",
":",
"return",
"(",
"isinstance",
"(",
"args",
",",
"collections",
".",
"Sequence",
")",
"and",
"not",
"_is_namedtuple",
"(",
"args",
")",
"and",
"not",
"_force_leaf",
"(",
"args",
")",
")"
] | Returns `True` if `args` should be expanded as `*args`. | [
"Returns",
"True",
"if",
"args",
"should",
"be",
"expanded",
"as",
"*",
"args",
"."
] | python | test |
saltstack/salt | salt/modules/nspawn.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L248-L268 | def _ensure_systemd(version):
'''
Raises an exception if the systemd version is not greater than the
passed version.
'''
try:
version = int(version)
except ValueError:
raise CommandExecutionError('Invalid version \'{0}\''.format(version))
try:
installed = _sd_version... | [
"def",
"_ensure_systemd",
"(",
"version",
")",
":",
"try",
":",
"version",
"=",
"int",
"(",
"version",
")",
"except",
"ValueError",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid version \\'{0}\\''",
".",
"format",
"(",
"version",
")",
")",
"try",
":",
... | Raises an exception if the systemd version is not greater than the
passed version. | [
"Raises",
"an",
"exception",
"if",
"the",
"systemd",
"version",
"is",
"not",
"greater",
"than",
"the",
"passed",
"version",
"."
] | python | train |
bigchaindb/bigchaindb | bigchaindb/common/schema/__init__.py | https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/common/schema/__init__.py#L71-L81 | def validate_transaction_schema(tx):
"""Validate a transaction dict.
TX_SCHEMA_COMMON contains properties that are common to all types of
transaction. TX_SCHEMA_[TRANSFER|CREATE] add additional constraints on top.
"""
_validate_schema(TX_SCHEMA_COMMON, tx)
if tx['operation'] == 'TRANSFER':
... | [
"def",
"validate_transaction_schema",
"(",
"tx",
")",
":",
"_validate_schema",
"(",
"TX_SCHEMA_COMMON",
",",
"tx",
")",
"if",
"tx",
"[",
"'operation'",
"]",
"==",
"'TRANSFER'",
":",
"_validate_schema",
"(",
"TX_SCHEMA_TRANSFER",
",",
"tx",
")",
"else",
":",
"_... | Validate a transaction dict.
TX_SCHEMA_COMMON contains properties that are common to all types of
transaction. TX_SCHEMA_[TRANSFER|CREATE] add additional constraints on top. | [
"Validate",
"a",
"transaction",
"dict",
"."
] | python | train |
neovim/pynvim | pynvim/api/nvim.py | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L301-L320 | def exec_lua(self, code, *args, **kwargs):
"""Execute lua code.
Additional parameters are available as `...` inside the lua chunk.
Only statements are executed. To evaluate an expression, prefix it
with `return`: `return my_function(...)`
There is a shorthand syntax to call lu... | [
"def",
"exec_lua",
"(",
"self",
",",
"code",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'nvim_execute_lua'",
",",
"code",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Execute lua code.
Additional parameters are available as `...` inside the lua chunk.
Only statements are executed. To evaluate an expression, prefix it
with `return`: `return my_function(...)`
There is a shorthand syntax to call lua functions with arguments:
nvim.lua.func... | [
"Execute",
"lua",
"code",
"."
] | python | train |
jashandeep-sohi/python-blowfish | blowfish.py | https://github.com/jashandeep-sohi/python-blowfish/blob/5ce7f6d54dcef7efd715b26f9a9ffee0d543047e/blowfish.py#L604-L655 | def decrypt_ecb_cts(self, data):
"""
Return an iterator that decrypts `data` using the Electronic Codebook with
Ciphertext Stealing (ECB-CTS) mode of operation.
ECB-CTS mode can only operate on `data` that is greater than 8 bytes in
length.
Each iteration, except the last, always retur... | [
"def",
"decrypt_ecb_cts",
"(",
"self",
",",
"data",
")",
":",
"data_len",
"=",
"len",
"(",
"data",
")",
"if",
"data_len",
"<=",
"8",
":",
"raise",
"ValueError",
"(",
"\"data is not greater than 8 bytes in length\"",
")",
"S1",
",",
"S2",
",",
"S3",
",",
"S... | Return an iterator that decrypts `data` using the Electronic Codebook with
Ciphertext Stealing (ECB-CTS) mode of operation.
ECB-CTS mode can only operate on `data` that is greater than 8 bytes in
length.
Each iteration, except the last, always returns a block-sized :obj:`bytes`
object (i.e... | [
"Return",
"an",
"iterator",
"that",
"decrypts",
"data",
"using",
"the",
"Electronic",
"Codebook",
"with",
"Ciphertext",
"Stealing",
"(",
"ECB",
"-",
"CTS",
")",
"mode",
"of",
"operation",
".",
"ECB",
"-",
"CTS",
"mode",
"can",
"only",
"operate",
"on",
"dat... | python | train |
mathiasertl/xmpp-backends | xmpp_backends/base.py | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L194-L224 | def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns ... | [
"def",
"datetime_to_timestamp",
"(",
"self",
",",
"dt",
")",
":",
"if",
"dt",
"is",
"None",
":",
"return",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"if",
"six",
".",
"PY3",
":",
"if",
"not",
"dt",
".",
"tzinfo",
":",
"dt",
"=",
"pytz",
"... | Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
... | [
"Helper",
"function",
"to",
"convert",
"a",
"datetime",
"object",
"to",
"a",
"timestamp",
"."
] | python | train |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L1137-L1144 | def getActivationsDict(self, nameList):
"""
Returns a dictionary of layer names that map to a list of activations.
"""
retval = {}
for name in nameList:
retval[name] = self.layersByName[name].getActivationsList()
return retval | [
"def",
"getActivationsDict",
"(",
"self",
",",
"nameList",
")",
":",
"retval",
"=",
"{",
"}",
"for",
"name",
"in",
"nameList",
":",
"retval",
"[",
"name",
"]",
"=",
"self",
".",
"layersByName",
"[",
"name",
"]",
".",
"getActivationsList",
"(",
")",
"re... | Returns a dictionary of layer names that map to a list of activations. | [
"Returns",
"a",
"dictionary",
"of",
"layer",
"names",
"that",
"map",
"to",
"a",
"list",
"of",
"activations",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.