repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
wavefrontHQ/python-client | wavefront_api_client/api/settings_api.py | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/settings_api.py#L301-L321 | def post_customer_preferences(self, **kwargs): # noqa: E501
"""Update selected fields of customer preferences # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.... | [
"def",
"post_customer_preferences",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"post_customer_pre... | Update selected fields of customer preferences # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.post_customer_preferences(async_req=True)
>>> result = thread.ge... | [
"Update",
"selected",
"fields",
"of",
"customer",
"preferences",
"#",
"noqa",
":",
"E501"
] | python | train | 43.238095 |
Equitable/trump | trump/aggregation/symbol_aggs.py | https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/trump/aggregation/symbol_aggs.py#L131-L159 | def most_populated(adf):
"""
Looks at each column, using the one with the most values
Honours the Trump override/failsafe logic. """
# just look at the feeds, ignore overrides and failsafes:
feeds_only = adf[adf.columns[1:-1]]
# find the most populated feed
cnt_... | [
"def",
"most_populated",
"(",
"adf",
")",
":",
"# just look at the feeds, ignore overrides and failsafes:",
"feeds_only",
"=",
"adf",
"[",
"adf",
".",
"columns",
"[",
"1",
":",
"-",
"1",
"]",
"]",
"# find the most populated feed",
"cnt_df",
"=",
"feeds_only",
".",
... | Looks at each column, using the one with the most values
Honours the Trump override/failsafe logic. | [
"Looks",
"at",
"each",
"column",
"using",
"the",
"one",
"with",
"the",
"most",
"values",
"Honours",
"the",
"Trump",
"override",
"/",
"failsafe",
"logic",
"."
] | python | train | 38.206897 |
michaelpb/omnic | omnic/conversion/resolver.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/conversion/resolver.py#L110-L120 | async def download(resource_url):
'''
Download given resource_url
'''
scheme = resource_url.parsed.scheme
if scheme in ('http', 'https'):
await download_http(resource_url)
elif scheme in ('git', 'git+https', 'git+http'):
await download_git(resource_url)
else:
raise Va... | [
"async",
"def",
"download",
"(",
"resource_url",
")",
":",
"scheme",
"=",
"resource_url",
".",
"parsed",
".",
"scheme",
"if",
"scheme",
"in",
"(",
"'http'",
",",
"'https'",
")",
":",
"await",
"download_http",
"(",
"resource_url",
")",
"elif",
"scheme",
"in... | Download given resource_url | [
"Download",
"given",
"resource_url"
] | python | train | 32.272727 |
pandas-dev/pandas | pandas/core/arrays/categorical.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1126-L1206 | def map(self, mapper):
"""
Map categories using input correspondence (dict, Series, or function).
Maps the categories to new categories. If the mapping correspondence is
one-to-one the result is a :class:`~pandas.Categorical` which has the
same order property as the original, ot... | [
"def",
"map",
"(",
"self",
",",
"mapper",
")",
":",
"new_categories",
"=",
"self",
".",
"categories",
".",
"map",
"(",
"mapper",
")",
"try",
":",
"return",
"self",
".",
"from_codes",
"(",
"self",
".",
"_codes",
".",
"copy",
"(",
")",
",",
"categories... | Map categories using input correspondence (dict, Series, or function).
Maps the categories to new categories. If the mapping correspondence is
one-to-one the result is a :class:`~pandas.Categorical` which has the
same order property as the original, otherwise a :class:`~pandas.Index`
is... | [
"Map",
"categories",
"using",
"input",
"correspondence",
"(",
"dict",
"Series",
"or",
"function",
")",
"."
] | python | train | 37.209877 |
cortical-io/retina-sdk.py | retinasdk/client/image_api.py | https://github.com/cortical-io/retina-sdk.py/blob/474c13ad399fe1e974d2650335537608f4456b07/retinasdk/client/image_api.py#L79-L105 | def getImageForBulkExpressions(self, retina_name, body, get_fingerprint=None, image_scalar=2, plot_shape="circle", sparsity=1.0):
"""Bulk get images for expressions
Args:
retina_name, str: The retina name (required)
body, ExpressionOperation: The JSON encoded expression to be eva... | [
"def",
"getImageForBulkExpressions",
"(",
"self",
",",
"retina_name",
",",
"body",
",",
"get_fingerprint",
"=",
"None",
",",
"image_scalar",
"=",
"2",
",",
"plot_shape",
"=",
"\"circle\"",
",",
"sparsity",
"=",
"1.0",
")",
":",
"resourcePath",
"=",
"'/image/bu... | Bulk get images for expressions
Args:
retina_name, str: The retina name (required)
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional)
... | [
"Bulk",
"get",
"images",
"for",
"expressions",
"Args",
":",
"retina_name",
"str",
":",
"The",
"retina",
"name",
"(",
"required",
")",
"body",
"ExpressionOperation",
":",
"The",
"JSON",
"encoded",
"expression",
"to",
"be",
"evaluated",
"(",
"required",
")",
"... | python | train | 49.814815 |
zhexiao/ezhost | ezhost/ServerCommon.py | https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/ServerCommon.py#L396-L449 | def add_spark_slave(self, master, slave, configure):
"""
add spark slave
:return:
"""
# go to master server, add config
self.reset_server_env(master, configure)
with cd(bigdata_conf.spark_home):
if not exists('conf/spark-env.sh'):
sudo(... | [
"def",
"add_spark_slave",
"(",
"self",
",",
"master",
",",
"slave",
",",
"configure",
")",
":",
"# go to master server, add config",
"self",
".",
"reset_server_env",
"(",
"master",
",",
"configure",
")",
"with",
"cd",
"(",
"bigdata_conf",
".",
"spark_home",
")",... | add spark slave
:return: | [
"add",
"spark",
"slave",
":",
"return",
":"
] | python | train | 35.425926 |
LeastAuthority/txkube | src/txkube/_swagger.py | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L98-L105 | def from_path(cls, spec_path):
"""
Load a specification from a path.
:param FilePath spec_path: The location of the specification to read.
"""
with spec_path.open() as spec_file:
return cls.from_document(load(spec_file)) | [
"def",
"from_path",
"(",
"cls",
",",
"spec_path",
")",
":",
"with",
"spec_path",
".",
"open",
"(",
")",
"as",
"spec_file",
":",
"return",
"cls",
".",
"from_document",
"(",
"load",
"(",
"spec_file",
")",
")"
] | Load a specification from a path.
:param FilePath spec_path: The location of the specification to read. | [
"Load",
"a",
"specification",
"from",
"a",
"path",
"."
] | python | train | 33.25 |
pypa/pipenv | pipenv/vendor/distlib/locators.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L1089-L1105 | def remove_distribution(self, dist):
"""
Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove.
"""
logger.debug('removing distribution %s', dist)
name = dist.key
del s... | [
"def",
"remove_distribution",
"(",
"self",
",",
"dist",
")",
":",
"logger",
".",
"debug",
"(",
"'removing distribution %s'",
",",
"dist",
")",
"name",
"=",
"dist",
".",
"key",
"del",
"self",
".",
"dists_by_name",
"[",
"name",
"]",
"del",
"self",
".",
"di... | Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove. | [
"Remove",
"a",
"distribution",
"from",
"the",
"finder",
".",
"This",
"will",
"update",
"internal",
"information",
"about",
"who",
"provides",
"what",
".",
":",
"param",
"dist",
":",
"The",
"distribution",
"to",
"remove",
"."
] | python | train | 39.764706 |
OldhamMade/PySO8601 | PySO8601/utility.py | https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/utility.py#L55-L72 | def _year_month_delta_from_elements(elements):
"""
Return a tuple of (years, months) from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
Example:
>>> _year_month_delta_from_elements({'years': 2, 'months': 14})
(3, 2)
"""
return di... | [
"def",
"_year_month_delta_from_elements",
"(",
"elements",
")",
":",
"return",
"divmod",
"(",
"(",
"int",
"(",
"elements",
".",
"get",
"(",
"'years'",
",",
"0",
")",
")",
"*",
"MONTHS_IN_YEAR",
")",
"+",
"elements",
".",
"get",
"(",
"'months'",
",",
"0",... | Return a tuple of (years, months) from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
Example:
>>> _year_month_delta_from_elements({'years': 2, 'months': 14})
(3, 2) | [
"Return",
"a",
"tuple",
"of",
"(",
"years",
"months",
")",
"from",
"a",
"dict",
"of",
"date",
"elements",
"."
] | python | train | 23.944444 |
zblz/naima | naima/radiative.py | https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1528-L1555 | def _nuclear_factor(self, Tp):
"""
Compute nuclear enhancement factor
"""
sigmaRpp = 10 * np.pi * 1e-27
sigmainel = self._sigma_inel(Tp)
sigmainel0 = self._sigma_inel(1e3) # at 1e3 GeV
f = sigmainel / sigmainel0
f2 = np.where(f > 1, f, 1.0)
G = 1.... | [
"def",
"_nuclear_factor",
"(",
"self",
",",
"Tp",
")",
":",
"sigmaRpp",
"=",
"10",
"*",
"np",
".",
"pi",
"*",
"1e-27",
"sigmainel",
"=",
"self",
".",
"_sigma_inel",
"(",
"Tp",
")",
"sigmainel0",
"=",
"self",
".",
"_sigma_inel",
"(",
"1e3",
")",
"# at... | Compute nuclear enhancement factor | [
"Compute",
"nuclear",
"enhancement",
"factor"
] | python | train | 30.321429 |
googleapis/google-cloud-python | logging/docs/snippets.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L169-L212 | def metric_crud(client, to_delete):
"""Metric CRUD."""
METRIC_NAME = "robots-%d" % (_millis(),)
DESCRIPTION = "Robots all up in your server"
FILTER = "logName:apache-access AND textPayload:robot"
UPDATED_FILTER = "textPayload:robot"
UPDATED_DESCRIPTION = "Danger, Will Robinson!"
# [START cl... | [
"def",
"metric_crud",
"(",
"client",
",",
"to_delete",
")",
":",
"METRIC_NAME",
"=",
"\"robots-%d\"",
"%",
"(",
"_millis",
"(",
")",
",",
")",
"DESCRIPTION",
"=",
"\"Robots all up in your server\"",
"FILTER",
"=",
"\"logName:apache-access AND textPayload:robot\"",
"UP... | Metric CRUD. | [
"Metric",
"CRUD",
"."
] | python | train | 33.204545 |
PredixDev/predixpy | predix/data/eventhub/publisher.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/eventhub/publisher.py#L349-L363 | def _on_ws_message(self, ws, message):
"""
on_message callback of websocket class, load the message into a dict and then
update an Ack Object with the results
:param ws: web socket connection that the message was received on
:param message: web socket message in text form
... | [
"def",
"_on_ws_message",
"(",
"self",
",",
"ws",
",",
"message",
")",
":",
"logging",
".",
"debug",
"(",
"message",
")",
"json_list",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"for",
"rx_ack",
"in",
"json_list",
":",
"ack",
"=",
"EventHub_pb2",
"... | on_message callback of websocket class, load the message into a dict and then
update an Ack Object with the results
:param ws: web socket connection that the message was received on
:param message: web socket message in text form
:return: None | [
"on_message",
"callback",
"of",
"websocket",
"class",
"load",
"the",
"message",
"into",
"a",
"dict",
"and",
"then",
"update",
"an",
"Ack",
"Object",
"with",
"the",
"results",
":",
"param",
"ws",
":",
"web",
"socket",
"connection",
"that",
"the",
"message",
... | python | train | 40.133333 |
childsish/lhc-python | lhc/io/gbk/iterator.py | https://github.com/childsish/lhc-python/blob/0a669f46a40a39f24d28665e8b5b606dc7e86beb/lhc/io/gbk/iterator.py#L124-L133 | def _parse_complement(self, tokens):
""" Parses a complement
Complement ::= 'complement' '(' SuperRange ')'
"""
tokens.pop(0) # Pop 'complement'
tokens.pop(0) # Pop '('
res = self._parse_nested_interval(tokens)
tokens.pop(0) # Pop ')'
res.switch_strand... | [
"def",
"_parse_complement",
"(",
"self",
",",
"tokens",
")",
":",
"tokens",
".",
"pop",
"(",
"0",
")",
"# Pop 'complement'",
"tokens",
".",
"pop",
"(",
"0",
")",
"# Pop '('",
"res",
"=",
"self",
".",
"_parse_nested_interval",
"(",
"tokens",
")",
"tokens",
... | Parses a complement
Complement ::= 'complement' '(' SuperRange ')' | [
"Parses",
"a",
"complement",
"Complement",
"::",
"=",
"complement",
"(",
"SuperRange",
")"
] | python | train | 33.2 |
python-diamond/Diamond | src/collectors/ipmisensor/ipmisensor.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ipmisensor/ipmisensor.py#L51-L74 | def parse_value(self, value):
"""
Convert value string to float for reporting
"""
value = value.strip()
# Skip missing sensors
if value == 'na':
return None
# Try just getting the float value
try:
return float(value)
excep... | [
"def",
"parse_value",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"# Skip missing sensors",
"if",
"value",
"==",
"'na'",
":",
"return",
"None",
"# Try just getting the float value",
"try",
":",
"return",
"float",
"(",
... | Convert value string to float for reporting | [
"Convert",
"value",
"string",
"to",
"float",
"for",
"reporting"
] | python | train | 20.375 |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2535-L2559 | def freemem(**kwargs):
'''
Return an int representing the amount of memory (in MB) that has not
been given to virtual machines on this node
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaul... | [
"def",
"freemem",
"(",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"mem",
"=",
"_freemem",
"(",
"conn",
")",
"conn",
".",
"close",
"(",
")",
"return",
"mem"
] | Return an int representing the amount of memory (in MB) that has not
been given to virtual machines on this node
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.... | [
"Return",
"an",
"int",
"representing",
"the",
"amount",
"of",
"memory",
"(",
"in",
"MB",
")",
"that",
"has",
"not",
"been",
"given",
"to",
"virtual",
"machines",
"on",
"this",
"node"
] | python | train | 24.36 |
RedFantom/ttkwidgets | ttkwidgets/tickscale.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/tickscale.py#L670-L674 | def _place_ticks_vertical(self):
"""Display the ticks for a vertical slider."""
for tick, label in zip(self.ticks, self.ticklabels):
y = self.convert_to_pixels(tick)
label.place_configure(y=y) | [
"def",
"_place_ticks_vertical",
"(",
"self",
")",
":",
"for",
"tick",
",",
"label",
"in",
"zip",
"(",
"self",
".",
"ticks",
",",
"self",
".",
"ticklabels",
")",
":",
"y",
"=",
"self",
".",
"convert_to_pixels",
"(",
"tick",
")",
"label",
".",
"place_con... | Display the ticks for a vertical slider. | [
"Display",
"the",
"ticks",
"for",
"a",
"vertical",
"slider",
"."
] | python | train | 45.6 |
ga4gh/ga4gh-server | ga4gh/server/datamodel/peers.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/peers.py#L17-L36 | def isUrl(urlString):
"""
Attempts to return whether a given URL string is valid by checking
for the presence of the URL scheme and netloc using the urlparse
module, and then using a regex.
From http://stackoverflow.com/questions/7160737/
"""
parsed = urlparse.urlparse(urlString)
urlpar... | [
"def",
"isUrl",
"(",
"urlString",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"urlString",
")",
"urlparseValid",
"=",
"parsed",
".",
"netloc",
"!=",
"''",
"and",
"parsed",
".",
"scheme",
"!=",
"''",
"regex",
"=",
"re",
".",
"compile",
"(... | Attempts to return whether a given URL string is valid by checking
for the presence of the URL scheme and netloc using the urlparse
module, and then using a regex.
From http://stackoverflow.com/questions/7160737/ | [
"Attempts",
"to",
"return",
"whether",
"a",
"given",
"URL",
"string",
"is",
"valid",
"by",
"checking",
"for",
"the",
"presence",
"of",
"the",
"URL",
"scheme",
"and",
"netloc",
"using",
"the",
"urlparse",
"module",
"and",
"then",
"using",
"a",
"regex",
"."
... | python | train | 39 |
pycontribs/jira | jira/client.py | https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L3198-L3234 | def reindex(self, force=False, background=True):
"""Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False.
If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it.
:param force: reindex even if JI... | [
"def",
"reindex",
"(",
"self",
",",
"force",
"=",
"False",
",",
"background",
"=",
"True",
")",
":",
"# /secure/admin/IndexAdmin.jspa",
"# /secure/admin/jira/IndexProgress.jspa?taskId=1",
"if",
"background",
":",
"indexingStrategy",
"=",
"'background'",
"else",
":",
"... | Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False.
If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it.
:param force: reindex even if JIRA doesn't say this is needed, False by default.
:pa... | [
"Start",
"jira",
"re",
"-",
"indexing",
".",
"Returns",
"True",
"if",
"reindexing",
"is",
"in",
"progress",
"or",
"not",
"needed",
"or",
"False",
"."
] | python | train | 48.27027 |
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 | 32 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L146-L181 | def create_spot_requests(self,
price,
instance_type='default',
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False... | [
"def",
"create_spot_requests",
"(",
"self",
",",
"price",
",",
"instance_type",
"=",
"'default'",
",",
"root_device_type",
"=",
"'ebs'",
",",
"size",
"=",
"'default'",
",",
"vol_type",
"=",
"'gp2'",
",",
"delete_on_termination",
"=",
"False",
",",
"timeout",
"... | Request creation of one or more EC2 spot instances.
:param size:
:param vol_type:
:param delete_on_termination:
:param root_device_type: The type of the root device.
:type root_device_type: str
:param price: Max price to pay for spot instance per hour.
:type pric... | [
"Request",
"creation",
"of",
"one",
"or",
"more",
"EC2",
"spot",
"instances",
"."
] | python | train | 42.444444 |
zhemao/funktown | funktown/dictionary.py | https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/dictionary.py#L30-L42 | def update(self, other=None, **kwargs):
'''Takes the same arguments as the update method in the builtin dict
class. However, this version returns a new ImmutableDict instead of
modifying in-place.'''
copydict = ImmutableDict()
if other:
vallist = [(hash(key), (key, ot... | [
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"copydict",
"=",
"ImmutableDict",
"(",
")",
"if",
"other",
":",
"vallist",
"=",
"[",
"(",
"hash",
"(",
"key",
")",
",",
"(",
"key",
",",
"other",
"[",
"... | Takes the same arguments as the update method in the builtin dict
class. However, this version returns a new ImmutableDict instead of
modifying in-place. | [
"Takes",
"the",
"same",
"arguments",
"as",
"the",
"update",
"method",
"in",
"the",
"builtin",
"dict",
"class",
".",
"However",
"this",
"version",
"returns",
"a",
"new",
"ImmutableDict",
"instead",
"of",
"modifying",
"in",
"-",
"place",
"."
] | python | train | 45.384615 |
secdev/scapy | scapy/layers/netflow.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/netflow.py#L1456-L1479 | def netflowv9_defragment(plist, verb=1):
"""Process all NetflowV9/10 Packets to match IDs of the DataFlowsets
with the Headers
params:
- plist: the list of mixed NetflowV9/10 packets.
- verb: verbose print (0/1)
"""
if not isinstance(plist, (PacketList, list)):
plist = [plist]
... | [
"def",
"netflowv9_defragment",
"(",
"plist",
",",
"verb",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"plist",
",",
"(",
"PacketList",
",",
"list",
")",
")",
":",
"plist",
"=",
"[",
"plist",
"]",
"# We need the whole packet to be dissected to access fi... | Process all NetflowV9/10 Packets to match IDs of the DataFlowsets
with the Headers
params:
- plist: the list of mixed NetflowV9/10 packets.
- verb: verbose print (0/1) | [
"Process",
"all",
"NetflowV9",
"/",
"10",
"Packets",
"to",
"match",
"IDs",
"of",
"the",
"DataFlowsets",
"with",
"the",
"Headers"
] | python | train | 35.583333 |
dade-ai/snipy | snipy/term.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/term.py#L163-L172 | def getch():
"""
get character. waiting for key
"""
try:
termios.tcsetattr(_fd, termios.TCSANOW, _new_settings)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings)
return ch | [
"def",
"getch",
"(",
")",
":",
"try",
":",
"termios",
".",
"tcsetattr",
"(",
"_fd",
",",
"termios",
".",
"TCSANOW",
",",
"_new_settings",
")",
"ch",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
"1",
")",
"finally",
":",
"termios",
".",
"tcsetattr",
... | get character. waiting for key | [
"get",
"character",
".",
"waiting",
"for",
"key"
] | python | valid | 24.9 |
hmmlearn/hmmlearn | lib/hmmlearn/base.py | https://github.com/hmmlearn/hmmlearn/blob/e86fe4349bce78ad6b3d3eb53e3545902d59abbd/lib/hmmlearn/base.py#L217-L256 | def score_samples(self, X, lengths=None):
"""Compute the log probability under the model and compute posteriors.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Feature matrix of individual samples.
lengths : array-like of integers, shape (n_sequ... | [
"def",
"score_samples",
"(",
"self",
",",
"X",
",",
"lengths",
"=",
"None",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"\"startprob_\"",
")",
"self",
".",
"_check",
"(",
")",
"X",
"=",
"check_array",
"(",
"X",
")",
"n_samples",
"=",
"X",
".",
"sh... | Compute the log probability under the model and compute posteriors.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Feature matrix of individual samples.
lengths : array-like of integers, shape (n_sequences, ), optional
Lengths of the individ... | [
"Compute",
"the",
"log",
"probability",
"under",
"the",
"model",
"and",
"compute",
"posteriors",
"."
] | python | train | 35.55 |
ramrod-project/database-brain | schema/brain/queries/decorators.py | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/decorators.py#L36-L48 | def wrap_rethink_errors(func_, *args, **kwargs):
"""
Wraps rethinkdb specific errors as builtin/Brain errors
:param func_: <function> to call
:param args: <tuple> positional arguments
:param kwargs: <dict> keyword arguments
:return: inherits from the called function
"""
try:
re... | [
"def",
"wrap_rethink_errors",
"(",
"func_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"WRAP_RETHINK_ERRORS",
"as",
"reql_err",
":",
"raise",
"ValueError",... | Wraps rethinkdb specific errors as builtin/Brain errors
:param func_: <function> to call
:param args: <tuple> positional arguments
:param kwargs: <dict> keyword arguments
:return: inherits from the called function | [
"Wraps",
"rethinkdb",
"specific",
"errors",
"as",
"builtin",
"/",
"Brain",
"errors"
] | python | train | 32.230769 |
APSL/transmanager | transmanager/manager.py | https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/manager.py#L321-L334 | def get_languages_from_model(app_label, model_label):
"""
Get the languages configured for the current model
:param model_label:
:param app_label:
:return:
"""
try:
mod_lan = TransModelLanguage.objects.filter(model='{} - {}'.format(app_label, model_la... | [
"def",
"get_languages_from_model",
"(",
"app_label",
",",
"model_label",
")",
":",
"try",
":",
"mod_lan",
"=",
"TransModelLanguage",
".",
"objects",
".",
"filter",
"(",
"model",
"=",
"'{} - {}'",
".",
"format",
"(",
"app_label",
",",
"model_label",
")",
")",
... | Get the languages configured for the current model
:param model_label:
:param app_label:
:return: | [
"Get",
"the",
"languages",
"configured",
"for",
"the",
"current",
"model"
] | python | train | 34.928571 |
geertj/gruvi | lib/gruvi/http.py | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L1141-L1160 | def getresponse(self):
"""Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :att... | [
"def",
"getresponse",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error",
":",
"raise",
"compat",
".",
"saved_exc",
"(",
"self",
".",
"_error",
")",
"elif",
"self",
".",
"_transport",
"is",
"None",
":",
"raise",
"HttpError",
"(",
"'not connected'",
")",
... | Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :attr:`~HttpMessage.body`.
No... | [
"Wait",
"for",
"and",
"return",
"a",
"HTTP",
"response",
"."
] | python | train | 42.15 |
google/pyu2f | pyu2f/hidtransport.py | https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L239-L258 | def InternalExchange(self, cmd, payload_in):
"""Sends and receives a message from the device."""
# make a copy because we destroy it below
self.logger.debug('payload: ' + str(list(payload_in)))
payload = bytearray()
payload[:] = payload_in
for _ in range(2):
self.InternalSend(cmd, payload)... | [
"def",
"InternalExchange",
"(",
"self",
",",
"cmd",
",",
"payload_in",
")",
":",
"# make a copy because we destroy it below",
"self",
".",
"logger",
".",
"debug",
"(",
"'payload: '",
"+",
"str",
"(",
"list",
"(",
"payload_in",
")",
")",
")",
"payload",
"=",
... | Sends and receives a message from the device. | [
"Sends",
"and",
"receives",
"a",
"message",
"from",
"the",
"device",
"."
] | python | train | 36.9 |
bitesofcode/projexui | projexui/xwidgetvalue.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xwidgetvalue.py#L74-L88 | def widgetValue( widget ):
"""
Returns the value for the inputed widget based on its type.
:param widget | <QWidget>
:return (<variant> value, <bool> success)
"""
for wtype in reversed(_widgetValueTypes):
if isinstance(widget, wtype[0]):
try:
... | [
"def",
"widgetValue",
"(",
"widget",
")",
":",
"for",
"wtype",
"in",
"reversed",
"(",
"_widgetValueTypes",
")",
":",
"if",
"isinstance",
"(",
"widget",
",",
"wtype",
"[",
"0",
"]",
")",
":",
"try",
":",
"return",
"(",
"wtype",
"[",
"1",
"]",
"(",
"... | Returns the value for the inputed widget based on its type.
:param widget | <QWidget>
:return (<variant> value, <bool> success) | [
"Returns",
"the",
"value",
"for",
"the",
"inputed",
"widget",
"based",
"on",
"its",
"type",
".",
":",
"param",
"widget",
"|",
"<QWidget",
">",
":",
"return",
"(",
"<variant",
">",
"value",
"<bool",
">",
"success",
")"
] | python | train | 29 |
readbeyond/aeneas | aeneas/tools/execute_task.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_task.py#L443-L680 | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 1:
return self.print_help()
if self.has_option([u"-e", u"--examples"]):
return self.print_examples(False)
... | [
"def",
"perform_command",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"actual_arguments",
")",
"<",
"1",
":",
"return",
"self",
".",
"print_help",
"(",
")",
"if",
"self",
".",
"has_option",
"(",
"[",
"u\"-e\"",
",",
"u\"--examples\"",
"]",
")... | Perform command and return the appropriate exit code.
:rtype: int | [
"Perform",
"command",
"and",
"return",
"the",
"appropriate",
"exit",
"code",
"."
] | python | train | 49.058824 |
base4sistemas/satcomum | satcomum/br.py | https://github.com/base4sistemas/satcomum/blob/b42bec06cb0fb0ad2f6b1a2644a1e8fc8403f2c3/satcomum/br.py#L171-L179 | def as_cnpj(numero):
"""Formata um número de CNPJ. Se o número não for um CNPJ válido apenas
retorna o argumento sem qualquer modificação.
"""
_num = digitos(numero)
if is_cnpj(_num):
return '{}.{}.{}/{}-{}'.format(
_num[:2], _num[2:5], _num[5:8], _num[8:12], _num[12:])
r... | [
"def",
"as_cnpj",
"(",
"numero",
")",
":",
"_num",
"=",
"digitos",
"(",
"numero",
")",
"if",
"is_cnpj",
"(",
"_num",
")",
":",
"return",
"'{}.{}.{}/{}-{}'",
".",
"format",
"(",
"_num",
"[",
":",
"2",
"]",
",",
"_num",
"[",
"2",
":",
"5",
"]",
","... | Formata um número de CNPJ. Se o número não for um CNPJ válido apenas
retorna o argumento sem qualquer modificação. | [
"Formata",
"um",
"número",
"de",
"CNPJ",
".",
"Se",
"o",
"número",
"não",
"for",
"um",
"CNPJ",
"válido",
"apenas",
"retorna",
"o",
"argumento",
"sem",
"qualquer",
"modificação",
"."
] | python | train | 36 |
phoebe-project/phoebe2 | phoebe/dependencies/autofig/call.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/autofig/call.py#L1397-L1408 | def direction(self, direction):
"""
set the direction
"""
if not isinstance(direction, str):
raise TypeError("direction must be of type str")
accepted_values = ['i', 'x', 'y', 'z', 's', 'c']
if direction not in accepted_values:
raise ValueError("m... | [
"def",
"direction",
"(",
"self",
",",
"direction",
")",
":",
"if",
"not",
"isinstance",
"(",
"direction",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"direction must be of type str\"",
")",
"accepted_values",
"=",
"[",
"'i'",
",",
"'x'",
",",
"'y'",
... | set the direction | [
"set",
"the",
"direction"
] | python | train | 32.416667 |
citronneur/rdpy | rdpy/protocol/rfb/rfb.py | https://github.com/citronneur/rdpy/blob/4109b7a6fe2abf3ddbaed54e29d2f31e63ed97f6/rdpy/protocol/rfb/rfb.py#L286-L306 | def recvSecurityList(self, data):
"""
Read security list packet send from server to client
@param data: Stream that contains well formed packet
"""
securityList = []
while data.dataLen() > 0:
securityElement = UInt8()
data.readType(securityElement)... | [
"def",
"recvSecurityList",
"(",
"self",
",",
"data",
")",
":",
"securityList",
"=",
"[",
"]",
"while",
"data",
".",
"dataLen",
"(",
")",
">",
"0",
":",
"securityElement",
"=",
"UInt8",
"(",
")",
"data",
".",
"readType",
"(",
"securityElement",
")",
"se... | Read security list packet send from server to client
@param data: Stream that contains well formed packet | [
"Read",
"security",
"list",
"packet",
"send",
"from",
"server",
"to",
"client"
] | python | train | 39.380952 |
llazzaro/django-scheduler | schedule/utils.py | https://github.com/llazzaro/django-scheduler/blob/0530b74a5fc0b1125645002deaa4da2337ed0f17/schedule/utils.py#L196-L219 | def coerce_date_dict(date_dict):
"""
given a dictionary (presumed to be from request.GET) it returns a tuple
that represents a date. It will return from year down to seconds until one
is not found. ie if year, month, and seconds are in the dictionary, only
year and month will be returned, the rest ... | [
"def",
"coerce_date_dict",
"(",
"date_dict",
")",
":",
"keys",
"=",
"[",
"'year'",
",",
"'month'",
",",
"'day'",
",",
"'hour'",
",",
"'minute'",
",",
"'second'",
"]",
"ret_val",
"=",
"{",
"'year'",
":",
"1",
",",
"'month'",
":",
"1",
",",
"'day'",
":... | given a dictionary (presumed to be from request.GET) it returns a tuple
that represents a date. It will return from year down to seconds until one
is not found. ie if year, month, and seconds are in the dictionary, only
year and month will be returned, the rest will be returned as min. If none
of the p... | [
"given",
"a",
"dictionary",
"(",
"presumed",
"to",
"be",
"from",
"request",
".",
"GET",
")",
"it",
"returns",
"a",
"tuple",
"that",
"represents",
"a",
"date",
".",
"It",
"will",
"return",
"from",
"year",
"down",
"to",
"seconds",
"until",
"one",
"is",
"... | python | train | 33.166667 |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L562-L569 | def _onDecorator(self, name, line, pos, absPosition):
"""Memorizes a function or a class decorator"""
# A class or a function must be on the top of the stack
d = Decorator(name, line, pos, absPosition)
if self.__lastDecorators is None:
self.__lastDecorators = [d]
else... | [
"def",
"_onDecorator",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
":",
"# A class or a function must be on the top of the stack",
"d",
"=",
"Decorator",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
"if",
"self... | Memorizes a function or a class decorator | [
"Memorizes",
"a",
"function",
"or",
"a",
"class",
"decorator"
] | python | train | 44.75 |
danilobellini/audiolazy | audiolazy/lazy_lpc.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_lpc.py#L460-L487 | def lsf_stable(filt):
"""
Tests whether the given filter is stable or not by using the Line Spectral
Frequencies (LSF) of the given filter. Needs NumPy.
Parameters
----------
filt :
A LTI filter as a LinearFilter object.
Returns
-------
A boolean that is true only when the LSF values from forwar... | [
"def",
"lsf_stable",
"(",
"filt",
")",
":",
"lsf_data",
"=",
"lsf",
"(",
"ZFilter",
"(",
"filt",
".",
"denpoly",
")",
")",
"return",
"all",
"(",
"a",
"<",
"b",
"for",
"a",
",",
"b",
"in",
"blocks",
"(",
"lsf_data",
",",
"size",
"=",
"2",
",",
"... | Tests whether the given filter is stable or not by using the Line Spectral
Frequencies (LSF) of the given filter. Needs NumPy.
Parameters
----------
filt :
A LTI filter as a LinearFilter object.
Returns
-------
A boolean that is true only when the LSF values from forward and backward
prediction fi... | [
"Tests",
"whether",
"the",
"given",
"filter",
"is",
"stable",
"or",
"not",
"by",
"using",
"the",
"Line",
"Spectral",
"Frequencies",
"(",
"LSF",
")",
"of",
"the",
"given",
"filter",
".",
"Needs",
"NumPy",
"."
] | python | train | 28.25 |
uw-it-aca/uw-restclients-canvas | uw_canvas/admins.py | https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/admins.py#L9-L20 | def get_admins(self, account_id, params={}):
"""
Return a list of the admins in the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.index
"""
url = ADMINS_API.format(account_id)
admins = []
for data in self._get_paged_resource(url, para... | [
"def",
"get_admins",
"(",
"self",
",",
"account_id",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"ADMINS_API",
".",
"format",
"(",
"account_id",
")",
"admins",
"=",
"[",
"]",
"for",
"data",
"in",
"self",
".",
"_get_paged_resource",
"(",
"url",
... | Return a list of the admins in the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.index | [
"Return",
"a",
"list",
"of",
"the",
"admins",
"in",
"the",
"account",
"."
] | python | test | 32.666667 |
pywbem/pywbem | wbemcli.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L433-L468 | def mi(mi, iq=None, pl=None):
# pylint: disable=redefined-outer-name
"""
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.ModifyInstance`.
Modify the property values of an instance.
Parameters:
mi (:class:`~pywbem.CIMInstance`):
Modified instance, also indicating i... | [
"def",
"mi",
"(",
"mi",
",",
"iq",
"=",
"None",
",",
"pl",
"=",
"None",
")",
":",
"# pylint: disable=redefined-outer-name",
"CONN",
".",
"ModifyInstance",
"(",
"mi",
",",
"IncludeQualifiers",
"=",
"iq",
",",
"PropertyList",
"=",
"pl",
")"
] | This function is a wrapper for
:meth:`~pywbem.WBEMConnection.ModifyInstance`.
Modify the property values of an instance.
Parameters:
mi (:class:`~pywbem.CIMInstance`):
Modified instance, also indicating its instance path.
The properties defined in this object specify the new pr... | [
"This",
"function",
"is",
"a",
"wrapper",
"for",
":",
"meth",
":",
"~pywbem",
".",
"WBEMConnection",
".",
"ModifyInstance",
"."
] | python | train | 35.666667 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L3978-L3982 | def user_organization_membership_create(self, user_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership"
api_path = "/api/v2/users/{user_id}/organization_memberships.json"
api_path = api_path.format(user_id=user_id)
return self... | [
"def",
"user_organization_membership_create",
"(",
"self",
",",
"user_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/users/{user_id}/organization_memberships.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"user_id",
"=",
... | https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"organization_memberships#create",
"-",
"membership"
] | python | train | 73.4 |
pywbem/pywbem | attic/cimxml_parse.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cimxml_parse.py#L347-L373 | def parse_instancepath(parser, event, node):
#pylint: disable=unused-argument
"""Parse the CIM/XML INSTANCEPATH element and return an
instancname
<!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)>
"""
(next_event, next_node) = six.next(parser)
if not _is_start(next_event, next_no... | [
"def",
"parse_instancepath",
"(",
"parser",
",",
"event",
",",
"node",
")",
":",
"#pylint: disable=unused-argument",
"(",
"next_event",
",",
"next_node",
")",
"=",
"six",
".",
"next",
"(",
"parser",
")",
"if",
"not",
"_is_start",
"(",
"next_event",
",",
"nex... | Parse the CIM/XML INSTANCEPATH element and return an
instancname
<!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)> | [
"Parse",
"the",
"CIM",
"/",
"XML",
"INSTANCEPATH",
"element",
"and",
"return",
"an",
"instancname"
] | python | train | 30.037037 |
coderholic/django-cities | cities/util.py | https://github.com/coderholic/django-cities/blob/5e1cf86ff1d05e2d325cb2770c6df279599f5f98/cities/util.py#L27-L34 | def geo_distance(a, b):
"""Distance between two geo points in km. (p.x = long, p.y = lat)"""
a_y = radians(a.y)
b_y = radians(b.y)
delta_x = radians(a.x - b.x)
cos_x = (sin(a_y) * sin(b_y) +
cos(a_y) * cos(b_y) * cos(delta_x))
return acos(cos_x) * earth_radius_km | [
"def",
"geo_distance",
"(",
"a",
",",
"b",
")",
":",
"a_y",
"=",
"radians",
"(",
"a",
".",
"y",
")",
"b_y",
"=",
"radians",
"(",
"b",
".",
"y",
")",
"delta_x",
"=",
"radians",
"(",
"a",
".",
"x",
"-",
"b",
".",
"x",
")",
"cos_x",
"=",
"(",
... | Distance between two geo points in km. (p.x = long, p.y = lat) | [
"Distance",
"between",
"two",
"geo",
"points",
"in",
"km",
".",
"(",
"p",
".",
"x",
"=",
"long",
"p",
".",
"y",
"=",
"lat",
")"
] | python | train | 36.625 |
welchbj/sublemon | sublemon/subprocess.py | https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/subprocess.py#L80-L94 | def _poll(self) -> None:
"""Check the status of the wrapped running subprocess.
Note:
This should only be called on currently-running tasks.
"""
if self._subprocess is None:
raise SublemonLifetimeError(
'Attempted to poll a non-active subprocess'... | [
"def",
"_poll",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_subprocess",
"is",
"None",
":",
"raise",
"SublemonLifetimeError",
"(",
"'Attempted to poll a non-active subprocess'",
")",
"elif",
"self",
".",
"_subprocess",
".",
"returncode",
"is",
"not... | Check the status of the wrapped running subprocess.
Note:
This should only be called on currently-running tasks. | [
"Check",
"the",
"status",
"of",
"the",
"wrapped",
"running",
"subprocess",
"."
] | python | train | 36.733333 |
singularityhub/sregistry-cli | sregistry/main/google_storage/build.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/google_storage/build.py#L144-L153 | def get_templates(self):
'''list templates in the builder bundle library. If a name is provided,
look it up
'''
base = 'https://singularityhub.github.io/builders'
base = self._get_and_update_setting('SREGISTRY_BUILDER_REPO', base)
base = "%s/configs.json" %base
return self._get(base) | [
"def",
"get_templates",
"(",
"self",
")",
":",
"base",
"=",
"'https://singularityhub.github.io/builders'",
"base",
"=",
"self",
".",
"_get_and_update_setting",
"(",
"'SREGISTRY_BUILDER_REPO'",
",",
"base",
")",
"base",
"=",
"\"%s/configs.json\"",
"%",
"base",
"return"... | list templates in the builder bundle library. If a name is provided,
look it up | [
"list",
"templates",
"in",
"the",
"builder",
"bundle",
"library",
".",
"If",
"a",
"name",
"is",
"provided",
"look",
"it",
"up"
] | python | test | 30.8 |
materialsproject/pymatgen | pymatgen/analysis/defects/core.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/defects/core.py#L159-L170 | def multiplicity(self):
"""
Returns the multiplicity of a defect site within the structure (needed for concentration analysis)
"""
sga = SpacegroupAnalyzer(self.bulk_structure)
periodic_struc = sga.get_symmetrized_structure()
poss_deflist = sorted(
periodic_st... | [
"def",
"multiplicity",
"(",
"self",
")",
":",
"sga",
"=",
"SpacegroupAnalyzer",
"(",
"self",
".",
"bulk_structure",
")",
"periodic_struc",
"=",
"sga",
".",
"get_symmetrized_structure",
"(",
")",
"poss_deflist",
"=",
"sorted",
"(",
"periodic_struc",
".",
"get_sit... | Returns the multiplicity of a defect site within the structure (needed for concentration analysis) | [
"Returns",
"the",
"multiplicity",
"of",
"a",
"defect",
"site",
"within",
"the",
"structure",
"(",
"needed",
"for",
"concentration",
"analysis",
")"
] | python | train | 47.083333 |
Azure/blobxfer | blobxfer/models/upload.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/upload.py#L892-L922 | def next_offsets(self):
# type: (Descriptor) -> Offsets
"""Retrieve the next offsets
:param Descriptor self: this
:rtype: Offsets
:return: upload offsets
"""
resume_bytes = self._resume()
with self._meta_lock:
if self._chunk_num >= self._total_... | [
"def",
"next_offsets",
"(",
"self",
")",
":",
"# type: (Descriptor) -> Offsets",
"resume_bytes",
"=",
"self",
".",
"_resume",
"(",
")",
"with",
"self",
".",
"_meta_lock",
":",
"if",
"self",
".",
"_chunk_num",
">=",
"self",
".",
"_total_chunks",
":",
"return",
... | Retrieve the next offsets
:param Descriptor self: this
:rtype: Offsets
:return: upload offsets | [
"Retrieve",
"the",
"next",
"offsets",
":",
"param",
"Descriptor",
"self",
":",
"this",
":",
"rtype",
":",
"Offsets",
":",
"return",
":",
"upload",
"offsets"
] | python | train | 35.741935 |
ivknv/s3m | s3m.py | https://github.com/ivknv/s3m/blob/71663c12613d41cf7d3dd99c819d50a7c1b7ff9d/s3m.py#L493-L503 | def fetchmany(self, *args, **kwargs):
"""
Analogous to :any:`sqlite3.Cursor.fetchmany`.
Works only in single cursor mode.
"""
if not self.single_cursor_mode:
raise S3MError("Calling Connection.fetchmany() while not in single cursor mode")
return sel... | [
"def",
"fetchmany",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"single_cursor_mode",
":",
"raise",
"S3MError",
"(",
"\"Calling Connection.fetchmany() while not in single cursor mode\"",
")",
"return",
"self",
".",
... | Analogous to :any:`sqlite3.Cursor.fetchmany`.
Works only in single cursor mode. | [
"Analogous",
"to",
":",
"any",
":",
"sqlite3",
".",
"Cursor",
".",
"fetchmany",
"."
] | python | train | 31.454545 |
jazzband/inflect | inflect.py | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2350-L2363 | def compare_adjs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
... | [
"def",
"compare_adjs",
"(",
"self",
",",
"word1",
",",
"word2",
")",
":",
"return",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_adj",
")"
] | compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural for... | [
"compare",
"word1",
"and",
"word2",
"for",
"equality",
"regardless",
"of",
"plurality",
"word1",
"and",
"word2",
"are",
"to",
"be",
"treated",
"as",
"adjectives"
] | python | train | 34.428571 |
kevinconway/confpy | confpy/options/numopt.py | https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/options/numopt.py#L16-L33 | def coerce(self, value):
"""Convert text values into integer values.
Args:
value (str or int): The value to coerce.
Raises:
TypeError: If the value is not an int or string.
ValueError: If the value is not int or an acceptable value.
Return... | [
"def",
"coerce",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
"or",
"isinstance",
"(",
"value",
",",
"compat",
".",
"long",
")",
":",
"return",
"value",
"return",
"int",
"(",
"value",
")"
] | Convert text values into integer values.
Args:
value (str or int): The value to coerce.
Raises:
TypeError: If the value is not an int or string.
ValueError: If the value is not int or an acceptable value.
Returns:
int: The integer valu... | [
"Convert",
"text",
"values",
"into",
"integer",
"values",
".",
"Args",
":",
"value",
"(",
"str",
"or",
"int",
")",
":",
"The",
"value",
"to",
"coerce",
".",
"Raises",
":",
"TypeError",
":",
"If",
"the",
"value",
"is",
"not",
"an",
"int",
"or",
"strin... | python | train | 27.444444 |
anomaly/prestans | prestans/types/data_url_file.py | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/data_url_file.py#L130-L142 | def save(self, path):
"""
Writes file to a particular location
This won't work for cloud environments like Google's App Engine, use with caution
ensure to catch exceptions so you can provide informed feedback.
prestans does not mask File IO exceptions so your handler can respon... | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"file_handle",
"=",
"open",
"(",
"path",
",",
"'wb'",
")",
"file_handle",
".",
"write",
"(",
"self",
".",
"_file_contents",
")",
"file_handle",
".",
"close",
"(",
")"
] | Writes file to a particular location
This won't work for cloud environments like Google's App Engine, use with caution
ensure to catch exceptions so you can provide informed feedback.
prestans does not mask File IO exceptions so your handler can respond better. | [
"Writes",
"file",
"to",
"a",
"particular",
"location"
] | python | train | 34.153846 |
geertj/gruvi | lib/gruvi/sync.py | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/sync.py#L381-L406 | def wait_for(self, predicate, timeout=None):
"""Like :meth:`wait` but additionally for *predicate* to be true.
The *predicate* argument must be a callable that takes no arguments.
Its result is interpreted as a boolean value.
"""
if not is_locked(self._lock):
raise R... | [
"def",
"wait_for",
"(",
"self",
",",
"predicate",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"is_locked",
"(",
"self",
".",
"_lock",
")",
":",
"raise",
"RuntimeError",
"(",
"'lock is not locked'",
")",
"hub",
"=",
"get_hub",
"(",
")",
"try",
"... | Like :meth:`wait` but additionally for *predicate* to be true.
The *predicate* argument must be a callable that takes no arguments.
Its result is interpreted as a boolean value. | [
"Like",
":",
"meth",
":",
"wait",
"but",
"additionally",
"for",
"*",
"predicate",
"*",
"to",
"be",
"true",
"."
] | python | train | 41.846154 |
maxzheng/localconfig | localconfig/manager.py | https://github.com/maxzheng/localconfig/blob/636087f2489295d9dae2693dda8a86e4daa4ff9d/localconfig/manager.py#L231-L265 | def _parse_extra(self, fp):
""" Parse and store the config comments and create maps for dot notion lookup """
comment = ''
section = ''
fp.seek(0)
for line in fp:
line = line.rstrip()
if not line:
if comment:
comment ... | [
"def",
"_parse_extra",
"(",
"self",
",",
"fp",
")",
":",
"comment",
"=",
"''",
"section",
"=",
"''",
"fp",
".",
"seek",
"(",
"0",
")",
"for",
"line",
"in",
"fp",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"not",
"line",
":",
"if",... | Parse and store the config comments and create maps for dot notion lookup | [
"Parse",
"and",
"store",
"the",
"config",
"comments",
"and",
"create",
"maps",
"for",
"dot",
"notion",
"lookup"
] | python | train | 29.057143 |
gdoermann/voicebase | voicebase/api/__init__.py | https://github.com/gdoermann/voicebase/blob/53cb4735327898a7a284dea3a60ace0b3956a8ec/voicebase/api/__init__.py#L39-L47 | def session(self):
"""
This is what you should use to make requests. It sill authenticate for you.
:return: requests.sessions.Session
"""
if not self._session:
self._session = requests.Session()
self._session.headers.update(dict(Authorization='Bearer {0}'... | [
"def",
"session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_session",
":",
"self",
".",
"_session",
"=",
"requests",
".",
"Session",
"(",
")",
"self",
".",
"_session",
".",
"headers",
".",
"update",
"(",
"dict",
"(",
"Authorization",
"=",
"'... | This is what you should use to make requests. It sill authenticate for you.
:return: requests.sessions.Session | [
"This",
"is",
"what",
"you",
"should",
"use",
"to",
"make",
"requests",
".",
"It",
"sill",
"authenticate",
"for",
"you",
".",
":",
"return",
":",
"requests",
".",
"sessions",
".",
"Session"
] | python | train | 40.222222 |
bspaans/python-mingus | mingus/midi/sequencer.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L104-L107 | def notify_listeners(self, msg_type, params):
"""Send a message to all the observers."""
for c in self.listeners:
c.notify(msg_type, params) | [
"def",
"notify_listeners",
"(",
"self",
",",
"msg_type",
",",
"params",
")",
":",
"for",
"c",
"in",
"self",
".",
"listeners",
":",
"c",
".",
"notify",
"(",
"msg_type",
",",
"params",
")"
] | Send a message to all the observers. | [
"Send",
"a",
"message",
"to",
"all",
"the",
"observers",
"."
] | python | train | 41.25 |
msmbuilder/msmbuilder | msmbuilder/tpt/flux.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/flux.py#L96-L143 | def net_fluxes(sources, sinks, msm, for_committors=None):
"""
Computes the transition path theory net flux matrix.
Parameters
----------
sources : array_like, int
The set of unfolded/reactant states.
sinks : array_like, int
The set of folded/product states.
msm : msmbuilder.... | [
"def",
"net_fluxes",
"(",
"sources",
",",
"sinks",
",",
"msm",
",",
"for_committors",
"=",
"None",
")",
":",
"flux_matrix",
"=",
"fluxes",
"(",
"sources",
",",
"sinks",
",",
"msm",
",",
"for_committors",
"=",
"for_committors",
")",
"net_flux",
"=",
"flux_m... | Computes the transition path theory net flux matrix.
Parameters
----------
sources : array_like, int
The set of unfolded/reactant states.
sinks : array_like, int
The set of folded/product states.
msm : msmbuilder.MarkovStateModel
MSM fit to data.
for_committors : np.ndar... | [
"Computes",
"the",
"transition",
"path",
"theory",
"net",
"flux",
"matrix",
"."
] | python | train | 33.0625 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L450-L464 | def vocab_account_type(instance):
"""Ensure a user-account objects' 'account-type' property is from the
account-type-ov vocabulary.
"""
for key, obj in instance['objects'].items():
if 'type' in obj and obj['type'] == 'user-account':
try:
acct_type = obj['account_type'... | [
"def",
"vocab_account_type",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'user-account'",
":",
"try",
... | Ensure a user-account objects' 'account-type' property is from the
account-type-ov vocabulary. | [
"Ensure",
"a",
"user",
"-",
"account",
"objects",
"account",
"-",
"type",
"property",
"is",
"from",
"the",
"account",
"-",
"type",
"-",
"ov",
"vocabulary",
"."
] | python | train | 48.6 |
joowani/binarytree | binarytree/__init__.py | https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L84-L98 | def _build_bst_from_sorted_values(sorted_values):
"""Recursively build a perfect BST from odd number of sorted values.
:param sorted_values: Odd number of sorted values.
:type sorted_values: [int | float]
:return: Root node of the BST.
:rtype: binarytree.Node
"""
if len(sorted_values) == 0:... | [
"def",
"_build_bst_from_sorted_values",
"(",
"sorted_values",
")",
":",
"if",
"len",
"(",
"sorted_values",
")",
"==",
"0",
":",
"return",
"None",
"mid_index",
"=",
"len",
"(",
"sorted_values",
")",
"//",
"2",
"root",
"=",
"Node",
"(",
"sorted_values",
"[",
... | Recursively build a perfect BST from odd number of sorted values.
:param sorted_values: Odd number of sorted values.
:type sorted_values: [int | float]
:return: Root node of the BST.
:rtype: binarytree.Node | [
"Recursively",
"build",
"a",
"perfect",
"BST",
"from",
"odd",
"number",
"of",
"sorted",
"values",
"."
] | python | train | 38.333333 |
google/prettytensor | prettytensor/replay_queue.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/replay_queue.py#L26-L39 | def _make_tuple(x):
"""TF has an obnoxious habit of being lenient with single vs tuple."""
if isinstance(x, prettytensor.PrettyTensor):
if x.is_sequence():
return tuple(x.sequence)
else:
return (x.tensor,)
elif isinstance(x, tuple):
return x
elif (isinstance(x, collections.Sequence) and
... | [
"def",
"_make_tuple",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"prettytensor",
".",
"PrettyTensor",
")",
":",
"if",
"x",
".",
"is_sequence",
"(",
")",
":",
"return",
"tuple",
"(",
"x",
".",
"sequence",
")",
"else",
":",
"return",
"(",
... | TF has an obnoxious habit of being lenient with single vs tuple. | [
"TF",
"has",
"an",
"obnoxious",
"habit",
"of",
"being",
"lenient",
"with",
"single",
"vs",
"tuple",
"."
] | python | train | 28.285714 |
CalebBell/fluids | fluids/two_phase.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L2399-L2481 | def two_phase_dP_acceleration(m, D, xi, xo, alpha_i, alpha_o, rho_li, rho_gi,
rho_lo=None, rho_go=None):
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to acceleration for flow inside channels. This is a discrete
calculation for a segment wit... | [
"def",
"two_phase_dP_acceleration",
"(",
"m",
",",
"D",
",",
"xi",
",",
"xo",
",",
"alpha_i",
",",
"alpha_o",
",",
"rho_li",
",",
"rho_gi",
",",
"rho_lo",
"=",
"None",
",",
"rho_go",
"=",
"None",
")",
":",
"G",
"=",
"4",
"*",
"m",
"/",
"(",
"pi",... | r'''This function handles calculation of two-phase liquid-gas pressure drop
due to acceleration for flow inside channels. This is a discrete
calculation for a segment with a known difference in quality (and ideally
known inlet and outlet pressures so density dependence can be included).
.. math::... | [
"r",
"This",
"function",
"handles",
"calculation",
"of",
"two",
"-",
"phase",
"liquid",
"-",
"gas",
"pressure",
"drop",
"due",
"to",
"acceleration",
"for",
"flow",
"inside",
"channels",
".",
"This",
"is",
"a",
"discrete",
"calculation",
"for",
"a",
"segment"... | python | train | 39.084337 |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L1741-L1757 | def disconnectMsToNet(Facility_presence=0, UserUser_presence=0,
SsVersionIndicator_presence=0):
"""Disconnect Section 9.3.7.2"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x25) # 00100101
c = Cause()
packet = a / b / c
if Facility_presence is 1:
d = FacilityHdr(ieiF... | [
"def",
"disconnectMsToNet",
"(",
"Facility_presence",
"=",
"0",
",",
"UserUser_presence",
"=",
"0",
",",
"SsVersionIndicator_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x25",
... | Disconnect Section 9.3.7.2 | [
"Disconnect",
"Section",
"9",
".",
"3",
".",
"7",
".",
"2"
] | python | train | 36.176471 |
bio2bel/bio2bel | src/bio2bel/manager/namespace_manager.py | https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L345-L365 | def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None:
"""Write as a BEL namespace file."""
if not self.is_populated():
self.populate()
if use_names and not self.has_names:
raise ValueError
values = (
self._get_namespace_name_t... | [
"def",
"write_bel_namespace",
"(",
"self",
",",
"file",
":",
"TextIO",
",",
"use_names",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"is_populated",
"(",
")",
":",
"self",
".",
"populate",
"(",
")",
"if",
"use_names",
... | Write as a BEL namespace file. | [
"Write",
"as",
"a",
"BEL",
"namespace",
"file",
"."
] | python | valid | 33.857143 |
elifesciences/proofreader-python | proofreader/license_checker/__init__.py | https://github.com/elifesciences/proofreader-python/blob/387b3c65ee7777e26b3a7340179dc4ed68f24f58/proofreader/license_checker/__init__.py#L12-L19 | def _get_packages():
# type: () -> List[Package]
"""Convert `pkg_resources.working_set` into a list of `Package` objects.
:return: list
"""
return [Package(pkg_obj=pkg) for pkg in sorted(pkg_resources.working_set,
key=lambda x: str(x).lower())] | [
"def",
"_get_packages",
"(",
")",
":",
"# type: () -> List[Package]",
"return",
"[",
"Package",
"(",
"pkg_obj",
"=",
"pkg",
")",
"for",
"pkg",
"in",
"sorted",
"(",
"pkg_resources",
".",
"working_set",
",",
"key",
"=",
"lambda",
"x",
":",
"str",
"(",
"x",
... | Convert `pkg_resources.working_set` into a list of `Package` objects.
:return: list | [
"Convert",
"pkg_resources",
".",
"working_set",
"into",
"a",
"list",
"of",
"Package",
"objects",
"."
] | python | train | 38.625 |
MacHu-GWU/angora-project | angora/bot/macro.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/bot/macro.py#L181-L185 | def Down(self, n = 1, dl = 0):
"""下方向键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.down_key, n) | [
"def",
"Down",
"(",
"self",
",",
"n",
"=",
"1",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"keyboard",
".",
"tap_key",
"(",
"self",
".",
"keyboard",
".",
"down_key",
",",
"n",
")"
] | 下方向键n次 | [
"下方向键n次"
] | python | train | 27.2 |
trustar/trustar-python | trustar/indicator_client.py | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L300-L321 | def get_indicators_metadata(self, indicators):
"""
Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings,
lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has
READ access to... | [
"def",
"get_indicators_metadata",
"(",
"self",
",",
"indicators",
")",
":",
"data",
"=",
"[",
"{",
"'value'",
":",
"i",
".",
"value",
",",
"'indicatorType'",
":",
"i",
".",
"type",
"}",
"for",
"i",
"in",
"indicators",
"]",
"resp",
"=",
"self",
".",
"... | Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings,
lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has
READ access to.
:param indicators: a list of |Indicator| objects to quer... | [
"Provide",
"metadata",
"associated",
"with",
"an",
"list",
"of",
"indicators",
"including",
"value",
"indicatorType",
"noteCount",
"sightings",
"lastSeen",
"enclaveIds",
"and",
"tags",
".",
"The",
"metadata",
"is",
"determined",
"based",
"on",
"the",
"enclaves",
"... | python | train | 50.954545 |
openstack/proliantutils | proliantutils/redfish/resources/system/secure_boot.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/secure_boot.py#L84-L98 | def get_allowed_reset_keys_values(self):
"""Get the allowed values for resetting the system.
:returns: A set with the allowed values.
"""
reset_keys_action = self._get_reset_keys_action_element()
if not reset_keys_action.allowed_values:
LOG.warning('Could not figure... | [
"def",
"get_allowed_reset_keys_values",
"(",
"self",
")",
":",
"reset_keys_action",
"=",
"self",
".",
"_get_reset_keys_action_element",
"(",
")",
"if",
"not",
"reset_keys_action",
".",
"allowed_values",
":",
"LOG",
".",
"warning",
"(",
"'Could not figure out the allowed... | Get the allowed values for resetting the system.
:returns: A set with the allowed values. | [
"Get",
"the",
"allowed",
"values",
"for",
"resetting",
"the",
"system",
"."
] | python | train | 44.466667 |
pytroll/pyspectral | pyspectral/atm_correction_ir.py | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/atm_correction_ir.py#L98-L132 | def viewzen_corr(data, view_zen):
"""Apply atmospheric correction on the given *data* using the
specified satellite zenith angles (*view_zen*). Both input data
are given as 2-dimensional Numpy (masked) arrays, and they should
have equal shapes.
The *data* array will be changed in place and has to be... | [
"def",
"viewzen_corr",
"(",
"data",
",",
"view_zen",
")",
":",
"def",
"ratio",
"(",
"value",
",",
"v_null",
",",
"v_ref",
")",
":",
"return",
"(",
"value",
"-",
"v_null",
")",
"/",
"(",
"v_ref",
"-",
"v_null",
")",
"def",
"tau0",
"(",
"t",
")",
"... | Apply atmospheric correction on the given *data* using the
specified satellite zenith angles (*view_zen*). Both input data
are given as 2-dimensional Numpy (masked) arrays, and they should
have equal shapes.
The *data* array will be changed in place and has to be copied before. | [
"Apply",
"atmospheric",
"correction",
"on",
"the",
"given",
"*",
"data",
"*",
"using",
"the",
"specified",
"satellite",
"zenith",
"angles",
"(",
"*",
"view_zen",
"*",
")",
".",
"Both",
"input",
"data",
"are",
"given",
"as",
"2",
"-",
"dimensional",
"Numpy"... | python | train | 29.857143 |
ValvePython/steam | steam/client/__init__.py | https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/client/__init__.py#L581-L647 | def cli_login(self, username='', password=''):
"""Generates CLI prompts to complete the login process
:param username: optionally provide username
:type username: :class:`str`
:param password: optionally provide password
:type password: :class:`str`
:return: logon resu... | [
"def",
"cli_login",
"(",
"self",
",",
"username",
"=",
"''",
",",
"password",
"=",
"''",
")",
":",
"if",
"not",
"username",
":",
"username",
"=",
"_cli_input",
"(",
"\"Username: \"",
")",
"if",
"not",
"password",
":",
"password",
"=",
"getpass",
"(",
"... | Generates CLI prompts to complete the login process
:param username: optionally provide username
:type username: :class:`str`
:param password: optionally provide password
:type password: :class:`str`
:return: logon result, see `CMsgClientLogonResponse.eresult <https://github.c... | [
"Generates",
"CLI",
"prompts",
"to",
"complete",
"the",
"login",
"process"
] | python | train | 44.074627 |
openvax/datacache | datacache/database_table.py | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_table.py#L43-L68 | def from_dataframe(cls, name, df, indices, primary_key=None):
"""Infer table metadata from a DataFrame"""
# ordered list (column_name, column_type) pairs
column_types = []
# which columns have nullable values
nullable = set()
# tag cached database by dataframe's number ... | [
"def",
"from_dataframe",
"(",
"cls",
",",
"name",
",",
"df",
",",
"indices",
",",
"primary_key",
"=",
"None",
")",
":",
"# ordered list (column_name, column_type) pairs",
"column_types",
"=",
"[",
"]",
"# which columns have nullable values",
"nullable",
"=",
"set",
... | Infer table metadata from a DataFrame | [
"Infer",
"table",
"metadata",
"from",
"a",
"DataFrame"
] | python | train | 34.538462 |
jobovy/galpy | galpy/util/bovy_coords.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_coords.py#L1783-L1823 | def Rz_to_coshucosv(R,z,delta=1.,oblate=False):
"""
NAME:
Rz_to_coshucosv
PURPOSE:
calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta
INPUT:
R - radius
z - height
delta= focus
oblate= (False) if True, compute oblate confocal co... | [
"def",
"Rz_to_coshucosv",
"(",
"R",
",",
"z",
",",
"delta",
"=",
"1.",
",",
"oblate",
"=",
"False",
")",
":",
"if",
"oblate",
":",
"d12",
"=",
"(",
"R",
"+",
"delta",
")",
"**",
"2.",
"+",
"z",
"**",
"2.",
"d22",
"=",
"(",
"R",
"-",
"delta",
... | NAME:
Rz_to_coshucosv
PURPOSE:
calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta
INPUT:
R - radius
z - height
delta= focus
oblate= (False) if True, compute oblate confocal coordinates instead of prolate
OUTPUT:
(cosh(u),co... | [
"NAME",
":"
] | python | train | 20.268293 |
googledatalab/pydatalab | datalab/bigquery/_query.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L496-L529 | def execute(self, table_name=None, table_mode='create', use_cache=True, priority='interactive',
allow_large_results=False, dialect=None, billing_tier=None):
""" Initiate the query, blocking until complete and then return the results.
Args:
table_name: the result table name as a string or Ta... | [
"def",
"execute",
"(",
"self",
",",
"table_name",
"=",
"None",
",",
"table_mode",
"=",
"'create'",
",",
"use_cache",
"=",
"True",
",",
"priority",
"=",
"'interactive'",
",",
"allow_large_results",
"=",
"False",
",",
"dialect",
"=",
"None",
",",
"billing_tier... | Initiate the query, blocking until complete and then return the results.
Args:
table_name: the result table name as a string or TableName; if None (the default), then a
temporary table will be used.
table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request
... | [
"Initiate",
"the",
"query",
"blocking",
"until",
"complete",
"and",
"then",
"return",
"the",
"results",
"."
] | python | train | 60.647059 |
inveniosoftware-attic/invenio-utils | invenio_utils/text.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/text.py#L680-L716 | def xml_entities_to_utf8(text, skip=('lt', 'gt', 'amp')):
"""Translate HTML or XML character references to UTF-8.
Removes HTML or XML character references and entities from a text string
and replaces them with their UTF-8 representation, if possible.
:param text: The HTML (or XML) source text.
:ty... | [
"def",
"xml_entities_to_utf8",
"(",
"text",
",",
"skip",
"=",
"(",
"'lt'",
",",
"'gt'",
",",
"'amp'",
")",
")",
":",
"def",
"fixup",
"(",
"m",
")",
":",
"text",
"=",
"m",
".",
"group",
"(",
"0",
")",
"if",
"text",
"[",
":",
"2",
"]",
"==",
"\... | Translate HTML or XML character references to UTF-8.
Removes HTML or XML character references and entities from a text string
and replaces them with their UTF-8 representation, if possible.
:param text: The HTML (or XML) source text.
:type text: string
:param skip: list of entity names to skip wh... | [
"Translate",
"HTML",
"or",
"XML",
"character",
"references",
"to",
"UTF",
"-",
"8",
"."
] | python | train | 34.783784 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1460-L1468 | def getwinsize(self):
"""This returns the terminal window size of the child tty. The return
value is a tuple of (rows, cols). """
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
r... | [
"def",
"getwinsize",
"(",
"self",
")",
":",
"TIOCGWINSZ",
"=",
"getattr",
"(",
"termios",
",",
"'TIOCGWINSZ'",
",",
"1074295912L",
")",
"s",
"=",
"struct",
".",
"pack",
"(",
"'HHHH'",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"x",
"=",
"fcntl",
... | This returns the terminal window size of the child tty. The return
value is a tuple of (rows, cols). | [
"This",
"returns",
"the",
"terminal",
"window",
"size",
"of",
"the",
"child",
"tty",
".",
"The",
"return",
"value",
"is",
"a",
"tuple",
"of",
"(",
"rows",
"cols",
")",
"."
] | python | test | 38.555556 |
thanethomson/statik | statik/views.py | https://github.com/thanethomson/statik/blob/56b1b5a2cb05a97afa81f428bfcefc833e935b8d/statik/views.py#L71-L100 | def create(
cls,
path,
template_engine=None,
output_filename=None,
output_ext=None,
view_name=None
):
"""Create the relevant subclass of StatikView based on the given path variable and
parameters."""
# if it's a comp... | [
"def",
"create",
"(",
"cls",
",",
"path",
",",
"template_engine",
"=",
"None",
",",
"output_filename",
"=",
"None",
",",
"output_ext",
"=",
"None",
",",
"view_name",
"=",
"None",
")",
":",
"# if it's a complex view",
"if",
"isinstance",
"(",
"path",
",",
"... | Create the relevant subclass of StatikView based on the given path variable and
parameters. | [
"Create",
"the",
"relevant",
"subclass",
"of",
"StatikView",
"based",
"on",
"the",
"given",
"path",
"variable",
"and",
"parameters",
"."
] | python | train | 32.1 |
CalebBell/ht | ht/conv_two_phase.py | https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/conv_two_phase.py#L266-L337 | def Hughmark(m, x, alpha, D, L, Cpl, kl, mu_b=None, mu_w=None):
r'''Calculates the two-phase non-boiling laminar heat transfer coefficient
of a liquid and gas flowing inside a tube of any inclination, as in [1]_
and reviewed in [2]_.
.. math::
\frac{h_{TP} D}{k_l} = 1.75(1-\alpha)^{-0.5}\le... | [
"def",
"Hughmark",
"(",
"m",
",",
"x",
",",
"alpha",
",",
"D",
",",
"L",
",",
"Cpl",
",",
"kl",
",",
"mu_b",
"=",
"None",
",",
"mu_w",
"=",
"None",
")",
":",
"ml",
"=",
"m",
"*",
"(",
"1",
"-",
"x",
")",
"RL",
"=",
"1",
"-",
"alpha",
"N... | r'''Calculates the two-phase non-boiling laminar heat transfer coefficient
of a liquid and gas flowing inside a tube of any inclination, as in [1]_
and reviewed in [2]_.
.. math::
\frac{h_{TP} D}{k_l} = 1.75(1-\alpha)^{-0.5}\left(\frac{m_l C_{p,l}}
{(1-\alpha)k_l L}\right)^{1/3}\left(\f... | [
"r",
"Calculates",
"the",
"two",
"-",
"phase",
"non",
"-",
"boiling",
"laminar",
"heat",
"transfer",
"coefficient",
"of",
"a",
"liquid",
"and",
"gas",
"flowing",
"inside",
"a",
"tube",
"of",
"any",
"inclination",
"as",
"in",
"[",
"1",
"]",
"_",
"and",
... | python | train | 34.277778 |
pbrisk/timewave | timewave/producers.py | https://github.com/pbrisk/timewave/blob/cf641391d1607a424042724c8b990d43ee270ef6/timewave/producers.py#L55-L61 | def initialize_path(self, path_num=None):
""" inits producer for next path, i.e. sets current state to initial state"""
for p in self.producers:
p.initialize_path(path_num)
# self.state = copy(self.initial_state)
# self.state.path = path_num
self.random.seed(hash(self... | [
"def",
"initialize_path",
"(",
"self",
",",
"path_num",
"=",
"None",
")",
":",
"for",
"p",
"in",
"self",
".",
"producers",
":",
"p",
".",
"initialize_path",
"(",
"path_num",
")",
"# self.state = copy(self.initial_state)",
"# self.state.path = path_num",
"self",
".... | inits producer for next path, i.e. sets current state to initial state | [
"inits",
"producer",
"for",
"next",
"path",
"i",
".",
"e",
".",
"sets",
"current",
"state",
"to",
"initial",
"state"
] | python | train | 48.285714 |
kvh/ramp | ramp/shortcuts.py | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/shortcuts.py#L109-L130 | def cross_validate(data=None, folds=5, repeat=1, metrics=None,
reporters=None, model_def=None, **kwargs):
"""Shortcut to cross-validate a single configuration.
ModelDefinition variables are passed in as keyword args, along
with the cross-validation parameters.
"""
md_kwargs = {}
... | [
"def",
"cross_validate",
"(",
"data",
"=",
"None",
",",
"folds",
"=",
"5",
",",
"repeat",
"=",
"1",
",",
"metrics",
"=",
"None",
",",
"reporters",
"=",
"None",
",",
"model_def",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"md_kwargs",
"=",
"{",... | Shortcut to cross-validate a single configuration.
ModelDefinition variables are passed in as keyword args, along
with the cross-validation parameters. | [
"Shortcut",
"to",
"cross",
"-",
"validate",
"a",
"single",
"configuration",
"."
] | python | train | 38.863636 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L602-L634 | def do_page_has_content(parser, token):
"""
Conditional tag that only renders its nodes if the page
has content for a particular content type. By default the
current page is used.
Syntax::
{% page_has_content <content_type> [<page var name>] %}
...
{%_end page_has_conte... | [
"def",
"do_page_has_content",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'end_page_has_content'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"args",
"=",
"token",
".",
"split_contents",
"(",
... | Conditional tag that only renders its nodes if the page
has content for a particular content type. By default the
current page is used.
Syntax::
{% page_has_content <content_type> [<page var name>] %}
...
{%_end page_has_content %}
Example use::
{% page_has_conten... | [
"Conditional",
"tag",
"that",
"only",
"renders",
"its",
"nodes",
"if",
"the",
"page",
"has",
"content",
"for",
"a",
"particular",
"content",
"type",
".",
"By",
"default",
"the",
"current",
"page",
"is",
"used",
"."
] | python | train | 28.606061 |
saltstack/salt | salt/modules/openbsdpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L57-L98 | def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet imple... | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"versions_as_list",
")",
"# not yet implemented or not applicable",
"if",
"any",
"(",
... | List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs | [
"List",
"the",
"packages",
"currently",
"installed",
"as",
"a",
"dict",
"::"
] | python | train | 30.595238 |
ioos/cc-plugin-ncei | cc_plugin_ncei/ncei_grid.py | https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/ncei_grid.py#L42-L93 | def check_bounds_variables(self, dataset):
'''
Checks the grid boundary variables.
:param netCDF4.Dataset dataset: An open netCDF dataset
'''
recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended variables to describe grid boundaries')
bounds_map = {
'lat... | [
"def",
"check_bounds_variables",
"(",
"self",
",",
"dataset",
")",
":",
"recommended_ctx",
"=",
"TestCtx",
"(",
"BaseCheck",
".",
"MEDIUM",
",",
"'Recommended variables to describe grid boundaries'",
")",
"bounds_map",
"=",
"{",
"'lat_bounds'",
":",
"{",
"'units'",
... | Checks the grid boundary variables.
:param netCDF4.Dataset dataset: An open netCDF dataset | [
"Checks",
"the",
"grid",
"boundary",
"variables",
"."
] | python | train | 39.019231 |
log2timeline/dfdatetime | dfdatetime/interface.py | https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L865-L886 | def CopyToStatTimeTuple(self):
"""Copies the date time value to a stat timestamp tuple.
Returns:
tuple[int, int]: a POSIX timestamp in seconds and the remainder in
100 nano seconds or (None, None) on error.
"""
normalized_timestamp = self._GetNormalizedTimestamp()
if normalized_time... | [
"def",
"CopyToStatTimeTuple",
"(",
"self",
")",
":",
"normalized_timestamp",
"=",
"self",
".",
"_GetNormalizedTimestamp",
"(",
")",
"if",
"normalized_timestamp",
"is",
"None",
":",
"return",
"None",
",",
"None",
"if",
"self",
".",
"_precision",
"in",
"(",
"def... | Copies the date time value to a stat timestamp tuple.
Returns:
tuple[int, int]: a POSIX timestamp in seconds and the remainder in
100 nano seconds or (None, None) on error. | [
"Copies",
"the",
"date",
"time",
"value",
"to",
"a",
"stat",
"timestamp",
"tuple",
"."
] | python | train | 34.818182 |
michaelpb/omnic | omnic/utils/filesystem.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/filesystem.py#L71-L134 | def flat_git_tree_to_nested(flat_tree, prefix=''):
'''
Given an array in format:
[
["100644", "blob", "ab3ce...", "748", ".gitignore" ],
["100644", "blob", "ab3ce...", "748", "path/to/thing" ],
...
]
Outputs in a nested format:
{
"path... | [
"def",
"flat_git_tree_to_nested",
"(",
"flat_tree",
",",
"prefix",
"=",
"''",
")",
":",
"root",
"=",
"_make_empty_dir_dict",
"(",
"prefix",
"if",
"prefix",
"else",
"'/'",
")",
"# Filter all descendents of this prefix",
"descendent_files",
"=",
"[",
"info",
"for",
... | Given an array in format:
[
["100644", "blob", "ab3ce...", "748", ".gitignore" ],
["100644", "blob", "ab3ce...", "748", "path/to/thing" ],
...
]
Outputs in a nested format:
{
"path": "/",
"type": "directory",
"children"... | [
"Given",
"an",
"array",
"in",
"format",
":",
"[",
"[",
"100644",
"blob",
"ab3ce",
"...",
"748",
".",
"gitignore",
"]",
"[",
"100644",
"blob",
"ab3ce",
"...",
"748",
"path",
"/",
"to",
"/",
"thing",
"]",
"...",
"]"
] | python | train | 28.640625 |
Contraz/demosys-py | demosys/context/pyqt/window.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/pyqt/window.py#L115-L128 | def resize(self, width, height):
"""
Pyqt specific resize callback.
"""
if not self.fbo:
return
# pyqt reports sizes in actual buffer size
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
... | [
"def",
"resize",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"if",
"not",
"self",
".",
"fbo",
":",
"return",
"# pyqt reports sizes in actual buffer size",
"self",
".",
"width",
"=",
"width",
"//",
"self",
".",
"widget",
".",
"devicePixelRatio",
"(",
... | Pyqt specific resize callback. | [
"Pyqt",
"specific",
"resize",
"callback",
"."
] | python | valid | 29.357143 |
jayclassless/tidypy | src/tidypy/collector.py | https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/collector.py#L88-L109 | def get_grouped_issues(self, keyfunc=None, sortby=None):
"""
Retrieves the issues in the collection grouped into buckets according
to the key generated by the keyfunc.
:param keyfunc:
a function that will be used to generate the key that identifies
the group that... | [
"def",
"get_grouped_issues",
"(",
"self",
",",
"keyfunc",
"=",
"None",
",",
"sortby",
"=",
"None",
")",
":",
"if",
"not",
"keyfunc",
":",
"keyfunc",
"=",
"default_group",
"if",
"not",
"sortby",
":",
"sortby",
"=",
"self",
".",
"DEFAULT_SORT",
"self",
"."... | Retrieves the issues in the collection grouped into buckets according
to the key generated by the keyfunc.
:param keyfunc:
a function that will be used to generate the key that identifies
the group that an issue will be assigned to. This function receives
a single ti... | [
"Retrieves",
"the",
"issues",
"in",
"the",
"collection",
"grouped",
"into",
"buckets",
"according",
"to",
"the",
"key",
"generated",
"by",
"the",
"keyfunc",
"."
] | python | valid | 40.227273 |
janpipek/physt | physt/io/json.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/json.py#L43-L47 | def load_json(path: str, encoding: str = "utf-8") -> HistogramBase:
"""Load histogram from a JSON file."""
with open(path, "r", encoding=encoding) as f:
text = f.read()
return parse_json(text) | [
"def",
"load_json",
"(",
"path",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
")",
"->",
"HistogramBase",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"r... | Load histogram from a JSON file. | [
"Load",
"histogram",
"from",
"a",
"JSON",
"file",
"."
] | python | train | 42.4 |
hydpy-dev/hydpy | hydpy/cythons/modelutils.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L66-L74 | def add(self, indent, line):
"""Appends the given text line with prefixed spaces in accordance with
the given number of indentation levels.
"""
if isinstance(line, str):
list.append(self, indent*4*' ' + line)
else:
for subline in line:
list... | [
"def",
"add",
"(",
"self",
",",
"indent",
",",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
":",
"list",
".",
"append",
"(",
"self",
",",
"indent",
"*",
"4",
"*",
"' '",
"+",
"line",
")",
"else",
":",
"for",
"subline",
"i... | Appends the given text line with prefixed spaces in accordance with
the given number of indentation levels. | [
"Appends",
"the",
"given",
"text",
"line",
"with",
"prefixed",
"spaces",
"in",
"accordance",
"with",
"the",
"given",
"number",
"of",
"indentation",
"levels",
"."
] | python | train | 38.777778 |
zblz/naima | naima/model_utils.py | https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/model_utils.py#L15-L84 | def memoize(func):
""" Cache decorator for functions inside model classes """
def model(cls, energy, *args, **kwargs):
try:
memoize = cls._memoize
cache = cls._cache
queue = cls._queue
except AttributeError:
memoize = False
if memoize:
... | [
"def",
"memoize",
"(",
"func",
")",
":",
"def",
"model",
"(",
"cls",
",",
"energy",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"memoize",
"=",
"cls",
".",
"_memoize",
"cache",
"=",
"cls",
".",
"_cache",
"queue",
"=",
"cls",
... | Cache decorator for functions inside model classes | [
"Cache",
"decorator",
"for",
"functions",
"inside",
"model",
"classes"
] | python | train | 31.257143 |
lago-project/lago | lago/templates.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L94-L107 | def get_metadata(self, handle):
"""
Returns the associated metadata info for the given handle, the metadata
file must exist (``handle + '.metadata'``).
Args:
handle (str): Path to the template to get the metadata from
Returns:
dict: Metadata for the give... | [
"def",
"get_metadata",
"(",
"self",
",",
"handle",
")",
":",
"handle",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"handle",
")",
")",
"with",
"open",
"(",
"self",
".",
"_prefixed",
"(",
"'%s.metadata'",
... | Returns the associated metadata info for the given handle, the metadata
file must exist (``handle + '.metadata'``).
Args:
handle (str): Path to the template to get the metadata from
Returns:
dict: Metadata for the given handle | [
"Returns",
"the",
"associated",
"metadata",
"info",
"for",
"the",
"given",
"handle",
"the",
"metadata",
"file",
"must",
"exist",
"(",
"handle",
"+",
".",
"metadata",
")",
"."
] | python | train | 34.785714 |
mwouts/jupytext | jupytext/cell_to_text.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L302-L311 | def simplify_soc_marker(self, text, prev_text):
"""Simplify start of cell marker when previous line is blank"""
if self.cell_marker_start:
return text
if self.is_code() and text and text[0] == self.comment + ' + {}':
if not prev_text or not prev_text[-1].strip():
... | [
"def",
"simplify_soc_marker",
"(",
"self",
",",
"text",
",",
"prev_text",
")",
":",
"if",
"self",
".",
"cell_marker_start",
":",
"return",
"text",
"if",
"self",
".",
"is_code",
"(",
")",
"and",
"text",
"and",
"text",
"[",
"0",
"]",
"==",
"self",
".",
... | Simplify start of cell marker when previous line is blank | [
"Simplify",
"start",
"of",
"cell",
"marker",
"when",
"previous",
"line",
"is",
"blank"
] | python | train | 37 |
rsheftel/raccoon | raccoon/series.py | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L430-L443 | def set(self, indexes, values=None):
"""
Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below
methods based on what types are passed in for the indexes. If the indexes contains values not in the Series
then new rows or columns will... | [
"def",
"set",
"(",
"self",
",",
"indexes",
",",
"values",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"indexes",
",",
"(",
"list",
",",
"blist",
")",
")",
":",
"self",
".",
"set_rows",
"(",
"indexes",
",",
"values",
")",
"else",
":",
"self",
... | Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below
methods based on what types are passed in for the indexes. If the indexes contains values not in the Series
then new rows or columns will be added.
:param indexes: indexes value, list o... | [
"Given",
"indexes",
"will",
"set",
"a",
"sub",
"-",
"set",
"of",
"the",
"Series",
"to",
"the",
"values",
"provided",
".",
"This",
"method",
"will",
"direct",
"to",
"the",
"below",
"methods",
"based",
"on",
"what",
"types",
"are",
"passed",
"in",
"for",
... | python | train | 50.571429 |
pycontribs/pyrax | pyrax/cloudmonitoring.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L131-L147 | def create_check(self, label=None, name=None, check_type=None,
disabled=False, metadata=None, details=None,
monitoring_zones_poll=None, timeout=None, period=None,
target_alias=None, target_hostname=None, target_receiver=None,
test_only=False, include_debug=False):
... | [
"def",
"create_check",
"(",
"self",
",",
"label",
"=",
"None",
",",
"name",
"=",
"None",
",",
"check_type",
"=",
"None",
",",
"disabled",
"=",
"False",
",",
"metadata",
"=",
"None",
",",
"details",
"=",
"None",
",",
"monitoring_zones_poll",
"=",
"None",
... | Creates a check on this entity with the specified attributes. The
'details' parameter should be a dict with the keys as the option name,
and the value as the desired setting. | [
"Creates",
"a",
"check",
"on",
"this",
"entity",
"with",
"the",
"specified",
"attributes",
".",
"The",
"details",
"parameter",
"should",
"be",
"a",
"dict",
"with",
"the",
"keys",
"as",
"the",
"option",
"name",
"and",
"the",
"value",
"as",
"the",
"desired",... | python | train | 57.941176 |
vslutov/turingmarkov | turingmarkov/turing.py | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L144-L157 | def execute(self, string, max_tacts=None):
"""Execute algorithm (if max_times = None, there can be forever loop)."""
self.init_tape(string)
counter = 0
while True:
self.execute_once()
if self.state == self.TERM_STATE:
break
counter += ... | [
"def",
"execute",
"(",
"self",
",",
"string",
",",
"max_tacts",
"=",
"None",
")",
":",
"self",
".",
"init_tape",
"(",
"string",
")",
"counter",
"=",
"0",
"while",
"True",
":",
"self",
".",
"execute_once",
"(",
")",
"if",
"self",
".",
"state",
"==",
... | Execute algorithm (if max_times = None, there can be forever loop). | [
"Execute",
"algorithm",
"(",
"if",
"max_times",
"=",
"None",
"there",
"can",
"be",
"forever",
"loop",
")",
"."
] | python | train | 33.642857 |
materialsproject/pymatgen | pymatgen/io/abinit/tasks.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L2701-L2732 | def filesfile_string(self):
"""String with the list of files and prefixes needed to execute ABINIT."""
lines = []
app = lines.append
pj = os.path.join
app(self.input_file.path) # Path to the input file
app(self.output_file.path) # Path to t... | [
"def",
"filesfile_string",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"app",
"=",
"lines",
".",
"append",
"pj",
"=",
"os",
".",
"path",
".",
"join",
"app",
"(",
"self",
".",
"input_file",
".",
"path",
")",
"# Path to the input file",
"app",
"(",
... | String with the list of files and prefixes needed to execute ABINIT. | [
"String",
"with",
"the",
"list",
"of",
"files",
"and",
"prefixes",
"needed",
"to",
"execute",
"ABINIT",
"."
] | python | train | 38.0625 |
ansible/tower-cli | tower_cli/resources/host.py | https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/host.py#L42-L66 | def list(self, group=None, host_filter=None, **kwargs):
"""Return a list of hosts.
=====API DOCS=====
Retrieve a list of hosts.
:param group: Primary key or name of the group whose hosts will be listed.
:type group: str
:param all_pages: Flag that if set, collect all pa... | [
"def",
"list",
"(",
"self",
",",
"group",
"=",
"None",
",",
"host_filter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"group",
":",
"kwargs",
"[",
"'query'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'query'",
",",
"(",
")",
")",
"+",
"(... | Return a list of hosts.
=====API DOCS=====
Retrieve a list of hosts.
:param group: Primary key or name of the group whose hosts will be listed.
:type group: str
:param all_pages: Flag that if set, collect all pages of content from the API when returning results.
:type a... | [
"Return",
"a",
"list",
"of",
"hosts",
"."
] | python | valid | 45.24 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_aaa.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_aaa.py#L526-L540 | def ldap_server_host_retries(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(ldap_server, "host")
hostname_key = ET.SubElement(host,... | [
"def",
"ldap_server_host_retries",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ldap_server",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ldap-server\"",
",",
"xmlns",
"=",
"\"urn:br... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 43.733333 |
sbneto/s3conf | s3conf/client.py | https://github.com/sbneto/s3conf/blob/92fd2973beccc85bb21d3157ff227929e62ed695/s3conf/client.py#L309-L327 | def unset_variable(section, value):
"""
Unset a variable in an environment file for the given section.
The value is given is the variable name, e.g.:
s3conf unset test ENV_VAR_NAME
"""
if not value:
value = section
section = None
try:
logger.debug('Running env comman... | [
"def",
"unset_variable",
"(",
"section",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"value",
"=",
"section",
"section",
"=",
"None",
"try",
":",
"logger",
".",
"debug",
"(",
"'Running env command'",
")",
"settings",
"=",
"config",
".",
"Settings",
... | Unset a variable in an environment file for the given section.
The value is given is the variable name, e.g.:
s3conf unset test ENV_VAR_NAME | [
"Unset",
"a",
"variable",
"in",
"an",
"environment",
"file",
"for",
"the",
"given",
"section",
".",
"The",
"value",
"is",
"given",
"is",
"the",
"variable",
"name",
"e",
".",
"g",
".",
":"
] | python | test | 30.684211 |
openstack/hacking | hacking/core.py | https://github.com/openstack/hacking/blob/10e58f907181cac91d3b2af422c2458b04a1ec79/hacking/core.py#L91-L97 | def is_import_exception(mod):
"""Check module name to see if import has been whitelisted.
Import based rules should not run on any whitelisted module
"""
return (mod in IMPORT_EXCEPTIONS or
any(mod.startswith(m + '.') for m in IMPORT_EXCEPTIONS)) | [
"def",
"is_import_exception",
"(",
"mod",
")",
":",
"return",
"(",
"mod",
"in",
"IMPORT_EXCEPTIONS",
"or",
"any",
"(",
"mod",
".",
"startswith",
"(",
"m",
"+",
"'.'",
")",
"for",
"m",
"in",
"IMPORT_EXCEPTIONS",
")",
")"
] | Check module name to see if import has been whitelisted.
Import based rules should not run on any whitelisted module | [
"Check",
"module",
"name",
"to",
"see",
"if",
"import",
"has",
"been",
"whitelisted",
"."
] | python | train | 39.285714 |
FujiMakoto/AgentML | agentml/parser/trigger/response/__init__.py | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/response/__init__.py#L119-L136 | def _parse(self):
"""
Loop through all child elements and execute any available parse methods for them
"""
# Is this a shorthand template?
if self._element.tag == 'template':
return self._parse_template(self._element)
# Is this a shorthand redirect?
i... | [
"def",
"_parse",
"(",
"self",
")",
":",
"# Is this a shorthand template?",
"if",
"self",
".",
"_element",
".",
"tag",
"==",
"'template'",
":",
"return",
"self",
".",
"_parse_template",
"(",
"self",
".",
"_element",
")",
"# Is this a shorthand redirect?",
"if",
"... | Loop through all child elements and execute any available parse methods for them | [
"Loop",
"through",
"all",
"child",
"elements",
"and",
"execute",
"any",
"available",
"parse",
"methods",
"for",
"them"
] | python | train | 33.388889 |
kevinconway/venvctrl | venvctrl/venv/base.py | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L269-L276 | def items(self):
"""Get an iter of VenvDirs and VenvFiles within the directory."""
contents = self.paths
contents = (
BinFile(path.path) if path.is_file else BinDir(path.path)
for path in contents
)
return contents | [
"def",
"items",
"(",
"self",
")",
":",
"contents",
"=",
"self",
".",
"paths",
"contents",
"=",
"(",
"BinFile",
"(",
"path",
".",
"path",
")",
"if",
"path",
".",
"is_file",
"else",
"BinDir",
"(",
"path",
".",
"path",
")",
"for",
"path",
"in",
"conte... | Get an iter of VenvDirs and VenvFiles within the directory. | [
"Get",
"an",
"iter",
"of",
"VenvDirs",
"and",
"VenvFiles",
"within",
"the",
"directory",
"."
] | python | train | 33.875 |
IvanMalison/okcupyd | okcupyd/profile_copy.py | https://github.com/IvanMalison/okcupyd/blob/46f4eaa9419098f6c299738ce148af55c64deb64/okcupyd/profile_copy.py#L115-L119 | def essays(self):
"""Copy essays from the source profile to the destination profile."""
for essay_name in self.dest_user.profile.essays.essay_names:
setattr(self.dest_user.profile.essays, essay_name,
getattr(self.source_profile.essays, essay_name)) | [
"def",
"essays",
"(",
"self",
")",
":",
"for",
"essay_name",
"in",
"self",
".",
"dest_user",
".",
"profile",
".",
"essays",
".",
"essay_names",
":",
"setattr",
"(",
"self",
".",
"dest_user",
".",
"profile",
".",
"essays",
",",
"essay_name",
",",
"getattr... | Copy essays from the source profile to the destination profile. | [
"Copy",
"essays",
"from",
"the",
"source",
"profile",
"to",
"the",
"destination",
"profile",
"."
] | python | train | 58.4 |
sibirrer/lenstronomy | lenstronomy/LensModel/Profiles/gaussian_kappa.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/Profiles/gaussian_kappa.py#L37-L45 | def _num_integral(self, r, c):
"""
numerical integral (1-e^{-c*x^2})/x dx [0..r]
:param r: radius
:param c: 1/2sigma^2
:return:
"""
out = integrate.quad(lambda x: (1-np.exp(-c*x**2))/x, 0, r)
return out[0] | [
"def",
"_num_integral",
"(",
"self",
",",
"r",
",",
"c",
")",
":",
"out",
"=",
"integrate",
".",
"quad",
"(",
"lambda",
"x",
":",
"(",
"1",
"-",
"np",
".",
"exp",
"(",
"-",
"c",
"*",
"x",
"**",
"2",
")",
")",
"/",
"x",
",",
"0",
",",
"r",... | numerical integral (1-e^{-c*x^2})/x dx [0..r]
:param r: radius
:param c: 1/2sigma^2
:return: | [
"numerical",
"integral",
"(",
"1",
"-",
"e^",
"{",
"-",
"c",
"*",
"x^2",
"}",
")",
"/",
"x",
"dx",
"[",
"0",
"..",
"r",
"]",
":",
"param",
"r",
":",
"radius",
":",
"param",
"c",
":",
"1",
"/",
"2sigma^2",
":",
"return",
":"
] | python | train | 29 |
timknip/pyswf | swf/movie.py | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/movie.py#L114-L131 | def export(self, exporter=None, force_stroke=False):
"""
Export this SWF using the specified exporter.
When no exporter is passed in the default exporter used
is swf.export.SVGExporter.
Exporters should extend the swf.export.BaseExporter class.
@param ... | [
"def",
"export",
"(",
"self",
",",
"exporter",
"=",
"None",
",",
"force_stroke",
"=",
"False",
")",
":",
"exporter",
"=",
"SVGExporter",
"(",
")",
"if",
"exporter",
"is",
"None",
"else",
"exporter",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"raise... | Export this SWF using the specified exporter.
When no exporter is passed in the default exporter used
is swf.export.SVGExporter.
Exporters should extend the swf.export.BaseExporter class.
@param exporter : the exporter to use
@param force_stroke : set to true ... | [
"Export",
"this",
"SWF",
"using",
"the",
"specified",
"exporter",
".",
"When",
"no",
"exporter",
"is",
"passed",
"in",
"the",
"default",
"exporter",
"used",
"is",
"swf",
".",
"export",
".",
"SVGExporter",
".",
"Exporters",
"should",
"extend",
"the",
"swf",
... | python | train | 43.611111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.