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 |
|---|---|---|---|---|---|---|---|---|
zsimic/runez | src/runez/serialize.py | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/serialize.py#L131-L141 | def save(self, path=None, fatal=True, logger=None, sort_keys=True, indent=2):
"""
:param str|None path: Save this serializable to file with 'path' (default: self._path)
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to use
:param bo... | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"None",
",",
"fatal",
"=",
"True",
",",
"logger",
"=",
"None",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"2",
")",
":",
"path",
"=",
"path",
"or",
"getattr",
"(",
"self",
",",
"\"_path\"",
",... | :param str|None path: Save this serializable to file with 'path' (default: self._path)
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to use
:param bool sort_keys: Sort keys
:param int indent: Indentation to use | [
":",
"param",
"str|None",
"path",
":",
"Save",
"this",
"serializable",
"to",
"file",
"with",
"path",
"(",
"default",
":",
"self",
".",
"_path",
")",
":",
"param",
"bool|None",
"fatal",
":",
"Abort",
"execution",
"on",
"failure",
"if",
"True",
":",
"param... | python | train |
INM-6/hybridLFPy | examples/example_microcircuit_params.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/example_microcircuit_params.py#L123-L168 | def get_T_yX(fname, y, y_in_Y, x_in_X, F_y):
'''
compute the cell type specificity, defined as:
::
T_yX = K_yX / K_YX
= F_y * k_yX / sum_y(F_y*k_yX)
'''
def _get_k_yX_mul_F_y(y, y_index, X_index):
# Load data from json dictionary
f = open(fname, 'r')
... | [
"def",
"get_T_yX",
"(",
"fname",
",",
"y",
",",
"y_in_Y",
",",
"x_in_X",
",",
"F_y",
")",
":",
"def",
"_get_k_yX_mul_F_y",
"(",
"y",
",",
"y_index",
",",
"X_index",
")",
":",
"# Load data from json dictionary",
"f",
"=",
"open",
"(",
"fname",
",",
"'r'",... | compute the cell type specificity, defined as:
::
T_yX = K_yX / K_YX
= F_y * k_yX / sum_y(F_y*k_yX) | [
"compute",
"the",
"cell",
"type",
"specificity",
"defined",
"as",
":",
"::",
"T_yX",
"=",
"K_yX",
"/",
"K_YX",
"=",
"F_y",
"*",
"k_yX",
"/",
"sum_y",
"(",
"F_y",
"*",
"k_yX",
")"
] | python | train |
OrangeTux/einder | einder/client.py | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L80-L86 | def send_key(self, key):
""" Send a key to the Horizon box. """
cmd = struct.pack(">BBBBBBH", 4, 1, 0, 0, 0, 0, key)
self.con.send(cmd)
cmd = struct.pack(">BBBBBBH", 4, 0, 0, 0, 0, 0, key)
self.con.send(cmd) | [
"def",
"send_key",
"(",
"self",
",",
"key",
")",
":",
"cmd",
"=",
"struct",
".",
"pack",
"(",
"\">BBBBBBH\"",
",",
"4",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"key",
")",
"self",
".",
"con",
".",
"send",
"(",
"cmd",
")",
"cm... | Send a key to the Horizon box. | [
"Send",
"a",
"key",
"to",
"the",
"Horizon",
"box",
"."
] | python | train |
awacha/sastool | sastool/io/twodim.py | https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/io/twodim.py#L438-L478 | def writebdfv2(filename, bdf, bdfext='.bdf', bhfext='.bhf'):
"""Write a version 2 Bessy Data File
Inputs
------
filename: string
the name of the output file. One can give the complete header or
datafile name or just the base name without the extensions.
bdf: dict
the BDF str... | [
"def",
"writebdfv2",
"(",
"filename",
",",
"bdf",
",",
"bdfext",
"=",
"'.bdf'",
",",
"bhfext",
"=",
"'.bhf'",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"bdfext",
")",
":",
"basename",
"=",
"filename",
"[",
":",
"-",
"len",
"(",
"bdfext",
")",... | Write a version 2 Bessy Data File
Inputs
------
filename: string
the name of the output file. One can give the complete header or
datafile name or just the base name without the extensions.
bdf: dict
the BDF structure (in the same format as loaded by ``readbdfv2()``
bdfext: ... | [
"Write",
"a",
"version",
"2",
"Bessy",
"Data",
"File"
] | python | train |
mfitzp/padua | padua/utils.py | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/utils.py#L8-L105 | def qvalues(pv, m = None, verbose = False, lowmem = False, pi0 = None):
"""
Copyright (c) 2012, Nicolo Fusi, University of Sheffield
All rights reserved.
Estimates q-values from p-values
Args
=====
m: number of tests. If not specified m = pv.size
verbose: print verbose messages? (defa... | [
"def",
"qvalues",
"(",
"pv",
",",
"m",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"lowmem",
"=",
"False",
",",
"pi0",
"=",
"None",
")",
":",
"assert",
"(",
"pv",
".",
"min",
"(",
")",
">=",
"0",
"and",
"pv",
".",
"max",
"(",
")",
"<=",
... | Copyright (c) 2012, Nicolo Fusi, University of Sheffield
All rights reserved.
Estimates q-values from p-values
Args
=====
m: number of tests. If not specified m = pv.size
verbose: print verbose messages? (default False)
lowmem: use memory-efficient in-place algorithm
pi0: if None, it'... | [
"Copyright",
"(",
"c",
")",
"2012",
"Nicolo",
"Fusi",
"University",
"of",
"Sheffield",
"All",
"rights",
"reserved",
"."
] | python | train |
mlperf/training | single_stage_detector/ssd/coco.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/single_stage_detector/ssd/coco.py#L200-L209 | def loadAnns(self, ids=[]):
"""
Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects
"""
if _isArrayLike(ids):
return [self.anns[id] for id in ids]
elif type(ids)... | [
"def",
"loadAnns",
"(",
"self",
",",
"ids",
"=",
"[",
"]",
")",
":",
"if",
"_isArrayLike",
"(",
"ids",
")",
":",
"return",
"[",
"self",
".",
"anns",
"[",
"id",
"]",
"for",
"id",
"in",
"ids",
"]",
"elif",
"type",
"(",
"ids",
")",
"==",
"int",
... | Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects | [
"Load",
"anns",
"with",
"the",
"specified",
"ids",
".",
":",
"param",
"ids",
"(",
"int",
"array",
")",
":",
"integer",
"ids",
"specifying",
"anns",
":",
"return",
":",
"anns",
"(",
"object",
"array",
")",
":",
"loaded",
"ann",
"objects"
] | python | train |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1887-L1901 | def write_from_file(library, session, filename, count):
"""Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename:... | [
"def",
"write_from_file",
"(",
"library",
",",
"session",
",",
"filename",
",",
"count",
")",
":",
"return_count",
"=",
"ViUInt32",
"(",
")",
"ret",
"=",
"library",
".",
"viWriteFromFile",
"(",
"session",
",",
"filename",
",",
"count",
",",
"return_count",
... | Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file from which data will be read.
:param count: N... | [
"Take",
"data",
"from",
"a",
"file",
"and",
"write",
"it",
"out",
"synchronously",
"."
] | python | train |
wummel/patool | patoolib/__init__.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L529-L546 | def _handle_archive(archive, command, verbosity=0, interactive=True,
program=None, format=None, compression=None):
"""Test and list archives."""
if format is None:
format, compression = get_archive_format(archive)
check_archive_format(format, compression)
if command not in ('... | [
"def",
"_handle_archive",
"(",
"archive",
",",
"command",
",",
"verbosity",
"=",
"0",
",",
"interactive",
"=",
"True",
",",
"program",
"=",
"None",
",",
"format",
"=",
"None",
",",
"compression",
"=",
"None",
")",
":",
"if",
"format",
"is",
"None",
":"... | Test and list archives. | [
"Test",
"and",
"list",
"archives",
"."
] | python | train |
apache/incubator-heron | heron/instance/src/python/utils/metrics/metrics_helper.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L219-L226 | def _init_multi_count_metrics(self, pplan_helper):
"""Initializes the default values for a necessary set of MultiCountMetrics"""
to_init = [self.metrics[i] for i in self.to_multi_init
if i in self.metrics and isinstance(self.metrics[i], MultiCountMetric)]
for out_stream in pplan_helper.get_my... | [
"def",
"_init_multi_count_metrics",
"(",
"self",
",",
"pplan_helper",
")",
":",
"to_init",
"=",
"[",
"self",
".",
"metrics",
"[",
"i",
"]",
"for",
"i",
"in",
"self",
".",
"to_multi_init",
"if",
"i",
"in",
"self",
".",
"metrics",
"and",
"isinstance",
"(",... | Initializes the default values for a necessary set of MultiCountMetrics | [
"Initializes",
"the",
"default",
"values",
"for",
"a",
"necessary",
"set",
"of",
"MultiCountMetrics"
] | python | valid |
saltstack/salt | salt/utils/network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L58-L64 | def sanitize_host(host):
'''
Sanitize host string.
https://tools.ietf.org/html/rfc1123#section-2.1
'''
RFC952_characters = ascii_letters + digits + ".-"
return "".join([c for c in host[0:255] if c in RFC952_characters]) | [
"def",
"sanitize_host",
"(",
"host",
")",
":",
"RFC952_characters",
"=",
"ascii_letters",
"+",
"digits",
"+",
"\".-\"",
"return",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"host",
"[",
"0",
":",
"255",
"]",
"if",
"c",
"in",
"RFC952_characte... | Sanitize host string.
https://tools.ietf.org/html/rfc1123#section-2.1 | [
"Sanitize",
"host",
"string",
".",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc1123#section",
"-",
"2",
".",
"1"
] | python | train |
mixmastamyk/fr | fr/__init__.py | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L41-L59 | def load_config(options):
''' Load options, platform, colors, and icons. '''
global opts, pform
opts = options
pform = options.pform
global_ns = globals()
# get colors
if pform.hicolor:
global_ns['dim_templ'] = ansi.dim8t
global_ns['swap_clr_templ'] = ansi.csi8_blk % ansi.bl... | [
"def",
"load_config",
"(",
"options",
")",
":",
"global",
"opts",
",",
"pform",
"opts",
"=",
"options",
"pform",
"=",
"options",
".",
"pform",
"global_ns",
"=",
"globals",
"(",
")",
"# get colors",
"if",
"pform",
".",
"hicolor",
":",
"global_ns",
"[",
"'... | Load options, platform, colors, and icons. | [
"Load",
"options",
"platform",
"colors",
"and",
"icons",
"."
] | python | train |
kevin1024/vcrpy | vcr/stubs/__init__.py | https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L129-L135 | def _port_postfix(self):
"""
Returns empty string for the default port and ':port' otherwise
"""
port = self.real_connection.port
default_port = {'https': 443, 'http': 80}[self._protocol]
return ':{}'.format(port) if port != default_port else '' | [
"def",
"_port_postfix",
"(",
"self",
")",
":",
"port",
"=",
"self",
".",
"real_connection",
".",
"port",
"default_port",
"=",
"{",
"'https'",
":",
"443",
",",
"'http'",
":",
"80",
"}",
"[",
"self",
".",
"_protocol",
"]",
"return",
"':{}'",
".",
"format... | Returns empty string for the default port and ':port' otherwise | [
"Returns",
"empty",
"string",
"for",
"the",
"default",
"port",
"and",
":",
"port",
"otherwise"
] | python | train |
jmgilman/Neolib | neolib/pyamf/remoting/amf0.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/amf0.py#L21-L37 | def authenticateRequest(self, request, service_request, *args, **kwargs):
"""
Authenticates the request against the service.
@param request: The AMF request
@type request: L{Request<pyamf.remoting.Request>}
"""
username = password = None
if 'Credentials' in requ... | [
"def",
"authenticateRequest",
"(",
"self",
",",
"request",
",",
"service_request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"username",
"=",
"password",
"=",
"None",
"if",
"'Credentials'",
"in",
"request",
".",
"headers",
":",
"cred",
"=",
"r... | Authenticates the request against the service.
@param request: The AMF request
@type request: L{Request<pyamf.remoting.Request>} | [
"Authenticates",
"the",
"request",
"against",
"the",
"service",
"."
] | python | train |
O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/utils/utils.py#L1134-L1148 | def order_by(self, attribute=None, *, ascending=True):
""" Applies a order_by clause
:param str attribute: attribute to apply on
:param bool ascending: should it apply ascending order or descending
:rtype: Query
"""
attribute = self._get_mapping(attribute) or self._attri... | [
"def",
"order_by",
"(",
"self",
",",
"attribute",
"=",
"None",
",",
"*",
",",
"ascending",
"=",
"True",
")",
":",
"attribute",
"=",
"self",
".",
"_get_mapping",
"(",
"attribute",
")",
"or",
"self",
".",
"_attribute",
"if",
"attribute",
":",
"self",
"."... | Applies a order_by clause
:param str attribute: attribute to apply on
:param bool ascending: should it apply ascending order or descending
:rtype: Query | [
"Applies",
"a",
"order_by",
"clause"
] | python | train |
christophertbrown/bioscripts | ctbBio/rRNA_insertions.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/rRNA_insertions.py#L212-L229 | def seqs2bool(seqs):
"""
convert orf and intron information to boolean
# seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]]
# seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]]
"""
for seq in s... | [
"def",
"seqs2bool",
"(",
"seqs",
")",
":",
"for",
"seq",
"in",
"seqs",
":",
"for",
"i",
",",
"ins",
"in",
"enumerate",
"(",
"seqs",
"[",
"seq",
"]",
"[",
"2",
"]",
")",
":",
"if",
"len",
"(",
"ins",
"[",
"4",
"]",
")",
">",
"0",
":",
"ins",... | convert orf and intron information to boolean
# seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]]
# seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]] | [
"convert",
"orf",
"and",
"intron",
"information",
"to",
"boolean",
"#",
"seqs",
"[",
"id",
"]",
"=",
"[",
"gene",
"model",
"[[",
"i",
"-",
"gene_pos",
"i",
"-",
"model_pos",
"i",
"-",
"length",
"iseq",
"[",
"orfs",
"]",
"[",
"introns",
"]]",
"...",
... | python | train |
bitesofcode/projexui | projexui/widgets/xorbquerywidget/xorbquickfilterwidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquickfilterwidget.py#L190-L208 | def setQuery(self, query):
"""
Sets the query information for this filter widget.
:param query | <orb.Query> || None
"""
if query is None:
return
count = {}
for widget in self.findChildren(QWidget):
... | [
"def",
"setQuery",
"(",
"self",
",",
"query",
")",
":",
"if",
"query",
"is",
"None",
":",
"return",
"count",
"=",
"{",
"}",
"for",
"widget",
"in",
"self",
".",
"findChildren",
"(",
"QWidget",
")",
":",
"column",
"=",
"nativestring",
"(",
"widget",
".... | Sets the query information for this filter widget.
:param query | <orb.Query> || None | [
"Sets",
"the",
"query",
"information",
"for",
"this",
"filter",
"widget",
".",
":",
"param",
"query",
"|",
"<orb",
".",
"Query",
">",
"||",
"None"
] | python | train |
jendrikseipp/vulture | vulture/core.py | https://github.com/jendrikseipp/vulture/blob/fed11fb7e7ed065058a9fb1acd10052ece37f984/vulture/core.py#L510-L519 | def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
for _, value in ast.iter_fields(node):
if isinstance(value, list):
self._handle_ast_list(value)
for item in value:
if isinstance(item, ast.AST):
... | [
"def",
"generic_visit",
"(",
"self",
",",
"node",
")",
":",
"for",
"_",
",",
"value",
"in",
"ast",
".",
"iter_fields",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"self",
".",
"_handle_ast_list",
"(",
"value",
")",... | Called if no explicit visitor function exists for a node. | [
"Called",
"if",
"no",
"explicit",
"visitor",
"function",
"exists",
"for",
"a",
"node",
"."
] | python | train |
scour-project/scour | scour/scour.py | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L857-L872 | def removeUnreferencedIDs(referencedIDs, identifiedElements):
"""
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
"""
global _num_ids_removed
keepTags = ['font']
num = 0
for id in identifiedElements:
node = identifiedElements[id]
if id... | [
"def",
"removeUnreferencedIDs",
"(",
"referencedIDs",
",",
"identifiedElements",
")",
":",
"global",
"_num_ids_removed",
"keepTags",
"=",
"[",
"'font'",
"]",
"num",
"=",
"0",
"for",
"id",
"in",
"identifiedElements",
":",
"node",
"=",
"identifiedElements",
"[",
"... | Removes the unreferenced ID attributes.
Returns the number of ID attributes removed | [
"Removes",
"the",
"unreferenced",
"ID",
"attributes",
"."
] | python | train |
PSPC-SPAC-buyandsell/von_agent | von_agent/agent/holder_prover.py | https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/agent/holder_prover.py#L539-L550 | def rev_regs(self) -> list:
"""
Return list of revocation registry identifiers for which HolderProver has tails files.
:return: list of revocation registry identifiers for which HolderProver has tails files
"""
LOGGER.debug('HolderProver.rev_regs >>>')
rv = [basename(f... | [
"def",
"rev_regs",
"(",
"self",
")",
"->",
"list",
":",
"LOGGER",
".",
"debug",
"(",
"'HolderProver.rev_regs >>>'",
")",
"rv",
"=",
"[",
"basename",
"(",
"f",
")",
"for",
"f",
"in",
"Tails",
".",
"links",
"(",
"self",
".",
"_dir_tails",
")",
"]",
"LO... | Return list of revocation registry identifiers for which HolderProver has tails files.
:return: list of revocation registry identifiers for which HolderProver has tails files | [
"Return",
"list",
"of",
"revocation",
"registry",
"identifiers",
"for",
"which",
"HolderProver",
"has",
"tails",
"files",
"."
] | python | train |
ibelie/typy | typy/google/protobuf/internal/well_known_types.py | https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/internal/well_known_types.py#L272-L299 | def FromJsonString(self, value):
"""Converts a string to Duration.
Args:
value: A string to be converted. The string must end with 's'. Any
fractional digits (or none) are accepted as long as they fit into
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
Raises:
... | [
"def",
"FromJsonString",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"<",
"1",
"or",
"value",
"[",
"-",
"1",
"]",
"!=",
"'s'",
":",
"raise",
"ParseError",
"(",
"'Duration must end with letter \"s\": {0}.'",
".",
"format",
"(",
"v... | Converts a string to Duration.
Args:
value: A string to be converted. The string must end with 's'. Any
fractional digits (or none) are accepted as long as they fit into
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
Raises:
ParseError: On parsing problems. | [
"Converts",
"a",
"string",
"to",
"Duration",
"."
] | python | valid |
cloudsigma/cgroupspy | cgroupspy/nodes.py | https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L137-L149 | def create_cgroup(self, name):
"""
Create a cgroup by name and attach it under this node.
"""
node = Node(name, parent=self)
if node in self.children:
raise RuntimeError('Node {} already exists under {}'.format(name, self.path))
name = name.encode()
f... | [
"def",
"create_cgroup",
"(",
"self",
",",
"name",
")",
":",
"node",
"=",
"Node",
"(",
"name",
",",
"parent",
"=",
"self",
")",
"if",
"node",
"in",
"self",
".",
"children",
":",
"raise",
"RuntimeError",
"(",
"'Node {} already exists under {}'",
".",
"format... | Create a cgroup by name and attach it under this node. | [
"Create",
"a",
"cgroup",
"by",
"name",
"and",
"attach",
"it",
"under",
"this",
"node",
"."
] | python | train |
rasbt/biopandas | biopandas/mol2/pandas_mol2.py | https://github.com/rasbt/biopandas/blob/615a7cf272692c12bbcfd9d1f217eab440120235/biopandas/mol2/pandas_mol2.py#L250-L271 | def distance_df(df, xyz=(0.00, 0.00, 0.00)):
"""Computes Euclidean distance between atoms and a 3D point.
Parameters
----------
df : DataFrame
DataFrame containing entries similar to the PandasMol2.df
format for the
the distance computation to the `xy... | [
"def",
"distance_df",
"(",
"df",
",",
"xyz",
"=",
"(",
"0.00",
",",
"0.00",
",",
"0.00",
")",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"df",
"[",
"[",
"'x'",
",",
"'y'",
",",
"'z'",
"]",
"]",
".",
"subtract",
"(",
... | Computes Euclidean distance between atoms and a 3D point.
Parameters
----------
df : DataFrame
DataFrame containing entries similar to the PandasMol2.df
format for the
the distance computation to the `xyz` reference coordinates.
xyz : tuple (0.00, 0.0... | [
"Computes",
"Euclidean",
"distance",
"between",
"atoms",
"and",
"a",
"3D",
"point",
"."
] | python | train |
boriel/zxbasic | asmlex.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmlex.py#L293-L297 | def t_LP(self, t):
r'[[(]'
if t.value != '[' and OPTIONS.bracket.value:
t.type = 'LPP'
return t | [
"def",
"t_LP",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
".",
"value",
"!=",
"'['",
"and",
"OPTIONS",
".",
"bracket",
".",
"value",
":",
"t",
".",
"type",
"=",
"'LPP'",
"return",
"t"
] | r'[[(] | [
"r",
"[[",
"(",
"]"
] | python | train |
Esri/ArcREST | src/arcrest/common/geometry.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/geometry.py#L239-L251 | def __geomToPointList(self, geom):
""" converts a geometry object to a common.Geometry object """
if arcpyFound and isinstance(geom, arcpy.Multipoint):
feature_geom = []
fPart = []
for part in geom:
fPart = []
for pnt in part:
... | [
"def",
"__geomToPointList",
"(",
"self",
",",
"geom",
")",
":",
"if",
"arcpyFound",
"and",
"isinstance",
"(",
"geom",
",",
"arcpy",
".",
"Multipoint",
")",
":",
"feature_geom",
"=",
"[",
"]",
"fPart",
"=",
"[",
"]",
"for",
"part",
"in",
"geom",
":",
... | converts a geometry object to a common.Geometry object | [
"converts",
"a",
"geometry",
"object",
"to",
"a",
"common",
".",
"Geometry",
"object"
] | python | train |
bitcraft/pyscroll | pyscroll/data.py | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L45-L106 | def process_animation_queue(self, tile_view):
""" Given the time and the tile view, process tile changes and return them
:param tile_view: rect representing tiles on the screen
:type tile_view: pygame.Rect
:rtype: list
"""
# verify that there are tile s... | [
"def",
"process_animation_queue",
"(",
"self",
",",
"tile_view",
")",
":",
"# verify that there are tile substitutions ready",
"self",
".",
"_update_time",
"(",
")",
"try",
":",
"if",
"self",
".",
"_animation_queue",
"[",
"0",
"]",
".",
"next",
">",
"self",
".",... | Given the time and the tile view, process tile changes and return them
:param tile_view: rect representing tiles on the screen
:type tile_view: pygame.Rect
:rtype: list | [
"Given",
"the",
"time",
"and",
"the",
"tile",
"view",
"process",
"tile",
"changes",
"and",
"return",
"them",
":",
"param",
"tile_view",
":",
"rect",
"representing",
"tiles",
"on",
"the",
"screen",
":",
"type",
"tile_view",
":",
"pygame",
".",
"Rect",
":",
... | python | train |
brian-rose/climlab | climlab/process/process.py | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L212-L282 | def add_subprocess(self, name, proc):
"""Adds a single subprocess to this process.
:param string name: name of the subprocess
:param proc: a Process object
:type proc: :class:`~climlab.process.process.Process`
:raises: :exc:`ValueError`
... | [
"def",
"add_subprocess",
"(",
"self",
",",
"name",
",",
"proc",
")",
":",
"if",
"isinstance",
"(",
"proc",
",",
"Process",
")",
":",
"self",
".",
"subprocess",
".",
"update",
"(",
"{",
"name",
":",
"proc",
"}",
")",
"self",
".",
"has_process_type_list"... | Adds a single subprocess to this process.
:param string name: name of the subprocess
:param proc: a Process object
:type proc: :class:`~climlab.process.process.Process`
:raises: :exc:`ValueError`
if ``proc`` is not a process
... | [
"Adds",
"a",
"single",
"subprocess",
"to",
"this",
"process",
"."
] | python | train |
learningequality/ricecooker | ricecooker/classes/questions.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/questions.py#L341-L370 | def _recursive_url_find(self, item, image_list):
"""
Recursively traverses a dictionary-like data structure for Khan Academy
assessment items in order to search for image links in `url` data attributes,
and if it finds any it adds them to `image_list` and rewrites `url` attribute.
... | [
"def",
"_recursive_url_find",
"(",
"self",
",",
"item",
",",
"image_list",
")",
":",
"recursive_fn",
"=",
"partial",
"(",
"self",
".",
"_recursive_url_find",
",",
"image_list",
"=",
"image_list",
")",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
... | Recursively traverses a dictionary-like data structure for Khan Academy
assessment items in order to search for image links in `url` data attributes,
and if it finds any it adds them to `image_list` and rewrites `url` attribute.
Use cases:
- `backgroundImage.url` attributes for graphs ... | [
"Recursively",
"traverses",
"a",
"dictionary",
"-",
"like",
"data",
"structure",
"for",
"Khan",
"Academy",
"assessment",
"items",
"in",
"order",
"to",
"search",
"for",
"image",
"links",
"in",
"url",
"data",
"attributes",
"and",
"if",
"it",
"finds",
"any",
"i... | python | train |
pyca/pyopenssl | src/OpenSSL/crypto.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2160-L2173 | def get_issuer(self):
"""
Get the CRL's issuer.
.. versionadded:: 16.1.0
:rtype: X509Name
"""
_issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
_openssl_assert(_issuer != _ffi.NULL)
_issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
... | [
"def",
"get_issuer",
"(",
"self",
")",
":",
"_issuer",
"=",
"_lib",
".",
"X509_NAME_dup",
"(",
"_lib",
".",
"X509_CRL_get_issuer",
"(",
"self",
".",
"_crl",
")",
")",
"_openssl_assert",
"(",
"_issuer",
"!=",
"_ffi",
".",
"NULL",
")",
"_issuer",
"=",
"_ff... | Get the CRL's issuer.
.. versionadded:: 16.1.0
:rtype: X509Name | [
"Get",
"the",
"CRL",
"s",
"issuer",
"."
] | python | test |
jeffknupp/sandman | sandman/model/models.py | https://github.com/jeffknupp/sandman/blob/253ea4d15cbccd9f0016d66fedd7478614cc0b2f/sandman/model/models.py#L147-L159 | def from_dict(self, dictionary):
"""Set a set of attributes which correspond to the
:class:`sandman.model.Model`'s columns.
:param dict dictionary: A dictionary of attributes to set on the
instance whose keys are the column names of
the :class:`sandman.model.Model`'s und... | [
"def",
"from_dict",
"(",
"self",
",",
"dictionary",
")",
":",
"for",
"column",
"in",
"self",
".",
"__table__",
".",
"columns",
".",
"keys",
"(",
")",
":",
"value",
"=",
"dictionary",
".",
"get",
"(",
"column",
",",
"None",
")",
"if",
"value",
":",
... | Set a set of attributes which correspond to the
:class:`sandman.model.Model`'s columns.
:param dict dictionary: A dictionary of attributes to set on the
instance whose keys are the column names of
the :class:`sandman.model.Model`'s underlying database table. | [
"Set",
"a",
"set",
"of",
"attributes",
"which",
"correspond",
"to",
"the",
":",
"class",
":",
"sandman",
".",
"model",
".",
"Model",
"s",
"columns",
"."
] | python | train |
sio2project/filetracker | filetracker/client/data_store.py | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/data_store.py#L38-L47 | def add_file(self, name, filename, compress_hint=True):
"""Saves the actual file in the store.
``compress_hint`` suggests whether the file should be compressed
before transfer
Works like :meth:`add_stream`, but ``filename`` is the name of
an existing file in the fil... | [
"def",
"add_file",
"(",
"self",
",",
"name",
",",
"filename",
",",
"compress_hint",
"=",
"True",
")",
":",
"return",
"self",
".",
"add_stream",
"(",
"name",
",",
"open",
"(",
"filename",
",",
"'rb'",
")",
")"
] | Saves the actual file in the store.
``compress_hint`` suggests whether the file should be compressed
before transfer
Works like :meth:`add_stream`, but ``filename`` is the name of
an existing file in the filesystem. | [
"Saves",
"the",
"actual",
"file",
"in",
"the",
"store",
"."
] | python | train |
cggh/scikit-allel | allel/chunked/storage_hdf5.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/chunked/storage_hdf5.py#L34-L50 | def h5ftmp(**kwargs):
"""Create an HDF5 file backed by a temporary file."""
# create temporary file name
suffix = kwargs.pop('suffix', '.h5')
prefix = kwargs.pop('prefix', 'scikit_allel_')
tempdir = kwargs.pop('dir', None)
fn = tempfile.mktemp(suffix=suffix, prefix=prefix, dir=tempdir)
atex... | [
"def",
"h5ftmp",
"(",
"*",
"*",
"kwargs",
")",
":",
"# create temporary file name",
"suffix",
"=",
"kwargs",
".",
"pop",
"(",
"'suffix'",
",",
"'.h5'",
")",
"prefix",
"=",
"kwargs",
".",
"pop",
"(",
"'prefix'",
",",
"'scikit_allel_'",
")",
"tempdir",
"=",
... | Create an HDF5 file backed by a temporary file. | [
"Create",
"an",
"HDF5",
"file",
"backed",
"by",
"a",
"temporary",
"file",
"."
] | python | train |
NLeSC/noodles | examples/soba/soba.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/examples/soba/soba.py#L128-L132 | def run(wf, *, display, n_threads=1):
"""Run the workflow using the dynamic-exclusion worker."""
worker = dynamic_exclusion_worker(display, n_threads)
return noodles.Scheduler(error_handler=display.error_handler)\
.run(worker, get_workflow(wf)) | [
"def",
"run",
"(",
"wf",
",",
"*",
",",
"display",
",",
"n_threads",
"=",
"1",
")",
":",
"worker",
"=",
"dynamic_exclusion_worker",
"(",
"display",
",",
"n_threads",
")",
"return",
"noodles",
".",
"Scheduler",
"(",
"error_handler",
"=",
"display",
".",
"... | Run the workflow using the dynamic-exclusion worker. | [
"Run",
"the",
"workflow",
"using",
"the",
"dynamic",
"-",
"exclusion",
"worker",
"."
] | python | train |
onicagroup/runway | runway/templates/stacker/tfstate_blueprints/tf_state.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/templates/stacker/tfstate_blueprints/tf_state.py#L29-L150 | def create_template(self):
"""Create template (main function called by Stacker)."""
template = self.template
variables = self.get_variables()
self.template.add_version('2010-09-09')
self.template.add_description('Terraform State Resources')
# Conditions
for i in ... | [
"def",
"create_template",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"template",
"variables",
"=",
"self",
".",
"get_variables",
"(",
")",
"self",
".",
"template",
".",
"add_version",
"(",
"'2010-09-09'",
")",
"self",
".",
"template",
".",
"add_d... | Create template (main function called by Stacker). | [
"Create",
"template",
"(",
"main",
"function",
"called",
"by",
"Stacker",
")",
"."
] | python | train |
sffjunkie/astral | src/astral.py | https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1024-L1060 | def daylight(self, date=None, local=True, use_elevation=True):
"""Calculates the daylight time (the time between sunrise and sunset)
:param date: The date for which to calculate daylight.
If no date is specified then the current date will be used.
:type date: :class:`~date... | [
"def",
"daylight",
"(",
"self",
",",
"date",
"=",
"None",
",",
"local",
"=",
"True",
",",
"use_elevation",
"=",
"True",
")",
":",
"if",
"local",
"and",
"self",
".",
"timezone",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Local time requested but Loca... | Calculates the daylight time (the time between sunrise and sunset)
:param date: The date for which to calculate daylight.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location'... | [
"Calculates",
"the",
"daylight",
"time",
"(",
"the",
"time",
"between",
"sunrise",
"and",
"sunset",
")"
] | python | train |
fastai/fastai | old/fastai/transforms.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/transforms.py#L68-L92 | def googlenet_resize(im, targ, min_area_frac, min_aspect_ratio, max_aspect_ratio, flip_hw_p, interpolation=cv2.INTER_AREA):
""" Randomly crop an image with an aspect ratio and returns a squared resized image of size targ
References:
1. https://arxiv.org/pdf/1409.4842.pdf
2. https://arxiv.org/pdf/18... | [
"def",
"googlenet_resize",
"(",
"im",
",",
"targ",
",",
"min_area_frac",
",",
"min_aspect_ratio",
",",
"max_aspect_ratio",
",",
"flip_hw_p",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_AREA",
")",
":",
"h",
",",
"w",
",",
"",
"*",
"_",
"=",
"im",
".",
... | Randomly crop an image with an aspect ratio and returns a squared resized image of size targ
References:
1. https://arxiv.org/pdf/1409.4842.pdf
2. https://arxiv.org/pdf/1802.07888.pdf | [
"Randomly",
"crop",
"an",
"image",
"with",
"an",
"aspect",
"ratio",
"and",
"returns",
"a",
"squared",
"resized",
"image",
"of",
"size",
"targ",
"References",
":",
"1",
".",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1409",
".",
"4842",
... | python | train |
sosreport/sos | sos/policies/__init__.py | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L70-L74 | def is_enabled(self, name):
"""Check if given service name is enabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'enabled'
return False | [
"def",
"is_enabled",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"services",
"and",
"name",
"in",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"[",
"name",
"]",
"[",
"'config'",
"]",
"==",
"'enabled'",
"return",
"False"
] | Check if given service name is enabled | [
"Check",
"if",
"given",
"service",
"name",
"is",
"enabled"
] | python | train |
googleapis/google-cloud-python | logging/google/cloud/logging/handlers/app_engine.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/app_engine.py#L88-L103 | def get_gae_labels(self):
"""Return the labels for GAE app.
If the trace ID can be detected, it will be included as a label.
Currently, no other labels are included.
:rtype: dict
:returns: Labels for GAE app.
"""
gae_labels = {}
trace_id = get_trace_id(... | [
"def",
"get_gae_labels",
"(",
"self",
")",
":",
"gae_labels",
"=",
"{",
"}",
"trace_id",
"=",
"get_trace_id",
"(",
")",
"if",
"trace_id",
"is",
"not",
"None",
":",
"gae_labels",
"[",
"_TRACE_ID_LABEL",
"]",
"=",
"trace_id",
"return",
"gae_labels"
] | Return the labels for GAE app.
If the trace ID can be detected, it will be included as a label.
Currently, no other labels are included.
:rtype: dict
:returns: Labels for GAE app. | [
"Return",
"the",
"labels",
"for",
"GAE",
"app",
"."
] | python | train |
googleapis/google-cloud-python | core/google/cloud/client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/client.py#L48-L82 | def from_service_account_json(cls, json_credentials_path, *args, **kwargs):
"""Factory to retrieve JSON credentials while creating client.
:type json_credentials_path: str
:param json_credentials_path: The path to a private key file (this file
was given to ... | [
"def",
"from_service_account_json",
"(",
"cls",
",",
"json_credentials_path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"credentials\"",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"\"credentials must not be in keyword arguments\"",
")",
"with... | Factory to retrieve JSON credentials while creating client.
:type json_credentials_path: str
:param json_credentials_path: The path to a private key file (this file
was given to you when you created the
service account). This f... | [
"Factory",
"to",
"retrieve",
"JSON",
"credentials",
"while",
"creating",
"client",
"."
] | python | train |
BD2KGenomics/toil-lib | src/toil_lib/tools/mutation_callers.py | https://github.com/BD2KGenomics/toil-lib/blob/022a615fc3dc98fc1aaa7bfd232409962ca44fbd/src/toil_lib/tools/mutation_callers.py#L93-L129 | def run_pindel(job, normal_bam, normal_bai, tumor_bam, tumor_bai, ref, fai):
"""
Calls Pindel to compute indels / deletions
:param JobFunctionWrappingJob job: Passed automatically by Toil
:param str normal_bam: Normal BAM FileStoreID
:param str normal_bai: Normal BAM index FileStoreID
:param st... | [
"def",
"run_pindel",
"(",
"job",
",",
"normal_bam",
",",
"normal_bai",
",",
"tumor_bam",
",",
"tumor_bai",
",",
"ref",
",",
"fai",
")",
":",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"file_ids",
"=",
"[",
"normal_bam",
"... | Calls Pindel to compute indels / deletions
:param JobFunctionWrappingJob job: Passed automatically by Toil
:param str normal_bam: Normal BAM FileStoreID
:param str normal_bai: Normal BAM index FileStoreID
:param str tumor_bam: Tumor BAM FileStoreID
:param str tumor_bai: Tumor BAM Index FileStoreID
... | [
"Calls",
"Pindel",
"to",
"compute",
"indels",
"/",
"deletions"
] | python | test |
summanlp/textrank | summa/preprocessing/snowball.py | https://github.com/summanlp/textrank/blob/6844bbe8c4b2b468020ae0dfd6574a743f9ad442/summa/preprocessing/snowball.py#L1875-L2017 | def stem(self, word):
"""
Stem an Hungarian word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
"""
word = word.lower()
r1 = self.__r1_hungarian(word, sel... | [
"def",
"stem",
"(",
"self",
",",
"word",
")",
":",
"word",
"=",
"word",
".",
"lower",
"(",
")",
"r1",
"=",
"self",
".",
"__r1_hungarian",
"(",
"word",
",",
"self",
".",
"__vowels",
",",
"self",
".",
"__digraphs",
")",
"# STEP 1: Remove instrumental case"... | Stem an Hungarian word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode | [
"Stem",
"an",
"Hungarian",
"word",
"and",
"return",
"the",
"stemmed",
"form",
"."
] | python | train |
gwastro/pycbc | pycbc/inference/io/base_mcmc.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L35-L47 | def write_resume_point(self):
"""Keeps a list of the number of iterations that were in a file when a
run was resumed from a checkpoint."""
try:
resume_pts = self.attrs["resume_points"].tolist()
except KeyError:
resume_pts = []
try:
niterations ... | [
"def",
"write_resume_point",
"(",
"self",
")",
":",
"try",
":",
"resume_pts",
"=",
"self",
".",
"attrs",
"[",
"\"resume_points\"",
"]",
".",
"tolist",
"(",
")",
"except",
"KeyError",
":",
"resume_pts",
"=",
"[",
"]",
"try",
":",
"niterations",
"=",
"self... | Keeps a list of the number of iterations that were in a file when a
run was resumed from a checkpoint. | [
"Keeps",
"a",
"list",
"of",
"the",
"number",
"of",
"iterations",
"that",
"were",
"in",
"a",
"file",
"when",
"a",
"run",
"was",
"resumed",
"from",
"a",
"checkpoint",
"."
] | python | train |
IdentityPython/pysaml2 | src/saml2/soap.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/soap.py#L253-L280 | def soap_fault(message=None, actor=None, code=None, detail=None):
""" Create a SOAP Fault message
:param message: Human readable error message
:param actor: Who discovered the error
:param code: Error code
:param detail: More specific error message
:return: A SOAP Fault message as a string
... | [
"def",
"soap_fault",
"(",
"message",
"=",
"None",
",",
"actor",
"=",
"None",
",",
"code",
"=",
"None",
",",
"detail",
"=",
"None",
")",
":",
"_string",
"=",
"_actor",
"=",
"_code",
"=",
"_detail",
"=",
"None",
"if",
"message",
":",
"_string",
"=",
... | Create a SOAP Fault message
:param message: Human readable error message
:param actor: Who discovered the error
:param code: Error code
:param detail: More specific error message
:return: A SOAP Fault message as a string | [
"Create",
"a",
"SOAP",
"Fault",
"message"
] | python | train |
Microsoft/nni | tools/nni_trial_tool/hdfsClientUtility.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L48-L67 | def copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient, override=True):
'''Copy file from HDFS to local'''
if not hdfsClient.exists(hdfsFilePath):
raise Exception('HDFS file {} does not exist!'.format(hdfsFilePath))
try:
file_status = hdfsClient.get_file_status(hdfsFilePath)
... | [
"def",
"copyHdfsFileToLocal",
"(",
"hdfsFilePath",
",",
"localFilePath",
",",
"hdfsClient",
",",
"override",
"=",
"True",
")",
":",
"if",
"not",
"hdfsClient",
".",
"exists",
"(",
"hdfsFilePath",
")",
":",
"raise",
"Exception",
"(",
"'HDFS file {} does not exist!'"... | Copy file from HDFS to local | [
"Copy",
"file",
"from",
"HDFS",
"to",
"local"
] | python | train |
geophysics-ubonn/crtomo_tools | lib/crtomo/tdManager.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/tdManager.py#L1686-L1698 | def register_forward_model(self, pid_mag, pid_pha):
"""Register parameter sets as the forward models for magnitude and
phase
Parameters
----------
pid_mag: int
parameter id corresponding to the magnitude model
pid_pha: int
parameter id correspondi... | [
"def",
"register_forward_model",
"(",
"self",
",",
"pid_mag",
",",
"pid_pha",
")",
":",
"self",
".",
"register_magnitude_model",
"(",
"pid_mag",
")",
"self",
".",
"register_phase_model",
"(",
"pid_pha",
")"
] | Register parameter sets as the forward models for magnitude and
phase
Parameters
----------
pid_mag: int
parameter id corresponding to the magnitude model
pid_pha: int
parameter id corresponding to the phase model | [
"Register",
"parameter",
"sets",
"as",
"the",
"forward",
"models",
"for",
"magnitude",
"and",
"phase"
] | python | train |
dmwm/DBS | Server/Python/src/dbs/business/DBSMigrate.py | https://github.com/dmwm/DBS/blob/9619bafce3783b3e77f0415f8f9a258e33dd1e6f/Server/Python/src/dbs/business/DBSMigrate.py#L77-L120 | def prepareDatasetMigrationList(self, conn, request):
"""
Prepare the ordered lists of blocks based on input DATASET (note Block is different)
1. Get list of blocks from source
2. Check and see if these blocks are already at DST
3. Check if dataset has parents
... | [
"def",
"prepareDatasetMigrationList",
"(",
"self",
",",
"conn",
",",
"request",
")",
":",
"ordered_dict",
"=",
"{",
"}",
"order_counter",
"=",
"0",
"srcdataset",
"=",
"request",
"[",
"\"migration_input\"",
"]",
"url",
"=",
"request",
"[",
"\"migration_url\"",
... | Prepare the ordered lists of blocks based on input DATASET (note Block is different)
1. Get list of blocks from source
2. Check and see if these blocks are already at DST
3. Check if dataset has parents
4. Check if parent blocks are already at DST | [
"Prepare",
"the",
"ordered",
"lists",
"of",
"blocks",
"based",
"on",
"input",
"DATASET",
"(",
"note",
"Block",
"is",
"different",
")",
"1",
".",
"Get",
"list",
"of",
"blocks",
"from",
"source",
"2",
".",
"Check",
"and",
"see",
"if",
"these",
"blocks",
... | python | train |
cds-astro/mocpy | mocpy/moc/moc.py | https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L646-L712 | def plot(self, title='MOC', frame=None):
"""
Plot the MOC object using a mollweide projection.
**Deprecated**: New `fill` and `border` methods produce more reliable results and allow you to specify additional
matplotlib style parameters.
Parameters
----------
t... | [
"def",
"plot",
"(",
"self",
",",
"title",
"=",
"'MOC'",
",",
"frame",
"=",
"None",
")",
":",
"frame",
"=",
"ICRS",
"(",
")",
"if",
"frame",
"is",
"None",
"else",
"frame",
"from",
"matplotlib",
".",
"colors",
"import",
"LinearSegmentedColormap",
"import",... | Plot the MOC object using a mollweide projection.
**Deprecated**: New `fill` and `border` methods produce more reliable results and allow you to specify additional
matplotlib style parameters.
Parameters
----------
title : str
The title of the plot
frame : ... | [
"Plot",
"the",
"MOC",
"object",
"using",
"a",
"mollweide",
"projection",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/core/states/container_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1390-L1400 | def get_scoped_variable_from_name(self, name):
""" Get the scoped variable for a unique name
:param name: the unique name of the scoped variable
:return: the scoped variable specified by the name
:raises exceptions.AttributeError: if the name is not in the the scoped_variables dictionar... | [
"def",
"get_scoped_variable_from_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"scoped_variable_id",
",",
"scoped_variable",
"in",
"self",
".",
"scoped_variables",
".",
"items",
"(",
")",
":",
"if",
"scoped_variable",
".",
"name",
"==",
"name",
":",
"retur... | Get the scoped variable for a unique name
:param name: the unique name of the scoped variable
:return: the scoped variable specified by the name
:raises exceptions.AttributeError: if the name is not in the the scoped_variables dictionary | [
"Get",
"the",
"scoped",
"variable",
"for",
"a",
"unique",
"name"
] | python | train |
JNRowe/jnrbase | jnrbase/httplib2_certs.py | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/httplib2_certs.py#L41-L76 | def find_certs() -> str:
"""Find suitable certificates for ``httplib2``.
Warning:
The default behaviour is to fall back to the bundled certificates when
no system certificates can be found. If you're packaging ``jnrbase``
*please* set ``ALLOW_FALLBACK`` to ``False`` to disable this ver... | [
"def",
"find_certs",
"(",
")",
"->",
"str",
":",
"bundle",
"=",
"path",
".",
"realpath",
"(",
"path",
".",
"dirname",
"(",
"httplib2",
".",
"CA_CERTS",
")",
")",
"# Some distros symlink the bundled path location to the system certs",
"if",
"not",
"bundle",
".",
... | Find suitable certificates for ``httplib2``.
Warning:
The default behaviour is to fall back to the bundled certificates when
no system certificates can be found. If you're packaging ``jnrbase``
*please* set ``ALLOW_FALLBACK`` to ``False`` to disable this very much
unwanted behaviou... | [
"Find",
"suitable",
"certificates",
"for",
"httplib2",
"."
] | python | train |
openvax/mhcflurry | mhcflurry/class1_neural_network.py | https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_neural_network.py#L226-L253 | def network(self, borrow=False):
"""
Return the keras model associated with this predictor.
Parameters
----------
borrow : bool
Whether to return a cached model if possible. See
borrow_cached_network for details
Returns
-------
ke... | [
"def",
"network",
"(",
"self",
",",
"borrow",
"=",
"False",
")",
":",
"if",
"self",
".",
"_network",
"is",
"None",
"and",
"self",
".",
"network_json",
"is",
"not",
"None",
":",
"self",
".",
"load_weights",
"(",
")",
"if",
"borrow",
":",
"return",
"se... | Return the keras model associated with this predictor.
Parameters
----------
borrow : bool
Whether to return a cached model if possible. See
borrow_cached_network for details
Returns
-------
keras.models.Model | [
"Return",
"the",
"keras",
"model",
"associated",
"with",
"this",
"predictor",
"."
] | python | train |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/inventory/__init__.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L196-L208 | def _hosts_in_unenumerated_pattern(self, pattern):
""" Get all host names matching the pattern """
hosts = {}
# ignore any negative checks here, this is handled elsewhere
pattern = pattern.replace("!","").replace("&", "")
groups = self.get_groups()
for group in groups:
... | [
"def",
"_hosts_in_unenumerated_pattern",
"(",
"self",
",",
"pattern",
")",
":",
"hosts",
"=",
"{",
"}",
"# ignore any negative checks here, this is handled elsewhere",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"\"!\"",
",",
"\"\"",
")",
".",
"replace",
"(",
... | Get all host names matching the pattern | [
"Get",
"all",
"host",
"names",
"matching",
"the",
"pattern"
] | python | train |
deifyed/vault | libconman/target.py | https://github.com/deifyed/vault/blob/e3c37ade6c3e6b61a76ec6cd2ba98881c7401d97/libconman/target.py#L83-L90 | def deploy(self):
'''
Creates a link at the original path of this target
'''
if not os.path.exists(self.path):
makedirs(self.path)
link(self.vault_path, self.real_path) | [
"def",
"deploy",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"makedirs",
"(",
"self",
".",
"path",
")",
"link",
"(",
"self",
".",
"vault_path",
",",
"self",
".",
"real_path",
")"
] | Creates a link at the original path of this target | [
"Creates",
"a",
"link",
"at",
"the",
"original",
"path",
"of",
"this",
"target"
] | python | train |
mitsei/dlkit | dlkit/json_/assessment/searches.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/searches.py#L218-L230 | def get_assessments(self):
"""Gets the assessment list resulting from the search.
return: (osid.assessment.AssessmentList) - the assessment list
raise: IllegalState - the assessment list has already been
retrieved
*compliance: mandatory -- This method must be implemente... | [
"def",
"get_assessments",
"(",
"self",
")",
":",
"if",
"self",
".",
"retrieved",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'List has already been retrieved.'",
")",
"self",
".",
"retrieved",
"=",
"True",
"return",
"objects",
".",
"AssessmentList",
"(",
... | Gets the assessment list resulting from the search.
return: (osid.assessment.AssessmentList) - the assessment list
raise: IllegalState - the assessment list has already been
retrieved
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"assessment",
"list",
"resulting",
"from",
"the",
"search",
"."
] | python | train |
trivago/Protector | contrib/helpers/benchmark.py | https://github.com/trivago/Protector/blob/7ebe7bde965e27737b961a0cb5740724d174fdc7/contrib/helpers/benchmark.py#L9-L17 | def batches(iterable, n=1):
"""
From http://stackoverflow.com/a/8290508/270334
:param n:
:param iterable:
"""
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)] | [
"def",
"batches",
"(",
"iterable",
",",
"n",
"=",
"1",
")",
":",
"l",
"=",
"len",
"(",
"iterable",
")",
"for",
"ndx",
"in",
"range",
"(",
"0",
",",
"l",
",",
"n",
")",
":",
"yield",
"iterable",
"[",
"ndx",
":",
"min",
"(",
"ndx",
"+",
"n",
... | From http://stackoverflow.com/a/8290508/270334
:param n:
:param iterable: | [
"From",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"8290508",
"/",
"270334",
":",
"param",
"n",
":",
":",
"param",
"iterable",
":"
] | python | valid |
viniciuschiele/flask-io | flask_io/tracing.py | https://github.com/viniciuschiele/flask-io/blob/4e559419b3d8e6859f83fa16557b00542d5f3aa7/flask_io/tracing.py#L71-L97 | def __collect_trace_data(self, request, response, error, latency):
"""
Collects the tracing data from the given parameters.
:param request: The Flask request.
:param response: The flask response.
:param error: The error occurred if any.
:param latency: The time elapsed to... | [
"def",
"__collect_trace_data",
"(",
"self",
",",
"request",
",",
"response",
",",
"error",
",",
"latency",
")",
":",
"data",
"=",
"OrderedDict",
"(",
")",
"data",
"[",
"'latency'",
"]",
"=",
"latency",
".",
"elapsed",
"data",
"[",
"'request_method'",
"]",
... | Collects the tracing data from the given parameters.
:param request: The Flask request.
:param response: The flask response.
:param error: The error occurred if any.
:param latency: The time elapsed to process the request.
:return: The tracing data. | [
"Collects",
"the",
"tracing",
"data",
"from",
"the",
"given",
"parameters",
".",
":",
"param",
"request",
":",
"The",
"Flask",
"request",
".",
":",
"param",
"response",
":",
"The",
"flask",
"response",
".",
":",
"param",
"error",
":",
"The",
"error",
"oc... | python | train |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/utilites/common_utils.py | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/utilites/common_utils.py#L11-L22 | def back_slash_to_front_converter(string):
"""
Replacing all \ in the str to /
:param string: single string to modify
:type string: str
"""
try:
if not string or not isinstance(string, str):
return string
return string.replace('\\', '/')
except Exception:
... | [
"def",
"back_slash_to_front_converter",
"(",
"string",
")",
":",
"try",
":",
"if",
"not",
"string",
"or",
"not",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"return",
"string",
"return",
"string",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"e... | Replacing all \ in the str to /
:param string: single string to modify
:type string: str | [
"Replacing",
"all",
"\\",
"in",
"the",
"str",
"to",
"/",
":",
"param",
"string",
":",
"single",
"string",
"to",
"modify",
":",
"type",
"string",
":",
"str"
] | python | train |
urinieto/msaf | msaf/algorithms/cnmf/segmenter.py | https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/algorithms/cnmf/segmenter.py#L78-L95 | def filter_activation_matrix(G, R):
"""Filters the activation matrix G, and returns a flattened copy."""
#import pylab as plt
#plt.imshow(G, interpolation="nearest", aspect="auto")
#plt.show()
idx = np.argmax(G, axis=1)
max_idx = np.arange(G.shape[0])
max_idx = (max_idx, idx.flatten())
... | [
"def",
"filter_activation_matrix",
"(",
"G",
",",
"R",
")",
":",
"#import pylab as plt",
"#plt.imshow(G, interpolation=\"nearest\", aspect=\"auto\")",
"#plt.show()",
"idx",
"=",
"np",
".",
"argmax",
"(",
"G",
",",
"axis",
"=",
"1",
")",
"max_idx",
"=",
"np",
".",
... | Filters the activation matrix G, and returns a flattened copy. | [
"Filters",
"the",
"activation",
"matrix",
"G",
"and",
"returns",
"a",
"flattened",
"copy",
"."
] | python | test |
amelchio/pysonos | pysonos/events.py | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L586-L633 | def unsubscribe(self):
"""Unsubscribe from the service's events.
Once unsubscribed, a Subscription instance should not be reused
"""
# Trying to unsubscribe if already unsubscribed, or not yet
# subscribed, fails silently
if self._has_been_unsubscribed or not self.is_sub... | [
"def",
"unsubscribe",
"(",
"self",
")",
":",
"# Trying to unsubscribe if already unsubscribed, or not yet",
"# subscribed, fails silently",
"if",
"self",
".",
"_has_been_unsubscribed",
"or",
"not",
"self",
".",
"is_subscribed",
":",
"return",
"# Cancel any auto renew",
"self"... | Unsubscribe from the service's events.
Once unsubscribed, a Subscription instance should not be reused | [
"Unsubscribe",
"from",
"the",
"service",
"s",
"events",
"."
] | python | train |
brocade/pynos | pynos/versions/base/yang/brocade_ras.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/brocade_ras.py#L429-L439 | def support_support_param_directory(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
support_param = ET.SubElement(support, "support-param")
directory = ET.SubEle... | [
"def",
"support_support_param_directory",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"support",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"support\"",
",",
"xmlns",
"=",
"\"urn:bro... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
ergo/ziggurat_foundations | ziggurat_foundations/models/services/resource_tree_postgres.py | https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/resource_tree_postgres.py#L318-L339 | def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs):
"""
Sets node position for new node in the tree
:param resource_id: resource to move
:param to_position: new position
:param db_session:
:return:def count_children(cls, resource_id, db_ses... | [
"def",
"set_position",
"(",
"cls",
",",
"resource_id",
",",
"to_position",
",",
"db_session",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"db_session",
"=",
"get_db_session",
"(",
"db_session",
")",
"# lets lock rows to prevent bad tree sta... | Sets node position for new node in the tree
:param resource_id: resource to move
:param to_position: new position
:param db_session:
:return:def count_children(cls, resource_id, db_session=None): | [
"Sets",
"node",
"position",
"for",
"new",
"node",
"in",
"the",
"tree"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/translate.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/translate.py#L278-L284 | def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False):
"""Get vocab for distill problems."""
# We assume that vocab file is present in data_dir directory where the
# data generated will be stored.
vocab_filepath = os.path.join(data_dir, self.vocab_filename)
encoder = text_encoder.Subword... | [
"def",
"get_or_create_vocab",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
",",
"force_get",
"=",
"False",
")",
":",
"# We assume that vocab file is present in data_dir directory where the",
"# data generated will be stored.",
"vocab_filepath",
"=",
"os",
".",
"path",
".",... | Get vocab for distill problems. | [
"Get",
"vocab",
"for",
"distill",
"problems",
"."
] | python | train |
scdoshi/django-bits | bits/templatetags/custom_utils.py | https://github.com/scdoshi/django-bits/blob/0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f/bits/templatetags/custom_utils.py#L19-L37 | def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
if not widget:
wid... | [
"def",
"as_widget",
"(",
"self",
",",
"widget",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"only_initial",
"=",
"False",
")",
":",
"if",
"not",
"widget",
":",
"widget",
"=",
"self",
".",
"field",
".",
"widget",
"attrs",
"=",
"attrs",
"or",
"{",
"... | Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used. | [
"Renders",
"the",
"field",
"by",
"rendering",
"the",
"passed",
"widget",
"adding",
"any",
"HTML",
"attributes",
"passed",
"as",
"attrs",
".",
"If",
"no",
"widget",
"is",
"specified",
"then",
"the",
"field",
"s",
"default",
"widget",
"will",
"be",
"used",
"... | python | train |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/translation/update.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/translation/update.py#L31-L46 | def cli(env, context_id, translation_id, static_ip, remote_ip, note):
"""Update an address translation for an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
succeeded = manager.update_... | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"translation_id",
",",
"static_ip",
",",
"remote_ip",
",",
"note",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"succeeded",
"=",
"manager",
".",
"update_trans... | Update an address translation for an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices. | [
"Update",
"an",
"address",
"translation",
"for",
"an",
"IPSEC",
"tunnel",
"context",
"."
] | python | train |
openwisp/netjsonconfig | netjsonconfig/utils.py | https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/utils.py#L114-L122 | def get_copy(dict_, key, default=None):
"""
Looks for a key in a dictionary, if found returns
a deepcopied value, otherwise returns default value
"""
value = dict_.get(key, default)
if value:
return deepcopy(value)
return value | [
"def",
"get_copy",
"(",
"dict_",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"value",
"=",
"dict_",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"value",
":",
"return",
"deepcopy",
"(",
"value",
")",
"return",
"value"
] | Looks for a key in a dictionary, if found returns
a deepcopied value, otherwise returns default value | [
"Looks",
"for",
"a",
"key",
"in",
"a",
"dictionary",
"if",
"found",
"returns",
"a",
"deepcopied",
"value",
"otherwise",
"returns",
"default",
"value"
] | python | valid |
sdss/tree | python/tree/tree.py | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L185-L202 | def get_paths(self, key):
''' Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the path... | [
"def",
"get_paths",
"(",
"self",
",",
"key",
")",
":",
"newkey",
"=",
"key",
"if",
"key",
"in",
"self",
".",
"environ",
"else",
"key",
".",
"upper",
"(",
")",
"if",
"key",
".",
"upper",
"(",
")",
"in",
"self",
".",
"environ",
"else",
"None",
"if"... | Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the paths from the
specified s... | [
"Retrieve",
"a",
"set",
"of",
"environment",
"paths",
"from",
"the",
"config"
] | python | train |
adewes/blitzdb | blitzdb/backends/file/queries.py | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L27-L48 | def filter_query(key, expression):
"""Filter documents with a key that satisfies an expression."""
if (isinstance(expression, dict)
and len(expression) == 1
and list(expression.keys())[0].startswith('$')):
compiled_expression = compile_query(expression)
elif callable(expressi... | [
"def",
"filter_query",
"(",
"key",
",",
"expression",
")",
":",
"if",
"(",
"isinstance",
"(",
"expression",
",",
"dict",
")",
"and",
"len",
"(",
"expression",
")",
"==",
"1",
"and",
"list",
"(",
"expression",
".",
"keys",
"(",
")",
")",
"[",
"0",
"... | Filter documents with a key that satisfies an expression. | [
"Filter",
"documents",
"with",
"a",
"key",
"that",
"satisfies",
"an",
"expression",
"."
] | python | train |
FutunnOpen/futuquant | futuquant/examples/TinyQuant/TinyQuantFrame.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/examples/TinyQuant/TinyQuantFrame.py#L130-L153 | def get_tiny_trade_order(self, order_id, acc_id=0):
"""得到订单信息"""
ret, data = self._trade_ctx.order_list_query(order_id=order_id, status_filter_list=[], code='', start='',
end='', trd_env=self._env_type, acc_id=acc_id)
if ret != ft.RET_OK:
... | [
"def",
"get_tiny_trade_order",
"(",
"self",
",",
"order_id",
",",
"acc_id",
"=",
"0",
")",
":",
"ret",
",",
"data",
"=",
"self",
".",
"_trade_ctx",
".",
"order_list_query",
"(",
"order_id",
"=",
"order_id",
",",
"status_filter_list",
"=",
"[",
"]",
",",
... | 得到订单信息 | [
"得到订单信息"
] | python | train |
horazont/aioxmpp | aioxmpp/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L634-L646 | def independent_from(self, other):
"""
Return whether the services are independent (neither depends on
the other).
:param other: Another service.
:type other: :class:`aioxmpp.service.Service`
.. versionadded:: 0.11
"""
if self is other:
retur... | [
"def",
"independent_from",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
"is",
"other",
":",
"return",
"False",
"return",
"not",
"self",
".",
"orders_after",
"(",
"other",
")",
"and",
"not",
"other",
".",
"orders_after",
"(",
"self",
")"
] | Return whether the services are independent (neither depends on
the other).
:param other: Another service.
:type other: :class:`aioxmpp.service.Service`
.. versionadded:: 0.11 | [
"Return",
"whether",
"the",
"services",
"are",
"independent",
"(",
"neither",
"depends",
"on",
"the",
"other",
")",
"."
] | python | train |
sternoru/goscalecms | goscale/themes/site_middleware.py | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/themes/site_middleware.py#L7-L28 | def make_tls_property(default=None):
"""Creates a class-wide instance property with a thread-specific value."""
class TLSProperty(object):
def __init__(self):
from threading import local
self.local = local()
def __get__(self, instance, cls):
if not instance:
... | [
"def",
"make_tls_property",
"(",
"default",
"=",
"None",
")",
":",
"class",
"TLSProperty",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"from",
"threading",
"import",
"local",
"self",
".",
"local",
"=",
"local",
"(",
")",
"def",
"... | Creates a class-wide instance property with a thread-specific value. | [
"Creates",
"a",
"class",
"-",
"wide",
"instance",
"property",
"with",
"a",
"thread",
"-",
"specific",
"value",
"."
] | python | train |
edx/ease | ease/util_functions.py | https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L428-L442 | def get_wordnet_syns(word):
"""
Utilize wordnet (installed with nltk) to get synonyms for words
word is the input word
returns a list of unique synonyms
"""
synonyms = []
regex = r"_"
pat = re.compile(regex)
synset = nltk.wordnet.wordnet.synsets(word)
for ss in synset:
fo... | [
"def",
"get_wordnet_syns",
"(",
"word",
")",
":",
"synonyms",
"=",
"[",
"]",
"regex",
"=",
"r\"_\"",
"pat",
"=",
"re",
".",
"compile",
"(",
"regex",
")",
"synset",
"=",
"nltk",
".",
"wordnet",
".",
"wordnet",
".",
"synsets",
"(",
"word",
")",
"for",
... | Utilize wordnet (installed with nltk) to get synonyms for words
word is the input word
returns a list of unique synonyms | [
"Utilize",
"wordnet",
"(",
"installed",
"with",
"nltk",
")",
"to",
"get",
"synonyms",
"for",
"words",
"word",
"is",
"the",
"input",
"word",
"returns",
"a",
"list",
"of",
"unique",
"synonyms"
] | python | valid |
jopohl/urh | src/urh/ainterpretation/AutoInterpretation.py | https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/ainterpretation/AutoInterpretation.py#L28-L47 | def get_most_frequent_value(values: list):
"""
Return the most frequent value in list.
If there is no unique one, return the maximum of the most frequent values
:param values:
:return:
"""
if len(values) == 0:
return None
most_common = Counter(values).most_common()
result, ... | [
"def",
"get_most_frequent_value",
"(",
"values",
":",
"list",
")",
":",
"if",
"len",
"(",
"values",
")",
"==",
"0",
":",
"return",
"None",
"most_common",
"=",
"Counter",
"(",
"values",
")",
".",
"most_common",
"(",
")",
"result",
",",
"max_count",
"=",
... | Return the most frequent value in list.
If there is no unique one, return the maximum of the most frequent values
:param values:
:return: | [
"Return",
"the",
"most",
"frequent",
"value",
"in",
"list",
".",
"If",
"there",
"is",
"no",
"unique",
"one",
"return",
"the",
"maximum",
"of",
"the",
"most",
"frequent",
"values"
] | python | train |
odlgroup/odl | odl/set/sets.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/set/sets.py#L267-L274 | def element(self, inp=None):
"""Return an element from ``inp`` or from scratch."""
if inp is not None:
s = str(inp)[:self.length]
s += ' ' * (self.length - len(s))
return s
else:
return ' ' * self.length | [
"def",
"element",
"(",
"self",
",",
"inp",
"=",
"None",
")",
":",
"if",
"inp",
"is",
"not",
"None",
":",
"s",
"=",
"str",
"(",
"inp",
")",
"[",
":",
"self",
".",
"length",
"]",
"s",
"+=",
"' '",
"*",
"(",
"self",
".",
"length",
"-",
"len",
... | Return an element from ``inp`` or from scratch. | [
"Return",
"an",
"element",
"from",
"inp",
"or",
"from",
"scratch",
"."
] | python | train |
DigitalGlobe/gbdxtools | gbdxtools/images/util/image.py | https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/util/image.py#L65-L81 | def can_acomp(cat_id):
"""
Checks to see if a CatalogID can be atmos. compensated or not.
Args:
catalogID (str): The catalog ID from the platform catalog.
Returns:
available (bool): Whether or not the image can be acomp'd
"""
url = 'https://rda.geobigdata.io/v1/stripMetada... | [
"def",
"can_acomp",
"(",
"cat_id",
")",
":",
"url",
"=",
"'https://rda.geobigdata.io/v1/stripMetadata/{}/capabilities'",
".",
"format",
"(",
"cat_id",
")",
"auth",
"=",
"Auth",
"(",
")",
"r",
"=",
"_req_with_retries",
"(",
"auth",
".",
"gbdx_connection",
",",
"u... | Checks to see if a CatalogID can be atmos. compensated or not.
Args:
catalogID (str): The catalog ID from the platform catalog.
Returns:
available (bool): Whether or not the image can be acomp'd | [
"Checks",
"to",
"see",
"if",
"a",
"CatalogID",
"can",
"be",
"atmos",
".",
"compensated",
"or",
"not",
"."
] | python | valid |
napalm-automation-community/napalm-panos | napalm_panos/panos.py | https://github.com/napalm-automation-community/napalm-panos/blob/9210a81a7a4a47c724d169031414a0743de4b035/napalm_panos/panos.py#L302-L321 | def commit_config(self):
"""
Netmiko is being used to commit the configuration because it takes
a better care of results compared to pan-python.
"""
if self.loaded:
if self.ssh_connection is False:
self._open_ssh()
try:
self... | [
"def",
"commit_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"loaded",
":",
"if",
"self",
".",
"ssh_connection",
"is",
"False",
":",
"self",
".",
"_open_ssh",
"(",
")",
"try",
":",
"self",
".",
"ssh_device",
".",
"commit",
"(",
")",
"time",
".",... | Netmiko is being used to commit the configuration because it takes
a better care of results compared to pan-python. | [
"Netmiko",
"is",
"being",
"used",
"to",
"commit",
"the",
"configuration",
"because",
"it",
"takes",
"a",
"better",
"care",
"of",
"results",
"compared",
"to",
"pan",
"-",
"python",
"."
] | python | train |
jdrumgoole/pymongo_formatter | pymongo_formatter/formatter.py | https://github.com/jdrumgoole/pymongo_formatter/blob/313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b/pymongo_formatter/formatter.py#L80-L99 | def select_fields(doc, field_list):
'''
Take 'doc' and create a new doc using only keys from the 'fields' list.
Supports referencing fields using dotted notation "a.b.c" so we can parse
nested fields the way MongoDB does. The nested field class is a hack. It should
be a sub-class... | [
"def",
"select_fields",
"(",
"doc",
",",
"field_list",
")",
":",
"if",
"field_list",
"is",
"None",
"or",
"len",
"(",
"field_list",
")",
"==",
"0",
":",
"return",
"doc",
"newDoc",
"=",
"Nested_Dict",
"(",
"{",
"}",
")",
"oldDoc",
"=",
"Nested_Dict",
"("... | Take 'doc' and create a new doc using only keys from the 'fields' list.
Supports referencing fields using dotted notation "a.b.c" so we can parse
nested fields the way MongoDB does. The nested field class is a hack. It should
be a sub-class of dict. | [
"Take",
"doc",
"and",
"create",
"a",
"new",
"doc",
"using",
"only",
"keys",
"from",
"the",
"fields",
"list",
".",
"Supports",
"referencing",
"fields",
"using",
"dotted",
"notation",
"a",
".",
"b",
".",
"c",
"so",
"we",
"can",
"parse",
"nested",
"fields",... | python | test |
callowayproject/Transmogrify | transmogrify/processors.py | https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/processors.py#L30-L49 | def parse_size(image, size):
"""
Parse a size string (i.e. "200", "200x100", "x200", etc.) into a
(width, height) tuple.
"""
bits = size.split("x")
if image.size[0] == 0 or image.size[1] == 0:
ratio = 1.0
else:
ratio = float(image.size[0]) ... | [
"def",
"parse_size",
"(",
"image",
",",
"size",
")",
":",
"bits",
"=",
"size",
".",
"split",
"(",
"\"x\"",
")",
"if",
"image",
".",
"size",
"[",
"0",
"]",
"==",
"0",
"or",
"image",
".",
"size",
"[",
"1",
"]",
"==",
"0",
":",
"ratio",
"=",
"1.... | Parse a size string (i.e. "200", "200x100", "x200", etc.) into a
(width, height) tuple. | [
"Parse",
"a",
"size",
"string",
"(",
"i",
".",
"e",
".",
"200",
"200x100",
"x200",
"etc",
".",
")",
"into",
"a",
"(",
"width",
"height",
")",
"tuple",
"."
] | python | train |
untwisted/quickirc | quickirc.py | https://github.com/untwisted/quickirc/blob/4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99/quickirc.py#L184-L197 | def extract_ctcp(self, spin, nick, user, host, target, msg):
"""
it is used to extract ctcp requests into pieces.
"""
# The ctcp delimiter token.
DELIM = '\001'
if not msg.startswith(DELIM) or not msg.endswith(DELIM):
return
ctcp_args =... | [
"def",
"extract_ctcp",
"(",
"self",
",",
"spin",
",",
"nick",
",",
"user",
",",
"host",
",",
"target",
",",
"msg",
")",
":",
"# The ctcp delimiter token.",
"DELIM",
"=",
"'\\001'",
"if",
"not",
"msg",
".",
"startswith",
"(",
"DELIM",
")",
"or",
"not",
... | it is used to extract ctcp requests into pieces. | [
"it",
"is",
"used",
"to",
"extract",
"ctcp",
"requests",
"into",
"pieces",
"."
] | python | train |
johnbywater/eventsourcing | eventsourcing/contrib/suffixtrees/domain/model/suffixtree.py | https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/suffixtrees/domain/model/suffixtree.py#L318-L325 | def register_new_node(suffix_node_id=None):
"""Factory method, registers new node.
"""
node_id = uuid4()
event = Node.Created(originator_id=node_id, suffix_node_id=suffix_node_id)
entity = Node.mutate(event=event)
publish(event)
return entity | [
"def",
"register_new_node",
"(",
"suffix_node_id",
"=",
"None",
")",
":",
"node_id",
"=",
"uuid4",
"(",
")",
"event",
"=",
"Node",
".",
"Created",
"(",
"originator_id",
"=",
"node_id",
",",
"suffix_node_id",
"=",
"suffix_node_id",
")",
"entity",
"=",
"Node",... | Factory method, registers new node. | [
"Factory",
"method",
"registers",
"new",
"node",
"."
] | python | train |
chrisjsewell/jsonextended | jsonextended/utils.py | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L59-L79 | def get_data_path(data, module, check_exists=True):
"""return a directory path to data within a module
Parameters
----------
data : str or list[str]
file name or list of sub-directories
and file name (e.g. ['lammps','data.txt'])
"""
basepath = os.path.dirname(os.path.abspath(in... | [
"def",
"get_data_path",
"(",
"data",
",",
"module",
",",
"check_exists",
"=",
"True",
")",
":",
"basepath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"inspect",
".",
"getfile",
"(",
"module",
")",
")",
")",
... | return a directory path to data within a module
Parameters
----------
data : str or list[str]
file name or list of sub-directories
and file name (e.g. ['lammps','data.txt']) | [
"return",
"a",
"directory",
"path",
"to",
"data",
"within",
"a",
"module"
] | python | train |
saltstack/salt | salt/returners/django_return.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/django_return.py#L70-L82 | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
signaled = dispatch.Signal(
providing_args=['jid', 'load']).send(
sender='save_load', jid=jid, load=load)
for signal in signaled:
log.debug(
'Django returner function \'save_lo... | [
"def",
"save_load",
"(",
"jid",
",",
"load",
",",
"minions",
"=",
"None",
")",
":",
"signaled",
"=",
"dispatch",
".",
"Signal",
"(",
"providing_args",
"=",
"[",
"'jid'",
",",
"'load'",
"]",
")",
".",
"send",
"(",
"sender",
"=",
"'save_load'",
",",
"j... | Save the load to the specified jid | [
"Save",
"the",
"load",
"to",
"the",
"specified",
"jid"
] | python | train |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L216-L222 | def get_short_name(self):
"""Get a short name for the notebook."""
sname = osp.splitext(osp.basename(self.filename))[0]
if len(sname) > 20:
fm = QFontMetrics(QFont())
sname = fm.elidedText(sname, Qt.ElideRight, 110)
return sname | [
"def",
"get_short_name",
"(",
"self",
")",
":",
"sname",
"=",
"osp",
".",
"splitext",
"(",
"osp",
".",
"basename",
"(",
"self",
".",
"filename",
")",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"sname",
")",
">",
"20",
":",
"fm",
"=",
"QFontMetrics",
"... | Get a short name for the notebook. | [
"Get",
"a",
"short",
"name",
"for",
"the",
"notebook",
"."
] | python | train |
ray-project/ray | python/ray/rllib/optimizers/segment_tree.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/segment_tree.py#L59-L83 | def reduce(self, start=0, end=None):
"""Returns result of applying `self.operation`
to a contiguous subsequence of the array.
self.operation(
arr[start], operation(arr[start+1], operation(... arr[end])))
Parameters
----------
start: int
beginni... | [
"def",
"reduce",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"self",
".",
"_capacity",
"-",
"1",
"if",
"end",
"<",
"0",
":",
"end",
"+=",
"self",
".",
"_capacity",
"return"... | Returns result of applying `self.operation`
to a contiguous subsequence of the array.
self.operation(
arr[start], operation(arr[start+1], operation(... arr[end])))
Parameters
----------
start: int
beginning of the subsequence
end: int
... | [
"Returns",
"result",
"of",
"applying",
"self",
".",
"operation",
"to",
"a",
"contiguous",
"subsequence",
"of",
"the",
"array",
"."
] | python | train |
BD2KGenomics/protect | src/protect/pipeline/ProTECT.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/pipeline/ProTECT.py#L860-L901 | def get_patient_bams(job, patient_dict, sample_type, univ_options, bwa_options, mutect_options):
"""
Convenience function to return the bam and its index in the correct format for a sample type.
:param dict patient_dict: dict of patient info
:param str sample_type: 'tumor_rna', 'tumor_dna', 'normal_dna... | [
"def",
"get_patient_bams",
"(",
"job",
",",
"patient_dict",
",",
"sample_type",
",",
"univ_options",
",",
"bwa_options",
",",
"mutect_options",
")",
":",
"output_dict",
"=",
"{",
"}",
"if",
"'dna'",
"in",
"sample_type",
":",
"sample_info",
"=",
"'fix_pg_sorted'"... | Convenience function to return the bam and its index in the correct format for a sample type.
:param dict patient_dict: dict of patient info
:param str sample_type: 'tumor_rna', 'tumor_dna', 'normal_dna'
:param dict univ_options: Dict of universal options used by almost all tools
:param dict bwa_option... | [
"Convenience",
"function",
"to",
"return",
"the",
"bam",
"and",
"its",
"index",
"in",
"the",
"correct",
"format",
"for",
"a",
"sample",
"type",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/http/generic_interface.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L367-L380 | def _results(self, scheduler_instance_id):
"""Get the results of the executed actions for the scheduler which instance id is provided
Calling this method for daemons that are not configured as passive do not make sense.
Indeed, this service should only be exposed on poller and reactionner daemo... | [
"def",
"_results",
"(",
"self",
",",
"scheduler_instance_id",
")",
":",
"with",
"self",
".",
"app",
".",
"lock",
":",
"res",
"=",
"self",
".",
"app",
".",
"get_results_from_passive",
"(",
"scheduler_instance_id",
")",
"return",
"serialize",
"(",
"res",
",",
... | Get the results of the executed actions for the scheduler which instance id is provided
Calling this method for daemons that are not configured as passive do not make sense.
Indeed, this service should only be exposed on poller and reactionner daemons.
:param scheduler_instance_id: instance id... | [
"Get",
"the",
"results",
"of",
"the",
"executed",
"actions",
"for",
"the",
"scheduler",
"which",
"instance",
"id",
"is",
"provided"
] | python | train |
keon/algorithms | algorithms/sort/merge_sort.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/merge_sort.py#L16-L38 | def merge(left, right, merged):
""" Merge helper
Complexity: O(n)
"""
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
# Sort each one and place into the result
if left[left_cursor] <= right[right_cursor]:
merged[left_curs... | [
"def",
"merge",
"(",
"left",
",",
"right",
",",
"merged",
")",
":",
"left_cursor",
",",
"right_cursor",
"=",
"0",
",",
"0",
"while",
"left_cursor",
"<",
"len",
"(",
"left",
")",
"and",
"right_cursor",
"<",
"len",
"(",
"right",
")",
":",
"# Sort each on... | Merge helper
Complexity: O(n) | [
"Merge",
"helper",
"Complexity",
":",
"O",
"(",
"n",
")"
] | python | train |
aio-libs/aiohttp | aiohttp/multipart.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/multipart.py#L435-L443 | def decode(self, data: bytes) -> bytes:
"""Decodes data according the specified Content-Encoding
or Content-Transfer-Encoding headers value.
"""
if CONTENT_TRANSFER_ENCODING in self.headers:
data = self._decode_content_transfer(data)
if CONTENT_ENCODING in self.header... | [
"def",
"decode",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"bytes",
":",
"if",
"CONTENT_TRANSFER_ENCODING",
"in",
"self",
".",
"headers",
":",
"data",
"=",
"self",
".",
"_decode_content_transfer",
"(",
"data",
")",
"if",
"CONTENT_ENCODING",
"in",
... | Decodes data according the specified Content-Encoding
or Content-Transfer-Encoding headers value. | [
"Decodes",
"data",
"according",
"the",
"specified",
"Content",
"-",
"Encoding",
"or",
"Content",
"-",
"Transfer",
"-",
"Encoding",
"headers",
"value",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/external_command.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L2885-L2898 | def enable_performance_data(self):
"""Enable performance data processing (globally)
Format of the line that triggers function call::
ENABLE_PERFORMANCE_DATA
:return: None
"""
if not self.my_conf.process_performance_data:
self.my_conf.modified_attributes |= \... | [
"def",
"enable_performance_data",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"my_conf",
".",
"process_performance_data",
":",
"self",
".",
"my_conf",
".",
"modified_attributes",
"|=",
"DICT_MODATTR",
"[",
"\"MODATTR_PERFORMANCE_DATA_ENABLED\"",
"]",
".",
"valu... | Enable performance data processing (globally)
Format of the line that triggers function call::
ENABLE_PERFORMANCE_DATA
:return: None | [
"Enable",
"performance",
"data",
"processing",
"(",
"globally",
")",
"Format",
"of",
"the",
"line",
"that",
"triggers",
"function",
"call",
"::"
] | python | train |
mwgielen/jackal | jackal/core.py | https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L100-L105 | def argument_count(self):
"""
Uses the command line arguments to fill the count function and call it.
"""
arguments, _ = self.argparser.parse_known_args()
return self.count(**vars(arguments)) | [
"def",
"argument_count",
"(",
"self",
")",
":",
"arguments",
",",
"_",
"=",
"self",
".",
"argparser",
".",
"parse_known_args",
"(",
")",
"return",
"self",
".",
"count",
"(",
"*",
"*",
"vars",
"(",
"arguments",
")",
")"
] | Uses the command line arguments to fill the count function and call it. | [
"Uses",
"the",
"command",
"line",
"arguments",
"to",
"fill",
"the",
"count",
"function",
"and",
"call",
"it",
"."
] | python | valid |
jstitch/MambuPy | MambuPy/mambuconfig.py | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuconfig.py#L119-L152 | def get_conf(conf, sect, opt):
""" Gets a config 'opt' from 'conf' file, under section 'sect'.
If no 'opt' exists under 'sect', it looks for option on the default_configs
dictionary
If there exists an environmental variable named MAMBUPY_{upper_case_opt},
it overrides whatever the conf files or de... | [
"def",
"get_conf",
"(",
"conf",
",",
"sect",
",",
"opt",
")",
":",
"argu",
"=",
"getattr",
"(",
"args",
",",
"\"mambupy_\"",
"+",
"opt",
".",
"lower",
"(",
")",
")",
"if",
"not",
"argu",
":",
"envir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
... | Gets a config 'opt' from 'conf' file, under section 'sect'.
If no 'opt' exists under 'sect', it looks for option on the default_configs
dictionary
If there exists an environmental variable named MAMBUPY_{upper_case_opt},
it overrides whatever the conf files or default_configs dict says.
But if yo... | [
"Gets",
"a",
"config",
"opt",
"from",
"conf",
"file",
"under",
"section",
"sect",
"."
] | python | train |
sassoftware/saspy | saspy/sasdata.py | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L520-L570 | def info(self):
"""
Display the column info on a SAS data object
:return: Pandas data frame
"""
if self.results.casefold() != 'pandas':
print("The info method only works with Pandas results")
return None
info_code = """
data work._statsInf... | [
"def",
"info",
"(",
"self",
")",
":",
"if",
"self",
".",
"results",
".",
"casefold",
"(",
")",
"!=",
"'pandas'",
":",
"print",
"(",
"\"The info method only works with Pandas results\"",
")",
"return",
"None",
"info_code",
"=",
"\"\"\"\n data work._statsInfo ;... | Display the column info on a SAS data object
:return: Pandas data frame | [
"Display",
"the",
"column",
"info",
"on",
"a",
"SAS",
"data",
"object"
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/df/expr/expressions.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/expressions.py#L207-L255 | def persist(self, name, partitions=None, partition=None, lifecycle=None, project=None, **kwargs):
"""
Persist the execution into a new table. If `partitions` not specified,
will create a new table without partitions if the table does not exist,
and insert the SQL result into it.
... | [
"def",
"persist",
"(",
"self",
",",
"name",
",",
"partitions",
"=",
"None",
",",
"partition",
"=",
"None",
",",
"lifecycle",
"=",
"None",
",",
"project",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"lifecycle",
"is",
"None",
"and",
"options... | Persist the execution into a new table. If `partitions` not specified,
will create a new table without partitions if the table does not exist,
and insert the SQL result into it.
If `partitions` are specified, they will be the partition fields of the new table.
If `partition` is specified... | [
"Persist",
"the",
"execution",
"into",
"a",
"new",
"table",
".",
"If",
"partitions",
"not",
"specified",
"will",
"create",
"a",
"new",
"table",
"without",
"partitions",
"if",
"the",
"table",
"does",
"not",
"exist",
"and",
"insert",
"the",
"SQL",
"result",
... | python | train |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L894-L945 | def _shru8(ins):
""" Shift 8bit unsigned integer to the right. The result is pushed onto the stack.
Optimizations:
* If 1nd or 2nd op is 0 then
do nothing
* If 2nd op is < 4 then
unroll loop
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int8(op2)
... | [
"def",
"_shru8",
"(",
"ins",
")",
":",
"op1",
",",
"op2",
"=",
"tuple",
"(",
"ins",
".",
"quad",
"[",
"2",
":",
"]",
")",
"if",
"is_int",
"(",
"op2",
")",
":",
"op2",
"=",
"int8",
"(",
"op2",
")",
"output",
"=",
"_8bit_oper",
"(",
"op1",
")",... | Shift 8bit unsigned integer to the right. The result is pushed onto the stack.
Optimizations:
* If 1nd or 2nd op is 0 then
do nothing
* If 2nd op is < 4 then
unroll loop | [
"Shift",
"8bit",
"unsigned",
"integer",
"to",
"the",
"right",
".",
"The",
"result",
"is",
"pushed",
"onto",
"the",
"stack",
"."
] | python | train |
globus/globus-cli | globus_cli/parsing/shared_options.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/parsing/shared_options.py#L403-L428 | def task_id_arg(*args, **kwargs):
"""
This is the `TASK_ID` argument consumed by many Transfer Task operations.
It accept a toggle on whether or not it is required
Usage:
>>> @task_id_option
>>> def command_func(task_id):
>>> ...
or
>>> @task_id_option(required=False)
>>>... | [
"def",
"task_id_arg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"inner_decorator",
"(",
"f",
",",
"required",
"=",
"True",
")",
":",
"f",
"=",
"click",
".",
"argument",
"(",
"\"TASK_ID\"",
",",
"required",
"=",
"required",
")",
"(",... | This is the `TASK_ID` argument consumed by many Transfer Task operations.
It accept a toggle on whether or not it is required
Usage:
>>> @task_id_option
>>> def command_func(task_id):
>>> ...
or
>>> @task_id_option(required=False)
>>> def command_func(task_id):
>>> ...
... | [
"This",
"is",
"the",
"TASK_ID",
"argument",
"consumed",
"by",
"many",
"Transfer",
"Task",
"operations",
".",
"It",
"accept",
"a",
"toggle",
"on",
"whether",
"or",
"not",
"it",
"is",
"required"
] | python | train |
CleanCut/green | green/output.py | https://github.com/CleanCut/green/blob/6434515302472363b7d10135be76ed8cd3934d80/green/output.py#L22-L27 | def debug(message, level=1):
"""
So we can tune how much debug output we get when we turn it on.
"""
if level <= debug_level:
logging.debug(' ' * (level - 1) * 2 + str(message)) | [
"def",
"debug",
"(",
"message",
",",
"level",
"=",
"1",
")",
":",
"if",
"level",
"<=",
"debug_level",
":",
"logging",
".",
"debug",
"(",
"' '",
"*",
"(",
"level",
"-",
"1",
")",
"*",
"2",
"+",
"str",
"(",
"message",
")",
")"
] | So we can tune how much debug output we get when we turn it on. | [
"So",
"we",
"can",
"tune",
"how",
"much",
"debug",
"output",
"we",
"get",
"when",
"we",
"turn",
"it",
"on",
"."
] | python | train |
OLC-Bioinformatics/sipprverse | cgecore/cmdline.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/cmdline.py#L93-L120 | def print_timers(self):
''' PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS '''
self.timer += time()
total_time = self.timer
tmp = '* %s *'
debug.log(
'',
'* '*29,
tmp%(' '*51),
tmp%('%s %s %s'%('Program Name'.ljust(20), 'Status'.ljust(7), 'Execute Ti... | [
"def",
"print_timers",
"(",
"self",
")",
":",
"self",
".",
"timer",
"+=",
"time",
"(",
")",
"total_time",
"=",
"self",
".",
"timer",
"tmp",
"=",
"'* %s *'",
"debug",
".",
"log",
"(",
"''",
",",
"'* '",
"*",
"29",
",",
"tmp",
"%",
"(",
"' '",
"*... | PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS | [
"PRINT",
"EXECUTION",
"TIMES",
"FOR",
"THE",
"LIST",
"OF",
"PROGRAMS"
] | python | train |
mottosso/be | be/vendor/requests/utils.py | https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L487-L530 | def should_bypass_proxies(url):
"""
Returns whether we should bypass proxies or not.
"""
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy = get_pr... | [
"def",
"should_bypass_proxies",
"(",
"url",
")",
":",
"get_proxy",
"=",
"lambda",
"k",
":",
"os",
".",
"environ",
".",
"get",
"(",
"k",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"k",
".",
"upper",
"(",
")",
")",
"# First check whether no_proxy ... | Returns whether we should bypass proxies or not. | [
"Returns",
"whether",
"we",
"should",
"bypass",
"proxies",
"or",
"not",
"."
] | python | train |
google/pyringe | pyringe/inferior.py | https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/inferior.py#L458-L466 | def needsattached(func):
"""Decorator to prevent commands from being used when not attached."""
@functools.wraps(func)
def wrap(self, *args, **kwargs):
if not self.attached:
raise PositionError('Not attached to any process.')
return func(self, *args, **kwargs)
return wrap | [
"def",
"needsattached",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"attached",
":",
"raise",
"PositionError",
"... | Decorator to prevent commands from being used when not attached. | [
"Decorator",
"to",
"prevent",
"commands",
"from",
"being",
"used",
"when",
"not",
"attached",
"."
] | python | train |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L1619-L1627 | def MatrixDiagPart(a):
"""
Batched diag op that returns only the diagonal elements.
"""
r = np.zeros(a.shape[:-2] + (min(a.shape[-2:]),))
for coord in np.ndindex(a.shape[:-2]):
pos = coord + (Ellipsis,)
r[pos] = np.diagonal(a[pos])
return r, | [
"def",
"MatrixDiagPart",
"(",
"a",
")",
":",
"r",
"=",
"np",
".",
"zeros",
"(",
"a",
".",
"shape",
"[",
":",
"-",
"2",
"]",
"+",
"(",
"min",
"(",
"a",
".",
"shape",
"[",
"-",
"2",
":",
"]",
")",
",",
")",
")",
"for",
"coord",
"in",
"np",
... | Batched diag op that returns only the diagonal elements. | [
"Batched",
"diag",
"op",
"that",
"returns",
"only",
"the",
"diagonal",
"elements",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/grading/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L730-L742 | def clear_numeric_score_increment(self):
"""Clears the numeric score increment.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for ... | [
"def",
"clear_numeric_score_increment",
"(",
"self",
")",
":",
"# Implemented from template for osid.grading.GradeSystemForm.clear_lowest_numeric_score",
"if",
"(",
"self",
".",
"get_numeric_score_increment_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
"."... | Clears the numeric score increment.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | [
"Clears",
"the",
"numeric",
"score",
"increment",
"."
] | python | train |
serge-sans-paille/pythran | pythran/toolchain.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L79-L84 | def _write_temp(content, suffix):
'''write `content` to a temporary XXX`suffix` file and return the filename.
It is user's responsibility to delete when done.'''
with NamedTemporaryFile(mode='w', suffix=suffix, delete=False) as out:
out.write(content)
return out.name | [
"def",
"_write_temp",
"(",
"content",
",",
"suffix",
")",
":",
"with",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"suffix",
"=",
"suffix",
",",
"delete",
"=",
"False",
")",
"as",
"out",
":",
"out",
".",
"write",
"(",
"content",
")",
"return",
... | write `content` to a temporary XXX`suffix` file and return the filename.
It is user's responsibility to delete when done. | [
"write",
"content",
"to",
"a",
"temporary",
"XXX",
"suffix",
"file",
"and",
"return",
"the",
"filename",
".",
"It",
"is",
"user",
"s",
"responsibility",
"to",
"delete",
"when",
"done",
"."
] | python | train |
pandas-dev/pandas | pandas/core/indexes/base.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4925-L4943 | def insert(self, loc, item):
"""
Make new Index inserting new item at location.
Follows Python list.append semantics for negative values.
Parameters
----------
loc : int
item : object
Returns
-------
new_index : Index
"""
... | [
"def",
"insert",
"(",
"self",
",",
"loc",
",",
"item",
")",
":",
"_self",
"=",
"np",
".",
"asarray",
"(",
"self",
")",
"item",
"=",
"self",
".",
"_coerce_scalar_to_index",
"(",
"item",
")",
".",
"_ndarray_values",
"idx",
"=",
"np",
".",
"concatenate",
... | Make new Index inserting new item at location.
Follows Python list.append semantics for negative values.
Parameters
----------
loc : int
item : object
Returns
-------
new_index : Index | [
"Make",
"new",
"Index",
"inserting",
"new",
"item",
"at",
"location",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.