repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
boriel/zxbasic | arch/zx48k/backend/__8bit.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L521-L533 | def _gtu8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('cp h')
o... | [
"def",
"_gtu8",
"(",
"ins",
")",
":",
"output",
"=",
"_8bit_oper",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
",",
"ins",
".",
"quad",
"[",
"3",
"]",
",",
"reversed_",
"=",
"True",
")",
"output",
".",
"append",
"(",
"'cp h'",
")",
"output",
".",
"... | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version | [
"Compares",
"&",
"pops",
"top",
"2",
"operands",
"out",
"of",
"the",
"stack",
"and",
"checks",
"if",
"the",
"1st",
"operand",
">",
"2nd",
"operand",
"(",
"top",
"of",
"the",
"stack",
")",
".",
"Pushes",
"0",
"if",
"False",
"1",
"if",
"True",
"."
] | python | train |
log2timeline/plaso | plaso/parsers/sqlite.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/sqlite.py#L95-L111 | def GetRowCache(self, query):
"""Retrieves the row cache for a specific query.
The row cache is a set that contains hashes of values in a row. The row
cache is used to find duplicate row when a database and a database with
a WAL file is parsed.
Args:
query (str): query.
Returns:
s... | [
"def",
"GetRowCache",
"(",
"self",
",",
"query",
")",
":",
"query_hash",
"=",
"hash",
"(",
"query",
")",
"if",
"query_hash",
"not",
"in",
"self",
".",
"_row_caches",
":",
"self",
".",
"_row_caches",
"[",
"query_hash",
"]",
"=",
"set",
"(",
")",
"return... | Retrieves the row cache for a specific query.
The row cache is a set that contains hashes of values in a row. The row
cache is used to find duplicate row when a database and a database with
a WAL file is parsed.
Args:
query (str): query.
Returns:
set: hashes of the rows that have been... | [
"Retrieves",
"the",
"row",
"cache",
"for",
"a",
"specific",
"query",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/brocade_mpls_rpc/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/brocade_mpls_rpc/__init__.py#L2868-L2889 | def _set_clear_mpls_auto_bandwidth_statistics_all(self, v, load=False):
"""
Setter method for clear_mpls_auto_bandwidth_statistics_all, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_all (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _... | [
"def",
"_set_clear_mpls_auto_bandwidth_statistics_all",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass... | Setter method for clear_mpls_auto_bandwidth_statistics_all, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_all (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_auto_bandwidth_statistics_all is considered as a private
method. ... | [
"Setter",
"method",
"for",
"clear_mpls_auto_bandwidth_statistics_all",
"mapped",
"from",
"YANG",
"variable",
"/",
"brocade_mpls_rpc",
"/",
"clear_mpls_auto_bandwidth_statistics_all",
"(",
"rpc",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
... | python | train |
relekang/python-semantic-release | semantic_release/history/parser_angular.py | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/parser_angular.py#L32-L69 | def parse_commit_message(message: str) -> Tuple[int, str, str, Tuple[str, str, str]]:
"""
Parses a commit message according to the angular commit guidelines specification.
:param message: A string of a commit message.
:return: A tuple of (level to bump, type of change, scope of change, a tuple with des... | [
"def",
"parse_commit_message",
"(",
"message",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"str",
",",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
"]",
":",
"parsed",
"=",
"re_parser",
".",
"match",
"(",
"message",
")",
"if",... | Parses a commit message according to the angular commit guidelines specification.
:param message: A string of a commit message.
:return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions)
:raises UnknownCommitMessageStyleError: if regular expression matching fails | [
"Parses",
"a",
"commit",
"message",
"according",
"to",
"the",
"angular",
"commit",
"guidelines",
"specification",
"."
] | python | train |
pallets/werkzeug | bench/wzbench.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/bench/wzbench.py#L48-L72 | def find_hg_tag(path):
"""Returns the current node or tag for the given path."""
tags = {}
try:
client = subprocess.Popen(
["hg", "cat", "-r", "tip", ".hgtags"], stdout=subprocess.PIPE, cwd=path
)
for line in client.communicate()[0].splitlines():
line = line.s... | [
"def",
"find_hg_tag",
"(",
"path",
")",
":",
"tags",
"=",
"{",
"}",
"try",
":",
"client",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"hg\"",
",",
"\"cat\"",
",",
"\"-r\"",
",",
"\"tip\"",
",",
"\".hgtags\"",
"]",
",",
"stdout",
"=",
"subprocess",
"... | Returns the current node or tag for the given path. | [
"Returns",
"the",
"current",
"node",
"or",
"tag",
"for",
"the",
"given",
"path",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/authentication_process/default_mdata.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authentication_process/default_mdata.py#L11-L35 | def get_authentication_mdata():
"""Return default mdata map for Authentication"""
return {
'agent': {
'element_label': {
'text': 'agent',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
'f... | [
"def",
"get_authentication_mdata",
"(",
")",
":",
"return",
"{",
"'agent'",
":",
"{",
"'element_label'",
":",
"{",
"'text'",
":",
"'agent'",
",",
"'languageTypeId'",
":",
"str",
"(",
"DEFAULT_LANGUAGE_TYPE",
")",
",",
"'scriptTypeId'",
":",
"str",
"(",
"DEFAUL... | Return default mdata map for Authentication | [
"Return",
"default",
"mdata",
"map",
"for",
"Authentication"
] | python | train |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L132-L140 | def _opposite_axis_margin(self):
"""ndarray representing margin along the axis opposite of self._axis
In the process of calculating p-values for the column significance testing we
need both the margin along the primary axis and the percentage margin along
the opposite axis.
"""
... | [
"def",
"_opposite_axis_margin",
"(",
"self",
")",
":",
"off_axis",
"=",
"1",
"-",
"self",
".",
"_axis",
"return",
"self",
".",
"_slice",
".",
"margin",
"(",
"axis",
"=",
"off_axis",
",",
"include_mr_cat",
"=",
"self",
".",
"_include_mr_cat",
")"
] | ndarray representing margin along the axis opposite of self._axis
In the process of calculating p-values for the column significance testing we
need both the margin along the primary axis and the percentage margin along
the opposite axis. | [
"ndarray",
"representing",
"margin",
"along",
"the",
"axis",
"opposite",
"of",
"self",
".",
"_axis"
] | python | train |
gem/oq-engine | openquake/risklib/asset.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L208-L217 | def deductible(self, loss_type, dummy=None):
"""
:returns: the deductible fraction of the asset cost for `loss_type`
"""
val = self.calc(loss_type, self.deductibles, self.area, self.number)
if self.calc.deduct_abs: # convert to relative value
return val / self.calc(l... | [
"def",
"deductible",
"(",
"self",
",",
"loss_type",
",",
"dummy",
"=",
"None",
")",
":",
"val",
"=",
"self",
".",
"calc",
"(",
"loss_type",
",",
"self",
".",
"deductibles",
",",
"self",
".",
"area",
",",
"self",
".",
"number",
")",
"if",
"self",
".... | :returns: the deductible fraction of the asset cost for `loss_type` | [
":",
"returns",
":",
"the",
"deductible",
"fraction",
"of",
"the",
"asset",
"cost",
"for",
"loss_type"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sql/literals.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L100-L107 | def sql_dequote_string(s: str) -> str:
"""
Reverses :func:`sql_quote_string`.
"""
if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE:
raise ValueError("Not an SQL string literal")
s = s[1:-1] # strip off the surrounding quotes
return s.replace(DOUBLE_SQUOTE, SQUOTE) | [
"def",
"sql_dequote_string",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"if",
"len",
"(",
"s",
")",
"<",
"2",
"or",
"s",
"[",
"0",
"]",
"!=",
"SQUOTE",
"or",
"s",
"[",
"-",
"1",
"]",
"!=",
"SQUOTE",
":",
"raise",
"ValueError",
"(",
"\"Not an ... | Reverses :func:`sql_quote_string`. | [
"Reverses",
":",
"func",
":",
"sql_quote_string",
"."
] | python | train |
SteveMcGrath/pySecurityCenter | securitycenter/sc5.py | https://github.com/SteveMcGrath/pySecurityCenter/blob/f0b10b1bcd4fd23a8d4d09ca6774cdf5e1cfd880/securitycenter/sc5.py#L42-L45 | def login(self, user, passwd):
'''Logs the user into SecurityCenter and stores the needed token and cookies.'''
resp = self.post('token', json={'username': user, 'password': passwd})
self._token = resp.json()['response']['token'] | [
"def",
"login",
"(",
"self",
",",
"user",
",",
"passwd",
")",
":",
"resp",
"=",
"self",
".",
"post",
"(",
"'token'",
",",
"json",
"=",
"{",
"'username'",
":",
"user",
",",
"'password'",
":",
"passwd",
"}",
")",
"self",
".",
"_token",
"=",
"resp",
... | Logs the user into SecurityCenter and stores the needed token and cookies. | [
"Logs",
"the",
"user",
"into",
"SecurityCenter",
"and",
"stores",
"the",
"needed",
"token",
"and",
"cookies",
"."
] | python | train |
usc-isi-i2/dig-extractor | digExtractor/extractor_processor.py | https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L45-L55 | def set_output_fields(self, output_fields):
"""Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys"""
if isinstance(output_fields, dict) or isinstance(output_fields, list):
se... | [
"def",
"set_output_fields",
"(",
"self",
",",
"output_fields",
")",
":",
"if",
"isinstance",
"(",
"output_fields",
",",
"dict",
")",
"or",
"isinstance",
"(",
"output_fields",
",",
"list",
")",
":",
"self",
".",
"output_fields",
"=",
"output_fields",
"elif",
... | Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys | [
"Defines",
"where",
"to",
"put",
"the",
"dictionary",
"output",
"of",
"the",
"extractor",
"in",
"the",
"doc",
"but",
"renames",
"the",
"fields",
"of",
"the",
"extracted",
"output",
"for",
"the",
"document",
"or",
"just",
"filters",
"the",
"keys"
] | python | train |
wrboyce/telegrambot | telegrambot/api/__init__.py | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/__init__.py#L120-L129 | def send_document(self, chat_id=None, document=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send general files. On success, the sent Message is returned.
Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the futur... | [
"def",
"send_document",
"(",
"self",
",",
"chat_id",
"=",
"None",
",",
"document",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
":",
"payload",
"=",
"dict",
"(",
"chat_id",
"=",
"chat_id",
",",
"reply_to_mess... | Use this method to send general files. On success, the sent Message is returned.
Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. | [
"Use",
"this",
"method",
"to",
"send",
"general",
"files",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
".",
"Bots",
"can",
"currently",
"send",
"files",
"of",
"any",
"type",
"of",
"up",
"to",
"50",
"MB",
"in",
"size",
"this",
"lim... | python | train |
google/tangent | tangent/utils.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/utils.py#L551-L574 | def register_shape_checker(left_type, right_type, shape_checker_function):
"""Register a new shape checking function supporting given types.
Shape checkers are primarily used to make sure that the seed derivatives
passed into generated autodiff functions match their corresponding
primal values.
Args:
le... | [
"def",
"register_shape_checker",
"(",
"left_type",
",",
"right_type",
",",
"shape_checker_function",
")",
":",
"key",
"=",
"(",
"left_type",
",",
"right_type",
")",
"if",
"key",
"in",
"shape_checkers",
":",
"raise",
"ValueError",
"(",
"'Types %s already mapped to %s... | Register a new shape checking function supporting given types.
Shape checkers are primarily used to make sure that the seed derivatives
passed into generated autodiff functions match their corresponding
primal values.
Args:
left_type: A Python type object. The data type of the left operand
supported... | [
"Register",
"a",
"new",
"shape",
"checking",
"function",
"supporting",
"given",
"types",
"."
] | python | train |
timothycrosley/short | short/compile.py | https://github.com/timothycrosley/short/blob/dcf25ec01b5406d9e0a35ac7dd8112239c0912a5/short/compile.py#L214-L243 | def get_indented_block(prefix_lines):
"""Returns an integer.
The return value is the number of lines that belong to block begun
on the first line.
Parameters
----------
prefix_lines : list of basestring pairs
Each pair corresponds to a line of SHPAML source code. The
first e... | [
"def",
"get_indented_block",
"(",
"prefix_lines",
")",
":",
"prefix",
",",
"line",
"=",
"prefix_lines",
"[",
"0",
"]",
"len_prefix",
"=",
"len",
"(",
"prefix",
")",
"# Find the first nonempty line with len(prefix) <= len(prefix)",
"i",
"=",
"1",
"while",
"i",
"<",... | Returns an integer.
The return value is the number of lines that belong to block begun
on the first line.
Parameters
----------
prefix_lines : list of basestring pairs
Each pair corresponds to a line of SHPAML source code. The
first element of each pair is indentation. The secon... | [
"Returns",
"an",
"integer",
"."
] | python | train |
estnltk/estnltk | estnltk/syntax/syntax_preprocessing.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/syntax/syntax_preprocessing.py#L156-L204 | def convert_Text_to_mrf( text ):
''' Converts from Text object into pre-syntactic mrf format, given as a list of
lines, as in the output of etmrf.
*) If the input Text has already been morphologically analysed, uses the existing
analysis;
*) If the input has not been analysed, p... | [
"def",
"convert_Text_to_mrf",
"(",
"text",
")",
":",
"from",
"estnltk",
".",
"text",
"import",
"Text",
"if",
"not",
"isinstance",
"(",
"text",
",",
"Text",
")",
":",
"raise",
"Exception",
"(",
"' Expected estnltk\\'s Text as an input argument! '",
")",
"if",
"no... | Converts from Text object into pre-syntactic mrf format, given as a list of
lines, as in the output of etmrf.
*) If the input Text has already been morphologically analysed, uses the existing
analysis;
*) If the input has not been analysed, performs the analysis with required settin... | [
"Converts",
"from",
"Text",
"object",
"into",
"pre",
"-",
"syntactic",
"mrf",
"format",
"given",
"as",
"a",
"list",
"of",
"lines",
"as",
"in",
"the",
"output",
"of",
"etmrf",
".",
"*",
")",
"If",
"the",
"input",
"Text",
"has",
"already",
"been",
"morph... | python | train |
mazulo/pynews_cli | pynews/utils.py | https://github.com/mazulo/pynews_cli/blob/88a6d70e18b9d8ea87ab7321a3d7ee78c4fa5ffb/pynews/utils.py#L56-L77 | def create_list_stories(
list_id_stories, number_of_stories, shuffle, max_threads
):
"""Show in a formatted way the stories for each item of the list."""
list_stories = []
with ThreadPoolExecutor(max_workers=max_threads) as executor:
futures = {
executor.submit(get_story, new)
... | [
"def",
"create_list_stories",
"(",
"list_id_stories",
",",
"number_of_stories",
",",
"shuffle",
",",
"max_threads",
")",
":",
"list_stories",
"=",
"[",
"]",
"with",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"max_threads",
")",
"as",
"executor",
":",
"futures"... | Show in a formatted way the stories for each item of the list. | [
"Show",
"in",
"a",
"formatted",
"way",
"the",
"stories",
"for",
"each",
"item",
"of",
"the",
"list",
"."
] | python | train |
tcalmant/ipopo | pelix/shell/report.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L293-L304 | def print_levels(self, session):
"""
Lists available levels
"""
lines = []
for level in sorted(self.get_levels()):
methods = sorted(
method.__name__ for method in self.get_level_methods(level)
)
lines.append("- {0}:".format(leve... | [
"def",
"print_levels",
"(",
"self",
",",
"session",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"level",
"in",
"sorted",
"(",
"self",
".",
"get_levels",
"(",
")",
")",
":",
"methods",
"=",
"sorted",
"(",
"method",
".",
"__name__",
"for",
"method",
"in",... | Lists available levels | [
"Lists",
"available",
"levels"
] | python | train |
cisco-sas/kitty | kitty/core/kitty_object.py | https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/core/kitty_object.py#L65-L76 | def set_verbosity(cls, verbosity):
'''
Set verbosity of logger
:param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG)
'''
if verbosity > 0:
# currently, we only toggle between INFO, DEBUG
logger = KittyObject.get_logger()
... | [
"def",
"set_verbosity",
"(",
"cls",
",",
"verbosity",
")",
":",
"if",
"verbosity",
">",
"0",
":",
"# currently, we only toggle between INFO, DEBUG",
"logger",
"=",
"KittyObject",
".",
"get_logger",
"(",
")",
"levels",
"=",
"[",
"logging",
".",
"DEBUG",
"]",
"v... | Set verbosity of logger
:param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG) | [
"Set",
"verbosity",
"of",
"logger"
] | python | train |
fabric-bolt/fabric-bolt | fabric_bolt/accounts/forms.py | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/accounts/forms.py#L90-L103 | def save(self, commit=True):
"""
Save the model instance with the correct Auth Group based on the user_level question
"""
instance = super(UserCreationForm, self).save(commit=commit)
random_password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32... | [
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"instance",
"=",
"super",
"(",
"UserCreationForm",
",",
"self",
")",
".",
"save",
"(",
"commit",
"=",
"commit",
")",
"random_password",
"=",
"''",
".",
"join",
"(",
"random",
".",
"cho... | Save the model instance with the correct Auth Group based on the user_level question | [
"Save",
"the",
"model",
"instance",
"with",
"the",
"correct",
"Auth",
"Group",
"based",
"on",
"the",
"user_level",
"question"
] | python | train |
glormph/msstitch | src/app/actions/headers/peptable.py | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/headers/peptable.py#L11-L20 | def switch_psm_to_peptable_fields(oldheader):
"""Returns a dict map with old to new header fields"""
return {old: new for old, new in zip([mzidtsvdata.HEADER_PEPTIDE,
mzidtsvdata.HEADER_PROTEIN,
mzidtsvdata.HEADER_PEPTIDE_Q,
... | [
"def",
"switch_psm_to_peptable_fields",
"(",
"oldheader",
")",
":",
"return",
"{",
"old",
":",
"new",
"for",
"old",
",",
"new",
"in",
"zip",
"(",
"[",
"mzidtsvdata",
".",
"HEADER_PEPTIDE",
",",
"mzidtsvdata",
".",
"HEADER_PROTEIN",
",",
"mzidtsvdata",
".",
"... | Returns a dict map with old to new header fields | [
"Returns",
"a",
"dict",
"map",
"with",
"old",
"to",
"new",
"header",
"fields"
] | python | train |
jrabbit/hitman | hitman.py | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L348-L362 | def directory():
"""Construct hitman_dir from os name"""
home = os.path.expanduser('~')
if platform.system() == 'Linux':
hitman_dir = os.path.join(home, '.hitman')
elif platform.system() == 'Darwin':
hitman_dir = os.path.join(home, 'Library', 'Application Support',
... | [
"def",
"directory",
"(",
")",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Linux'",
":",
"hitman_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'.hitman'"... | Construct hitman_dir from os name | [
"Construct",
"hitman_dir",
"from",
"os",
"name"
] | python | train |
stlehmann/pyads | pyads/pyads_ex.py | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L263-L293 | def adsSyncReadDeviceInfoReqEx(port, address):
# type: (int, AmsAddr) -> Tuple[str, AdsVersion]
"""Read the name and the version number of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: string, Ads... | [
"def",
"adsSyncReadDeviceInfoReqEx",
"(",
"port",
",",
"address",
")",
":",
"# type: (int, AmsAddr) -> Tuple[str, AdsVersion]",
"sync_read_device_info_request",
"=",
"_adsDLL",
".",
"AdsSyncReadDeviceInfoReqEx",
"# Get pointer to the target AMS address",
"ams_address_pointer",
"=",
... | Read the name and the version number of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: string, AdsVersion
:return: device name, version | [
"Read",
"the",
"name",
"and",
"the",
"version",
"number",
"of",
"the",
"ADS",
"-",
"server",
"."
] | python | valid |
spdx/tools-python | spdx/parsers/rdf.py | https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L715-L726 | def get_review_date(self, r_term):
"""Returns review date or None if not found.
Reports error on failure.
Note does not check value format.
"""
reviewed_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewDate'], None)))
if len(reviewed_list) != 1:
... | [
"def",
"get_review_date",
"(",
"self",
",",
"r_term",
")",
":",
"reviewed_list",
"=",
"list",
"(",
"self",
".",
"graph",
".",
"triples",
"(",
"(",
"r_term",
",",
"self",
".",
"spdx_namespace",
"[",
"'reviewDate'",
"]",
",",
"None",
")",
")",
")",
"if",... | Returns review date or None if not found.
Reports error on failure.
Note does not check value format. | [
"Returns",
"review",
"date",
"or",
"None",
"if",
"not",
"found",
".",
"Reports",
"error",
"on",
"failure",
".",
"Note",
"does",
"not",
"check",
"value",
"format",
"."
] | python | valid |
epio/mantrid | mantrid/socketmeld.py | https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/socketmeld.py#L16-L33 | def piper(self, in_sock, out_sock, out_addr, onkill):
"Worker thread for data reading"
try:
while True:
written = in_sock.recv(32768)
if not written:
try:
out_sock.shutdown(socket.SHUT_WR)
except ... | [
"def",
"piper",
"(",
"self",
",",
"in_sock",
",",
"out_sock",
",",
"out_addr",
",",
"onkill",
")",
":",
"try",
":",
"while",
"True",
":",
"written",
"=",
"in_sock",
".",
"recv",
"(",
"32768",
")",
"if",
"not",
"written",
":",
"try",
":",
"out_sock",
... | Worker thread for data reading | [
"Worker",
"thread",
"for",
"data",
"reading"
] | python | train |
mitsei/dlkit | dlkit/services/osid.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/osid.py#L295-L311 | def _get_agent_key(self, proxy=None):
"""Gets an agent key for session management.
Side effect of setting a new proxy if one is sent along,
and initializing the provider session map if agent key has
not been seen before
"""
if self._proxy is None:
self._prox... | [
"def",
"_get_agent_key",
"(",
"self",
",",
"proxy",
"=",
"None",
")",
":",
"if",
"self",
".",
"_proxy",
"is",
"None",
":",
"self",
".",
"_proxy",
"=",
"proxy",
"if",
"self",
".",
"_proxy",
"is",
"not",
"None",
"and",
"self",
".",
"_proxy",
".",
"ha... | Gets an agent key for session management.
Side effect of setting a new proxy if one is sent along,
and initializing the provider session map if agent key has
not been seen before | [
"Gets",
"an",
"agent",
"key",
"for",
"session",
"management",
"."
] | python | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L438-L461 | async def receive_updates(self, request: Request):
"""
Handle updates from Telegram
"""
body = await request.read()
try:
content = ujson.loads(body)
except ValueError:
return json_response({
'error': True,
'message... | [
"async",
"def",
"receive_updates",
"(",
"self",
",",
"request",
":",
"Request",
")",
":",
"body",
"=",
"await",
"request",
".",
"read",
"(",
")",
"try",
":",
"content",
"=",
"ujson",
".",
"loads",
"(",
"body",
")",
"except",
"ValueError",
":",
"return"... | Handle updates from Telegram | [
"Handle",
"updates",
"from",
"Telegram"
] | python | train |
mitsei/dlkit | dlkit/json_/assessment/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/sessions.py#L6029-L6070 | def update_assessment_offered(self, assessment_offered_form):
"""Updates an existing assessment offered.
arg: assessment_offered_form
(osid.assessment.AssessmentOfferedForm): the form
containing the elements to be updated
raise: IllegalState - ``assessment_of... | [
"def",
"update_assessment_offered",
"(",
"self",
",",
"assessment_offered_form",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.update_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'assessment'",
",",
"collection",
"=",
"'... | Updates an existing assessment offered.
arg: assessment_offered_form
(osid.assessment.AssessmentOfferedForm): the form
containing the elements to be updated
raise: IllegalState - ``assessment_offrered_form`` already used
in an update transaction
... | [
"Updates",
"an",
"existing",
"assessment",
"offered",
"."
] | python | train |
cs50/check50 | check50/api.py | https://github.com/cs50/check50/blob/42c1f0c36baa6a24f69742d74551a9ea7a5ceb33/check50/api.py#L89-L104 | def exists(*paths):
"""
Assert that all given paths exist.
:params paths: files/directories to be checked for existence
:raises check50.Failure: if any ``path in paths`` does not exist
Example usage::
check50.exists("foo.c", "foo.h")
"""
for path in paths:
log(_("checking... | [
"def",
"exists",
"(",
"*",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"log",
"(",
"_",
"(",
"\"checking that {} exists...\"",
")",
".",
"format",
"(",
"path",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":"... | Assert that all given paths exist.
:params paths: files/directories to be checked for existence
:raises check50.Failure: if any ``path in paths`` does not exist
Example usage::
check50.exists("foo.c", "foo.h") | [
"Assert",
"that",
"all",
"given",
"paths",
"exist",
"."
] | python | train |
brainiak/brainiak | brainiak/factoranalysis/htfa.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/factoranalysis/htfa.py#L422-L453 | def _get_subject_info(self, n_local_subj, data):
"""Calculate metadata for subjects allocated to this process
Parameters
----------
n_local_subj : int
Number of subjects allocated to this process.
data : list of 2D array. Each in shape [n_voxel, n_tr]
T... | [
"def",
"_get_subject_info",
"(",
"self",
",",
"n_local_subj",
",",
"data",
")",
":",
"max_sample_tr",
"=",
"np",
".",
"zeros",
"(",
"n_local_subj",
")",
".",
"astype",
"(",
"int",
")",
"max_sample_voxel",
"=",
"np",
".",
"zeros",
"(",
"n_local_subj",
")",
... | Calculate metadata for subjects allocated to this process
Parameters
----------
n_local_subj : int
Number of subjects allocated to this process.
data : list of 2D array. Each in shape [n_voxel, n_tr]
Total number of MPI process.
Returns
-------... | [
"Calculate",
"metadata",
"for",
"subjects",
"allocated",
"to",
"this",
"process"
] | python | train |
gbowerman/azurerm | azurerm/amsrp.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/amsrp.py#L578-L597 | def create_asset_accesspolicy(access_token, name, duration, permission="1"):
'''Create Media Service Asset Access Policy.
Args:
access_token (str): A valid Azure authentication token.
name (str): A Media Service Asset Access Policy Name.
duration (str): A Media Service duration.
... | [
"def",
"create_asset_accesspolicy",
"(",
"access_token",
",",
"name",
",",
"duration",
",",
"permission",
"=",
"\"1\"",
")",
":",
"path",
"=",
"'/AccessPolicies'",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"ams_rest_endpoint",
",",
"path",
"]",
")",
"bod... | Create Media Service Asset Access Policy.
Args:
access_token (str): A valid Azure authentication token.
name (str): A Media Service Asset Access Policy Name.
duration (str): A Media Service duration.
permission (str): A Media Service permission.
Returns:
HTTP response. ... | [
"Create",
"Media",
"Service",
"Asset",
"Access",
"Policy",
"."
] | python | train |
closeio/redis-hashring | redis_hashring/__init__.py | https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L135-L194 | def debug_print(self):
"""
Prints the ring for debugging purposes.
"""
ring = self._fetch_all()
print('Hash ring "{key}" replicas:'.format(key=self.key))
now = time.time()
n_replicas = len(ring)
if ring:
print('{:10} {:6} {:7} {}'.format('St... | [
"def",
"debug_print",
"(",
"self",
")",
":",
"ring",
"=",
"self",
".",
"_fetch_all",
"(",
")",
"print",
"(",
"'Hash ring \"{key}\" replicas:'",
".",
"format",
"(",
"key",
"=",
"self",
".",
"key",
")",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"... | Prints the ring for debugging purposes. | [
"Prints",
"the",
"ring",
"for",
"debugging",
"purposes",
"."
] | python | train |
mingchen/django-cas-ng | django_cas_ng/utils.py | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/utils.py#L43-L61 | def get_service_url(request, redirect_to=None):
"""Generates application django service URL for CAS"""
if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
service = django_settings.CAS_ROOT_PROXIED_AS + request.path
else:
protocol = get_protocol(request)
host = request.get_host()
... | [
"def",
"get_service_url",
"(",
"request",
",",
"redirect_to",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"django_settings",
",",
"'CAS_ROOT_PROXIED_AS'",
")",
":",
"service",
"=",
"django_settings",
".",
"CAS_ROOT_PROXIED_AS",
"+",
"request",
".",
"path",
"els... | Generates application django service URL for CAS | [
"Generates",
"application",
"django",
"service",
"URL",
"for",
"CAS"
] | python | train |
PyThaiNLP/pythainlp | pythainlp/transliterate/__init__.py | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/transliterate/__init__.py#L26-L42 | def transliterate(text: str, engine: str = "ipa") -> str:
"""
Transliteration of Thai text
:param str text: Thai text to be transliterated
:param str engine: 'ipa' (International Phonetic Alphabet; default) or 'icu'.
:return: A string of Internaitonal Phonetic Alphabets indicating how the text shoul... | [
"def",
"transliterate",
"(",
"text",
":",
"str",
",",
"engine",
":",
"str",
"=",
"\"ipa\"",
")",
"->",
"str",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"\"\"",
"if",
"engine",
"==",
"\"icu\"",
... | Transliteration of Thai text
:param str text: Thai text to be transliterated
:param str engine: 'ipa' (International Phonetic Alphabet; default) or 'icu'.
:return: A string of Internaitonal Phonetic Alphabets indicating how the text should be pronounced. | [
"Transliteration",
"of",
"Thai",
"text",
":",
"param",
"str",
"text",
":",
"Thai",
"text",
"to",
"be",
"transliterated",
":",
"param",
"str",
"engine",
":",
"ipa",
"(",
"International",
"Phonetic",
"Alphabet",
";",
"default",
")",
"or",
"icu",
".",
":",
... | python | train |
user-cont/colin | colin/core/colin.py | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L26-L78 | def run(
target,
target_type,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
pull=None,
insecure=False,
skips=None,
timeout=None,
):
"""
Runs the sanity checks for the target.
:param timeout: t... | [
"def",
"run",
"(",
"target",
",",
"target_type",
",",
"tags",
"=",
"None",
",",
"ruleset_name",
"=",
"None",
",",
"ruleset_file",
"=",
"None",
",",
"ruleset",
"=",
"None",
",",
"logging_level",
"=",
"logging",
".",
"WARNING",
",",
"checks_paths",
"=",
"N... | Runs the sanity checks for the target.
:param timeout: timeout per-check (in seconds)
:param skips: name of checks to skip
:param target: str (image name, ostree or dockertar)
or ImageTarget
or path/file-like object for dockerfile
:param target_type: string, eith... | [
"Runs",
"the",
"sanity",
"checks",
"for",
"the",
"target",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/srna/group.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/group.py#L167-L173 | def _guess_header(info):
"""Add the first group to get report with some factor"""
value = "group"
if "metadata" in info:
if info["metadata"]:
return ",".join(map(str, info["metadata"].keys()))
return value | [
"def",
"_guess_header",
"(",
"info",
")",
":",
"value",
"=",
"\"group\"",
"if",
"\"metadata\"",
"in",
"info",
":",
"if",
"info",
"[",
"\"metadata\"",
"]",
":",
"return",
"\",\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"info",
"[",
"\"metadata\"",
"]... | Add the first group to get report with some factor | [
"Add",
"the",
"first",
"group",
"to",
"get",
"report",
"with",
"some",
"factor"
] | python | train |
DataBiosphere/toil | attic/absolute_imports.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/attic/absolute_imports.py#L9-L93 | def enable_absolute_imports(script, script_name):
"""
Empty modules
>>> enable_absolute_imports('')
'from __future__ import absolute_import\\n'
Ignore empty lines
>>> enable_absolute_imports('\\n')
'from __future__ import absolute_import\\n'
Append after initial comments, like shebangs... | [
"def",
"enable_absolute_imports",
"(",
"script",
",",
"script_name",
")",
":",
"tree",
"=",
"ast",
".",
"parse",
"(",
"script",
",",
"filename",
"=",
"script_name",
")",
"lines",
"=",
"script",
".",
"split",
"(",
"'\\n'",
")",
"while",
"lines",
"and",
"l... | Empty modules
>>> enable_absolute_imports('')
'from __future__ import absolute_import\\n'
Ignore empty lines
>>> enable_absolute_imports('\\n')
'from __future__ import absolute_import\\n'
Append after initial comments, like shebangs
>>> enable_absolute_imports('#foo\\n')
'#foo\\nfrom _... | [
"Empty",
"modules",
">>>",
"enable_absolute_imports",
"(",
")",
"from",
"__future__",
"import",
"absolute_import",
"\\\\",
"n"
] | python | train |
django-fluent/fluentcms-googlemaps | fluentcms_googlemaps/views.py | https://github.com/django-fluent/fluentcms-googlemaps/blob/e4034b0f1c9896ce355628ed8e0c3532c08214d1/fluentcms_googlemaps/views.py#L24-L43 | def get_object(self, queryset=None):
"""
Returns the object the view is displaying.
"""
if queryset is None:
queryset = self.get_queryset()
# Take a GET parameter instead of URLConf variable.
try:
pk = long(self.request.GET[self.pk_url_kwarg])
... | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"if",
"queryset",
"is",
"None",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"# Take a GET parameter instead of URLConf variable.",
"try",
":",
"pk",
"=",
"long",
"(",
... | Returns the object the view is displaying. | [
"Returns",
"the",
"object",
"the",
"view",
"is",
"displaying",
"."
] | python | train |
numba/llvmlite | llvmlite/binding/executionengine.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L146-L154 | def add_object_file(self, obj_file):
"""
Add object file to the jit. object_file can be instance of
:class:ObjectFile or a string representing file system path
"""
if isinstance(obj_file, str):
obj_file = object_file.ObjectFileRef.from_path(obj_file)
ffi.lib.... | [
"def",
"add_object_file",
"(",
"self",
",",
"obj_file",
")",
":",
"if",
"isinstance",
"(",
"obj_file",
",",
"str",
")",
":",
"obj_file",
"=",
"object_file",
".",
"ObjectFileRef",
".",
"from_path",
"(",
"obj_file",
")",
"ffi",
".",
"lib",
".",
"LLVMPY_MCJIT... | Add object file to the jit. object_file can be instance of
:class:ObjectFile or a string representing file system path | [
"Add",
"object",
"file",
"to",
"the",
"jit",
".",
"object_file",
"can",
"be",
"instance",
"of",
":",
"class",
":",
"ObjectFile",
"or",
"a",
"string",
"representing",
"file",
"system",
"path"
] | python | train |
marshmallow-code/webargs | src/webargs/aiohttpparser.py | https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/aiohttpparser.py#L112-L114 | def parse_cookies(self, req: Request, name: str, field: Field) -> typing.Any:
"""Pull a value from the cookiejar."""
return core.get_value(req.cookies, name, field) | [
"def",
"parse_cookies",
"(",
"self",
",",
"req",
":",
"Request",
",",
"name",
":",
"str",
",",
"field",
":",
"Field",
")",
"->",
"typing",
".",
"Any",
":",
"return",
"core",
".",
"get_value",
"(",
"req",
".",
"cookies",
",",
"name",
",",
"field",
"... | Pull a value from the cookiejar. | [
"Pull",
"a",
"value",
"from",
"the",
"cookiejar",
"."
] | python | train |
codelv/enaml-native | src/enamlnative/ios/uikit_edit_text.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/uikit_edit_text.py#L106-L110 | def on_value_changed(self, text):
""" Update text field """
d = self.declaration
with self.widget.get_member('text').suppressed(self.widget):
d.text = text | [
"def",
"on_value_changed",
"(",
"self",
",",
"text",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"with",
"self",
".",
"widget",
".",
"get_member",
"(",
"'text'",
")",
".",
"suppressed",
"(",
"self",
".",
"widget",
")",
":",
"d",
".",
"text",
"=",... | Update text field | [
"Update",
"text",
"field"
] | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/brocade_vswitch_rpc/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/brocade_vswitch_rpc/__init__.py#L331-L354 | def _set_get_vmpolicy_macaddr(self, v, load=False):
"""
Setter method for get_vmpolicy_macaddr, mapped from YANG variable /brocade_vswitch_rpc/get_vmpolicy_macaddr (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vmpolicy_macaddr is considered as a private
m... | [
"def",
"_set_get_vmpolicy_macaddr",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
"... | Setter method for get_vmpolicy_macaddr, mapped from YANG variable /brocade_vswitch_rpc/get_vmpolicy_macaddr (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vmpolicy_macaddr is considered as a private
method. Backends looking to populate this variable should
do ... | [
"Setter",
"method",
"for",
"get_vmpolicy_macaddr",
"mapped",
"from",
"YANG",
"variable",
"/",
"brocade_vswitch_rpc",
"/",
"get_vmpolicy_macaddr",
"(",
"rpc",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the... | python | train |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/drivers/dokan/solrclient.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/drivers/dokan/solrclient.py#L441-L453 | def get(self, id):
"""Retrieves the specified document."""
params = {'q': 'id:%s' % str(id), 'wt': 'python'}
request = urllib.parse.urlencode(params, doseq=True)
data = None
try:
rsp = self.doPost(self.solrBase + '', request, self.formheaders)
data = eval(... | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"params",
"=",
"{",
"'q'",
":",
"'id:%s'",
"%",
"str",
"(",
"id",
")",
",",
"'wt'",
":",
"'python'",
"}",
"request",
"=",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"params",
",",
"doseq",
"=",
... | Retrieves the specified document. | [
"Retrieves",
"the",
"specified",
"document",
"."
] | python | train |
gccxml/pygccxml | pygccxml/declarations/templates.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/templates.py#L127-L140 | def normalize_full_name_false(decl):
"""
Cached variant of normalize
Args:
decl (declaration.declaration_t): the declaration
Returns:
str: normalized name
"""
if decl.cache.normalized_full_name_false is None:
decl.cache.normalized_full_name_false = normalize(
... | [
"def",
"normalize_full_name_false",
"(",
"decl",
")",
":",
"if",
"decl",
".",
"cache",
".",
"normalized_full_name_false",
"is",
"None",
":",
"decl",
".",
"cache",
".",
"normalized_full_name_false",
"=",
"normalize",
"(",
"declaration_utils",
".",
"full_name",
"(",... | Cached variant of normalize
Args:
decl (declaration.declaration_t): the declaration
Returns:
str: normalized name | [
"Cached",
"variant",
"of",
"normalize"
] | python | train |
applegrew/django-select2 | django_select2/forms.py | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L89-L93 | def optgroups(self, name, value, attrs=None):
"""Add empty option for clearable selects."""
if not self.is_required and not self.allow_multiple_selected:
self.choices = list(chain([('', '')], self.choices))
return super(Select2Mixin, self).optgroups(name, value, attrs=attrs) | [
"def",
"optgroups",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_required",
"and",
"not",
"self",
".",
"allow_multiple_selected",
":",
"self",
".",
"choices",
"=",
"list",
"(",
"chain",
"(",... | Add empty option for clearable selects. | [
"Add",
"empty",
"option",
"for",
"clearable",
"selects",
"."
] | python | train |
saltstack/salt | salt/modules/cron.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L411-L438 | def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with ident... | [
"def",
"get_entry",
"(",
"user",
",",
"identifier",
"=",
"None",
",",
"cmd",
"=",
"None",
")",
":",
"cron_entries",
"=",
"list_tab",
"(",
"user",
")",
".",
"get",
"(",
"'crons'",
",",
"False",
")",
"for",
"cron_entry",
"in",
"cron_entries",
":",
"if",
... | Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
C... | [
"Return",
"the",
"specified",
"entry",
"from",
"user",
"s",
"crontab",
".",
"identifier",
"will",
"be",
"used",
"if",
"specified",
"otherwise",
"will",
"lookup",
"cmd",
"Either",
"identifier",
"or",
"cmd",
"should",
"be",
"specified",
"."
] | python | train |
dev-pipeline/dev-pipeline-core | lib/devpipeline_core/toolsupport.py | https://github.com/dev-pipeline/dev-pipeline-core/blob/fa40c050a56202485070b0300bb8695e9388c34f/lib/devpipeline_core/toolsupport.py#L115-L142 | def args_builder(prefix, current_target, args_dict, value_found_fn):
"""
Process arguments a tool cares about.
Since most tools require configuration, this function helps deal with the
boilerplate. Each option will be processed based on all modifications
supported by dev-pipeline (i.e., profiles a... | [
"def",
"args_builder",
"(",
"prefix",
",",
"current_target",
",",
"args_dict",
",",
"value_found_fn",
")",
":",
"current_config",
"=",
"current_target",
".",
"config",
"for",
"key",
",",
"separator",
"in",
"args_dict",
".",
"items",
"(",
")",
":",
"option",
... | Process arguments a tool cares about.
Since most tools require configuration, this function helps deal with the
boilerplate. Each option will be processed based on all modifications
supported by dev-pipeline (i.e., profiles and overrides) in the proper
order.
Arguments:
prefix -- The prefix f... | [
"Process",
"arguments",
"a",
"tool",
"cares",
"about",
"."
] | python | train |
chrisnorman7/confmanager | confmanager/parser.py | https://github.com/chrisnorman7/confmanager/blob/54a3ce0b596f9da32ae82fd4ff4cb46bb1cf23b1/confmanager/parser.py#L6-L20 | def parse_template(template, target):
"""Given a dictionary template containing at least most of the relevant information and a dictionary target containing sections, options and values, consolidate target into a new confmanager object and return it."""
c = ConfManager('')
for section in template:
c.add_sectio... | [
"def",
"parse_template",
"(",
"template",
",",
"target",
")",
":",
"c",
"=",
"ConfManager",
"(",
"''",
")",
"for",
"section",
"in",
"template",
":",
"c",
".",
"add_section",
"(",
"section",
")",
"for",
"option",
",",
"o",
"in",
"template",
"[",
"sectio... | Given a dictionary template containing at least most of the relevant information and a dictionary target containing sections, options and values, consolidate target into a new confmanager object and return it. | [
"Given",
"a",
"dictionary",
"template",
"containing",
"at",
"least",
"most",
"of",
"the",
"relevant",
"information",
"and",
"a",
"dictionary",
"target",
"containing",
"sections",
"options",
"and",
"values",
"consolidate",
"target",
"into",
"a",
"new",
"confmanager... | python | train |
happyleavesaoc/gstreamer-player | gsp/__init__.py | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L153-L157 | def set_volume(self, volume):
"""Set volume."""
self._player.set_property(PROP_VOLUME, volume)
self._manager[ATTR_VOLUME] = volume
_LOGGER.info('volume set to %.2f', volume) | [
"def",
"set_volume",
"(",
"self",
",",
"volume",
")",
":",
"self",
".",
"_player",
".",
"set_property",
"(",
"PROP_VOLUME",
",",
"volume",
")",
"self",
".",
"_manager",
"[",
"ATTR_VOLUME",
"]",
"=",
"volume",
"_LOGGER",
".",
"info",
"(",
"'volume set to %.... | Set volume. | [
"Set",
"volume",
"."
] | python | train |
mithro/python-datetime-tz | datetime_tz/__init__.py | https://github.com/mithro/python-datetime-tz/blob/3c682d003f8b28e39f0c096773e471aeb68e6bbb/datetime_tz/__init__.py#L813-L824 | def hours(start, end=None):
"""Iterate over the hours between the given datetime_tzs.
Args:
start: datetime_tz to start from.
end: (Optional) Date to end at, if not given the iterator will never
terminate.
Returns:
An iterator which generates datetime_tz objects a hour apart.
... | [
"def",
"hours",
"(",
"start",
",",
"end",
"=",
"None",
")",
":",
"return",
"iterate",
".",
"between",
"(",
"start",
",",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"1",
")",
",",
"end",
")"
] | Iterate over the hours between the given datetime_tzs.
Args:
start: datetime_tz to start from.
end: (Optional) Date to end at, if not given the iterator will never
terminate.
Returns:
An iterator which generates datetime_tz objects a hour apart. | [
"Iterate",
"over",
"the",
"hours",
"between",
"the",
"given",
"datetime_tzs",
"."
] | python | train |
h2oai/h2o-3 | scripts/run.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/scripts/run.py#L645-L651 | def get_port(self):
""" Return a port to use to talk to this cluster. """
if len(self.client_nodes) > 0:
node = self.client_nodes[0]
else:
node = self.nodes[0]
return node.get_port() | [
"def",
"get_port",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"client_nodes",
")",
">",
"0",
":",
"node",
"=",
"self",
".",
"client_nodes",
"[",
"0",
"]",
"else",
":",
"node",
"=",
"self",
".",
"nodes",
"[",
"0",
"]",
"return",
"node",... | Return a port to use to talk to this cluster. | [
"Return",
"a",
"port",
"to",
"use",
"to",
"talk",
"to",
"this",
"cluster",
"."
] | python | test |
confluentinc/confluent-kafka-python | examples/adminapi.py | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/adminapi.py#L235-L274 | def example_list(a, args):
""" list topics and cluster metadata """
if len(args) == 0:
what = "all"
else:
what = args[0]
md = a.list_topics(timeout=10)
print("Cluster {} metadata (response from broker {}):".format(md.cluster_id, md.orig_broker_name))
if what in ("all", "broke... | [
"def",
"example_list",
"(",
"a",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"what",
"=",
"\"all\"",
"else",
":",
"what",
"=",
"args",
"[",
"0",
"]",
"md",
"=",
"a",
".",
"list_topics",
"(",
"timeout",
"=",
"10",
")",
... | list topics and cluster metadata | [
"list",
"topics",
"and",
"cluster",
"metadata"
] | python | train |
ssato/python-anyconfig | src/anyconfig/cli.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L74-L89 | def to_log_level(level):
"""
:param level: Logging level in int = 0 .. 2
>>> to_log_level(0) == logging.WARN
True
>>> to_log_level(5) # doctest: +IGNORE_EXCEPTION_DETAIL, +ELLIPSIS
Traceback (most recent call last):
...
ValueError: wrong log level passed: 5
>>>
"""
if l... | [
"def",
"to_log_level",
"(",
"level",
")",
":",
"if",
"level",
"<",
"0",
"or",
"level",
">=",
"3",
":",
"raise",
"ValueError",
"(",
"\"wrong log level passed: \"",
"+",
"str",
"(",
"level",
")",
")",
"return",
"[",
"logging",
".",
"WARN",
",",
"logging",
... | :param level: Logging level in int = 0 .. 2
>>> to_log_level(0) == logging.WARN
True
>>> to_log_level(5) # doctest: +IGNORE_EXCEPTION_DETAIL, +ELLIPSIS
Traceback (most recent call last):
...
ValueError: wrong log level passed: 5
>>> | [
":",
"param",
"level",
":",
"Logging",
"level",
"in",
"int",
"=",
"0",
"..",
"2"
] | python | train |
tornadoweb/tornado | tornado/websocket.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L429-L448 | def ping(self, data: Union[str, bytes] = b"") -> None:
"""Send ping frame to the remote end.
The data argument allows a small amount of data (up to 125
bytes) to be sent as a part of the ping message. Note that not
all websocket implementations expose this data to
applications.
... | [
"def",
"ping",
"(",
"self",
",",
"data",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
"=",
"b\"\"",
")",
"->",
"None",
":",
"data",
"=",
"utf8",
"(",
"data",
")",
"if",
"self",
".",
"ws_connection",
"is",
"None",
"or",
"self",
".",
"ws_connection",... | Send ping frame to the remote end.
The data argument allows a small amount of data (up to 125
bytes) to be sent as a part of the ping message. Note that not
all websocket implementations expose this data to
applications.
Consider using the ``websocket_ping_interval`` applicatio... | [
"Send",
"ping",
"frame",
"to",
"the",
"remote",
"end",
"."
] | python | train |
emlazzarin/acrylic | acrylic/datatable.py | https://github.com/emlazzarin/acrylic/blob/08c6702d73b9660ead1024653f4fa016f6340e46/acrylic/datatable.py#L856-L873 | def writexlsx(self, path, sheetname="default"):
"""
Writes this table to an .xlsx file at the specified path.
If you'd like to specify a sheetname, you may do so.
If you'd like to write one workbook with different DataTables
for each sheet, import the `excel` function from acry... | [
"def",
"writexlsx",
"(",
"self",
",",
"path",
",",
"sheetname",
"=",
"\"default\"",
")",
":",
"writer",
"=",
"ExcelRW",
".",
"UnicodeWriter",
"(",
"path",
")",
"writer",
".",
"set_active_sheet",
"(",
"sheetname",
")",
"writer",
".",
"writerow",
"(",
"self"... | Writes this table to an .xlsx file at the specified path.
If you'd like to specify a sheetname, you may do so.
If you'd like to write one workbook with different DataTables
for each sheet, import the `excel` function from acrylic. You
can see that code in `utils.py`.
Note that... | [
"Writes",
"this",
"table",
"to",
"an",
".",
"xlsx",
"file",
"at",
"the",
"specified",
"path",
"."
] | python | train |
ssalentin/plip | plip/modules/pymolplip.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L305-L311 | def additional_cleanup(self):
"""Cleanup of various representations"""
cmd.remove('not alt ""+A') # Remove alternate conformations
cmd.hide('labels', 'Interactions') # Hide labels of lines
cmd.disable('%sCartoon' % self.protname)
cmd.hide('everything', 'hydrogens') | [
"def",
"additional_cleanup",
"(",
"self",
")",
":",
"cmd",
".",
"remove",
"(",
"'not alt \"\"+A'",
")",
"# Remove alternate conformations",
"cmd",
".",
"hide",
"(",
"'labels'",
",",
"'Interactions'",
")",
"# Hide labels of lines",
"cmd",
".",
"disable",
"(",
"'%sC... | Cleanup of various representations | [
"Cleanup",
"of",
"various",
"representations"
] | python | train |
invinst/ResponseBot | responsebot/responsebot_client.py | https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L125-L138 | def remove_tweet(self, id):
"""
Delete a tweet.
:param id: ID of the tweet in question
:return: True if success, False otherwise
"""
try:
self._client.destroy_status(id=id)
return True
except TweepError as e:
if e.api_code in [... | [
"def",
"remove_tweet",
"(",
"self",
",",
"id",
")",
":",
"try",
":",
"self",
".",
"_client",
".",
"destroy_status",
"(",
"id",
"=",
"id",
")",
"return",
"True",
"except",
"TweepError",
"as",
"e",
":",
"if",
"e",
".",
"api_code",
"in",
"[",
"TWITTER_P... | Delete a tweet.
:param id: ID of the tweet in question
:return: True if success, False otherwise | [
"Delete",
"a",
"tweet",
"."
] | python | train |
googleapis/oauth2client | oauth2client/_helpers.py | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L230-L246 | def _add_query_parameter(url, name, value):
"""Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
... | [
"def",
"_add_query_parameter",
"(",
"url",
",",
"name",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"url",
"else",
":",
"return",
"update_query_params",
"(",
"url",
",",
"{",
"name",
":",
"value",
"}",
")"
] | Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
Updated query parameter. Does not update th... | [
"Adds",
"a",
"query",
"parameter",
"to",
"a",
"url",
"."
] | python | valid |
eventbrite/pysoa | pysoa/server/standalone.py | https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/standalone.py#L146-L199 | def django_main(server_getter):
"""
Call this within `__main__` to start the service as a standalone server with Django support. Your server should have
`use_django=True`. If it does not, see `simple_main`, instead.
:param server_getter: A callable that returns the service's `Server` class (not an inst... | [
"def",
"django_main",
"(",
"server_getter",
")",
":",
"import",
"os",
"# noinspection PyUnresolvedReferences,PyPackageRequirements",
"import",
"django",
"parser",
"=",
"_get_arg_parser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--settings'",
",",
"... | Call this within `__main__` to start the service as a standalone server with Django support. Your server should have
`use_django=True`. If it does not, see `simple_main`, instead.
:param server_getter: A callable that returns the service's `Server` class (not an instance of it). Your service
... | [
"Call",
"this",
"within",
"__main__",
"to",
"start",
"the",
"service",
"as",
"a",
"standalone",
"server",
"with",
"Django",
"support",
".",
"Your",
"server",
"should",
"have",
"use_django",
"=",
"True",
".",
"If",
"it",
"does",
"not",
"see",
"simple_main",
... | python | train |
O365/python-o365 | O365/planner.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/planner.py#L112-L129 | def get_my_tasks(self, *args):
""" Returns a list of open planner tasks assigned to me
:rtype: tasks
"""
url = self.build_url(self._endpoints.get('get_my_tasks'))
response = self.con.get(url)
if not response:
return None
data = response.json()
... | [
"def",
"get_my_tasks",
"(",
"self",
",",
"*",
"args",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_my_tasks'",
")",
")",
"response",
"=",
"self",
".",
"con",
".",
"get",
"(",
"url",
")",
"if... | Returns a list of open planner tasks assigned to me
:rtype: tasks | [
"Returns",
"a",
"list",
"of",
"open",
"planner",
"tasks",
"assigned",
"to",
"me"
] | python | train |
blockstack/blockstack-core | blockstack/lib/scripts.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L99-L122 | def is_namespace_valid( namespace_id ):
"""
Is a namespace ID valid?
>>> is_namespace_valid('abcd')
True
>>> is_namespace_valid('+abcd')
False
>>> is_namespace_valid('abc.def')
False
>>> is_namespace_valid('.abcd')
False
>>> is_namespace_valid('abcdabcdabcdabcdabcd')
Fal... | [
"def",
"is_namespace_valid",
"(",
"namespace_id",
")",
":",
"if",
"not",
"is_b40",
"(",
"namespace_id",
")",
"or",
"\"+\"",
"in",
"namespace_id",
"or",
"namespace_id",
".",
"count",
"(",
"\".\"",
")",
">",
"0",
":",
"return",
"False",
"if",
"len",
"(",
"... | Is a namespace ID valid?
>>> is_namespace_valid('abcd')
True
>>> is_namespace_valid('+abcd')
False
>>> is_namespace_valid('abc.def')
False
>>> is_namespace_valid('.abcd')
False
>>> is_namespace_valid('abcdabcdabcdabcdabcd')
False
>>> is_namespace_valid('abcdabcdabcdabcdabc')... | [
"Is",
"a",
"namespace",
"ID",
"valid?"
] | python | train |
F5Networks/f5-common-python | f5/bigip/mixins.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L237-L241 | def exec_cmd(self, command, **kwargs):
"""Wrapper method that can be changed in the inheriting classes."""
self._is_allowed_command(command)
self._check_command_parameters(**kwargs)
return self._exec_cmd(command, **kwargs) | [
"def",
"exec_cmd",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_allowed_command",
"(",
"command",
")",
"self",
".",
"_check_command_parameters",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_exec_cmd",
"(",
"... | Wrapper method that can be changed in the inheriting classes. | [
"Wrapper",
"method",
"that",
"can",
"be",
"changed",
"in",
"the",
"inheriting",
"classes",
"."
] | python | train |
tanghaibao/jcvi | jcvi/assembly/ca.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/ca.py#L258-L336 | def overlap(args):
"""
%prog overlap best.contains iid
Visualize overlaps for a given fragment. Must be run in 4-unitigger. All
overlaps for iid were retrieved, excluding the ones matching best.contains.
"""
from jcvi.apps.console import green
p = OptionParser(overlap.__doc__)
p.add_op... | [
"def",
"overlap",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"console",
"import",
"green",
"p",
"=",
"OptionParser",
"(",
"overlap",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--maxerr\"",
",",
"default",
"=",
"2",
",",
"type",
... | %prog overlap best.contains iid
Visualize overlaps for a given fragment. Must be run in 4-unitigger. All
overlaps for iid were retrieved, excluding the ones matching best.contains. | [
"%prog",
"overlap",
"best",
".",
"contains",
"iid"
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/textio.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L1598-L1702 | def dump_memory_map(memoryMap, mappedFilenames = None, bits = None):
"""
Dump the memory map of a process. Optionally show the filenames for
memory mapped files as well.
@type memoryMap: list( L{win32.MemoryBasicInformation} )
@param memoryMap: Memory map returned by L{Process.... | [
"def",
"dump_memory_map",
"(",
"memoryMap",
",",
"mappedFilenames",
"=",
"None",
",",
"bits",
"=",
"None",
")",
":",
"if",
"not",
"memoryMap",
":",
"return",
"''",
"table",
"=",
"Table",
"(",
")",
"if",
"mappedFilenames",
":",
"table",
".",
"addRow",
"("... | Dump the memory map of a process. Optionally show the filenames for
memory mapped files as well.
@type memoryMap: list( L{win32.MemoryBasicInformation} )
@param memoryMap: Memory map returned by L{Process.get_memory_map}.
@type mappedFilenames: dict( int S{->} str )
@param ma... | [
"Dump",
"the",
"memory",
"map",
"of",
"a",
"process",
".",
"Optionally",
"show",
"the",
"filenames",
"for",
"memory",
"mapped",
"files",
"as",
"well",
"."
] | python | train |
mandiant/ioc_writer | ioc_writer/ioc_common.py | https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_common.py#L93-L105 | def make_eventlogitem_log(log, condition='is', negate=False, preserve_case=False):
"""
Create a node for EventLogItem/log
:return: A IndicatorItem represented as an Element node
"""
document = 'EventLogItem'
search = 'EventLogItem/log'
content_type = 'string'
content = log
ii_no... | [
"def",
"make_eventlogitem_log",
"(",
"log",
",",
"condition",
"=",
"'is'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'EventLogItem'",
"search",
"=",
"'EventLogItem/log'",
"content_type",
"=",
"'string'",
"conten... | Create a node for EventLogItem/log
:return: A IndicatorItem represented as an Element node | [
"Create",
"a",
"node",
"for",
"EventLogItem",
"/",
"log",
":",
"return",
":",
"A",
"IndicatorItem",
"represented",
"as",
"an",
"Element",
"node"
] | python | train |
Erotemic/utool | utool/util_str.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L395-L465 | def pack_into(text, textwidth=160, breakchars=' ', break_words=True,
newline_prefix='', wordsep=' ', remove_newlines=True):
r"""
DEPRICATE IN FAVOR OF textwrap.wrap
TODO: Look into textwrap.wrap
Inserts newlines into a string enforcing a maximum textwidth.
Similar to vim's gq comman... | [
"def",
"pack_into",
"(",
"text",
",",
"textwidth",
"=",
"160",
",",
"breakchars",
"=",
"' '",
",",
"break_words",
"=",
"True",
",",
"newline_prefix",
"=",
"''",
",",
"wordsep",
"=",
"' '",
",",
"remove_newlines",
"=",
"True",
")",
":",
"#FIXME: messy code"... | r"""
DEPRICATE IN FAVOR OF textwrap.wrap
TODO: Look into textwrap.wrap
Inserts newlines into a string enforcing a maximum textwidth.
Similar to vim's gq command in visual select mode.
breakchars is a string containing valid characters to insert a newline
before or after.
break_words is ... | [
"r"
] | python | train |
tanghaibao/jcvi | jcvi/formats/base.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/base.py#L495-L501 | def get_number(s, cast=int):
"""
Try to get a number out of a string, and cast it.
"""
import string
d = "".join(x for x in str(s) if x in string.digits)
return cast(d) | [
"def",
"get_number",
"(",
"s",
",",
"cast",
"=",
"int",
")",
":",
"import",
"string",
"d",
"=",
"\"\"",
".",
"join",
"(",
"x",
"for",
"x",
"in",
"str",
"(",
"s",
")",
"if",
"x",
"in",
"string",
".",
"digits",
")",
"return",
"cast",
"(",
"d",
... | Try to get a number out of a string, and cast it. | [
"Try",
"to",
"get",
"a",
"number",
"out",
"of",
"a",
"string",
"and",
"cast",
"it",
"."
] | python | train |
pysal/esda | esda/tabular.py | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L156-L177 | def _swap_ending(s, ending, delim='_'):
"""
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to ... | [
"def",
"_swap_ending",
"(",
"s",
",",
"ending",
",",
"delim",
"=",
"'_'",
")",
":",
"parts",
"=",
"[",
"x",
"for",
"x",
"in",
"s",
".",
"split",
"(",
"delim",
")",
"[",
":",
"-",
"1",
"]",
"if",
"x",
"!=",
"''",
"]",
"parts",
".",
"append",
... | Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to replace ending of `s`
delim : string
... | [
"Replace",
"the",
"ending",
"of",
"a",
"string",
"delimited",
"into",
"an",
"arbitrary",
"number",
"of",
"chunks",
"by",
"delim",
"with",
"the",
"ending",
"provided"
] | python | train |
inveniosoftware-attic/invenio-utils | invenio_utils/text.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/text.py#L498-L541 | def decode_to_unicode(text, default_encoding='utf-8'):
"""Decode input text into Unicode representation.
Decode input text into Unicode representation by first using the default
encoding utf-8.
If the operation fails, it detects the type of encoding used in the
given text.
For optimal result, i... | [
"def",
"decode_to_unicode",
"(",
"text",
",",
"default_encoding",
"=",
"'utf-8'",
")",
":",
"if",
"not",
"text",
":",
"return",
"\"\"",
"try",
":",
"return",
"text",
".",
"decode",
"(",
"default_encoding",
")",
"except",
"(",
"UnicodeError",
",",
"LookupErro... | Decode input text into Unicode representation.
Decode input text into Unicode representation by first using the default
encoding utf-8.
If the operation fails, it detects the type of encoding used in the
given text.
For optimal result, it is recommended that the 'chardet' module is
installed.
... | [
"Decode",
"input",
"text",
"into",
"Unicode",
"representation",
"."
] | python | train |
mistio/mist.client | src/mistclient/model.py | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L739-L747 | def public(self):
"""
Return the public ssh-key
:returns: The public ssh-key as string
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id+"/public")
public = req.get().json()
return public | [
"def",
"public",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/keys/'",
"+",
"self",
".",
"id",
"+",
"\"/public\"",
")",
"public",
"=",
"req",
".",
"get",
"(",
")",
".",
"json",
"(... | Return the public ssh-key
:returns: The public ssh-key as string | [
"Return",
"the",
"public",
"ssh",
"-",
"key"
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/flask/helpers.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/helpers.py#L186-L316 | def url_for(endpoint, **values):
"""Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended
to the generated URL as query arguments. If the value of a query argument
is `None`, the whole pair is skipped. In case blueprint... | [
"def",
"url_for",
"(",
"endpoint",
",",
"*",
"*",
"values",
")",
":",
"appctx",
"=",
"_app_ctx_stack",
".",
"top",
"reqctx",
"=",
"_request_ctx_stack",
".",
"top",
"if",
"appctx",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Attempted to generate a URL w... | Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended
to the generated URL as query arguments. If the value of a query argument
is `None`, the whole pair is skipped. In case blueprints are active
you can shortcut refere... | [
"Generates",
"a",
"URL",
"to",
"the",
"given",
"endpoint",
"with",
"the",
"method",
"provided",
"."
] | python | test |
JoeVirtual/KonFoo | konfoo/providers.py | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/providers.py#L102-L113 | def flush(self, file=str()):
""" Flushes the updated file content to the given *file*.
.. note:: Overwrites an existing file.
:param str file: name and location of the file.
Default is the original file.
"""
if file:
Path(file).write_bytes(self._cache)
... | [
"def",
"flush",
"(",
"self",
",",
"file",
"=",
"str",
"(",
")",
")",
":",
"if",
"file",
":",
"Path",
"(",
"file",
")",
".",
"write_bytes",
"(",
"self",
".",
"_cache",
")",
"else",
":",
"self",
".",
"path",
".",
"write_bytes",
"(",
"self",
".",
... | Flushes the updated file content to the given *file*.
.. note:: Overwrites an existing file.
:param str file: name and location of the file.
Default is the original file. | [
"Flushes",
"the",
"updated",
"file",
"content",
"to",
"the",
"given",
"*",
"file",
"*",
"."
] | python | train |
twisted/txaws | txaws/ec2/client.py | https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/ec2/client.py#L173-L235 | def authorize_security_group(
self, group_name=None, group_id=None, source_group_name="", source_group_owner_id="",
ip_protocol="", from_port="", to_port="", cidr_ip=""):
"""
There are two ways to use C{authorize_security_group}:
1) associate an existing group (source group) ... | [
"def",
"authorize_security_group",
"(",
"self",
",",
"group_name",
"=",
"None",
",",
"group_id",
"=",
"None",
",",
"source_group_name",
"=",
"\"\"",
",",
"source_group_owner_id",
"=",
"\"\"",
",",
"ip_protocol",
"=",
"\"\"",
",",
"from_port",
"=",
"\"\"",
",",... | There are two ways to use C{authorize_security_group}:
1) associate an existing group (source group) with the one that you
are targeting (group_name) with an authorization update; or
2) associate a set of IP permissions with the group you are
targeting with an authorizati... | [
"There",
"are",
"two",
"ways",
"to",
"use",
"C",
"{",
"authorize_security_group",
"}",
":",
"1",
")",
"associate",
"an",
"existing",
"group",
"(",
"source",
"group",
")",
"with",
"the",
"one",
"that",
"you",
"are",
"targeting",
"(",
"group_name",
")",
"w... | python | train |
nitely/v8-cffi | v8cffi/context.py | https://github.com/nitely/v8-cffi/blob/e3492e7eaacb30be75999c24413aa15eeab57a5d/v8cffi/context.py#L168-L185 | def load_libs(self, scripts_paths):
"""
Load script files into the context.\
This can be thought as the HTML script tag.\
The files content must be utf-8 encoded.
This is a shortcut for reading the files\
and pass the content to :py:func:`run_script`
:param list... | [
"def",
"load_libs",
"(",
"self",
",",
"scripts_paths",
")",
":",
"for",
"path",
"in",
"scripts_paths",
":",
"self",
".",
"run_script",
"(",
"_read_file",
"(",
"path",
")",
",",
"identifier",
"=",
"path",
")"
] | Load script files into the context.\
This can be thought as the HTML script tag.\
The files content must be utf-8 encoded.
This is a shortcut for reading the files\
and pass the content to :py:func:`run_script`
:param list scripts_paths: Script file paths.
:raises OSErr... | [
"Load",
"script",
"files",
"into",
"the",
"context",
".",
"\\",
"This",
"can",
"be",
"thought",
"as",
"the",
"HTML",
"script",
"tag",
".",
"\\",
"The",
"files",
"content",
"must",
"be",
"utf",
"-",
"8",
"encoded",
"."
] | python | train |
crdoconnor/strictyaml | strictyaml/yamllocation.py | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L170-L180 | def _select(self, pointer):
"""
Get a YAMLChunk referenced by a pointer.
"""
return YAMLChunk(
self._ruamelparsed,
pointer=pointer,
label=self._label,
strictparsed=self._strictparsed,
key_association=copy(self._key_association),... | [
"def",
"_select",
"(",
"self",
",",
"pointer",
")",
":",
"return",
"YAMLChunk",
"(",
"self",
".",
"_ruamelparsed",
",",
"pointer",
"=",
"pointer",
",",
"label",
"=",
"self",
".",
"_label",
",",
"strictparsed",
"=",
"self",
".",
"_strictparsed",
",",
"key... | Get a YAMLChunk referenced by a pointer. | [
"Get",
"a",
"YAMLChunk",
"referenced",
"by",
"a",
"pointer",
"."
] | python | train |
bitesofcode/projex | projex/xbuild/builder.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xbuild/builder.py#L1855-L1888 | def fromYaml(cls, ydata, filepath=''):
"""
Generates a new builder from the given xml data and then
loads its information.
:param ydata | <xml.etree.ElementTree.Element>
:return <Builder> || None
"""
module = None
pkg_data = ydat... | [
"def",
"fromYaml",
"(",
"cls",
",",
"ydata",
",",
"filepath",
"=",
"''",
")",
":",
"module",
"=",
"None",
"pkg_data",
"=",
"ydata",
".",
"get",
"(",
"'package'",
")",
"if",
"pkg_data",
"is",
"not",
"None",
":",
"path",
"=",
"pkg_data",
".",
"get",
... | Generates a new builder from the given xml data and then
loads its information.
:param ydata | <xml.etree.ElementTree.Element>
:return <Builder> || None | [
"Generates",
"a",
"new",
"builder",
"from",
"the",
"given",
"xml",
"data",
"and",
"then",
"loads",
"its",
"information",
".",
":",
"param",
"ydata",
"|",
"<xml",
".",
"etree",
".",
"ElementTree",
".",
"Element",
">",
":",
"return",
"<Builder",
">",
"||",... | python | train |
Grk0/python-libconf | libconf.py | https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L501-L521 | def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> conf... | [
"def",
"loads",
"(",
"string",
",",
"filename",
"=",
"None",
",",
"includedir",
"=",
"''",
")",
":",
"try",
":",
"f",
"=",
"io",
".",
"StringIO",
"(",
"string",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"libconf.loads() input string mus... | Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
... | [
"Load",
"the",
"contents",
"of",
"string",
"to",
"a",
"Python",
"object"
] | python | train |
sibirrer/lenstronomy | lenstronomy/Sampling/likelihood.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Sampling/likelihood.py#L96-L123 | def logL(self, args):
"""
routine to compute X2 given variable parameters for a MCMC/PSO chain
"""
#extract parameters
kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo = self.param.args2kwargs(args)
#generate image and computes likelihood
sel... | [
"def",
"logL",
"(",
"self",
",",
"args",
")",
":",
"#extract parameters",
"kwargs_lens",
",",
"kwargs_source",
",",
"kwargs_lens_light",
",",
"kwargs_ps",
",",
"kwargs_cosmo",
"=",
"self",
".",
"param",
".",
"args2kwargs",
"(",
"args",
")",
"#generate image and ... | routine to compute X2 given variable parameters for a MCMC/PSO chain | [
"routine",
"to",
"compute",
"X2",
"given",
"variable",
"parameters",
"for",
"a",
"MCMC",
"/",
"PSO",
"chain"
] | python | train |
loli/medpy | medpy/features/histogram.py | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/histogram.py#L289-L359 | def gaussian_membership(bin_center, bin_width, smoothness):
r"""Create a gaussian membership function for a fuzzy histogram bin.
Parameters
----------
bin_center : number
The center of the bin of which to compute the membership function.
bin_width : number
The width of a single ... | [
"def",
"gaussian_membership",
"(",
"bin_center",
",",
"bin_width",
",",
"smoothness",
")",
":",
"if",
"smoothness",
">",
"10",
"or",
"smoothness",
"<",
"1.",
"/",
"10",
":",
"raise",
"AttributeError",
"(",
"'the gaussian membership function supports only smoothnesses ... | r"""Create a gaussian membership function for a fuzzy histogram bin.
Parameters
----------
bin_center : number
The center of the bin of which to compute the membership function.
bin_width : number
The width of a single bin (all expected to be of equal width).
smoothness : number... | [
"r",
"Create",
"a",
"gaussian",
"membership",
"function",
"for",
"a",
"fuzzy",
"histogram",
"bin",
".",
"Parameters",
"----------",
"bin_center",
":",
"number",
"The",
"center",
"of",
"the",
"bin",
"of",
"which",
"to",
"compute",
"the",
"membership",
"function... | python | train |
python-gitlab/python-gitlab | gitlab/v4/objects.py | https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/v4/objects.py#L3402-L3421 | def repository_contributors(self, **kwargs):
"""Return a list of contributors for the project.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts wit... | [
"def",
"repository_contributors",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"'/projects/%s/repository/contributors'",
"%",
"self",
".",
"get_id",
"(",
")",
"return",
"self",
".",
"manager",
".",
"gitlab",
".",
"http_list",
"(",
"path",
","... | Return a list of contributors for the project.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to False an... | [
"Return",
"a",
"list",
"of",
"contributors",
"for",
"the",
"project",
"."
] | python | train |
Workiva/furious | furious/context/context.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L127-L157 | def _handle_tasks_insert(self, batch_size=None):
"""Convert all Async's into tasks, then insert them into queues."""
if self._tasks_inserted:
raise errors.ContextAlreadyStartedError(
"This Context has already had its tasks inserted.")
task_map = self._get_tasks_by_qu... | [
"def",
"_handle_tasks_insert",
"(",
"self",
",",
"batch_size",
"=",
"None",
")",
":",
"if",
"self",
".",
"_tasks_inserted",
":",
"raise",
"errors",
".",
"ContextAlreadyStartedError",
"(",
"\"This Context has already had its tasks inserted.\"",
")",
"task_map",
"=",
"s... | Convert all Async's into tasks, then insert them into queues. | [
"Convert",
"all",
"Async",
"s",
"into",
"tasks",
"then",
"insert",
"them",
"into",
"queues",
"."
] | python | train |
ethpm/py-ethpm | ethpm/package.py | https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/package.py#L160-L176 | def from_uri(cls, uri: URI, w3: Web3) -> "Package":
"""
Returns a Package object instantiated by a manifest located at a content-addressed URI.
A valid ``Web3`` instance is also required.
URI schemes supported:
- IPFS `ipfs://Qm...`
- HTTP `https://api.g... | [
"def",
"from_uri",
"(",
"cls",
",",
"uri",
":",
"URI",
",",
"w3",
":",
"Web3",
")",
"->",
"\"Package\"",
":",
"contents",
"=",
"to_text",
"(",
"resolve_uri_contents",
"(",
"uri",
")",
")",
"validate_raw_manifest_format",
"(",
"contents",
")",
"manifest",
"... | Returns a Package object instantiated by a manifest located at a content-addressed URI.
A valid ``Web3`` instance is also required.
URI schemes supported:
- IPFS `ipfs://Qm...`
- HTTP `https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha`
- Registry ... | [
"Returns",
"a",
"Package",
"object",
"instantiated",
"by",
"a",
"manifest",
"located",
"at",
"a",
"content",
"-",
"addressed",
"URI",
".",
"A",
"valid",
"Web3",
"instance",
"is",
"also",
"required",
".",
"URI",
"schemes",
"supported",
":",
"-",
"IPFS",
"ip... | python | train |
mnick/scikit-tensor | sktensor/dedicom.py | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/dedicom.py#L241-L269 | def updateD_H(self, x):
"""
Compute Hessian for update of D
See [2] for derivation of Hessian
"""
self.precompute(x)
H = zeros((len(x), len(x)))
Ai = zeros(self.A.shape[0])
Aj = zeros(Ai.shape)
for i in range(len(x)):
Ai = self.A[:, i]... | [
"def",
"updateD_H",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"precompute",
"(",
"x",
")",
"H",
"=",
"zeros",
"(",
"(",
"len",
"(",
"x",
")",
",",
"len",
"(",
"x",
")",
")",
")",
"Ai",
"=",
"zeros",
"(",
"self",
".",
"A",
".",
"shape",
... | Compute Hessian for update of D
See [2] for derivation of Hessian | [
"Compute",
"Hessian",
"for",
"update",
"of",
"D"
] | python | train |
cs50/style50 | style50/_api.py | https://github.com/cs50/style50/blob/2dfe5957f7b727ee5163499e7b8191275aee914c/style50/_api.py#L238-L250 | def html_diff(self, old, new):
"""
Return HTML formatted character-based diff between old and new (used for CS50 IDE).
"""
def html_transition(old_type, new_type):
tags = []
for tag in [("/", old_type), ("", new_type)]:
if tag[1] not in ["+", "-"]:... | [
"def",
"html_diff",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"def",
"html_transition",
"(",
"old_type",
",",
"new_type",
")",
":",
"tags",
"=",
"[",
"]",
"for",
"tag",
"in",
"[",
"(",
"\"/\"",
",",
"old_type",
")",
",",
"(",
"\"\"",
",",
"n... | Return HTML formatted character-based diff between old and new (used for CS50 IDE). | [
"Return",
"HTML",
"formatted",
"character",
"-",
"based",
"diff",
"between",
"old",
"and",
"new",
"(",
"used",
"for",
"CS50",
"IDE",
")",
"."
] | python | train |
jmbhughes/suvi-trainer | scripts/clean_by_agreement.py | https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/scripts/clean_by_agreement.py#L9-L14 | def parse_args():
""" parse arguments"""
ap = argparse.ArgumentParser()
ap.add_argument("directory", help="where the labeled data is saved")
ap.add_argument("output", help="the drectory to save files")
return ap.parse_args() | [
"def",
"parse_args",
"(",
")",
":",
"ap",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"ap",
".",
"add_argument",
"(",
"\"directory\"",
",",
"help",
"=",
"\"where the labeled data is saved\"",
")",
"ap",
".",
"add_argument",
"(",
"\"output\"",
",",
"help"... | parse arguments | [
"parse",
"arguments"
] | python | train |
mar10/wsgidav | wsgidav/server/ext_wsgiutils_server.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/ext_wsgiutils_server.py#L331-L367 | def stop_serve_forever(self):
"""Stop serve_forever_stoppable()."""
assert hasattr(
self, "stop_request"
), "serve_forever_stoppable() must be called before"
assert not self.stop_request, "stop_serve_forever() must only be called once"
# # Flag stop request
... | [
"def",
"stop_serve_forever",
"(",
"self",
")",
":",
"assert",
"hasattr",
"(",
"self",
",",
"\"stop_request\"",
")",
",",
"\"serve_forever_stoppable() must be called before\"",
"assert",
"not",
"self",
".",
"stop_request",
",",
"\"stop_serve_forever() must only be called onc... | Stop serve_forever_stoppable(). | [
"Stop",
"serve_forever_stoppable",
"()",
"."
] | python | valid |
google/grr | grr/client/grr_response_client/windows/process.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/windows/process.py#L195-L209 | def ReadBytes(self, address, num_bytes):
"""Reads at most num_bytes starting from offset <address>."""
address = int(address)
buf = ctypes.create_string_buffer(num_bytes)
bytesread = ctypes.c_size_t(0)
res = ReadProcessMemory(self.h_process, address, buf, num_bytes,
ctype... | [
"def",
"ReadBytes",
"(",
"self",
",",
"address",
",",
"num_bytes",
")",
":",
"address",
"=",
"int",
"(",
"address",
")",
"buf",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"num_bytes",
")",
"bytesread",
"=",
"ctypes",
".",
"c_size_t",
"(",
"0",
")",... | Reads at most num_bytes starting from offset <address>. | [
"Reads",
"at",
"most",
"num_bytes",
"starting",
"from",
"offset",
"<address",
">",
"."
] | python | train |
empymod/empymod | empymod/scripts/fdesign.py | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L247-L466 | def design(n, spacing, shift, fI, fC=False, r=None, r_def=(1, 1, 2), reim=None,
cvar='amp', error=0.01, name=None, full_output=False, finish=False,
save=True, path='filters', verb=2, plot=1):
r"""Digital linear filter (DLF) design
This routine can be used to design digital linear filters ... | [
"def",
"design",
"(",
"n",
",",
"spacing",
",",
"shift",
",",
"fI",
",",
"fC",
"=",
"False",
",",
"r",
"=",
"None",
",",
"r_def",
"=",
"(",
"1",
",",
"1",
",",
"2",
")",
",",
"reim",
"=",
"None",
",",
"cvar",
"=",
"'amp'",
",",
"error",
"="... | r"""Digital linear filter (DLF) design
This routine can be used to design digital linear filters for the Hankel or
Fourier transform, or for any linear transform ([Ghos70]_). For this
included or provided theoretical transform pairs can be used.
Alternatively, one can use the EM modeller empymod to use... | [
"r",
"Digital",
"linear",
"filter",
"(",
"DLF",
")",
"design"
] | python | train |
shoebot/shoebot | shoebot/grammar/bot.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L199-L203 | def _makeInstance(self, clazz, args, kwargs):
'''Creates an instance of a class defined in this document.
This method sets the context of the object to the current context.'''
inst = clazz(self, *args, **kwargs)
return inst | [
"def",
"_makeInstance",
"(",
"self",
",",
"clazz",
",",
"args",
",",
"kwargs",
")",
":",
"inst",
"=",
"clazz",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inst"
] | Creates an instance of a class defined in this document.
This method sets the context of the object to the current context. | [
"Creates",
"an",
"instance",
"of",
"a",
"class",
"defined",
"in",
"this",
"document",
".",
"This",
"method",
"sets",
"the",
"context",
"of",
"the",
"object",
"to",
"the",
"current",
"context",
"."
] | python | valid |
Robpol86/libnl | libnl/netlink_private/netlink.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/netlink_private/netlink.py#L18-L34 | def nl_cb_call(cb, type_, msg):
"""Call a callback function.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback type integer (e.g. NL_CB_MSG_OUT).
msg -- Netlink message (nl_msg class inst... | [
"def",
"nl_cb_call",
"(",
"cb",
",",
"type_",
",",
"msg",
")",
":",
"cb",
".",
"cb_active",
"=",
"type_",
"ret",
"=",
"cb",
".",
"cb_set",
"[",
"type_",
"]",
"(",
"msg",
",",
"cb",
".",
"cb_args",
"[",
"type_",
"]",
")",
"cb",
".",
"cb_active",
... | Call a callback function.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback type integer (e.g. NL_CB_MSG_OUT).
msg -- Netlink message (nl_msg class instance).
Returns:
Integer from t... | [
"Call",
"a",
"callback",
"function",
"."
] | python | train |
edeposit/marcxml2mods | src/marcxml2mods/mods_postprocessor/shared_funcs.py | https://github.com/edeposit/marcxml2mods/blob/7b44157e859b4d2a372f79598ddbf77e43d39812/src/marcxml2mods/mods_postprocessor/shared_funcs.py#L42-L63 | def transform_content(tags, content_transformer):
"""
Transform content in all `tags` using result of `content_transformer(tag)`
call.
Args:
tags (obj/list): HTMLElement instance, or list of HTMLElement
instances.
content_transformer (function): Function which i... | [
"def",
"transform_content",
"(",
"tags",
",",
"content_transformer",
")",
":",
"if",
"type",
"(",
"tags",
")",
"not",
"in",
"[",
"tuple",
",",
"list",
"]",
":",
"tags",
"=",
"[",
"tags",
"]",
"for",
"tag",
"in",
"tags",
":",
"new_child",
"=",
"dhtmlp... | Transform content in all `tags` using result of `content_transformer(tag)`
call.
Args:
tags (obj/list): HTMLElement instance, or list of HTMLElement
instances.
content_transformer (function): Function which is called as
``content_... | [
"Transform",
"content",
"in",
"all",
"tags",
"using",
"result",
"of",
"content_transformer",
"(",
"tag",
")",
"call",
"."
] | python | train |
sassoftware/saspy | saspy/sasdata.py | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L1005-L1045 | def to_json(self, pretty: bool = False, sastag: bool = False, **kwargs) -> str:
"""
Export this SAS Data Set to a JSON Object
PROC JSON documentation: http://go.documentation.sas.com/?docsetId=proc&docsetVersion=9.4&docsetTarget=p06hstivs0b3hsn1cb4zclxukkut.htm&locale=en
:param pretty: ... | [
"def",
"to_json",
"(",
"self",
",",
"pretty",
":",
"bool",
"=",
"False",
",",
"sastag",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"code",
"=",
"\"filename file1 temp;\"",
"code",
"+=",
"\"proc json out=file1\"",
"if",
"pr... | Export this SAS Data Set to a JSON Object
PROC JSON documentation: http://go.documentation.sas.com/?docsetId=proc&docsetVersion=9.4&docsetTarget=p06hstivs0b3hsn1cb4zclxukkut.htm&locale=en
:param pretty: boolean False return JSON on one line True returns formatted JSON
:param sastag: include SAS... | [
"Export",
"this",
"SAS",
"Data",
"Set",
"to",
"a",
"JSON",
"Object",
"PROC",
"JSON",
"documentation",
":",
"http",
":",
"//",
"go",
".",
"documentation",
".",
"sas",
".",
"com",
"/",
"?docsetId",
"=",
"proc&docsetVersion",
"=",
"9",
".",
"4&docsetTarget",
... | python | train |
Esri/ArcREST | src/arcrest/ags/layer.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/layer.py#L1094-L1135 | def validateSQL(self, sql, sqlType="where"):
"""
The validateSQL operation validates an SQL-92 expression or WHERE
clause.
The validateSQL operation ensures that an SQL-92 expression, such
as one written by a user through a user interface, is correct
before performing ano... | [
"def",
"validateSQL",
"(",
"self",
",",
"sql",
",",
"sqlType",
"=",
"\"where\"",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/validateSQL\"",
"if",
"not",
"sqlType",
".",
"lower",
"(",
")",
"in",
"[",
"'where'",
",",
"'expression'",
",",
"'state... | The validateSQL operation validates an SQL-92 expression or WHERE
clause.
The validateSQL operation ensures that an SQL-92 expression, such
as one written by a user through a user interface, is correct
before performing another operation that uses the expression. For
example, val... | [
"The",
"validateSQL",
"operation",
"validates",
"an",
"SQL",
"-",
"92",
"expression",
"or",
"WHERE",
"clause",
".",
"The",
"validateSQL",
"operation",
"ensures",
"that",
"an",
"SQL",
"-",
"92",
"expression",
"such",
"as",
"one",
"written",
"by",
"a",
"user",... | python | train |
awslabs/aws-sam-cli | samcli/lib/build/app_builder.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/app_builder.py#L112-L153 | def update_template(self, template_dict, original_template_path, built_artifacts):
"""
Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path... | [
"def",
"update_template",
"(",
"self",
",",
"template_dict",
",",
"original_template_path",
",",
"built_artifacts",
")",
":",
"original_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"original_template_path",
")",
"for",
"logical_id",
",",
"resource",
"in",
... | Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path : str
Path where the template file will be written to
built_artifacts : dict
... | [
"Given",
"the",
"path",
"to",
"built",
"artifacts",
"update",
"the",
"template",
"to",
"point",
"appropriate",
"resource",
"CodeUris",
"to",
"the",
"artifacts",
"folder"
] | python | train |
yahoo/TensorFlowOnSpark | tensorflowonspark/TFManager.py | https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFManager.py#L40-L65 | def start(authkey, queues, mode='local'):
"""Create a new multiprocess.Manager (or return existing one).
Args:
:authkey: string authorization key
:queues: *INTERNAL_USE*
:mode: 'local' indicates that the manager will only be accessible from the same host, otherwise remotely accessible.
Returns:
... | [
"def",
"start",
"(",
"authkey",
",",
"queues",
",",
"mode",
"=",
"'local'",
")",
":",
"global",
"mgr",
",",
"qdict",
",",
"kdict",
"qdict",
".",
"clear",
"(",
")",
"kdict",
".",
"clear",
"(",
")",
"for",
"q",
"in",
"queues",
":",
"qdict",
"[",
"q... | Create a new multiprocess.Manager (or return existing one).
Args:
:authkey: string authorization key
:queues: *INTERNAL_USE*
:mode: 'local' indicates that the manager will only be accessible from the same host, otherwise remotely accessible.
Returns:
A TFManager instance, which is also cached in l... | [
"Create",
"a",
"new",
"multiprocess",
".",
"Manager",
"(",
"or",
"return",
"existing",
"one",
")",
"."
] | python | train |
UDST/urbansim | urbansim/models/dcm.py | https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/dcm.py#L986-L1014 | def apply_fit_filters(self, choosers, alternatives):
"""
Filter `choosers` and `alternatives` for fitting.
This is done by filtering each submodel and concatenating
the results.
Parameters
----------
choosers : pandas.DataFrame
Table describing the ag... | [
"def",
"apply_fit_filters",
"(",
"self",
",",
"choosers",
",",
"alternatives",
")",
":",
"ch",
"=",
"[",
"]",
"alts",
"=",
"[",
"]",
"for",
"name",
",",
"df",
"in",
"self",
".",
"_iter_groups",
"(",
"choosers",
")",
":",
"filtered_choosers",
",",
"filt... | Filter `choosers` and `alternatives` for fitting.
This is done by filtering each submodel and concatenating
the results.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataF... | [
"Filter",
"choosers",
"and",
"alternatives",
"for",
"fitting",
".",
"This",
"is",
"done",
"by",
"filtering",
"each",
"submodel",
"and",
"concatenating",
"the",
"results",
"."
] | python | train |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/expressions.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/expressions.py#L781-L789 | def visit_and_update(self, visitor_fn):
"""Create an updated version (if needed) of BinaryComposition via the visitor pattern."""
new_left = self.left.visit_and_update(visitor_fn)
new_right = self.right.visit_and_update(visitor_fn)
if new_left is not self.left or new_right is not self.r... | [
"def",
"visit_and_update",
"(",
"self",
",",
"visitor_fn",
")",
":",
"new_left",
"=",
"self",
".",
"left",
".",
"visit_and_update",
"(",
"visitor_fn",
")",
"new_right",
"=",
"self",
".",
"right",
".",
"visit_and_update",
"(",
"visitor_fn",
")",
"if",
"new_le... | Create an updated version (if needed) of BinaryComposition via the visitor pattern. | [
"Create",
"an",
"updated",
"version",
"(",
"if",
"needed",
")",
"of",
"BinaryComposition",
"via",
"the",
"visitor",
"pattern",
"."
] | python | train |
theislab/scanpy | scanpy/tools/_sim.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/tools/_sim.py#L1054-L1081 | def sim_combi(self):
""" Simulate data to model combi regulation.
"""
n_samples = 500
sigma_glob = 1.8
X = np.zeros((n_samples,3))
X[:,0] = np.random.uniform(-sigma_glob,sigma_glob,n_samples)
X[:,1] = np.random.uniform(-sigma_glob,sigma_glob,n_samples)
... | [
"def",
"sim_combi",
"(",
"self",
")",
":",
"n_samples",
"=",
"500",
"sigma_glob",
"=",
"1.8",
"X",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"3",
")",
")",
"X",
"[",
":",
",",
"0",
"]",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
... | Simulate data to model combi regulation. | [
"Simulate",
"data",
"to",
"model",
"combi",
"regulation",
"."
] | python | train |
MIT-LCP/wfdb-python | wfdb/io/_header.py | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_header.py#L780-L824 | def _parse_signal_lines(signal_lines):
"""
Extract fields from a list of signal line strings into a dictionary.
"""
n_sig = len(signal_lines)
# Dictionary for signal fields
signal_fields = {}
# Each dictionary field is a list
for field in SIGNAL_SPECS.index:
signal_fields[field... | [
"def",
"_parse_signal_lines",
"(",
"signal_lines",
")",
":",
"n_sig",
"=",
"len",
"(",
"signal_lines",
")",
"# Dictionary for signal fields",
"signal_fields",
"=",
"{",
"}",
"# Each dictionary field is a list",
"for",
"field",
"in",
"SIGNAL_SPECS",
".",
"index",
":",
... | Extract fields from a list of signal line strings into a dictionary. | [
"Extract",
"fields",
"from",
"a",
"list",
"of",
"signal",
"line",
"strings",
"into",
"a",
"dictionary",
"."
] | python | train |
jorahn/icy | icy/icy.py | https://github.com/jorahn/icy/blob/d0bd765c933b2d9bff4d7d646c0938348b9c5c25/icy/icy.py#L568-L621 | def run_examples(examples):
"""Run read() on a number of examples, supress output, generate summary.
Parameters
----------
examples : list of tuples of three str elements
Tuples contain the path and cfg argument to the read function,
as well as the cfg argument to the merge function... | [
"def",
"run_examples",
"(",
"examples",
")",
":",
"import",
"inspect",
"PATH_TEST_DATA",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"inspect",
".",
"getfile",
"(",
"inspect"... | Run read() on a number of examples, supress output, generate summary.
Parameters
----------
examples : list of tuples of three str elements
Tuples contain the path and cfg argument to the read function,
as well as the cfg argument to the merge function (*TODO*)
e.g. [(path, read... | [
"Run",
"read",
"()",
"on",
"a",
"number",
"of",
"examples",
"supress",
"output",
"generate",
"summary",
".",
"Parameters",
"----------",
"examples",
":",
"list",
"of",
"tuples",
"of",
"three",
"str",
"elements",
"Tuples",
"contain",
"the",
"path",
"and",
"cf... | python | train |
gwpy/gwpy | gwpy/utils/lal.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/utils/lal.py#L79-L119 | def to_lal_type_str(pytype):
"""Convert the input python type to a LAL type string
Examples
--------
To convert a python type:
>>> from gwpy.utils.lal import to_lal_type_str
>>> to_lal_type_str(float)
'REAL8'
To convert a `numpy.dtype`:
>>> import numpy
>>> to_lal_type_str(nu... | [
"def",
"to_lal_type_str",
"(",
"pytype",
")",
":",
"# noop",
"if",
"pytype",
"in",
"LAL_TYPE_FROM_STR",
":",
"return",
"pytype",
"# convert type code",
"if",
"pytype",
"in",
"LAL_TYPE_STR",
":",
"return",
"LAL_TYPE_STR",
"[",
"pytype",
"]",
"# convert python type",
... | Convert the input python type to a LAL type string
Examples
--------
To convert a python type:
>>> from gwpy.utils.lal import to_lal_type_str
>>> to_lal_type_str(float)
'REAL8'
To convert a `numpy.dtype`:
>>> import numpy
>>> to_lal_type_str(numpy.dtype('uint32'))
'UINT4'
... | [
"Convert",
"the",
"input",
"python",
"type",
"to",
"a",
"LAL",
"type",
"string"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.