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 |
|---|---|---|---|---|---|---|---|---|---|
anteater/anteater | anteater/src/patch_scan.py | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L209-L240 | def scan_binary(patch_file, project, sha256hash, apikey):
"""
Sends Binary (sha256hash) to Virus Total API
"""
v_api = virus_total.VirusTotal()
while True:
binary_report = v_api.binary_report(sha256hash, apikey)
response_code = binary_report['response_code']
# report does n... | [
"def",
"scan_binary",
"(",
"patch_file",
",",
"project",
",",
"sha256hash",
",",
"apikey",
")",
":",
"v_api",
"=",
"virus_total",
".",
"VirusTotal",
"(",
")",
"while",
"True",
":",
"binary_report",
"=",
"v_api",
".",
"binary_report",
"(",
"sha256hash",
",",
... | Sends Binary (sha256hash) to Virus Total API | [
"Sends",
"Binary",
"(",
"sha256hash",
")",
"to",
"Virus",
"Total",
"API"
] | python | train | 35.59375 |
steven-lang/bottr | bottr/bot.py | https://github.com/steven-lang/bottr/blob/c1b92becc31adfbd5a7b77179b852a51da70b193/bottr/bot.py#L50-L61 | def stop(self):
"""
Stops this bot.
Returns as soon as all running threads have finished processing.
"""
self.log.debug('Stopping bot {}'.format(self._name))
self._stop = True
for t in self._threads:
t.join()
self.log.debug('Stopping bot {} f... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Stopping bot {}'",
".",
"format",
"(",
"self",
".",
"_name",
")",
")",
"self",
".",
"_stop",
"=",
"True",
"for",
"t",
"in",
"self",
".",
"_threads",
":",
"t",
".",
"jo... | Stops this bot.
Returns as soon as all running threads have finished processing. | [
"Stops",
"this",
"bot",
"."
] | python | train | 29.833333 |
ojarva/python-sshpubkeys | sshpubkeys/keys.py | https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L149-L156 | def hash_md5(self):
"""Calculate md5 fingerprint.
Shamelessly copied from http://stackoverflow.com/questions/6682815/deriving-an-ssh-fingerprint-from-a-public-key-in-python
For specification, see RFC4716, section 4."""
fp_plain = hashlib.md5(self._decoded_key).hexdigest()
retur... | [
"def",
"hash_md5",
"(",
"self",
")",
":",
"fp_plain",
"=",
"hashlib",
".",
"md5",
"(",
"self",
".",
"_decoded_key",
")",
".",
"hexdigest",
"(",
")",
"return",
"\"MD5:\"",
"+",
"':'",
".",
"join",
"(",
"a",
"+",
"b",
"for",
"a",
",",
"b",
"in",
"z... | Calculate md5 fingerprint.
Shamelessly copied from http://stackoverflow.com/questions/6682815/deriving-an-ssh-fingerprint-from-a-public-key-in-python
For specification, see RFC4716, section 4. | [
"Calculate",
"md5",
"fingerprint",
"."
] | python | test | 48.25 |
merll/docker-map | dockermap/map/runner/image.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/image.py#L51-L71 | def pull(self, action, image_name, **kwargs):
"""
Pulls an image for a container configuration
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param image_name: Image name.
:type image_name: unicode | str
:param kwargs: Addit... | [
"def",
"pull",
"(",
"self",
",",
"action",
",",
"image_name",
",",
"*",
"*",
"kwargs",
")",
":",
"config_id",
"=",
"action",
".",
"config_id",
"registry",
",",
"__",
",",
"image",
"=",
"config_id",
".",
"config_name",
".",
"rpartition",
"(",
"'/'",
")"... | Pulls an image for a container configuration
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param image_name: Image name.
:type image_name: unicode | str
:param kwargs: Additional keyword arguments to complement or override the configuratio... | [
"Pulls",
"an",
"image",
"for",
"a",
"container",
"configuration"
] | python | train | 55.857143 |
eighthave/pyvendapin | vendapin.py | https://github.com/eighthave/pyvendapin/blob/270c4da5c31ab4a0435660b25b655692fdffcf01/vendapin.py#L180-L188 | def parsedata(self, packet):
'''parse the data section of a packet, it can range from 0 to many bytes'''
data = []
datalength = ord(packet[3])
position = 4
while position < datalength + 4:
data.append(packet[position])
position += 1
return data | [
"def",
"parsedata",
"(",
"self",
",",
"packet",
")",
":",
"data",
"=",
"[",
"]",
"datalength",
"=",
"ord",
"(",
"packet",
"[",
"3",
"]",
")",
"position",
"=",
"4",
"while",
"position",
"<",
"datalength",
"+",
"4",
":",
"data",
".",
"append",
"(",
... | parse the data section of a packet, it can range from 0 to many bytes | [
"parse",
"the",
"data",
"section",
"of",
"a",
"packet",
"it",
"can",
"range",
"from",
"0",
"to",
"many",
"bytes"
] | python | train | 34.222222 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/lm1b.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lm1b.py#L35-L55 | def _original_vocab(tmp_dir):
"""Returns a set containing the original vocabulary.
This is important for comparing with published results.
Args:
tmp_dir: directory containing dataset.
Returns:
a set of strings
"""
vocab_url = ("http://download.tensorflow.org/models/LM_LSTM_CNN/"
"v... | [
"def",
"_original_vocab",
"(",
"tmp_dir",
")",
":",
"vocab_url",
"=",
"(",
"\"http://download.tensorflow.org/models/LM_LSTM_CNN/\"",
"\"vocab-2016-09-10.txt\"",
")",
"vocab_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"vocab_url",
"+",
"\".en\"",
")",
"voc... | Returns a set containing the original vocabulary.
This is important for comparing with published results.
Args:
tmp_dir: directory containing dataset.
Returns:
a set of strings | [
"Returns",
"a",
"set",
"containing",
"the",
"original",
"vocabulary",
"."
] | python | train | 31.333333 |
jaraco/jaraco.windows | jaraco/windows/security.py | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/security.py#L43-L67 | def get_security_attributes_for_user(user=None):
"""
Return a SECURITY_ATTRIBUTES structure with the SID set to the
specified user (uses current user if none is specified).
"""
if user is None:
user = get_current_user()
assert isinstance(user, security.TOKEN_USER), (
"user must be TOKEN_USER instance")
SD ... | [
"def",
"get_security_attributes_for_user",
"(",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"get_current_user",
"(",
")",
"assert",
"isinstance",
"(",
"user",
",",
"security",
".",
"TOKEN_USER",
")",
",",
"(",
"\"user must be... | Return a SECURITY_ATTRIBUTES structure with the SID set to the
specified user (uses current user if none is specified). | [
"Return",
"a",
"SECURITY_ATTRIBUTES",
"structure",
"with",
"the",
"SID",
"set",
"to",
"the",
"specified",
"user",
"(",
"uses",
"current",
"user",
"if",
"none",
"is",
"specified",
")",
"."
] | python | train | 29.28 |
HDI-Project/RDT | rdt/hyper_transformer.py | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L101-L118 | def _get_transformers(self):
"""Load the contents of meta_file and extract information about the transformers.
Returns:
dict: tuple(str, str) -> Transformer.
"""
transformer_dict = {}
for table in self.metadata['tables']:
table_name = table['name']
... | [
"def",
"_get_transformers",
"(",
"self",
")",
":",
"transformer_dict",
"=",
"{",
"}",
"for",
"table",
"in",
"self",
".",
"metadata",
"[",
"'tables'",
"]",
":",
"table_name",
"=",
"table",
"[",
"'name'",
"]",
"for",
"field",
"in",
"table",
"[",
"'fields'"... | Load the contents of meta_file and extract information about the transformers.
Returns:
dict: tuple(str, str) -> Transformer. | [
"Load",
"the",
"contents",
"of",
"meta_file",
"and",
"extract",
"information",
"about",
"the",
"transformers",
"."
] | python | train | 32.666667 |
a1ezzz/wasp-general | wasp_general/uri.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L752-L762 | def handler(self, scheme_name=None):
""" Return handler which scheme name matches the specified one
:param scheme_name: scheme name to search for
:return: WSchemeHandler class or None (if matching handler was not found)
"""
if scheme_name is None:
return self.__default_handler_cls
for handler in self.__... | [
"def",
"handler",
"(",
"self",
",",
"scheme_name",
"=",
"None",
")",
":",
"if",
"scheme_name",
"is",
"None",
":",
"return",
"self",
".",
"__default_handler_cls",
"for",
"handler",
"in",
"self",
".",
"__handlers_cls",
":",
"if",
"handler",
".",
"scheme_specif... | Return handler which scheme name matches the specified one
:param scheme_name: scheme name to search for
:return: WSchemeHandler class or None (if matching handler was not found) | [
"Return",
"handler",
"which",
"scheme",
"name",
"matches",
"the",
"specified",
"one"
] | python | train | 37.181818 |
Netflix-Skunkworks/swag-client | swag_client/schemas/v2.py | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/schemas/v2.py#L86-L95 | def validate_account_status(self, data):
"""Performs field validation for account_status. If any
region is not deleted, account_status cannot be deleted
"""
deleted_status = 'deleted'
region_status = data.get('status')
account_status = data.get('account_status')
... | [
"def",
"validate_account_status",
"(",
"self",
",",
"data",
")",
":",
"deleted_status",
"=",
"'deleted'",
"region_status",
"=",
"data",
".",
"get",
"(",
"'status'",
")",
"account_status",
"=",
"data",
".",
"get",
"(",
"'account_status'",
")",
"for",
"region",
... | Performs field validation for account_status. If any
region is not deleted, account_status cannot be deleted | [
"Performs",
"field",
"validation",
"for",
"account_status",
".",
"If",
"any",
"region",
"is",
"not",
"deleted",
"account_status",
"cannot",
"be",
"deleted"
] | python | train | 53.2 |
ArchiveTeam/wpull | wpull/robotstxt.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/robotstxt.py#L18-L21 | def has_parser(self, url_info: URLInfo):
'''Return whether a parser has been created for the URL.'''
key = self.url_info_key(url_info)
return key in self._parsers | [
"def",
"has_parser",
"(",
"self",
",",
"url_info",
":",
"URLInfo",
")",
":",
"key",
"=",
"self",
".",
"url_info_key",
"(",
"url_info",
")",
"return",
"key",
"in",
"self",
".",
"_parsers"
] | Return whether a parser has been created for the URL. | [
"Return",
"whether",
"a",
"parser",
"has",
"been",
"created",
"for",
"the",
"URL",
"."
] | python | train | 45.75 |
carta/franz | franz/kafka/producer.py | https://github.com/carta/franz/blob/85678878eee8dad0fbe933d0cff819c2d16caa12/franz/kafka/producer.py#L35-L52 | def _send_message_to_topic(self, topic, message):
"""
Send a message to a Kafka topic.
Parameters
----------
topic : str
The kafka topic where the message should be sent to.
message : FranzEvent
The message to be sent.
Raises
----... | [
"def",
"_send_message_to_topic",
"(",
"self",
",",
"topic",
",",
"message",
")",
":",
"message_result",
"=",
"self",
".",
"producer",
".",
"send",
"(",
"topic",
",",
"message",
")",
"self",
".",
"check_for_message_exception",
"(",
"message_result",
")",
"retur... | Send a message to a Kafka topic.
Parameters
----------
topic : str
The kafka topic where the message should be sent to.
message : FranzEvent
The message to be sent.
Raises
------
franz.InvalidMessage | [
"Send",
"a",
"message",
"to",
"a",
"Kafka",
"topic",
"."
] | python | train | 27.388889 |
Kentzo/git-archive-all | git_archive_all.py | https://github.com/Kentzo/git-archive-all/blob/fed1f48f1287c84220be08d63181a2816bde7a64/git_archive_all.py#L242-L310 | def walk_git_files(self, repo_path=''):
"""
An iterator method that yields a file path relative to main_repo_abspath
for each file that should be included in the archive.
Skips those that match the exclusion patterns found in
any discovered .gitattributes files along the way.
... | [
"def",
"walk_git_files",
"(",
"self",
",",
"repo_path",
"=",
"''",
")",
":",
"repo_abspath",
"=",
"path",
".",
"join",
"(",
"self",
".",
"main_repo_abspath",
",",
"repo_path",
")",
"assert",
"repo_abspath",
"not",
"in",
"self",
".",
"_check_attr_gens",
"self... | An iterator method that yields a file path relative to main_repo_abspath
for each file that should be included in the archive.
Skips those that match the exclusion patterns found in
any discovered .gitattributes files along the way.
Recurs into submodules as well.
@param repo_p... | [
"An",
"iterator",
"method",
"that",
"yields",
"a",
"file",
"path",
"relative",
"to",
"main_repo_abspath",
"for",
"each",
"file",
"that",
"should",
"be",
"included",
"in",
"the",
"archive",
".",
"Skips",
"those",
"that",
"match",
"the",
"exclusion",
"patterns",... | python | train | 43.275362 |
andy-esch/sqterritory | sqterritory/territory.py | https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L104-L137 | def _get_demand_graph(self):
"""create demand graph"""
# The number of clusters
K = self.origins.shape[0]
# Set the number of accounts in each cluster to be the same
# as for the nearest neighbor solution
demand = self.nearest_targets.groupby('origin_id')['geometry'].cou... | [
"def",
"_get_demand_graph",
"(",
"self",
")",
":",
"# The number of clusters",
"K",
"=",
"self",
".",
"origins",
".",
"shape",
"[",
"0",
"]",
"# Set the number of accounts in each cluster to be the same",
"# as for the nearest neighbor solution",
"demand",
"=",
"self",
".... | create demand graph | [
"create",
"demand",
"graph"
] | python | train | 37.764706 |
scikit-hep/root_pandas | root_pandas/readwrite.py | https://github.com/scikit-hep/root_pandas/blob/57991a4feaeb9213575cfba7a369fc05cc0d846b/root_pandas/readwrite.py#L334-L417 | def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs):
"""
Write DataFrame to a ROOT file.
Parameters
----------
path: string
File path to new ROOT file (will be overwritten)
key: string
Name of tree that the DataFrame will be saved as
mode: stri... | [
"def",
"to_root",
"(",
"df",
",",
"path",
",",
"key",
"=",
"'my_ttree'",
",",
"mode",
"=",
"'w'",
",",
"store_index",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"==",
"'a'",
":",
"mode",
"=",
"'update'",
"elif... | Write DataFrame to a ROOT file.
Parameters
----------
path: string
File path to new ROOT file (will be overwritten)
key: string
Name of tree that the DataFrame will be saved as
mode: string, {'w', 'a'}
Mode that the file should be opened in (default: 'w')
store_index: bo... | [
"Write",
"DataFrame",
"to",
"a",
"ROOT",
"file",
"."
] | python | train | 32.821429 |
quantopian/pgcontents | pgcontents/checkpoints.py | https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/checkpoints.py#L71-L76 | def delete_checkpoint(self, checkpoint_id, path):
"""delete a checkpoint for a file"""
with self.engine.begin() as db:
return delete_single_remote_checkpoint(
db, self.user_id, path, checkpoint_id,
) | [
"def",
"delete_checkpoint",
"(",
"self",
",",
"checkpoint_id",
",",
"path",
")",
":",
"with",
"self",
".",
"engine",
".",
"begin",
"(",
")",
"as",
"db",
":",
"return",
"delete_single_remote_checkpoint",
"(",
"db",
",",
"self",
".",
"user_id",
",",
"path",
... | delete a checkpoint for a file | [
"delete",
"a",
"checkpoint",
"for",
"a",
"file"
] | python | test | 41.666667 |
jwodder/javaproperties | javaproperties/writing.py | https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/writing.py#L79-L97 | def to_comment(comment):
"""
Convert a string to a ``.properties`` file comment. All non-Latin-1
characters in the string are escaped using ``\\uXXXX`` escapes (after
converting non-BMP characters to surrogate pairs), a ``#`` is prepended to
the string, any CR LF or CR line breaks in the string are... | [
"def",
"to_comment",
"(",
"comment",
")",
":",
"return",
"'#'",
"+",
"re",
".",
"sub",
"(",
"r'[^\\x00-\\xFF]'",
",",
"_esc",
",",
"re",
".",
"sub",
"(",
"r'\\n(?![#!])'",
",",
"'\\n#'",
",",
"re",
".",
"sub",
"(",
"r'\\r\\n?'",
",",
"'\\n'",
",",
"c... | Convert a string to a ``.properties`` file comment. All non-Latin-1
characters in the string are escaped using ``\\uXXXX`` escapes (after
converting non-BMP characters to surrogate pairs), a ``#`` is prepended to
the string, any CR LF or CR line breaks in the string are converted to LF,
and a ``#`` is ... | [
"Convert",
"a",
"string",
"to",
"a",
".",
"properties",
"file",
"comment",
".",
"All",
"non",
"-",
"Latin",
"-",
"1",
"characters",
"in",
"the",
"string",
"are",
"escaped",
"using",
"\\\\",
"uXXXX",
"escapes",
"(",
"after",
"converting",
"non",
"-",
"BMP... | python | train | 44.157895 |
Shizmob/pydle | pydle/features/rfc1459/parsing.py | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/parsing.py#L184-L197 | def parse_user(raw):
""" Parse nick(!user(@host)?)? structure. """
nick = raw
user = None
host = None
# Attempt to extract host.
if protocol.HOST_SEPARATOR in raw:
raw, host = raw.split(protocol.HOST_SEPARATOR)
# Attempt to extract user.
if protocol.USER_SEPARATOR in raw:
... | [
"def",
"parse_user",
"(",
"raw",
")",
":",
"nick",
"=",
"raw",
"user",
"=",
"None",
"host",
"=",
"None",
"# Attempt to extract host.",
"if",
"protocol",
".",
"HOST_SEPARATOR",
"in",
"raw",
":",
"raw",
",",
"host",
"=",
"raw",
".",
"split",
"(",
"protocol... | Parse nick(!user(@host)?)? structure. | [
"Parse",
"nick",
"(",
"!user",
"("
] | python | train | 27.5 |
arokem/python-matlab-bridge | tools/gh_api.py | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L122-L139 | def get_paged_request(url, headers=None, **params):
"""get a full list, handling APIv3's paging"""
results = []
params.setdefault("per_page", 100)
while True:
if '?' in url:
params = None
print("fetching %s" % url, file=sys.stderr)
else:
print("fetchin... | [
"def",
"get_paged_request",
"(",
"url",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"results",
"=",
"[",
"]",
"params",
".",
"setdefault",
"(",
"\"per_page\"",
",",
"100",
")",
"while",
"True",
":",
"if",
"'?'",
"in",
"url",
":",
... | get a full list, handling APIv3's paging | [
"get",
"a",
"full",
"list",
"handling",
"APIv3",
"s",
"paging"
] | python | train | 35.055556 |
wdbm/shijian | shijian.py | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L657-L676 | def tail(
filepath = "log.txt",
lines = 50
):
"""
Return a specified number of last lines of a specified file. If there is an
error or the file does not exist, return False.
"""
try:
filepath = os.path.expanduser(os.path.expandvars(filepath))
if os.path.isfile(filepath... | [
"def",
"tail",
"(",
"filepath",
"=",
"\"log.txt\"",
",",
"lines",
"=",
"50",
")",
":",
"try",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"filepath",
")",
")",
"if",
"os",
".",
"path",... | Return a specified number of last lines of a specified file. If there is an
error or the file does not exist, return False. | [
"Return",
"a",
"specified",
"number",
"of",
"last",
"lines",
"of",
"a",
"specified",
"file",
".",
"If",
"there",
"is",
"an",
"error",
"or",
"the",
"file",
"does",
"not",
"exist",
"return",
"False",
"."
] | python | train | 27.6 |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L517-L588 | def loadTableData(self, df, df_key='index',table="node", table_key_column = "name", \
network="current",namespace="default",verbose=False):
"""
Loads tables into cytoscape.
:param df: a pandas dataframe to load
:param df_key: key column in df, default="index"
:param tabl... | [
"def",
"loadTableData",
"(",
"self",
",",
"df",
",",
"df_key",
"=",
"'index'",
",",
"table",
"=",
"\"node\"",
",",
"table_key_column",
"=",
"\"name\"",
",",
"network",
"=",
"\"current\"",
",",
"namespace",
"=",
"\"default\"",
",",
"verbose",
"=",
"False",
... | Loads tables into cytoscape.
:param df: a pandas dataframe to load
:param df_key: key column in df, default="index"
:param table: target table, default="node"
:param table_key_column: table key column, default="name"
:param network (string, optional): Specifies a network by name... | [
"Loads",
"tables",
"into",
"cytoscape",
"."
] | python | train | 38.930556 |
nanoporetech/ont_fast5_api | ont_fast5_api/fast5_file.py | https://github.com/nanoporetech/ont_fast5_api/blob/352b3903155fcf4f19234c4f429dcefaa6d6bc4a/ont_fast5_api/fast5_file.py#L504-L516 | def add_analysis_attributes(self, group_name, attrs, clear=False):
""" Add attributes on the group or dataset specified.
:param group_name: The name of the group (or dataset).
:param attrs: A dictionary representing the attributes to add.
:param clear: If set, any existing attri... | [
"def",
"add_analysis_attributes",
"(",
"self",
",",
"group_name",
",",
"attrs",
",",
"clear",
"=",
"False",
")",
":",
"self",
".",
"assert_writeable",
"(",
")",
"group",
"=",
"'Analyses/{}'",
".",
"format",
"(",
"group_name",
")",
"self",
".",
"_add_attribut... | Add attributes on the group or dataset specified.
:param group_name: The name of the group (or dataset).
:param attrs: A dictionary representing the attributes to add.
:param clear: If set, any existing attributes will be cleared.
The specified group name can be any exi... | [
"Add",
"attributes",
"on",
"the",
"group",
"or",
"dataset",
"specified",
".",
":",
"param",
"group_name",
":",
"The",
"name",
"of",
"the",
"group",
"(",
"or",
"dataset",
")",
".",
":",
"param",
"attrs",
":",
"A",
"dictionary",
"representing",
"the",
"att... | python | train | 47.307692 |
draios/python-sdc-client | sdcclient/_common.py | https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L954-L980 | def remove_memberships(self, team, users):
'''
**Description**
Remove user memberships from specified team.
**Arguments**
- **team**: the name of the team from which user memberships are removed
- **users**: list of usernames which should be removed from team... | [
"def",
"remove_memberships",
"(",
"self",
",",
"team",
",",
"users",
")",
":",
"res",
"=",
"self",
".",
"list_memberships",
"(",
"team",
")",
"if",
"res",
"[",
"0",
"]",
"is",
"False",
":",
"return",
"res",
"old_memberships",
"=",
"res",
"[",
"1",
"]... | **Description**
Remove user memberships from specified team.
**Arguments**
- **team**: the name of the team from which user memberships are removed
- **users**: list of usernames which should be removed from team
**Example**
`examples/user_team_mgmt_exte... | [
"**",
"Description",
"**",
"Remove",
"user",
"memberships",
"from",
"specified",
"team",
"."
] | python | test | 31.074074 |
Netflix-Skunkworks/historical | historical/common/dynamodb.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L206-L226 | def deserialize_current_record_to_current_model(record, current_model):
"""
Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object.
This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away.
:param reco... | [
"def",
"deserialize_current_record_to_current_model",
"(",
"record",
",",
"current_model",
")",
":",
"# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:",
"if",
"record",
".",
"get",
"(",
"EVENT_TOO_BIG_FLAG",
")",
":",
... | Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object.
This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away.
:param record:
:param current_model:
:return: | [
"Utility",
"function",
"that",
"will",
"take",
"a",
"Dynamo",
"event",
"record",
"and",
"turn",
"it",
"into",
"the",
"proper",
"Current",
"Dynamo",
"object",
"."
] | python | train | 41.52381 |
tanghaibao/jcvi | jcvi/assembly/postprocess.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/postprocess.py#L102-L146 | def circular(args):
"""
%prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based.
"""
from jcvi.assembly.goldenpath import overlap
p = Opti... | [
"def",
"circular",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"assembly",
".",
"goldenpath",
"import",
"overlap",
"p",
"=",
"OptionParser",
"(",
"circular",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--flip\"",
",",
"default",
"=",
"False",
",... | %prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based. | [
"%prog",
"circular",
"fastafile",
"startpos"
] | python | train | 27.755556 |
PaulHancock/Aegean | AegeanTools/MIMAS.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/MIMAS.py#L307-L338 | def box2poly(line):
"""
Convert a string that describes a box in ds9 format, into a polygon that is given by the corners of the box
Parameters
----------
line : str
A string containing a DS9 region command for a box.
Returns
-------
poly : [ra, dec, ...]
The corners of ... | [
"def",
"box2poly",
"(",
"line",
")",
":",
"words",
"=",
"re",
".",
"split",
"(",
"'[(\\s,)]'",
",",
"line",
")",
"ra",
"=",
"words",
"[",
"1",
"]",
"dec",
"=",
"words",
"[",
"2",
"]",
"width",
"=",
"words",
"[",
"3",
"]",
"height",
"=",
"words"... | Convert a string that describes a box in ds9 format, into a polygon that is given by the corners of the box
Parameters
----------
line : str
A string containing a DS9 region command for a box.
Returns
-------
poly : [ra, dec, ...]
The corners of the box in clockwise order from ... | [
"Convert",
"a",
"string",
"that",
"describes",
"a",
"box",
"in",
"ds9",
"format",
"into",
"a",
"polygon",
"that",
"is",
"given",
"by",
"the",
"corners",
"of",
"the",
"box"
] | python | train | 34.5625 |
OCHA-DAP/hdx-python-api | src/hdx/data/hdxobject.py | https://github.com/OCHA-DAP/hdx-python-api/blob/212440f54f73805826a16db77dbcb6033b18a313/src/hdx/data/hdxobject.py#L568-L583 | def _add_strings_to_commastring(self, field, strings):
# type: (str, List[str]) -> bool
"""Add a list of strings to a comma separated list of strings
Args:
field (str): Field containing comma separated list
strings (List[str]): list of strings to add
Returns:
... | [
"def",
"_add_strings_to_commastring",
"(",
"self",
",",
"field",
",",
"strings",
")",
":",
"# type: (str, List[str]) -> bool",
"allstringsadded",
"=",
"True",
"for",
"string",
"in",
"strings",
":",
"if",
"not",
"self",
".",
"_add_string_to_commastring",
"(",
"field"... | Add a list of strings to a comma separated list of strings
Args:
field (str): Field containing comma separated list
strings (List[str]): list of strings to add
Returns:
bool: True if all strings added or False if any already present. | [
"Add",
"a",
"list",
"of",
"strings",
"to",
"a",
"comma",
"separated",
"list",
"of",
"strings"
] | python | train | 36.9375 |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L910-L961 | def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The e... | [
"def",
"CheckNextIncludeOrder",
"(",
"self",
",",
"header_type",
")",
":",
"error_message",
"=",
"(",
"'Found %s after %s'",
"%",
"(",
"self",
".",
"_TYPE_NAMES",
"[",
"header_type",
"]",
",",
"self",
".",
"_SECTION_NAMES",
"[",
"self",
".",
"_section",
"]",
... | Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or a... | [
"Returns",
"a",
"non",
"-",
"empty",
"error",
"message",
"if",
"the",
"next",
"header",
"is",
"out",
"of",
"order",
"."
] | python | valid | 31.711538 |
fhcrc/taxtastic | taxtastic/taxonomy.py | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/taxonomy.py#L724-L750 | def child_of(self, tax_id):
"""Return None or a tax id of a child of *tax_id*.
If *tax_id* is None, then always returns None. Otherwise
returns a child if one exists, else None. The child must have
a proper rank below that of tax_id (i.e., genus, species, but
not no_rank or belo... | [
"def",
"child_of",
"(",
"self",
",",
"tax_id",
")",
":",
"if",
"tax_id",
"is",
"None",
":",
"return",
"None",
"parent_id",
",",
"rank",
"=",
"self",
".",
"_node",
"(",
"tax_id",
")",
"s",
"=",
"select",
"(",
"[",
"self",
".",
"nodes",
".",
"c",
"... | Return None or a tax id of a child of *tax_id*.
If *tax_id* is None, then always returns None. Otherwise
returns a child if one exists, else None. The child must have
a proper rank below that of tax_id (i.e., genus, species, but
not no_rank or below_below_kingdom). | [
"Return",
"None",
"or",
"a",
"tax",
"id",
"of",
"a",
"child",
"of",
"*",
"tax_id",
"*",
"."
] | python | train | 38.222222 |
aws/sagemaker-python-sdk | src/sagemaker/fw_utils.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/fw_utils.py#L49-L103 | def create_image_uri(region, framework, instance_type, framework_version, py_version=None,
account='520713654638', accelerator_type=None, optimized_families=None):
"""Return the ECR URI of an image.
Args:
region (str): AWS region where the image is uploaded.
framework (str)... | [
"def",
"create_image_uri",
"(",
"region",
",",
"framework",
",",
"instance_type",
",",
"framework_version",
",",
"py_version",
"=",
"None",
",",
"account",
"=",
"'520713654638'",
",",
"accelerator_type",
"=",
"None",
",",
"optimized_families",
"=",
"None",
")",
... | Return the ECR URI of an image.
Args:
region (str): AWS region where the image is uploaded.
framework (str): framework used by the image.
instance_type (str): SageMaker instance type. Used to determine device type (cpu/gpu/family-specific optimized).
framework_version (str): The ver... | [
"Return",
"the",
"ECR",
"URI",
"of",
"an",
"image",
"."
] | python | train | 47.363636 |
psd-tools/psd-tools | src/psd_tools/utils.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L255-L260 | def be_array_from_bytes(fmt, data):
"""
Reads an array from bytestring with big-endian data.
"""
arr = array.array(str(fmt), data)
return fix_byteorder(arr) | [
"def",
"be_array_from_bytes",
"(",
"fmt",
",",
"data",
")",
":",
"arr",
"=",
"array",
".",
"array",
"(",
"str",
"(",
"fmt",
")",
",",
"data",
")",
"return",
"fix_byteorder",
"(",
"arr",
")"
] | Reads an array from bytestring with big-endian data. | [
"Reads",
"an",
"array",
"from",
"bytestring",
"with",
"big",
"-",
"endian",
"data",
"."
] | python | train | 28.5 |
apache/airflow | airflow/contrib/hooks/gcs_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcs_hook.py#L98-L150 | def rewrite(self, source_bucket, source_object, destination_bucket,
destination_object=None):
"""
Has the same functionality as copy, except that will work on files
over 5 TB, as well as when copying between locations and/or storage
classes.
destination_object ca... | [
"def",
"rewrite",
"(",
"self",
",",
"source_bucket",
",",
"source_object",
",",
"destination_bucket",
",",
"destination_object",
"=",
"None",
")",
":",
"destination_object",
"=",
"destination_object",
"or",
"source_object",
"if",
"(",
"source_bucket",
"==",
"destina... | Has the same functionality as copy, except that will work on files
over 5 TB, as well as when copying between locations and/or storage
classes.
destination_object can be omitted, in which case source_object is used.
:param source_bucket: The bucket of the object to copy from.
:... | [
"Has",
"the",
"same",
"functionality",
"as",
"copy",
"except",
"that",
"will",
"work",
"on",
"files",
"over",
"5",
"TB",
"as",
"well",
"as",
"when",
"copying",
"between",
"locations",
"and",
"/",
"or",
"storage",
"classes",
"."
] | python | test | 45.962264 |
estnltk/estnltk | estnltk/text.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L1127-L1131 | def wordnet_annotations(self):
"""The list of wordnet annotations of ``words`` layer."""
if not self.is_tagged(WORDNET):
self.tag_wordnet()
return [[a[WORDNET] for a in analysis] for analysis in self.analysis] | [
"def",
"wordnet_annotations",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"WORDNET",
")",
":",
"self",
".",
"tag_wordnet",
"(",
")",
"return",
"[",
"[",
"a",
"[",
"WORDNET",
"]",
"for",
"a",
"in",
"analysis",
"]",
"for",
"analy... | The list of wordnet annotations of ``words`` layer. | [
"The",
"list",
"of",
"wordnet",
"annotations",
"of",
"words",
"layer",
"."
] | python | train | 48.2 |
arista-eosplus/pyeapi | pyeapi/api/interfaces.py | https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/interfaces.py#L398-L413 | def _parse_flowcontrol_receive(self, config):
"""Scans the config block and returns the flowcontrol receive value
Args:
config (str): The interface config block to scan
Returns:
dict: Returns a dict object with the flowcontrol receive value
retrieved fro... | [
"def",
"_parse_flowcontrol_receive",
"(",
"self",
",",
"config",
")",
":",
"value",
"=",
"'off'",
"match",
"=",
"re",
".",
"search",
"(",
"r'flowcontrol receive (\\w+)$'",
",",
"config",
",",
"re",
".",
"M",
")",
"if",
"match",
":",
"value",
"=",
"match",
... | Scans the config block and returns the flowcontrol receive value
Args:
config (str): The interface config block to scan
Returns:
dict: Returns a dict object with the flowcontrol receive value
retrieved from the config block. The returned dict object
... | [
"Scans",
"the",
"config",
"block",
"and",
"returns",
"the",
"flowcontrol",
"receive",
"value"
] | python | train | 39.3125 |
poldracklab/niworkflows | niworkflows/viz/plots.py | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/viz/plots.py#L274-L397 | def spikesplot(ts_z, outer_gs=None, tr=None, zscored=True, spike_thresh=6., title='Spike plot',
ax=None, cmap='viridis', hide_x=True, nskip=0):
"""
A spikes plot. Thanks to Bob Dogherty (this docstring needs be improved with proper ack)
"""
if ax is None:
ax = plt.gca()
if o... | [
"def",
"spikesplot",
"(",
"ts_z",
",",
"outer_gs",
"=",
"None",
",",
"tr",
"=",
"None",
",",
"zscored",
"=",
"True",
",",
"spike_thresh",
"=",
"6.",
",",
"title",
"=",
"'Spike plot'",
",",
"ax",
"=",
"None",
",",
"cmap",
"=",
"'viridis'",
",",
"hide_... | A spikes plot. Thanks to Bob Dogherty (this docstring needs be improved with proper ack) | [
"A",
"spikes",
"plot",
".",
"Thanks",
"to",
"Bob",
"Dogherty",
"(",
"this",
"docstring",
"needs",
"be",
"improved",
"with",
"proper",
"ack",
")"
] | python | train | 34.951613 |
toastdriven/alligator | alligator/backends/beanstalk_backend.py | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/backends/beanstalk_backend.py#L25-L32 | def get_connection(self, host, port):
"""
Returns a ``StrictRedis`` connection instance.
"""
return beanstalkc.Connection(
host=host,
port=port
) | [
"def",
"get_connection",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"return",
"beanstalkc",
".",
"Connection",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")"
] | Returns a ``StrictRedis`` connection instance. | [
"Returns",
"a",
"StrictRedis",
"connection",
"instance",
"."
] | python | train | 25.25 |
collectiveacuity/jsonModel | jsonmodel/validators.py | https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L732-L904 | def _validate_dict(self, input_dict, schema_dict, path_to_root, object_title=''):
''' a helper method for recursively validating keys in dictionaries
:return input_dict
'''
# reconstruct key path to current dictionary in model
rules_top_level_key = re.sub('\[\d+\]', '[0]', path_to... | [
"def",
"_validate_dict",
"(",
"self",
",",
"input_dict",
",",
"schema_dict",
",",
"path_to_root",
",",
"object_title",
"=",
"''",
")",
":",
"# reconstruct key path to current dictionary in model",
"rules_top_level_key",
"=",
"re",
".",
"sub",
"(",
"'\\[\\d+\\]'",
",",... | a helper method for recursively validating keys in dictionaries
:return input_dict | [
"a",
"helper",
"method",
"for",
"recursively",
"validating",
"keys",
"in",
"dictionaries"
] | python | train | 43.924855 |
pyviz/holoviews | holoviews/util/parser.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/util/parser.py#L81-L121 | def todict(cls, parseresult, mode='parens', ns={}):
"""
Helper function to return dictionary given the parse results
from a pyparsing.nestedExpr object (containing keywords).
The ns is a dynamic namespace (typically the IPython Notebook
namespace) used to update the class-level ... | [
"def",
"todict",
"(",
"cls",
",",
"parseresult",
",",
"mode",
"=",
"'parens'",
",",
"ns",
"=",
"{",
"}",
")",
":",
"grouped",
",",
"kwargs",
"=",
"[",
"]",
",",
"{",
"}",
"tokens",
"=",
"cls",
".",
"collect_tokens",
"(",
"parseresult",
",",
"mode",... | Helper function to return dictionary given the parse results
from a pyparsing.nestedExpr object (containing keywords).
The ns is a dynamic namespace (typically the IPython Notebook
namespace) used to update the class-level namespace. | [
"Helper",
"function",
"to",
"return",
"dictionary",
"given",
"the",
"parse",
"results",
"from",
"a",
"pyparsing",
".",
"nestedExpr",
"object",
"(",
"containing",
"keywords",
")",
"."
] | python | train | 45.926829 |
pilosus/ForgeryPy3 | forgery_py/forgery/email.py | https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/email.py#L36-L43 | def body(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Return a random email text."""
return lorem_ipsum.paragraphs(quantity=quantity, separator=separator,
wrap_start=wrap_start, wrap_end=wrap_end,
... | [
"def",
"body",
"(",
"quantity",
"=",
"2",
",",
"separator",
"=",
"'\\n\\n'",
",",
"wrap_start",
"=",
"''",
",",
"wrap_end",
"=",
"''",
",",
"html",
"=",
"False",
",",
"sentences_quantity",
"=",
"3",
",",
"as_list",
"=",
"False",
")",
":",
"return",
"... | Return a random email text. | [
"Return",
"a",
"random",
"email",
"text",
"."
] | python | valid | 59.375 |
plotly/octogrid | octogrid/publisher/publisher.py | https://github.com/plotly/octogrid/blob/46237a72c79765fe5a48af7065049c692e6457a7/octogrid/publisher/publisher.py#L19-L83 | def prepare_plot_data(data_file):
"""
Return a list of Plotly elements representing the network graph
"""
G = ig.Graph.Read_GML(data_file)
layout = G.layout('graphopt')
labels = list(G.vs['label'])
N = len(labels)
E = [e.tuple for e in G.es]
community = G.community_multilevel().m... | [
"def",
"prepare_plot_data",
"(",
"data_file",
")",
":",
"G",
"=",
"ig",
".",
"Graph",
".",
"Read_GML",
"(",
"data_file",
")",
"layout",
"=",
"G",
".",
"layout",
"(",
"'graphopt'",
")",
"labels",
"=",
"list",
"(",
"G",
".",
"vs",
"[",
"'label'",
"]",
... | Return a list of Plotly elements representing the network graph | [
"Return",
"a",
"list",
"of",
"Plotly",
"elements",
"representing",
"the",
"network",
"graph"
] | python | train | 28.307692 |
docker/docker-py | docker/api/container.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/container.py#L996-L1011 | def rename(self, container, name):
"""
Rename a container. Similar to the ``docker rename`` command.
Args:
container (str): ID of the container to rename
name (str): New name for the container
Raises:
:py:class:`docker.errors.APIError`
... | [
"def",
"rename",
"(",
"self",
",",
"container",
",",
"name",
")",
":",
"url",
"=",
"self",
".",
"_url",
"(",
"\"/containers/{0}/rename\"",
",",
"container",
")",
"params",
"=",
"{",
"'name'",
":",
"name",
"}",
"res",
"=",
"self",
".",
"_post",
"(",
"... | Rename a container. Similar to the ``docker rename`` command.
Args:
container (str): ID of the container to rename
name (str): New name for the container
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. | [
"Rename",
"a",
"container",
".",
"Similar",
"to",
"the",
"docker",
"rename",
"command",
"."
] | python | train | 32.75 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/utils.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/utils.py#L16-L65 | def get_tag_value(string, pre, post, tagtype=float, greedy=True):
"""
Extracts the value of a tag from a string.
Parameters
-----------------
pre : str
regular expression to match before the the tag value
post : str | list | tuple
regular expression to match after the the tag ... | [
"def",
"get_tag_value",
"(",
"string",
",",
"pre",
",",
"post",
",",
"tagtype",
"=",
"float",
",",
"greedy",
"=",
"True",
")",
":",
"greedy",
"=",
"'?'",
"if",
"greedy",
"else",
"''",
"# For greedy search",
"if",
"isinstance",
"(",
"post",
",",
"(",
"l... | Extracts the value of a tag from a string.
Parameters
-----------------
pre : str
regular expression to match before the the tag value
post : str | list | tuple
regular expression to match after the the tag value
if list than the regular expressions will be combined into the ... | [
"Extracts",
"the",
"value",
"of",
"a",
"tag",
"from",
"a",
"string",
"."
] | python | train | 31.94 |
wind-python/windpowerlib | windpowerlib/tools.py | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/tools.py#L131-L171 | def gauss_distribution(function_variable, standard_deviation, mean=0):
r"""
Gauss distribution.
The Gauss distribution is used in the function
:py:func:`~.power_curves.smooth_power_curve` for power curve smoothing.
Parameters
----------
function_variable : float
Variable of the gau... | [
"def",
"gauss_distribution",
"(",
"function_variable",
",",
"standard_deviation",
",",
"mean",
"=",
"0",
")",
":",
"return",
"(",
"1",
"/",
"(",
"standard_deviation",
"*",
"np",
".",
"sqrt",
"(",
"2",
"*",
"np",
".",
"pi",
")",
")",
"*",
"np",
".",
"... | r"""
Gauss distribution.
The Gauss distribution is used in the function
:py:func:`~.power_curves.smooth_power_curve` for power curve smoothing.
Parameters
----------
function_variable : float
Variable of the gaussian distribution.
standard_deviation : float
Standard deviati... | [
"r",
"Gauss",
"distribution",
"."
] | python | train | 29.463415 |
buildbot/buildbot | master/buildbot/changes/hgpoller.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/changes/hgpoller.py#L240-L254 | def _processChanges(self, unused_output):
"""Send info about pulled changes to the master and record current.
HgPoller does the recording by moving the working dir to the head
of the branch.
We don't update the tree (unnecessary treatment and waste of space)
instead, we simply s... | [
"def",
"_processChanges",
"(",
"self",
",",
"unused_output",
")",
":",
"for",
"branch",
"in",
"self",
".",
"branches",
"+",
"self",
".",
"bookmarks",
":",
"rev",
"=",
"yield",
"self",
".",
"_getHead",
"(",
"branch",
")",
"if",
"rev",
"is",
"None",
":",... | Send info about pulled changes to the master and record current.
HgPoller does the recording by moving the working dir to the head
of the branch.
We don't update the tree (unnecessary treatment and waste of space)
instead, we simply store the current rev number in a file.
Recall... | [
"Send",
"info",
"about",
"pulled",
"changes",
"to",
"the",
"master",
"and",
"record",
"current",
"."
] | python | train | 44.2 |
common-workflow-language/cwltool | cwltool/provenance.py | https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/provenance.py#L1048-L1060 | def write_bag_file(self, path, encoding=ENCODING):
# type: (Text, Optional[str]) -> IO
"""Write the bag file into our research object."""
self.self_check()
# For some reason below throws BlockingIOError
#fp = BufferedWriter(WritableBagFile(self, path))
bag_file = cast(IO,... | [
"def",
"write_bag_file",
"(",
"self",
",",
"path",
",",
"encoding",
"=",
"ENCODING",
")",
":",
"# type: (Text, Optional[str]) -> IO",
"self",
".",
"self_check",
"(",
")",
"# For some reason below throws BlockingIOError",
"#fp = BufferedWriter(WritableBagFile(self, path))",
"b... | Write the bag file into our research object. | [
"Write",
"the",
"bag",
"file",
"into",
"our",
"research",
"object",
"."
] | python | train | 47.538462 |
hobson/pug-dj | pug/dj/db.py | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L736-L760 | def model_from_path(model_path, fuzziness=False):
"""Find the model class for a given model path like 'project.app.model'
Args:
path (str): dot-delimited model path, like 'project.app.model'
Returns:
Django Model-based class
"""
app_name = '.'.join(model_path.split('.')[:-1])
m... | [
"def",
"model_from_path",
"(",
"model_path",
",",
"fuzziness",
"=",
"False",
")",
":",
"app_name",
"=",
"'.'",
".",
"join",
"(",
"model_path",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"model_name",
"=",
"model_path",
".",
"split",
... | Find the model class for a given model path like 'project.app.model'
Args:
path (str): dot-delimited model path, like 'project.app.model'
Returns:
Django Model-based class | [
"Find",
"the",
"model",
"class",
"for",
"a",
"given",
"model",
"path",
"like",
"project",
".",
"app",
".",
"model"
] | python | train | 28.2 |
log2timeline/plaso | plaso/analyzers/hashing_analyzer.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analyzers/hashing_analyzer.py#L42-L56 | def GetResults(self):
"""Retrieves the hashing results.
Returns:
list[AnalyzerResult]: results.
"""
results = []
for hasher in self._hashers:
logger.debug('Processing results for hasher {0:s}'.format(hasher.NAME))
result = analyzer_result.AnalyzerResult()
result.analyzer_nam... | [
"def",
"GetResults",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"hasher",
"in",
"self",
".",
"_hashers",
":",
"logger",
".",
"debug",
"(",
"'Processing results for hasher {0:s}'",
".",
"format",
"(",
"hasher",
".",
"NAME",
")",
")",
"result",
... | Retrieves the hashing results.
Returns:
list[AnalyzerResult]: results. | [
"Retrieves",
"the",
"hashing",
"results",
"."
] | python | train | 32.4 |
pyviz/imagen | imagen/__init__.py | https://github.com/pyviz/imagen/blob/53c5685c880f54b42795964d8db50b02e8590e88/imagen/__init__.py#L567-L576 | def num_channels(self):
"""
Get the number of channels in the input generators.
"""
if(self.inspect_value('index') is None):
if(len(self.generators)>0):
return self.generators[0].num_channels()
return 0
return self.get_current_generator().... | [
"def",
"num_channels",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"inspect_value",
"(",
"'index'",
")",
"is",
"None",
")",
":",
"if",
"(",
"len",
"(",
"self",
".",
"generators",
")",
">",
"0",
")",
":",
"return",
"self",
".",
"generators",
"[",... | Get the number of channels in the input generators. | [
"Get",
"the",
"number",
"of",
"channels",
"in",
"the",
"input",
"generators",
"."
] | python | train | 32.5 |
sveetch/djangocodemirror | djangocodemirror/manifest.py | https://github.com/sveetch/djangocodemirror/blob/7d556eec59861b2f619398e837bdd089b3a8a7d7/djangocodemirror/manifest.py#L114-L134 | def resolve_mode(self, name):
"""
From given mode name, return mode file path from
``settings.CODEMIRROR_MODES`` map.
Arguments:
name (string): Mode name.
Raises:
KeyError: When given name does not exist in
``settings.CODEMIRROR_MODES``.
... | [
"def",
"resolve_mode",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"settings",
".",
"CODEMIRROR_MODES",
":",
"msg",
"=",
"(",
"\"Given config name '{}' does not exists in \"",
"\"'settings.CODEMIRROR_MODES'.\"",
")",
"raise",
"UnknowModeError",
"(",... | From given mode name, return mode file path from
``settings.CODEMIRROR_MODES`` map.
Arguments:
name (string): Mode name.
Raises:
KeyError: When given name does not exist in
``settings.CODEMIRROR_MODES``.
Returns:
string: Mode file pa... | [
"From",
"given",
"mode",
"name",
"return",
"mode",
"file",
"path",
"from",
"settings",
".",
"CODEMIRROR_MODES",
"map",
"."
] | python | train | 30.190476 |
nccgroup/opinel | opinel/utils/credentials.py | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L155-L187 | def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
"""
Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return:
"""
# Set STS arguments
sts_args = ... | [
"def",
"init_sts_session",
"(",
"profile_name",
",",
"credentials",
",",
"duration",
"=",
"28800",
",",
"session_name",
"=",
"None",
",",
"save_creds",
"=",
"True",
")",
":",
"# Set STS arguments",
"sts_args",
"=",
"{",
"'DurationSeconds'",
":",
"duration",
"}",... | Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return: | [
"Fetch",
"STS",
"credentials"
] | python | train | 42.181818 |
exhuma/python-cluster | cluster/util.py | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L127-L132 | def centroid(data, method=median):
"returns the central vector of a list of vectors"
out = []
for i in range(len(data[0])):
out.append(method([x[i] for x in data]))
return tuple(out) | [
"def",
"centroid",
"(",
"data",
",",
"method",
"=",
"median",
")",
":",
"out",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data",
"[",
"0",
"]",
")",
")",
":",
"out",
".",
"append",
"(",
"method",
"(",
"[",
"x",
"[",
"i",
"]... | returns the central vector of a list of vectors | [
"returns",
"the",
"central",
"vector",
"of",
"a",
"list",
"of",
"vectors"
] | python | train | 33.5 |
apple/turicreate | deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L145-L157 | def generate_take(out_f, steps, line_prefix):
"""Generate the take function"""
out_f.write(
'{0}constexpr inline int take(int n_)\n'
'{0}{{\n'
'{0} return {1} 0 {2};\n'
'{0}}}\n'
'\n'.format(
line_prefix,
''.join('n_ >= {0} ? {0} : ('.format(s) fo... | [
"def",
"generate_take",
"(",
"out_f",
",",
"steps",
",",
"line_prefix",
")",
":",
"out_f",
".",
"write",
"(",
"'{0}constexpr inline int take(int n_)\\n'",
"'{0}{{\\n'",
"'{0} return {1} 0 {2};\\n'",
"'{0}}}\\n'",
"'\\n'",
".",
"format",
"(",
"line_prefix",
",",
"''",... | Generate the take function | [
"Generate",
"the",
"take",
"function"
] | python | train | 28.230769 |
glitchassassin/lackey | lackey/TemplateMatchers.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L16-L43 | def findBestMatch(self, needle, similarity):
""" Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``.
Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise.
*Developer's Note - Despite the name, this method actually... | [
"def",
"findBestMatch",
"(",
"self",
",",
"needle",
",",
"similarity",
")",
":",
"method",
"=",
"cv2",
".",
"TM_CCOEFF_NORMED",
"position",
"=",
"None",
"match",
"=",
"cv2",
".",
"matchTemplate",
"(",
"self",
".",
"haystack",
",",
"needle",
",",
"method",
... | Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``.
Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise.
*Developer's Note - Despite the name, this method actually returns the **first** result
with enough similar... | [
"Find",
"the",
"best",
"match",
"for",
"needle",
"that",
"has",
"a",
"similarity",
"better",
"than",
"or",
"equal",
"to",
"similarity",
"."
] | python | train | 37.607143 |
python-xlib/python-xlib | Xlib/rdb.py | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/rdb.py#L154-L191 | def insert(self, resource, value):
"""insert(resource, value)
Insert a resource entry into the database. RESOURCE is a
string and VALUE can be any Python value.
"""
# Split res into components and bindings
parts = resource_parts_re.split(resource)
# If the la... | [
"def",
"insert",
"(",
"self",
",",
"resource",
",",
"value",
")",
":",
"# Split res into components and bindings",
"parts",
"=",
"resource_parts_re",
".",
"split",
"(",
"resource",
")",
"# If the last part is empty, this is an invalid resource",
"# which we simply ignore",
... | insert(resource, value)
Insert a resource entry into the database. RESOURCE is a
string and VALUE can be any Python value. | [
"insert",
"(",
"resource",
"value",
")"
] | python | train | 27.657895 |
kwikteam/phy | phy/cluster/_history.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_history.py#L28-L32 | def current_item(self):
"""Return the current element."""
if self._history and self._index >= 0:
self._check_index()
return self._history[self._index] | [
"def",
"current_item",
"(",
"self",
")",
":",
"if",
"self",
".",
"_history",
"and",
"self",
".",
"_index",
">=",
"0",
":",
"self",
".",
"_check_index",
"(",
")",
"return",
"self",
".",
"_history",
"[",
"self",
".",
"_index",
"]"
] | Return the current element. | [
"Return",
"the",
"current",
"element",
"."
] | python | train | 37.2 |
numberoverzero/bloop | bloop/session.py | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L288-L302 | def enable_backups(self, table_name, model):
"""Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"]
:param table_name: The name of the table to enable Continuous Backups on
:param model: The model to get Continuous Backups settings from
"""
s... | [
"def",
"enable_backups",
"(",
"self",
",",
"table_name",
",",
"model",
")",
":",
"self",
".",
"_tables",
".",
"pop",
"(",
"table_name",
",",
"None",
")",
"request",
"=",
"{",
"\"TableName\"",
":",
"table_name",
",",
"\"PointInTimeRecoverySpecification\"",
":",... | Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"]
:param table_name: The name of the table to enable Continuous Backups on
:param model: The model to get Continuous Backups settings from | [
"Calls",
"UpdateContinuousBackups",
"on",
"the",
"table",
"according",
"to",
"model",
".",
"Meta",
"[",
"continuous_backups",
"]"
] | python | train | 48.6 |
ottogroup/palladium | palladium/util.py | https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L62-L84 | def args_from_config(func):
"""Decorator that injects parameters from the configuration.
"""
func_args = signature(func).parameters
@wraps(func)
def wrapper(*args, **kwargs):
config = get_config()
for i, argname in enumerate(func_args):
if len(args) > i or argname in kwa... | [
"def",
"args_from_config",
"(",
"func",
")",
":",
"func_args",
"=",
"signature",
"(",
"func",
")",
".",
"parameters",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"get_config",
... | Decorator that injects parameters from the configuration. | [
"Decorator",
"that",
"injects",
"parameters",
"from",
"the",
"configuration",
"."
] | python | train | 31.173913 |
boriel/zxbasic | asmparse.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmparse.py#L1400-L1404 | def p_preprocessor_line_line_file(p):
""" preproc_line : _LINE INTEGER STRING
"""
p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(3) - 1
gl.FILENAME = p[3] | [
"def",
"p_preprocessor_line_line_file",
"(",
"p",
")",
":",
"p",
".",
"lexer",
".",
"lineno",
"=",
"int",
"(",
"p",
"[",
"2",
"]",
")",
"+",
"p",
".",
"lexer",
".",
"lineno",
"-",
"p",
".",
"lineno",
"(",
"3",
")",
"-",
"1",
"gl",
".",
"FILENAM... | preproc_line : _LINE INTEGER STRING | [
"preproc_line",
":",
"_LINE",
"INTEGER",
"STRING"
] | python | train | 34.8 |
senaite/senaite.core | bika/lims/browser/workflow/worksheet.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/workflow/worksheet.py#L45-L77 | def sorted_analyses(self, analyses):
"""Sort the analyses by AR ID ascending and subsorted by priority
sortkey within the AR they belong to
"""
analyses = sorted(analyses, key=lambda an: an.getRequestID())
def sorted_by_sortkey(objs):
return sorted(objs, key=lambda a... | [
"def",
"sorted_analyses",
"(",
"self",
",",
"analyses",
")",
":",
"analyses",
"=",
"sorted",
"(",
"analyses",
",",
"key",
"=",
"lambda",
"an",
":",
"an",
".",
"getRequestID",
"(",
")",
")",
"def",
"sorted_by_sortkey",
"(",
"objs",
")",
":",
"return",
"... | Sort the analyses by AR ID ascending and subsorted by priority
sortkey within the AR they belong to | [
"Sort",
"the",
"analyses",
"by",
"AR",
"ID",
"ascending",
"and",
"subsorted",
"by",
"priority",
"sortkey",
"within",
"the",
"AR",
"they",
"belong",
"to"
] | python | train | 42.363636 |
mitsei/dlkit | dlkit/json_/resource/default_mdata.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/default_mdata.py#L11-L55 | def get_resource_mdata():
"""Return default mdata map for Resource"""
return {
'group': {
'element_label': {
'text': 'group',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
'formatTypeId'... | [
"def",
"get_resource_mdata",
"(",
")",
":",
"return",
"{",
"'group'",
":",
"{",
"'element_label'",
":",
"{",
"'text'",
":",
"'group'",
",",
"'languageTypeId'",
":",
"str",
"(",
"DEFAULT_LANGUAGE_TYPE",
")",
",",
"'scriptTypeId'",
":",
"str",
"(",
"DEFAULT_SCRI... | Return default mdata map for Resource | [
"Return",
"default",
"mdata",
"map",
"for",
"Resource"
] | python | train | 35.4 |
wbond/oscrypto | oscrypto/_win/asymmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2306-L2412 | def _advapi32_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False):
"""
Verifies an RSA, DSA or ECDSA signature via CryptoAPI
:param certificate_or_public_key:
A Certificate or PublicKey instance to verify the signature with
:param signature:
A byte... | [
"def",
"_advapi32_verify",
"(",
"certificate_or_public_key",
",",
"signature",
",",
"data",
",",
"hash_algorithm",
",",
"rsa_pss_padding",
"=",
"False",
")",
":",
"algo",
"=",
"certificate_or_public_key",
".",
"algorithm",
"if",
"algo",
"==",
"'rsa'",
"and",
"rsa_... | Verifies an RSA, DSA or ECDSA signature via CryptoAPI
:param certificate_or_public_key:
A Certificate or PublicKey instance to verify the signature with
:param signature:
A byte string of the signature to verify
:param data:
A byte string of the data the signature is for
:par... | [
"Verifies",
"an",
"RSA",
"DSA",
"or",
"ECDSA",
"signature",
"via",
"CryptoAPI"
] | python | valid | 35.308411 |
solvebio/solvebio-python | solvebio/resource/object.py | https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/resource/object.py#L46-L135 | def validate_full_path(cls, full_path, **kwargs):
"""Helper method to parse a full or partial path and
return a full path as well as a dict containing path parts.
Uses the following rules when processing the path:
* If no domain, uses the current user's account domain
*... | [
"def",
"validate_full_path",
"(",
"cls",
",",
"full_path",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"solvebio",
".",
"resource",
".",
"vault",
"import",
"Vault",
"_client",
"=",
"kwargs",
".",
"pop",
"(",
"'client'",
",",
"None",
")",
"or",
"cls",
".... | Helper method to parse a full or partial path and
return a full path as well as a dict containing path parts.
Uses the following rules when processing the path:
* If no domain, uses the current user's account domain
* If no vault, uses the current user's personal vault.
... | [
"Helper",
"method",
"to",
"parse",
"a",
"full",
"or",
"partial",
"path",
"and",
"return",
"a",
"full",
"path",
"as",
"well",
"as",
"a",
"dict",
"containing",
"path",
"parts",
"."
] | python | test | 39.9 |
saltstack/salt | salt/modules/win_dsc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L183-L329 | def compile_config(path,
source=None,
config_name=None,
config_data=None,
config_data_source=None,
script_parameters=None,
salt_env='base'):
r'''
Compile a config from a PowerShell script (``.ps1``)... | [
"def",
"compile_config",
"(",
"path",
",",
"source",
"=",
"None",
",",
"config_name",
"=",
"None",
",",
"config_data",
"=",
"None",
",",
"config_data_source",
"=",
"None",
",",
"script_parameters",
"=",
"None",
",",
"salt_env",
"=",
"'base'",
")",
":",
"if... | r'''
Compile a config from a PowerShell script (``.ps1``)
Args:
path (str): Path (local) to the script that will create the ``.mof``
configuration file. If no source is passed, the file must exist
locally. Required.
source (str): Path to the script on ``file_roots`` to... | [
"r",
"Compile",
"a",
"config",
"from",
"a",
"PowerShell",
"script",
"(",
".",
"ps1",
")"
] | python | train | 36.673469 |
gem/oq-engine | openquake/hazardlib/calc/disagg.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/disagg.py#L114-L122 | def get_shape(bin_edges, sid):
"""
:returns:
the shape of the disaggregation matrix for the given site, of form
(#mags-1, #dists-1, #lons-1, #lats-1, #eps-1)
"""
mag_bins, dist_bins, lon_bins, lat_bins, eps_bins = bin_edges
return (len(mag_bins) - 1, len(dist_bins) - 1,
l... | [
"def",
"get_shape",
"(",
"bin_edges",
",",
"sid",
")",
":",
"mag_bins",
",",
"dist_bins",
",",
"lon_bins",
",",
"lat_bins",
",",
"eps_bins",
"=",
"bin_edges",
"return",
"(",
"len",
"(",
"mag_bins",
")",
"-",
"1",
",",
"len",
"(",
"dist_bins",
")",
"-",... | :returns:
the shape of the disaggregation matrix for the given site, of form
(#mags-1, #dists-1, #lons-1, #lats-1, #eps-1) | [
":",
"returns",
":",
"the",
"shape",
"of",
"the",
"disaggregation",
"matrix",
"for",
"the",
"given",
"site",
"of",
"form",
"(",
"#mags",
"-",
"1",
"#dists",
"-",
"1",
"#lons",
"-",
"1",
"#lats",
"-",
"1",
"#eps",
"-",
"1",
")"
] | python | train | 41.888889 |
ggravlingen/pytradfri | pytradfri/api/libcoap_api.py | https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/api/libcoap_api.py#L46-L91 | def _execute(self, api_command, *, timeout=None):
"""Execute the command."""
if api_command.observe:
self._observe(api_command)
return
method = api_command.method
path = api_command.path
data = api_command.data
parse_json = api_command.parse_json... | [
"def",
"_execute",
"(",
"self",
",",
"api_command",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"api_command",
".",
"observe",
":",
"self",
".",
"_observe",
"(",
"api_command",
")",
"return",
"method",
"=",
"api_command",
".",
"method",
"path"... | Execute the command. | [
"Execute",
"the",
"command",
"."
] | python | train | 30.804348 |
hydraplatform/hydra-base | hydra_base/lib/template.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L44-L68 | def _check_dimension(typeattr, unit_id=None):
"""
Check that the unit and dimension on a type attribute match.
Alternatively, pass in a unit manually to check against the dimension
of the type attribute
"""
if unit_id is None:
unit_id = typeattr.unit_id
dimension_id = _g... | [
"def",
"_check_dimension",
"(",
"typeattr",
",",
"unit_id",
"=",
"None",
")",
":",
"if",
"unit_id",
"is",
"None",
":",
"unit_id",
"=",
"typeattr",
".",
"unit_id",
"dimension_id",
"=",
"_get_attr",
"(",
"typeattr",
".",
"attr_id",
")",
".",
"dimension_id",
... | Check that the unit and dimension on a type attribute match.
Alternatively, pass in a unit manually to check against the dimension
of the type attribute | [
"Check",
"that",
"the",
"unit",
"and",
"dimension",
"on",
"a",
"type",
"attribute",
"match",
".",
"Alternatively",
"pass",
"in",
"a",
"unit",
"manually",
"to",
"check",
"against",
"the",
"dimension",
"of",
"the",
"type",
"attribute"
] | python | train | 58.08 |
Julian/Filesystems | filesystems/common.py | https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L204-L217 | def _is_link(fs, path):
"""
Check that the given path is a symbolic link.
Note that unlike `os.path.islink`, we *do* propagate file system errors
other than a non-existent path or non-existent directory component.
E.g., should EPERM or ELOOP be raised, an exception will bubble up.
"""
try... | [
"def",
"_is_link",
"(",
"fs",
",",
"path",
")",
":",
"try",
":",
"return",
"stat",
".",
"S_ISLNK",
"(",
"fs",
".",
"lstat",
"(",
"path",
")",
".",
"st_mode",
")",
"except",
"exceptions",
".",
"FileNotFound",
":",
"return",
"False"
] | Check that the given path is a symbolic link.
Note that unlike `os.path.islink`, we *do* propagate file system errors
other than a non-existent path or non-existent directory component.
E.g., should EPERM or ELOOP be raised, an exception will bubble up. | [
"Check",
"that",
"the",
"given",
"path",
"is",
"a",
"symbolic",
"link",
"."
] | python | train | 29.785714 |
seb-m/pyinotify | python3/pyinotify.py | https://github.com/seb-m/pyinotify/blob/0f3f8950d12e4a6534320153eed1a90a778da4ae/python3/pyinotify.py#L283-L292 | def get_val(self):
"""
Gets attribute's value.
@return: stored value.
@rtype: int
@raise IOError: if corresponding file in /proc/sys cannot be read.
"""
with open(os.path.join(self._base, self._attr), 'r') as file_obj:
return int(file_obj.readline()) | [
"def",
"get_val",
"(",
"self",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_base",
",",
"self",
".",
"_attr",
")",
",",
"'r'",
")",
"as",
"file_obj",
":",
"return",
"int",
"(",
"file_obj",
".",
"readline",
"(... | Gets attribute's value.
@return: stored value.
@rtype: int
@raise IOError: if corresponding file in /proc/sys cannot be read. | [
"Gets",
"attribute",
"s",
"value",
"."
] | python | train | 31 |
inspirehep/inspire-utils | inspire_utils/name.py | https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L261-L280 | def _generate_non_lastnames_variations(non_lastnames):
"""Generate variations for all non-lastnames.
E.g. For 'John Richard', this method generates: [
'John', 'J', 'Richard', 'R', 'John Richard', 'John R', 'J Richard', 'J R',
]
"""
if not non_lastnames:
return []
# Generate nam... | [
"def",
"_generate_non_lastnames_variations",
"(",
"non_lastnames",
")",
":",
"if",
"not",
"non_lastnames",
":",
"return",
"[",
"]",
"# Generate name transformations in place for all non lastnames. Transformations include:",
"# 1. Drop non last name, 2. use initial, 3. use full non lastna... | Generate variations for all non-lastnames.
E.g. For 'John Richard', this method generates: [
'John', 'J', 'Richard', 'R', 'John Richard', 'John R', 'J Richard', 'J R',
] | [
"Generate",
"variations",
"for",
"all",
"non",
"-",
"lastnames",
"."
] | python | train | 39.95 |
zetaops/zengine | zengine/wf_daemon.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/wf_daemon.py#L165-L224 | def handle_message(self, ch, method, properties, body):
"""
this is a pika.basic_consumer callback
handles client inputs, runs appropriate workflows and views
Args:
ch: amqp channel
method: amqp method
properties:
body: message body
... | [
"def",
"handle_message",
"(",
"self",
",",
"ch",
",",
"method",
",",
"properties",
",",
"body",
")",
":",
"input",
"=",
"{",
"}",
"headers",
"=",
"{",
"}",
"try",
":",
"self",
".",
"sessid",
"=",
"method",
".",
"routing_key",
"input",
"=",
"json_deco... | this is a pika.basic_consumer callback
handles client inputs, runs appropriate workflows and views
Args:
ch: amqp channel
method: amqp method
properties:
body: message body | [
"this",
"is",
"a",
"pika",
".",
"basic_consumer",
"callback",
"handles",
"client",
"inputs",
"runs",
"appropriate",
"workflows",
"and",
"views"
] | python | train | 36.15 |
rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1053-L1055 | def delete_lbaas_l7rule(self, l7rule, l7policy):
"""Deletes the specified L7 rule."""
return self.delete(self.lbaas_l7rule_path % (l7policy, l7rule)) | [
"def",
"delete_lbaas_l7rule",
"(",
"self",
",",
"l7rule",
",",
"l7policy",
")",
":",
"return",
"self",
".",
"delete",
"(",
"self",
".",
"lbaas_l7rule_path",
"%",
"(",
"l7policy",
",",
"l7rule",
")",
")"
] | Deletes the specified L7 rule. | [
"Deletes",
"the",
"specified",
"L7",
"rule",
"."
] | python | train | 54.333333 |
boris-savic/python-mbills | python_mbills/base.py | https://github.com/boris-savic/python-mbills/blob/a2147810c8c54b9242d9bcc2218622f1e19f9ac3/python_mbills/base.py#L87-L93 | def convert_decimal_to_hundreds(self, amount):
"""
Convert Decimal(10.10) to string "1010"
:param amount:
:return:
"""
return str((amount.quantize(Decimal('.01'), rounding=ROUND_FLOOR) * 100).quantize(Decimal('0'))) | [
"def",
"convert_decimal_to_hundreds",
"(",
"self",
",",
"amount",
")",
":",
"return",
"str",
"(",
"(",
"amount",
".",
"quantize",
"(",
"Decimal",
"(",
"'.01'",
")",
",",
"rounding",
"=",
"ROUND_FLOOR",
")",
"*",
"100",
")",
".",
"quantize",
"(",
"Decimal... | Convert Decimal(10.10) to string "1010"
:param amount:
:return: | [
"Convert",
"Decimal",
"(",
"10",
".",
"10",
")",
"to",
"string",
"1010",
":",
"param",
"amount",
":",
":",
"return",
":"
] | python | train | 37 |
openstack/proliantutils | proliantutils/ilo/ris.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L1703-L1748 | def update_firmware(self, file_url, component_type):
"""Updates the given firmware on the server for the given component.
:param file_url: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen pr... | [
"def",
"update_firmware",
"(",
"self",
",",
"file_url",
",",
"component_type",
")",
":",
"fw_update_uri",
"=",
"self",
".",
"_get_firmware_update_service_resource",
"(",
")",
"action_data",
"=",
"{",
"'Action'",
":",
"'InstallFromURI'",
",",
"'FirmwareURI'",
":",
... | Updates the given firmware on the server for the given component.
:param file_url: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen prior to this invocation.
:param component_type: Type of c... | [
"Updates",
"the",
"given",
"firmware",
"on",
"the",
"server",
"for",
"the",
"given",
"component",
"."
] | python | train | 41.804348 |
numenta/htmresearch | htmresearch/algorithms/sparse_net.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/sparse_net.py#L156-L205 | def encode(self, data, flatten=False):
"""
Encodes the provided input data, returning a sparse vector of activations.
It solves a dynamic system to find optimal activations, as proposed by
Rozell et al. (2008).
:param data: (array) Data to be encoded (single point or multiple)
:param f... | [
"def",
"encode",
"(",
"self",
",",
"data",
",",
"flatten",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"# flatten if necessary",
"if",
"flatte... | Encodes the provided input data, returning a sparse vector of activations.
It solves a dynamic system to find optimal activations, as proposed by
Rozell et al. (2008).
:param data: (array) Data to be encoded (single point or multiple)
:param flatten (bool) Whether or not the data needs... | [
"Encodes",
"the",
"provided",
"input",
"data",
"returning",
"a",
"sparse",
"vector",
"of",
"activations",
"."
] | python | train | 37.6 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L609-L627 | def complete_io(self, iocb, msg):
"""Called by a handler to return data to the client."""
if _debug: IOController._debug("complete_io %r %r", iocb, msg)
# if it completed, leave it alone
if iocb.ioState == COMPLETED:
pass
# if it already aborted, leave it alone
... | [
"def",
"complete_io",
"(",
"self",
",",
"iocb",
",",
"msg",
")",
":",
"if",
"_debug",
":",
"IOController",
".",
"_debug",
"(",
"\"complete_io %r %r\"",
",",
"iocb",
",",
"msg",
")",
"# if it completed, leave it alone",
"if",
"iocb",
".",
"ioState",
"==",
"CO... | Called by a handler to return data to the client. | [
"Called",
"by",
"a",
"handler",
"to",
"return",
"data",
"to",
"the",
"client",
"."
] | python | train | 27.842105 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L334-L373 | def add_package(self, login, package_name,
summary=None,
license=None,
public=True,
license_url=None,
license_family=None,
attrs=None,
package_type=None):
'''
Add a... | [
"def",
"add_package",
"(",
"self",
",",
"login",
",",
"package_name",
",",
"summary",
"=",
"None",
",",
"license",
"=",
"None",
",",
"public",
"=",
"True",
",",
"license_url",
"=",
"None",
",",
"license_family",
"=",
"None",
",",
"attrs",
"=",
"None",
... | Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:pa... | [
"Add",
"a",
"new",
"package",
"to",
"a",
"users",
"account"
] | python | train | 37.6 |
saltstack/salt | salt/modules/zpool.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L680-L807 | def create(zpool, *vdevs, **kwargs):
'''
.. versionadded:: 2015.5.0
Create a simple zpool, a mirrored zpool, a zpool having nested VDEVs, a hybrid zpool with cache, spare and log drives or a zpool with RAIDZ-1, RAIDZ-2 or RAIDZ-3
zpool : string
Name of storage pool
vdevs : string
... | [
"def",
"create",
"(",
"zpool",
",",
"*",
"vdevs",
",",
"*",
"*",
"kwargs",
")",
":",
"## Configure pool",
"# NOTE: initialize the defaults",
"flags",
"=",
"[",
"]",
"opts",
"=",
"{",
"}",
"target",
"=",
"[",
"]",
"# NOTE: push pool and filesystem properties",
... | .. versionadded:: 2015.5.0
Create a simple zpool, a mirrored zpool, a zpool having nested VDEVs, a hybrid zpool with cache, spare and log drives or a zpool with RAIDZ-1, RAIDZ-2 or RAIDZ-3
zpool : string
Name of storage pool
vdevs : string
One or move devices
force : boolean
... | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | python | train | 34.929688 |
freshbooks/refreshbooks | refreshbooks/api.py | https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L72-L92 | def AuthorizingClient(
domain,
auth,
request_encoder,
response_decoder,
user_agent=None
):
"""Creates a Freshbooks client for a freshbooks domain, using
an auth object.
"""
http_transport = transport.HttpTransport(
api_url(domain),
build_headers(auth, user_agent)... | [
"def",
"AuthorizingClient",
"(",
"domain",
",",
"auth",
",",
"request_encoder",
",",
"response_decoder",
",",
"user_agent",
"=",
"None",
")",
":",
"http_transport",
"=",
"transport",
".",
"HttpTransport",
"(",
"api_url",
"(",
"domain",
")",
",",
"build_headers",... | Creates a Freshbooks client for a freshbooks domain, using
an auth object. | [
"Creates",
"a",
"Freshbooks",
"client",
"for",
"a",
"freshbooks",
"domain",
"using",
"an",
"auth",
"object",
"."
] | python | train | 19.857143 |
gbowerman/azurerm | azurerm/keyvault.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/keyvault.py#L169-L183 | def delete_keyvault_secret(access_token, vault_uri, secret_name):
'''Deletes a secret from a key vault using the key vault URI.
Args:
access_token (str): A valid Azure authentication token.
vault_uri (str): Vault URI e.g. https://myvault.azure.net.
secret_name (str): Name of the secret... | [
"def",
"delete_keyvault_secret",
"(",
"access_token",
",",
"vault_uri",
",",
"secret_name",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"vault_uri",
",",
"'/secrets/'",
",",
"secret_name",
",",
"'?api-version='",
",",
"'7.0'",
"]",
")",
"return",
... | Deletes a secret from a key vault using the key vault URI.
Args:
access_token (str): A valid Azure authentication token.
vault_uri (str): Vault URI e.g. https://myvault.azure.net.
secret_name (str): Name of the secret to add.
Returns:
HTTP response. 200 OK. | [
"Deletes",
"a",
"secret",
"from",
"a",
"key",
"vault",
"using",
"the",
"key",
"vault",
"URI",
"."
] | python | train | 35.866667 |
riga/law | law/target/local.py | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/target/local.py#L252-L309 | def localize(self, mode="r", perm=None, parent_perm=None, **kwargs):
""" localize(mode="r", perm=None, parent_perm=None, skip_copy=False, is_tmp=None, **kwargs)
"""
if mode not in ("r", "w"):
raise Exception("unknown mode '{}', use r or w".format(mode))
# get additional argu... | [
"def",
"localize",
"(",
"self",
",",
"mode",
"=",
"\"r\"",
",",
"perm",
"=",
"None",
",",
"parent_perm",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"not",
"in",
"(",
"\"r\"",
",",
"\"w\"",
")",
":",
"raise",
"Exception",
"(",
"... | localize(mode="r", perm=None, parent_perm=None, skip_copy=False, is_tmp=None, **kwargs) | [
"localize",
"(",
"mode",
"=",
"r",
"perm",
"=",
"None",
"parent_perm",
"=",
"None",
"skip_copy",
"=",
"False",
"is_tmp",
"=",
"None",
"**",
"kwargs",
")"
] | python | train | 31.87931 |
pypa/pipenv | pipenv/patched/notpip/_internal/req/req_uninstall.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L137-L183 | def compress_for_output_listing(paths):
"""Returns a tuple of 2 sets of which paths to display to user
The first set contains paths that would be deleted. Files of a package
are not added and the top-level directory of the package has a '*' added
at the end - to signify that all it's contents are remov... | [
"def",
"compress_for_output_listing",
"(",
"paths",
")",
":",
"will_remove",
"=",
"list",
"(",
"paths",
")",
"will_skip",
"=",
"set",
"(",
")",
"# Determine folders and files",
"folders",
"=",
"set",
"(",
")",
"files",
"=",
"set",
"(",
")",
"for",
"path",
... | Returns a tuple of 2 sets of which paths to display to user
The first set contains paths that would be deleted. Files of a package
are not added and the top-level directory of the package has a '*' added
at the end - to signify that all it's contents are removed.
The second set contains files that wou... | [
"Returns",
"a",
"tuple",
"of",
"2",
"sets",
"of",
"which",
"paths",
"to",
"display",
"to",
"user"
] | python | train | 31.957447 |
ruipgil/TrackToTrip | tracktotrip/location.py | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/location.py#L49-L92 | def update_location_centroid(point, cluster, max_distance, min_samples):
""" Updates the centroid of a location cluster with another point
Args:
point (:obj:`Point`): Point to add to the cluster
cluster (:obj:`list` of :obj:`Point`): Location cluster
max_distance (float): Max neighbour ... | [
"def",
"update_location_centroid",
"(",
"point",
",",
"cluster",
",",
"max_distance",
",",
"min_samples",
")",
":",
"cluster",
".",
"append",
"(",
"point",
")",
"points",
"=",
"[",
"p",
".",
"gen2arr",
"(",
")",
"for",
"p",
"in",
"cluster",
"]",
"# Estim... | Updates the centroid of a location cluster with another point
Args:
point (:obj:`Point`): Point to add to the cluster
cluster (:obj:`list` of :obj:`Point`): Location cluster
max_distance (float): Max neighbour distance
min_samples (int): Minimum number of samples
Returns:
... | [
"Updates",
"the",
"centroid",
"of",
"a",
"location",
"cluster",
"with",
"another",
"point"
] | python | train | 33.022727 |
ray-project/ray | python/ray/tune/schedulers/hyperband.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/hyperband.py#L217-L235 | def choose_trial_to_run(self, trial_runner):
"""Fair scheduling within iteration by completion percentage.
List of trials not used since all trials are tracked as state
of scheduler. If iteration is occupied (ie, no trials to run),
then look into next iteration.
"""
for... | [
"def",
"choose_trial_to_run",
"(",
"self",
",",
"trial_runner",
")",
":",
"for",
"hyperband",
"in",
"self",
".",
"_hyperbands",
":",
"# band will have None entries if no resources",
"# are to be allocated to that bracket.",
"scrubbed",
"=",
"[",
"b",
"for",
"b",
"in",
... | Fair scheduling within iteration by completion percentage.
List of trials not used since all trials are tracked as state
of scheduler. If iteration is occupied (ie, no trials to run),
then look into next iteration. | [
"Fair",
"scheduling",
"within",
"iteration",
"by",
"completion",
"percentage",
"."
] | python | train | 45.052632 |
LCAV/pylocus | pylocus/lateration.py | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/lateration.py#L204-L218 | def PozyxLS(anchors, W, r2, print_out=False):
''' Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work)
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:returns: estimated position of point x.
'''
N = anchors.shape[0]
anc... | [
"def",
"PozyxLS",
"(",
"anchors",
",",
"W",
",",
"r2",
",",
"print_out",
"=",
"False",
")",
":",
"N",
"=",
"anchors",
".",
"shape",
"[",
"0",
"]",
"anchors_term",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"power",
"(",
"anchors",
"[",
":",
"-",
"1... | Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work)
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:returns: estimated position of point x. | [
"Algorithm",
"used",
"by",
"pozyx",
"(",
"https",
":",
"//",
"www",
".",
"pozyx",
".",
"io",
"/",
"Documentation",
"/",
"how_does_positioning_work",
")"
] | python | train | 37.266667 |
AmesCornish/buttersink | buttersink/btrfs.py | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/btrfs.py#L527-L541 | def _rescanSizes(self, force=True):
""" Zero and recalculate quota sizes to subvolume sizes will be correct. """
status = self.QUOTA_CTL(cmd=BTRFS_QUOTA_CTL_ENABLE).status
logger.debug("CTL Status: %s", hex(status))
status = self.QUOTA_RESCAN_STATUS()
logger.debug("RESCAN Status... | [
"def",
"_rescanSizes",
"(",
"self",
",",
"force",
"=",
"True",
")",
":",
"status",
"=",
"self",
".",
"QUOTA_CTL",
"(",
"cmd",
"=",
"BTRFS_QUOTA_CTL_ENABLE",
")",
".",
"status",
"logger",
".",
"debug",
"(",
"\"CTL Status: %s\"",
",",
"hex",
"(",
"status",
... | Zero and recalculate quota sizes to subvolume sizes will be correct. | [
"Zero",
"and",
"recalculate",
"quota",
"sizes",
"to",
"subvolume",
"sizes",
"will",
"be",
"correct",
"."
] | python | train | 35.066667 |
naphatkrit/click-extensions | click_extensions/decorators.py | https://github.com/naphatkrit/click-extensions/blob/80fc1a70419fdaf00833649677a9031bdbf8c47b/click_extensions/decorators.py#L10-L55 | def print_markers(f):
"""A decorator that prints the invoked command
before and after the command.
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
command = ctx.info_name
assert command is not None
command_name = ctx.command_path
click_extensions.echo_with... | [
"def",
"print_markers",
"(",
"f",
")",
":",
"@",
"click",
".",
"pass_context",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"command",
"=",
"ctx",
".",
"info_name",
"assert",
"command",
"is",
"not",
"None",
"com... | A decorator that prints the invoked command
before and after the command. | [
"A",
"decorator",
"that",
"prints",
"the",
"invoked",
"command",
"before",
"and",
"after",
"the",
"command",
"."
] | python | train | 31.630435 |
gwastro/pycbc | pycbc/inference/models/base.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L782-L793 | def write_metadata(self, fp):
"""Writes metadata to the given file handler.
Parameters
----------
fp : pycbc.inference.io.BaseInferenceFile instance
The inference file to write to.
"""
fp.attrs['model'] = self.name
fp.attrs['variable_params'] = list(s... | [
"def",
"write_metadata",
"(",
"self",
",",
"fp",
")",
":",
"fp",
".",
"attrs",
"[",
"'model'",
"]",
"=",
"self",
".",
"name",
"fp",
".",
"attrs",
"[",
"'variable_params'",
"]",
"=",
"list",
"(",
"self",
".",
"variable_params",
")",
"fp",
".",
"attrs"... | Writes metadata to the given file handler.
Parameters
----------
fp : pycbc.inference.io.BaseInferenceFile instance
The inference file to write to. | [
"Writes",
"metadata",
"to",
"the",
"given",
"file",
"handler",
"."
] | python | train | 39.25 |
PSPC-SPAC-buyandsell/von_agent | von_agent/codec.py | https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/codec.py#L35-L67 | def encode(raw: Any) -> str:
"""
Encode credential attribute value, leaving any (stringified) int32 alone: indy-sdk predicates
operate on int32 values properly only when their encoded values match their raw values.
To disambiguate for decoding, the operation reserves a sentinel for the null value and o... | [
"def",
"encode",
"(",
"raw",
":",
"Any",
")",
"->",
"str",
":",
"if",
"raw",
"is",
"None",
":",
"return",
"str",
"(",
"I32_BOUND",
")",
"# sentinel",
"stringified",
"=",
"str",
"(",
"raw",
")",
"if",
"isinstance",
"(",
"raw",
",",
"bool",
")",
":",... | Encode credential attribute value, leaving any (stringified) int32 alone: indy-sdk predicates
operate on int32 values properly only when their encoded values match their raw values.
To disambiguate for decoding, the operation reserves a sentinel for the null value and otherwise adds
2**31 to any non-trivia... | [
"Encode",
"credential",
"attribute",
"value",
"leaving",
"any",
"(",
"stringified",
")",
"int32",
"alone",
":",
"indy",
"-",
"sdk",
"predicates",
"operate",
"on",
"int32",
"values",
"properly",
"only",
"when",
"their",
"encoded",
"values",
"match",
"their",
"r... | python | train | 36.818182 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/publisher/plos.py | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/publisher/plos.py#L31-L63 | def get_contrib_names(self, contrib):
"""
Returns an appropriate Name and File-As-Name for a contrib element.
This code was refactored out of nav_contributors and
package_contributors to provide a single definition point for a common
job. This is a useful utility that may be wel... | [
"def",
"get_contrib_names",
"(",
"self",
",",
"contrib",
")",
":",
"collab",
"=",
"contrib",
".",
"find",
"(",
"'collab'",
")",
"anon",
"=",
"contrib",
".",
"find",
"(",
"'anonymous'",
")",
"if",
"collab",
"is",
"not",
"None",
":",
"proper_name",
"=",
... | Returns an appropriate Name and File-As-Name for a contrib element.
This code was refactored out of nav_contributors and
package_contributors to provide a single definition point for a common
job. This is a useful utility that may be well-employed for other
publishers as well. | [
"Returns",
"an",
"appropriate",
"Name",
"and",
"File",
"-",
"As",
"-",
"Name",
"for",
"a",
"contrib",
"element",
"."
] | python | train | 41.393939 |
saltstack/salt | salt/modules/boto_iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1458-L1483 | def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None):
'''
Delete a user policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.delete_user_policy myuser mypolicy
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=prof... | [
"def",
"delete_user_policy",
"(",
"user_name",
",",
"policy_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key"... | Delete a user policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.delete_user_policy myuser mypolicy | [
"Delete",
"a",
"user",
"policy",
"."
] | python | train | 31.923077 |
clalancette/pycdlib | pycdlib/rockridge.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/rockridge.py#L1623-L1642 | def record(self):
# type: () -> bytes
'''
Generate a string representing the Rock Ridge Time Stamp record.
Parameters:
None.
Returns:
String containing the Rock Ridge record.
'''
if not self._initialized:
raise pycdlibexception.PyCdl... | [
"def",
"record",
"(",
"self",
")",
":",
"# type: () -> bytes",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'TF record not yet initialized!'",
")",
"outlist",
"=",
"[",
"b'TF'",
",",
"struct",
".",
... | Generate a string representing the Rock Ridge Time Stamp record.
Parameters:
None.
Returns:
String containing the Rock Ridge record. | [
"Generate",
"a",
"string",
"representing",
"the",
"Rock",
"Ridge",
"Time",
"Stamp",
"record",
"."
] | python | train | 33.55 |
idlesign/django-sitetree | sitetree/sitetreeapp.py | https://github.com/idlesign/django-sitetree/blob/61de4608e6e415247c75fe8691027d7c4ed0d1e7/sitetree/sitetreeapp.py#L1083-L1104 | def resolve_var(self, varname, context=None):
"""Resolves name as a variable in a given context.
If no context specified page context' is considered as context.
:param str|unicode varname:
:param Context context:
:return:
"""
context = context or self.current_pa... | [
"def",
"resolve_var",
"(",
"self",
",",
"varname",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"context",
"or",
"self",
".",
"current_page_context",
"if",
"isinstance",
"(",
"varname",
",",
"FilterExpression",
")",
":",
"varname",
"=",
"varname",
... | Resolves name as a variable in a given context.
If no context specified page context' is considered as context.
:param str|unicode varname:
:param Context context:
:return: | [
"Resolves",
"name",
"as",
"a",
"variable",
"in",
"a",
"given",
"context",
"."
] | python | test | 28.954545 |
django-treebeard/django-treebeard | treebeard/ns_tree.py | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/ns_tree.py#L339-L466 | def move(self, target, pos=None):
"""
Moves the current node and all it's descendants to a new position
relative to another node.
"""
pos = self._prepare_pos_var_for_move(pos)
cls = get_result_class(self.__class__)
parent = None
if pos in ('first-child'... | [
"def",
"move",
"(",
"self",
",",
"target",
",",
"pos",
"=",
"None",
")",
":",
"pos",
"=",
"self",
".",
"_prepare_pos_var_for_move",
"(",
"pos",
")",
"cls",
"=",
"get_result_class",
"(",
"self",
".",
"__class__",
")",
"parent",
"=",
"None",
"if",
"pos",... | Moves the current node and all it's descendants to a new position
relative to another node. | [
"Moves",
"the",
"current",
"node",
"and",
"all",
"it",
"s",
"descendants",
"to",
"a",
"new",
"position",
"relative",
"to",
"another",
"node",
"."
] | python | train | 36.164063 |
contains-io/rcli | rcli/log.py | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L70-L89 | def handle_unexpected_exception(exc):
# type: (BaseException) -> str
"""Return an error message and write a log file if logging was not enabled.
Args:
exc: The unexpected exception.
Returns:
A message to display to the user concerning the unexpected exception.
"""
try:
... | [
"def",
"handle_unexpected_exception",
"(",
"exc",
")",
":",
"# type: (BaseException) -> str",
"try",
":",
"write_logfile",
"(",
")",
"addendum",
"=",
"'Please see the log file for more information.'",
"except",
"IOError",
":",
"addendum",
"=",
"'Unable to write log file.'",
... | Return an error message and write a log file if logging was not enabled.
Args:
exc: The unexpected exception.
Returns:
A message to display to the user concerning the unexpected exception. | [
"Return",
"an",
"error",
"message",
"and",
"write",
"a",
"log",
"file",
"if",
"logging",
"was",
"not",
"enabled",
"."
] | python | train | 31.95 |
KelSolaar/Manager | manager/components_manager.py | https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/components_manager.py#L226-L237 | def attribute(self, value):
"""
Setter for **self.__attribute** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"a... | [
"def",
"attribute",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"unicode",
",",
"\"'{0}' attribute: '{1}' type is not 'unicode'!\"",
".",
"format",
"(",
"\"attribute\"",
",",
"value",... | Setter for **self.__attribute** attribute.
:param value: Attribute value.
:type value: unicode | [
"Setter",
"for",
"**",
"self",
".",
"__attribute",
"**",
"attribute",
"."
] | python | train | 29.916667 |
HewlettPackard/python-hpOneView | hpOneView/resources/storage/storage_volume_attachments.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/storage_volume_attachments.py#L98-L113 | def remove_extra_presentations(self, resource, timeout=-1):
"""
Removes extra presentations from a specified server profile.
Args:
resource (dict):
Object to create
timeout:
Timeout in seconds. Wait for task completion by default. The time... | [
"def",
"remove_extra_presentations",
"(",
"self",
",",
"resource",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"uri",
"=",
"self",
".",
"URI",
"+",
"\"/repair\"",
"custom_headers",
"=",
"{",
"'Accept-Language'",
":",
"'en_US'",
"}",
"return",
"self",
".",
"_c... | Removes extra presentations from a specified server profile.
Args:
resource (dict):
Object to create
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiti... | [
"Removes",
"extra",
"presentations",
"from",
"a",
"specified",
"server",
"profile",
"."
] | python | train | 42.8125 |
theolind/pymysensors | mysensors/gateway_serial.py | https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_serial.py#L30-L33 | def get_gateway_id(self):
"""Return a unique id for the gateway."""
info = next(serial.tools.list_ports.grep(self.port), None)
return info.serial_number if info is not None else None | [
"def",
"get_gateway_id",
"(",
"self",
")",
":",
"info",
"=",
"next",
"(",
"serial",
".",
"tools",
".",
"list_ports",
".",
"grep",
"(",
"self",
".",
"port",
")",
",",
"None",
")",
"return",
"info",
".",
"serial_number",
"if",
"info",
"is",
"not",
"Non... | Return a unique id for the gateway. | [
"Return",
"a",
"unique",
"id",
"for",
"the",
"gateway",
"."
] | python | train | 50.75 |
nerdvegas/rez | src/rez/utils/graph_utils.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L229-L252 | def view_graph(graph_str, dest_file=None):
"""View a dot graph in an image viewer."""
from rez.system import system
from rez.config import config
if (system.platform == "linux") and (not os.getenv("DISPLAY")):
print >> sys.stderr, "Unable to open display."
sys.exit(1)
dest_file = _... | [
"def",
"view_graph",
"(",
"graph_str",
",",
"dest_file",
"=",
"None",
")",
":",
"from",
"rez",
".",
"system",
"import",
"system",
"from",
"rez",
".",
"config",
"import",
"config",
"if",
"(",
"system",
".",
"platform",
"==",
"\"linux\"",
")",
"and",
"(",
... | View a dot graph in an image viewer. | [
"View",
"a",
"dot",
"graph",
"in",
"an",
"image",
"viewer",
"."
] | python | train | 29.708333 |
saltstack/salt | salt/utils/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virt.py#L66-L72 | def authorize(self):
'''
Prepare the master to expect a signing request
'''
with salt.utils.files.fopen(self.path, 'w+') as fp_:
fp_.write(str(int(time.time()))) # future lint: disable=blacklisted-function
return True | [
"def",
"authorize",
"(",
"self",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"self",
".",
"path",
",",
"'w+'",
")",
"as",
"fp_",
":",
"fp_",
".",
"write",
"(",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
... | Prepare the master to expect a signing request | [
"Prepare",
"the",
"master",
"to",
"expect",
"a",
"signing",
"request"
] | python | train | 37.714286 |
pypa/setuptools | setuptools/wheel.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/wheel.py#L77-L80 | def is_compatible(self):
'''Is the wheel is compatible with the current platform?'''
supported_tags = pep425tags.get_supported()
return next((True for t in self.tags() if t in supported_tags), False) | [
"def",
"is_compatible",
"(",
"self",
")",
":",
"supported_tags",
"=",
"pep425tags",
".",
"get_supported",
"(",
")",
"return",
"next",
"(",
"(",
"True",
"for",
"t",
"in",
"self",
".",
"tags",
"(",
")",
"if",
"t",
"in",
"supported_tags",
")",
",",
"False... | Is the wheel is compatible with the current platform? | [
"Is",
"the",
"wheel",
"is",
"compatible",
"with",
"the",
"current",
"platform?"
] | python | train | 55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.