repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
IAMconsortium/pyam | pyam/iiasa.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/iiasa.py#L67-L84 | def scenario_list(self, default=True):
"""
Metadata regarding the list of scenarios (e.g., models, scenarios,
run identifier, etc.) in the connected data source.
Parameter
---------
default : bool, optional, default True
Return *only* the default version of e... | [
"def",
"scenario_list",
"(",
"self",
",",
"default",
"=",
"True",
")",
":",
"default",
"=",
"'true'",
"if",
"default",
"else",
"'false'",
"add_url",
"=",
"'runs?getOnlyDefaultRuns={}'",
"url",
"=",
"self",
".",
"base_url",
"+",
"add_url",
".",
"format",
"(",... | Metadata regarding the list of scenarios (e.g., models, scenarios,
run identifier, etc.) in the connected data source.
Parameter
---------
default : bool, optional, default True
Return *only* the default version of each Scenario.
Any (`model`, `scenario`) without... | [
"Metadata",
"regarding",
"the",
"list",
"of",
"scenarios",
"(",
"e",
".",
"g",
".",
"models",
"scenarios",
"run",
"identifier",
"etc",
".",
")",
"in",
"the",
"connected",
"data",
"source",
"."
] | python | train | 43.166667 |
jadolg/rocketchat_API | rocketchat_API/rocketchat.py | https://github.com/jadolg/rocketchat_API/blob/f220d094434991cb9892418245f054ea06f28aad/rocketchat_API/rocketchat.py#L600-L607 | def im_files(self, room_id=None, user_name=None, **kwargs):
"""Retrieves the files from a direct message."""
if room_id:
return self.__call_api_get('im.files', roomId=room_id, kwargs=kwargs)
elif user_name:
return self.__call_api_get('im.files', username=user_name, kwargs... | [
"def",
"im_files",
"(",
"self",
",",
"room_id",
"=",
"None",
",",
"user_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"room_id",
":",
"return",
"self",
".",
"__call_api_get",
"(",
"'im.files'",
",",
"roomId",
"=",
"room_id",
",",
"kwargs... | Retrieves the files from a direct message. | [
"Retrieves",
"the",
"files",
"from",
"a",
"direct",
"message",
"."
] | python | train | 51.5 |
wummel/linkchecker | linkcheck/log.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/log.py#L98-L105 | def warn (logname, msg, *args, **kwargs):
"""Log a warning.
return: None
"""
log = logging.getLogger(logname)
if log.isEnabledFor(logging.WARN):
_log(log.warn, msg, args, **kwargs) | [
"def",
"warn",
"(",
"logname",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logname",
")",
"if",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"WARN",
")",
":",
"_log",
"(",
"l... | Log a warning.
return: None | [
"Log",
"a",
"warning",
"."
] | python | train | 25.25 |
ethereum/py-trie | trie/hexary.py | https://github.com/ethereum/py-trie/blob/d33108d21b54d59ee311f61d978496c84a6f1f8b/trie/hexary.py#L361-L381 | def _delete_branch_node(self, node, trie_key):
"""
Delete a key from inside or underneath a branch node
"""
if not trie_key:
node[-1] = BLANK_NODE
return self._normalize_branch_node(node)
node_to_delete = self.get_node(node[trie_key[0]])
sub_node... | [
"def",
"_delete_branch_node",
"(",
"self",
",",
"node",
",",
"trie_key",
")",
":",
"if",
"not",
"trie_key",
":",
"node",
"[",
"-",
"1",
"]",
"=",
"BLANK_NODE",
"return",
"self",
".",
"_normalize_branch_node",
"(",
"node",
")",
"node_to_delete",
"=",
"self"... | Delete a key from inside or underneath a branch node | [
"Delete",
"a",
"key",
"from",
"inside",
"or",
"underneath",
"a",
"branch",
"node"
] | python | train | 30.428571 |
fedora-infra/fedora-messaging | fedora_messaging/twisted/factory.py | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/factory.py#L174-L182 | def stopFactory(self):
"""Stop the factory.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
"""
if self.client:
yield self.client.stopProducing()
protocol.ReconnectingClientFactory.stopFactory(self) | [
"def",
"stopFactory",
"(",
"self",
")",
":",
"if",
"self",
".",
"client",
":",
"yield",
"self",
".",
"client",
".",
"stopProducing",
"(",
")",
"protocol",
".",
"ReconnectingClientFactory",
".",
"stopFactory",
"(",
"self",
")"
] | Stop the factory.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details. | [
"Stop",
"the",
"factory",
"."
] | python | train | 32.777778 |
spacetelescope/stsci.tools | lib/stsci/tools/validate.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/validate.py#L1233-L1253 | def force_list(value, min=None, max=None):
"""
Check that a value is a list, coercing strings into
a list with one member. Useful where users forget the
trailing comma that turns a single value into a list.
You can optionally specify the minimum and maximum number of members.
A minumum of great... | [
"def",
"force_list",
"(",
"value",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
"is_list",
"(",
"val... | Check that a value is a list, coercing strings into
a list with one member. Useful where users forget the
trailing comma that turns a single value into a list.
You can optionally specify the minimum and maximum number of members.
A minumum of greater than one will fail if the user only supplies a
s... | [
"Check",
"that",
"a",
"value",
"is",
"a",
"list",
"coercing",
"strings",
"into",
"a",
"list",
"with",
"one",
"member",
".",
"Useful",
"where",
"users",
"forget",
"the",
"trailing",
"comma",
"that",
"turns",
"a",
"single",
"value",
"into",
"a",
"list",
".... | python | train | 30.761905 |
apache/incubator-heron | heron/instance/src/python/network/protocol.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/protocol.py#L152-L166 | def create_packet(header, data):
"""Creates an IncomingPacket object from header and data
This method is for testing purposes
"""
packet = IncomingPacket()
packet.header = header
packet.data = data
if len(header) == HeronProtocol.HEADER_SIZE:
packet.is_header_read = True
if len... | [
"def",
"create_packet",
"(",
"header",
",",
"data",
")",
":",
"packet",
"=",
"IncomingPacket",
"(",
")",
"packet",
".",
"header",
"=",
"header",
"packet",
".",
"data",
"=",
"data",
"if",
"len",
"(",
"header",
")",
"==",
"HeronProtocol",
".",
"HEADER_SIZE... | Creates an IncomingPacket object from header and data
This method is for testing purposes | [
"Creates",
"an",
"IncomingPacket",
"object",
"from",
"header",
"and",
"data"
] | python | valid | 26.066667 |
JasonKessler/scattertext | scattertext/termranking/TermRanker.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termranking/TermRanker.py#L34-L41 | def get_X(self):
'''
:return: term freq matrix or metadata freq matrix
'''
if self._use_non_text_features:
return self._term_doc_matrix._mX
else:
return self._term_doc_matrix._X | [
"def",
"get_X",
"(",
"self",
")",
":",
"if",
"self",
".",
"_use_non_text_features",
":",
"return",
"self",
".",
"_term_doc_matrix",
".",
"_mX",
"else",
":",
"return",
"self",
".",
"_term_doc_matrix",
".",
"_X"
] | :return: term freq matrix or metadata freq matrix | [
":",
"return",
":",
"term",
"freq",
"matrix",
"or",
"metadata",
"freq",
"matrix"
] | python | train | 23.25 |
genialis/resolwe | resolwe/flow/migrations/0005_data_dependency_3.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migrations/0005_data_dependency_3.py#L10-L35 | def update_dependency_kinds(apps, schema_editor):
"""Update historical dependency kinds as they may be wrong."""
DataDependency = apps.get_model('flow', 'DataDependency')
for dependency in DataDependency.objects.all():
# Assume dependency is of subprocess kind.
dependency.kind = 'subprocess'... | [
"def",
"update_dependency_kinds",
"(",
"apps",
",",
"schema_editor",
")",
":",
"DataDependency",
"=",
"apps",
".",
"get_model",
"(",
"'flow'",
",",
"'DataDependency'",
")",
"for",
"dependency",
"in",
"DataDependency",
".",
"objects",
".",
"all",
"(",
")",
":",... | Update historical dependency kinds as they may be wrong. | [
"Update",
"historical",
"dependency",
"kinds",
"as",
"they",
"may",
"be",
"wrong",
"."
] | python | train | 39.615385 |
cosven/feeluown-core | fuocore/local/provider.py | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/local/provider.py#L67-L170 | def add_song(fpath, g_songs, g_artists, g_albums):
"""
parse music file metadata with Easymp3 and return a song
model.
"""
try:
if fpath.endswith('mp3') or fpath.endswith('ogg') or fpath.endswith('wma'):
metadata = EasyMP3(fpath)
elif fpath.endswith('m4a'):
me... | [
"def",
"add_song",
"(",
"fpath",
",",
"g_songs",
",",
"g_artists",
",",
"g_albums",
")",
":",
"try",
":",
"if",
"fpath",
".",
"endswith",
"(",
"'mp3'",
")",
"or",
"fpath",
".",
"endswith",
"(",
"'ogg'",
")",
"or",
"fpath",
".",
"endswith",
"(",
"'wma... | parse music file metadata with Easymp3 and return a song
model. | [
"parse",
"music",
"file",
"metadata",
"with",
"Easymp3",
"and",
"return",
"a",
"song",
"model",
"."
] | python | train | 34.557692 |
timothycrosley/blox | blox/builder.py | https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/builder.py#L37-L43 | def add(self, *names):
'''Returns back a class decorator that enables registering Blox to this factory'''
def decorator(blok):
for name in names or (blok.__name__, ):
self[name] = blok
return blok
return decorator | [
"def",
"add",
"(",
"self",
",",
"*",
"names",
")",
":",
"def",
"decorator",
"(",
"blok",
")",
":",
"for",
"name",
"in",
"names",
"or",
"(",
"blok",
".",
"__name__",
",",
")",
":",
"self",
"[",
"name",
"]",
"=",
"blok",
"return",
"blok",
"return",... | Returns back a class decorator that enables registering Blox to this factory | [
"Returns",
"back",
"a",
"class",
"decorator",
"that",
"enables",
"registering",
"Blox",
"to",
"this",
"factory"
] | python | valid | 38.714286 |
Aula13/poloniex | poloniex/poloniex.py | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L282-L292 | def moveOrder(self, orderNumber, rate, amount=None, postOnly=None,
immediateOrCancel=None):
"""Cancels an order and places a new one of the same type in a single
atomic transaction, meaning either both operations will succeed or both
will fail. Required POST parameters are "or... | [
"def",
"moveOrder",
"(",
"self",
",",
"orderNumber",
",",
"rate",
",",
"amount",
"=",
"None",
",",
"postOnly",
"=",
"None",
",",
"immediateOrCancel",
"=",
"None",
")",
":",
"return",
"self",
".",
"_private",
"(",
"'moveOrder'",
",",
"orderNumber",
"=",
"... | Cancels an order and places a new one of the same type in a single
atomic transaction, meaning either both operations will succeed or both
will fail. Required POST parameters are "orderNumber" and "rate"; you
may optionally specify "amount" if you wish to change the amount of
the new ... | [
"Cancels",
"an",
"order",
"and",
"places",
"a",
"new",
"one",
"of",
"the",
"same",
"type",
"in",
"a",
"single",
"atomic",
"transaction",
"meaning",
"either",
"both",
"operations",
"will",
"succeed",
"or",
"both",
"will",
"fail",
".",
"Required",
"POST",
"p... | python | train | 70.090909 |
onicagroup/runway | runway/module/__init__.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/__init__.py#L28-L52 | def generate_node_command(command, command_opts, path):
"""Return node bin command list for subprocess execution."""
if which(NPX_BIN):
# Use npx if available (npm v5.2+)
LOGGER.debug("Using npx to invoke %s.", command)
if platform.system().lower() == 'windows':
cmd_list = [N... | [
"def",
"generate_node_command",
"(",
"command",
",",
"command_opts",
",",
"path",
")",
":",
"if",
"which",
"(",
"NPX_BIN",
")",
":",
"# Use npx if available (npm v5.2+)",
"LOGGER",
".",
"debug",
"(",
"\"Using npx to invoke %s.\"",
",",
"command",
")",
"if",
"platf... | Return node bin command list for subprocess execution. | [
"Return",
"node",
"bin",
"command",
"list",
"for",
"subprocess",
"execution",
"."
] | python | train | 40.32 |
rocky/python3-trepan | trepan/lib/printing.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/printing.py#L44-L84 | def print_obj(arg, frame, format=None, short=False):
"""Return a string representation of an object """
try:
if not frame:
# ?? Should we have set up a dummy globals
# to have persistence?
obj = eval(arg, None, None)
else:
obj = eval(arg, frame.f_g... | [
"def",
"print_obj",
"(",
"arg",
",",
"frame",
",",
"format",
"=",
"None",
",",
"short",
"=",
"False",
")",
":",
"try",
":",
"if",
"not",
"frame",
":",
"# ?? Should we have set up a dummy globals",
"# to have persistence?",
"obj",
"=",
"eval",
"(",
"arg",
","... | Return a string representation of an object | [
"Return",
"a",
"string",
"representation",
"of",
"an",
"object"
] | python | test | 32.634146 |
fracpete/python-weka-wrapper3 | python/weka/core/classes.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/classes.py#L52-L67 | def get_jclass(classname):
"""
Returns the Java class object associated with the dot-notation classname.
:param classname: the classname
:type classname: str
:return: the class object
:rtype: JB_Object
"""
try:
return javabridge.class_for_name(classname)
except:
retu... | [
"def",
"get_jclass",
"(",
"classname",
")",
":",
"try",
":",
"return",
"javabridge",
".",
"class_for_name",
"(",
"classname",
")",
"except",
":",
"return",
"javabridge",
".",
"static_call",
"(",
"\"Lweka/core/ClassHelper;\"",
",",
"\"forName\"",
",",
"\"(Ljava/lan... | Returns the Java class object associated with the dot-notation classname.
:param classname: the classname
:type classname: str
:return: the class object
:rtype: JB_Object | [
"Returns",
"the",
"Java",
"class",
"object",
"associated",
"with",
"the",
"dot",
"-",
"notation",
"classname",
"."
] | python | train | 32.5625 |
joke2k/faker | faker/providers/__init__.py | https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/__init__.py#L250-L274 | def randomize_nb_elements(
self,
number=10,
le=False,
ge=False,
min=None,
max=None):
"""
Returns a random value near number.
:param number: value to which the result must be near
:param le: result must be lower or e... | [
"def",
"randomize_nb_elements",
"(",
"self",
",",
"number",
"=",
"10",
",",
"le",
"=",
"False",
",",
"ge",
"=",
"False",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"if",
"le",
"and",
"ge",
":",
"return",
"number",
"_min",
"=",
"1... | Returns a random value near number.
:param number: value to which the result must be near
:param le: result must be lower or equal to number
:param ge: result must be greater or equal to number
:returns: a random int near number | [
"Returns",
"a",
"random",
"value",
"near",
"number",
"."
] | python | train | 30.32 |
msmbuilder/msmbuilder | msmbuilder/decomposition/ksparsetica.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/ksparsetica.py#L191-L212 | def summarize(self, n_timescales_to_report=5):
"""Some summary information."""
nonzeros = np.sum(np.abs(self.eigenvectors_) > 0, axis=0)
active = '[%s]' % ', '.join(['%d/%d' % (n, self.n_features) for n in nonzeros[:n_timescales_to_report]])
return """K-sparse time-structure Independent... | [
"def",
"summarize",
"(",
"self",
",",
"n_timescales_to_report",
"=",
"5",
")",
":",
"nonzeros",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"self",
".",
"eigenvectors_",
")",
">",
"0",
",",
"axis",
"=",
"0",
")",
"active",
"=",
"'[%s]'",
"%"... | Some summary information. | [
"Some",
"summary",
"information",
"."
] | python | train | 49.772727 |
ceph/ceph-deploy | ceph_deploy/util/system.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/system.py#L64-L88 | def enable_service(conn, service='ceph'):
"""
Enable a service on a remote host depending on the type of init system.
Obviously, this should be done for RHEL/Fedora/CentOS systems.
This function does not do any kind of detection.
"""
if is_systemd(conn):
remoto.process.run(
... | [
"def",
"enable_service",
"(",
"conn",
",",
"service",
"=",
"'ceph'",
")",
":",
"if",
"is_systemd",
"(",
"conn",
")",
":",
"remoto",
".",
"process",
".",
"run",
"(",
"conn",
",",
"[",
"'systemctl'",
",",
"'enable'",
",",
"'{service}'",
".",
"format",
"(... | Enable a service on a remote host depending on the type of init system.
Obviously, this should be done for RHEL/Fedora/CentOS systems.
This function does not do any kind of detection. | [
"Enable",
"a",
"service",
"on",
"a",
"remote",
"host",
"depending",
"on",
"the",
"type",
"of",
"init",
"system",
".",
"Obviously",
"this",
"should",
"be",
"done",
"for",
"RHEL",
"/",
"Fedora",
"/",
"CentOS",
"systems",
"."
] | python | train | 25.8 |
5monkeys/djedi-cms | djedi/backends/django/cache/backend.py | https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/backends/django/cache/backend.py#L55-L63 | def _decode_content(self, content):
"""
Split node string to uri and content and convert back to unicode.
"""
content = smart_unicode(content)
uri, _, content = content.partition(u'|')
if content == self.NONE:
content = None
return uri or None, content | [
"def",
"_decode_content",
"(",
"self",
",",
"content",
")",
":",
"content",
"=",
"smart_unicode",
"(",
"content",
")",
"uri",
",",
"_",
",",
"content",
"=",
"content",
".",
"partition",
"(",
"u'|'",
")",
"if",
"content",
"==",
"self",
".",
"NONE",
":",... | Split node string to uri and content and convert back to unicode. | [
"Split",
"node",
"string",
"to",
"uri",
"and",
"content",
"and",
"convert",
"back",
"to",
"unicode",
"."
] | python | train | 34.666667 |
viniciuschiele/flask-io | flask_io/io.py | https://github.com/viniciuschiele/flask-io/blob/4e559419b3d8e6859f83fa16557b00542d5f3aa7/flask_io/io.py#L296-L304 | def trace_emit(self):
"""
A decorator that allows to change the trace emitter.
By default Python logging is used to emit the trace data.
"""
def decorator(f):
self.tracer.emitter = f
return f
return decorator | [
"def",
"trace_emit",
"(",
"self",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"tracer",
".",
"emitter",
"=",
"f",
"return",
"f",
"return",
"decorator"
] | A decorator that allows to change the trace emitter.
By default Python logging is used to emit the trace data. | [
"A",
"decorator",
"that",
"allows",
"to",
"change",
"the",
"trace",
"emitter",
".",
"By",
"default",
"Python",
"logging",
"is",
"used",
"to",
"emit",
"the",
"trace",
"data",
"."
] | python | train | 30.222222 |
vicalloy/lbutils | lbutils/utils.py | https://github.com/vicalloy/lbutils/blob/66ae7e73bc939f073cdc1b91602a95e67caf4ba6/lbutils/utils.py#L21-L25 | def fmt_num(num, zero_num=None):
""" humanize number(9000 to 9,000) """
if zero_num is not None:
num = floatformat(num, zero_num)
return intcomma(num, False) | [
"def",
"fmt_num",
"(",
"num",
",",
"zero_num",
"=",
"None",
")",
":",
"if",
"zero_num",
"is",
"not",
"None",
":",
"num",
"=",
"floatformat",
"(",
"num",
",",
"zero_num",
")",
"return",
"intcomma",
"(",
"num",
",",
"False",
")"
] | humanize number(9000 to 9,000) | [
"humanize",
"number",
"(",
"9000",
"to",
"9",
"000",
")"
] | python | train | 34.6 |
joshspeagle/dynesty | dynesty/bounding.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L506-L528 | def monte_carlo_vol(self, ndraws=10000, rstate=None,
return_overlap=True):
"""Using `ndraws` Monte Carlo draws, estimate the volume of the
*union* of ellipsoids. If `return_overlap=True`, also returns the
estimated fractional overlap with the unit cube."""
if rst... | [
"def",
"monte_carlo_vol",
"(",
"self",
",",
"ndraws",
"=",
"10000",
",",
"rstate",
"=",
"None",
",",
"return_overlap",
"=",
"True",
")",
":",
"if",
"rstate",
"is",
"None",
":",
"rstate",
"=",
"np",
".",
"random",
"# Estimate volume using Monte Carlo integratio... | Using `ndraws` Monte Carlo draws, estimate the volume of the
*union* of ellipsoids. If `return_overlap=True`, also returns the
estimated fractional overlap with the unit cube. | [
"Using",
"ndraws",
"Monte",
"Carlo",
"draws",
"estimate",
"the",
"volume",
"of",
"the",
"*",
"union",
"*",
"of",
"ellipsoids",
".",
"If",
"return_overlap",
"=",
"True",
"also",
"returns",
"the",
"estimated",
"fractional",
"overlap",
"with",
"the",
"unit",
"c... | python | train | 40.26087 |
google/grumpy | third_party/pythonparser/parser.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L803-L808 | def tfpdef(self, ident_tok, annotation_opt):
"""(3.0-) tfpdef: NAME [':' test]"""
if annotation_opt:
colon_loc, annotation = annotation_opt
return self._arg(ident_tok, colon_loc, annotation)
return self._arg(ident_tok) | [
"def",
"tfpdef",
"(",
"self",
",",
"ident_tok",
",",
"annotation_opt",
")",
":",
"if",
"annotation_opt",
":",
"colon_loc",
",",
"annotation",
"=",
"annotation_opt",
"return",
"self",
".",
"_arg",
"(",
"ident_tok",
",",
"colon_loc",
",",
"annotation",
")",
"r... | (3.0-) tfpdef: NAME [':' test] | [
"(",
"3",
".",
"0",
"-",
")",
"tfpdef",
":",
"NAME",
"[",
":",
"test",
"]"
] | python | valid | 43.5 |
jazzband/django-authority | authority/permissions.py | https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L240-L269 | def has_group_perms(self, perm, obj, approved):
"""
Check if group has the permission for the given object
"""
if not self.group:
return False
if self.use_smart_cache:
content_type_pk = Permission.objects.get_content_type(obj).pk
def _group_h... | [
"def",
"has_group_perms",
"(",
"self",
",",
"perm",
",",
"obj",
",",
"approved",
")",
":",
"if",
"not",
"self",
".",
"group",
":",
"return",
"False",
"if",
"self",
".",
"use_smart_cache",
":",
"content_type_pk",
"=",
"Permission",
".",
"objects",
".",
"g... | Check if group has the permission for the given object | [
"Check",
"if",
"group",
"has",
"the",
"permission",
"for",
"the",
"given",
"object"
] | python | train | 30.9 |
tapilab/brandelion | brandelion/cli/analyze.py | https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L249-L259 | def compute_log_degrees(brands, exemplars):
""" For each follower, let Z be the total number of brands they follow.
Return a dictionary of 1. / log(Z), for each follower.
"""
counts = Counter()
for followers in brands.values(): # + exemplars.values(): # Include exemplars in these counts? No, don't... | [
"def",
"compute_log_degrees",
"(",
"brands",
",",
"exemplars",
")",
":",
"counts",
"=",
"Counter",
"(",
")",
"for",
"followers",
"in",
"brands",
".",
"values",
"(",
")",
":",
"# + exemplars.values(): # Include exemplars in these counts? No, don't want to penalize people ... | For each follower, let Z be the total number of brands they follow.
Return a dictionary of 1. / log(Z), for each follower. | [
"For",
"each",
"follower",
"let",
"Z",
"be",
"the",
"total",
"number",
"of",
"brands",
"they",
"follow",
".",
"Return",
"a",
"dictionary",
"of",
"1",
".",
"/",
"log",
"(",
"Z",
")",
"for",
"each",
"follower",
"."
] | python | train | 48.636364 |
zalando/patroni | patroni/dcs/__init__.py | https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/dcs/__init__.py#L489-L506 | def timeline(self):
"""
>>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline
0
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline
1
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline
0
"""
if self.... | [
"def",
"timeline",
"(",
"self",
")",
":",
"if",
"self",
".",
"history",
":",
"if",
"self",
".",
"history",
".",
"lines",
":",
"try",
":",
"return",
"int",
"(",
"self",
".",
"history",
".",
"lines",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
")",
"+",
... | >>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline
0
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline
1
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline
0 | [
">>>",
"Cluster",
"(",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
")",
".",
"timeline",
"0",
">>>",
"Cluster",
"(",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"TimelineHistory",
".",
"from_node",
"(",
"1",
"[]",
"))",
".",
"timeline",
"1",
">>>",
"Cluster... | python | train | 36.166667 |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/blocks.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/blocks.py#L133-L145 | def visit_and_update_expressions(self, visitor_fn):
"""Create an updated version (if needed) of the ConstructResult via the visitor pattern."""
new_fields = {}
for key, value in six.iteritems(self.fields):
new_value = value.visit_and_update(visitor_fn)
if new_value is no... | [
"def",
"visit_and_update_expressions",
"(",
"self",
",",
"visitor_fn",
")",
":",
"new_fields",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"fields",
")",
":",
"new_value",
"=",
"value",
".",
"visit_and_update... | Create an updated version (if needed) of the ConstructResult via the visitor pattern. | [
"Create",
"an",
"updated",
"version",
"(",
"if",
"needed",
")",
"of",
"the",
"ConstructResult",
"via",
"the",
"visitor",
"pattern",
"."
] | python | train | 37.692308 |
andrewsnowden/dota2py | dota2py/parser.py | https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/parser.py#L282-L327 | def parse(self):
"""
Parse a replay
"""
self.important("Parsing demo file '%s'" % (self.filename, ))
with open(self.filename, 'rb') as f:
reader = Reader(StringIO(f.read()))
filestamp = reader.read(8)
offset = reader.read_int32()
... | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"important",
"(",
"\"Parsing demo file '%s'\"",
"%",
"(",
"self",
".",
"filename",
",",
")",
")",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"reader",
"=",
"Read... | Parse a replay | [
"Parse",
"a",
"replay"
] | python | train | 29.152174 |
saltstack/salt | salt/states/pagerduty_schedule.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_schedule.py#L94-L163 | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
state_data['id'] = resource_object['schedule'... | [
"def",
"_diff",
"(",
"state_data",
",",
"resource_object",
")",
":",
"state_data",
"[",
"'id'",
"]",
"=",
"resource_object",
"[",
"'schedule'",
"]",
"[",
"'id'",
"]",
"objects_differ",
"=",
"None",
"# first check all the easy top-level properties: everything except the ... | helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update. | [
"helper",
"method",
"to",
"compare",
"salt",
"state",
"info",
"with",
"the",
"PagerDuty",
"API",
"json",
"structure",
"and",
"determine",
"if",
"we",
"need",
"to",
"update",
"."
] | python | train | 46.328571 |
buildbot/buildbot | master/buildbot/www/hooks/gitlab.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/www/hooks/gitlab.py#L157-L202 | def getChanges(self, request):
"""
Reponds only to POST events and starts the build process
:arguments:
request
the http request object
"""
expected_secret = isinstance(self.options, dict) and self.options.get('secret')
if expected_secret:
... | [
"def",
"getChanges",
"(",
"self",
",",
"request",
")",
":",
"expected_secret",
"=",
"isinstance",
"(",
"self",
".",
"options",
",",
"dict",
")",
"and",
"self",
".",
"options",
".",
"get",
"(",
"'secret'",
")",
"if",
"expected_secret",
":",
"received_secret... | Reponds only to POST events and starts the build process
:arguments:
request
the http request object | [
"Reponds",
"only",
"to",
"POST",
"events",
"and",
"starts",
"the",
"build",
"process"
] | python | train | 41.652174 |
dylanaraps/pywal | pywal/__main__.py | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/__main__.py#L150-L195 | def parse_args(parser):
"""Process args."""
args = parser.parse_args()
if args.q:
logging.getLogger().disabled = True
sys.stdout = sys.stderr = open(os.devnull, "w")
if args.a:
util.Color.alpha_num = args.a
if args.i:
image_file = image.get(args.i, iterative=args.i... | [
"def",
"parse_args",
"(",
"parser",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"args",
".",
"q",
":",
"logging",
".",
"getLogger",
"(",
")",
".",
"disabled",
"=",
"True",
"sys",
".",
"stdout",
"=",
"sys",
".",
"stderr",
"="... | Process args. | [
"Process",
"args",
"."
] | python | train | 24.826087 |
kylef/refract.py | refract/contrib/apielements.py | https://github.com/kylef/refract.py/blob/f58ddf619038b580ab50c2e7f867d59d153eabbb/refract/contrib/apielements.py#L79-L84 | def assets(self) -> List[Asset]:
"""
Returns the assets in the transaction.
"""
return list(filter(is_element(Asset), self.content)) | [
"def",
"assets",
"(",
"self",
")",
"->",
"List",
"[",
"Asset",
"]",
":",
"return",
"list",
"(",
"filter",
"(",
"is_element",
"(",
"Asset",
")",
",",
"self",
".",
"content",
")",
")"
] | Returns the assets in the transaction. | [
"Returns",
"the",
"assets",
"in",
"the",
"transaction",
"."
] | python | train | 26.666667 |
gears/gears | gears/environment.py | https://github.com/gears/gears/blob/5729c2525a8c04c185e998bd9a86233708972921/gears/environment.py#L307-L311 | def register_defaults(self):
"""Register default compilers, preprocessors and MIME types."""
self.mimetypes.register_defaults()
self.preprocessors.register_defaults()
self.postprocessors.register_defaults() | [
"def",
"register_defaults",
"(",
"self",
")",
":",
"self",
".",
"mimetypes",
".",
"register_defaults",
"(",
")",
"self",
".",
"preprocessors",
".",
"register_defaults",
"(",
")",
"self",
".",
"postprocessors",
".",
"register_defaults",
"(",
")"
] | Register default compilers, preprocessors and MIME types. | [
"Register",
"default",
"compilers",
"preprocessors",
"and",
"MIME",
"types",
"."
] | python | test | 46.8 |
saltstack/salt | salt/utils/decorators/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/state.py#L48-L73 | def content_check(self, result):
'''
Checks for specific types in the state output.
Raises an Exception in case particular rule is broken.
:param result:
:return:
'''
if not isinstance(result, dict):
err_msg = 'Malformed state return. Data must be a d... | [
"def",
"content_check",
"(",
"self",
",",
"result",
")",
":",
"if",
"not",
"isinstance",
"(",
"result",
",",
"dict",
")",
":",
"err_msg",
"=",
"'Malformed state return. Data must be a dictionary type.'",
"elif",
"not",
"isinstance",
"(",
"result",
".",
"get",
"(... | Checks for specific types in the state output.
Raises an Exception in case particular rule is broken.
:param result:
:return: | [
"Checks",
"for",
"specific",
"types",
"in",
"the",
"state",
"output",
".",
"Raises",
"an",
"Exception",
"in",
"case",
"particular",
"rule",
"is",
"broken",
"."
] | python | train | 34 |
AirtestProject/Poco | poco/utils/track.py | https://github.com/AirtestProject/Poco/blob/2c559a586adf3fd11ee81cabc446d4d3f6f2d119/poco/utils/track.py#L78-L117 | def discretize(self, contact_id=0, accuracy=0.004, dt=0.001):
"""
Sample this motion track into discretized motion events.
Args:
contact_id: contact point id
accuracy: motion minimum difference in space
dt: sample time difference
"""
if not s... | [
"def",
"discretize",
"(",
"self",
",",
"contact_id",
"=",
"0",
",",
"accuracy",
"=",
"0.004",
",",
"dt",
"=",
"0.001",
")",
":",
"if",
"not",
"self",
".",
"event_points",
":",
"return",
"[",
"]",
"events",
"=",
"[",
"]",
"action_dt",
"=",
"accuracy",... | Sample this motion track into discretized motion events.
Args:
contact_id: contact point id
accuracy: motion minimum difference in space
dt: sample time difference | [
"Sample",
"this",
"motion",
"track",
"into",
"discretized",
"motion",
"events",
"."
] | python | train | 32.175 |
pixelogik/NearPy | nearpy/hashes/permutation/hashpermutations.py | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/permutation/hashpermutations.py#L144-L171 | def build_permuted_index(self):
"""
Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
... | [
"def",
"build_permuted_index",
"(",
"self",
")",
":",
"for",
"child_hash",
"in",
"self",
".",
"child_hashes",
":",
"# Get config values for child hash",
"config",
"=",
"child_hash",
"[",
"'config'",
"]",
"num_permutation",
"=",
"config",
"[",
"'num_permutation'",
"]... | Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
{ "num_permutation":50,
... | [
"Build",
"PermutedIndex",
"for",
"all",
"your",
"binary",
"hashings",
".",
"PermutedIndex",
"would",
"be",
"used",
"to",
"find",
"the",
"neighbour",
"bucket",
"key",
"in",
"terms",
"of",
"Hamming",
"distance",
".",
"Permute_configs",
"is",
"nested",
"dict",
"i... | python | train | 39.678571 |
ssato/python-anytemplate | anytemplate/engines/pystache.py | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/pystache.py#L101-L125 | def render_impl(self, template, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
"""
Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
... | [
"def",
"render_impl",
"(",
"self",
",",
"template",
",",
"context",
",",
"at_paths",
"=",
"None",
",",
"at_encoding",
"=",
"anytemplate",
".",
"compat",
".",
"ENCODING",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer",
"=",
"self",
".",
"_make_renderer",
"... | Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arg... | [
"Render",
"given",
"template",
"file",
"and",
"return",
"the",
"result",
"."
] | python | train | 41.2 |
leonjza/filesmudge | filesmudge/smudge.py | https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L163-L173 | def available():
"""
List available types for 'smudge'
"""
db = smudge_db.get()
click.echo('{:<6} {:<6} {:<50}'.format('Type', 'Offset', 'Magic'))
for k, v in db.items():
click.echo('{type:<6} {offset:<6} {magic}'.format(
type=k, magic=v['magic'].encode('hex'), offset=v... | [
"def",
"available",
"(",
")",
":",
"db",
"=",
"smudge_db",
".",
"get",
"(",
")",
"click",
".",
"echo",
"(",
"'{:<6} {:<6} {:<50}'",
".",
"format",
"(",
"'Type'",
",",
"'Offset'",
",",
"'Magic'",
")",
")",
"for",
"k",
",",
"v",
"in",
"db",
".",
"ite... | List available types for 'smudge' | [
"List",
"available",
"types",
"for",
"smudge"
] | python | train | 29.272727 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ambiente.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ambiente.py#L160-L197 | def buscar_por_id(self, id_ambiente):
"""Obtém um ambiente a partir da chave primária (identificador).
:param id_ambiente: Identificador do ambiente.
:return: Dicionário com a seguinte estrutura:
::
{'ambiente': {'id': < id_ambiente >,
'link': < link >,
... | [
"def",
"buscar_por_id",
"(",
"self",
",",
"id_ambiente",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_ambiente",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'O identificador do ambiente é inválido ou não foi informado.')",
"",
"url",
"=",
"'environment/id/... | Obtém um ambiente a partir da chave primária (identificador).
:param id_ambiente: Identificador do ambiente.
:return: Dicionário com a seguinte estrutura:
::
{'ambiente': {'id': < id_ambiente >,
'link': < link >,
'id_divisao': < id_divisao >,
'... | [
"Obtém",
"um",
"ambiente",
"a",
"partir",
"da",
"chave",
"primária",
"(",
"identificador",
")",
"."
] | python | train | 38.842105 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2516-L2621 | def run_cell(self, raw_cell, store_history=False, silent=False):
"""Run a complete IPython cell.
Parameters
----------
raw_cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell ... | [
"def",
"run_cell",
"(",
"self",
",",
"raw_cell",
",",
"store_history",
"=",
"False",
",",
"silent",
"=",
"False",
")",
":",
"if",
"(",
"not",
"raw_cell",
")",
"or",
"raw_cell",
".",
"isspace",
"(",
")",
":",
"return",
"if",
"silent",
":",
"store_histor... | Run a complete IPython cell.
Parameters
----------
raw_cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell will be stored in IPython's
history. For user code calling back in... | [
"Run",
"a",
"complete",
"IPython",
"cell",
"."
] | python | test | 45.377358 |
RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/resources.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L651-L691 | def search_by_age(cls, *, limit=100, page=1, accounts=None, locations=None, age=720,
properties=None, include_disabled=False):
"""Search for resources based on the provided filters
Args:
limit (`int`): Number of results to return. Default: 100
page (`int`):... | [
"def",
"search_by_age",
"(",
"cls",
",",
"*",
",",
"limit",
"=",
"100",
",",
"page",
"=",
"1",
",",
"accounts",
"=",
"None",
",",
"locations",
"=",
"None",
",",
"age",
"=",
"720",
",",
"properties",
"=",
"None",
",",
"include_disabled",
"=",
"False",... | Search for resources based on the provided filters
Args:
limit (`int`): Number of results to return. Default: 100
page (`int`): Pagination offset for results. Default: 1
accounts (`list` of `int`): A list of account id's to limit the returned resources to
locatio... | [
"Search",
"for",
"resources",
"based",
"on",
"the",
"provided",
"filters"
] | python | train | 42.341463 |
idlesign/django-sitemessage | sitemessage/messengers/telegram.py | https://github.com/idlesign/django-sitemessage/blob/25b179b798370354c5988042ec209e255d23793f/sitemessage/messengers/telegram.py#L56-L69 | def get_chat_ids(self):
"""Returns unique chat IDs from `/start` command messages sent to our bot by users.
Those chat IDs can be used to send messages to chats.
:rtype: list
"""
updates = self.get_updates()
chat_ids = []
if updates:
for update in upd... | [
"def",
"get_chat_ids",
"(",
"self",
")",
":",
"updates",
"=",
"self",
".",
"get_updates",
"(",
")",
"chat_ids",
"=",
"[",
"]",
"if",
"updates",
":",
"for",
"update",
"in",
"updates",
":",
"message",
"=",
"update",
"[",
"'message'",
"]",
"if",
"message"... | Returns unique chat IDs from `/start` command messages sent to our bot by users.
Those chat IDs can be used to send messages to chats.
:rtype: list | [
"Returns",
"unique",
"chat",
"IDs",
"from",
"/",
"start",
"command",
"messages",
"sent",
"to",
"our",
"bot",
"by",
"users",
".",
"Those",
"chat",
"IDs",
"can",
"be",
"used",
"to",
"send",
"messages",
"to",
"chats",
"."
] | python | train | 35.571429 |
tensorflow/tensor2tensor | tensor2tensor/trax/rlax/ppo.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L799-L816 | def value_opt_step(i,
opt_state,
opt_update,
value_net_apply,
padded_observations,
padded_rewards,
reward_mask,
gamma=0.99):
"""Value optimizer step."""
value_params = trax_opt.get_pa... | [
"def",
"value_opt_step",
"(",
"i",
",",
"opt_state",
",",
"opt_update",
",",
"value_net_apply",
",",
"padded_observations",
",",
"padded_rewards",
",",
"reward_mask",
",",
"gamma",
"=",
"0.99",
")",
":",
"value_params",
"=",
"trax_opt",
".",
"get_params",
"(",
... | Value optimizer step. | [
"Value",
"optimizer",
"step",
"."
] | python | train | 33.111111 |
Clinical-Genomics/scout | scout/build/case.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/build/case.py#L11-L33 | def build_phenotype(phenotype_id, adapter):
"""Build a small phenotype object
Build a dictionary with phenotype_id and description
Args:
phenotype_id (str): The phenotype id
adapter (scout.adapter.MongoAdapter)
Returns:
phenotype_obj (dict):
dict(
phen... | [
"def",
"build_phenotype",
"(",
"phenotype_id",
",",
"adapter",
")",
":",
"phenotype_obj",
"=",
"{",
"}",
"phenotype",
"=",
"adapter",
".",
"hpo_term",
"(",
"phenotype_id",
")",
"if",
"phenotype",
":",
"phenotype_obj",
"[",
"'phenotype_id'",
"]",
"=",
"phenotyp... | Build a small phenotype object
Build a dictionary with phenotype_id and description
Args:
phenotype_id (str): The phenotype id
adapter (scout.adapter.MongoAdapter)
Returns:
phenotype_obj (dict):
dict(
phenotype_id = str,
feature = str, # descri... | [
"Build",
"a",
"small",
"phenotype",
"object"
] | python | test | 26.869565 |
BreakingBytes/simkit | simkit/core/layers.py | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/layers.py#L64-L79 | def add(self, src_cls, module, package=None):
"""
Add layer class to model. This method may be overloaded by layer.
:param src_cls: layer class to add, should not start with underscores
:type src_cls: str
:param module: Python module that contains layer class
:type modul... | [
"def",
"add",
"(",
"self",
",",
"src_cls",
",",
"module",
",",
"package",
"=",
"None",
")",
":",
"# import module containing the layer class",
"mod",
"=",
"importlib",
".",
"import_module",
"(",
"module",
",",
"package",
")",
"# get layer class definition from the m... | Add layer class to model. This method may be overloaded by layer.
:param src_cls: layer class to add, should not start with underscores
:type src_cls: str
:param module: Python module that contains layer class
:type module: str
:param package: optional package containing module ... | [
"Add",
"layer",
"class",
"to",
"model",
".",
"This",
"method",
"may",
"be",
"overloaded",
"by",
"layer",
"."
] | python | train | 43.4375 |
a1ezzz/wasp-general | wasp_general/crypto/aes.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/aes.py#L180-L191 | def reverse_pad(self, data, block_size):
""" :meth:`.WBlockPadding.reverse_pad` method implementation
"""
pad_byte = data[-1]
if pad_byte > block_size:
raise ValueError('Invalid padding')
padding = bytes([pad_byte] * pad_byte)
if data[-pad_byte:] != padding:
raise ValueError('Invalid padding')
ret... | [
"def",
"reverse_pad",
"(",
"self",
",",
"data",
",",
"block_size",
")",
":",
"pad_byte",
"=",
"data",
"[",
"-",
"1",
"]",
"if",
"pad_byte",
">",
"block_size",
":",
"raise",
"ValueError",
"(",
"'Invalid padding'",
")",
"padding",
"=",
"bytes",
"(",
"[",
... | :meth:`.WBlockPadding.reverse_pad` method implementation | [
":",
"meth",
":",
".",
"WBlockPadding",
".",
"reverse_pad",
"method",
"implementation"
] | python | train | 27.416667 |
pkkid/python-plexapi | plexapi/video.py | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/video.py#L75-L79 | def markUnwatched(self):
""" Mark video unwatched. """
key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | [
"def",
"markUnwatched",
"(",
"self",
")",
":",
"key",
"=",
"'/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library'",
"%",
"self",
".",
"ratingKey",
"self",
".",
"_server",
".",
"query",
"(",
"key",
")",
"self",
".",
"reload",
"(",
")"
] | Mark video unwatched. | [
"Mark",
"video",
"unwatched",
"."
] | python | train | 41 |
thusoy/pwm | pwm/core.py | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L147-L155 | def bootstrap(self, path_or_uri):
""" Initialize a database.
:param database_path: The absolute path to the database to initialize.
"""
_logger.debug("Bootstrapping new database: %s", path_or_uri)
self.database_uri = _urify_db(path_or_uri)
db = sa.create_engine(self.data... | [
"def",
"bootstrap",
"(",
"self",
",",
"path_or_uri",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Bootstrapping new database: %s\"",
",",
"path_or_uri",
")",
"self",
".",
"database_uri",
"=",
"_urify_db",
"(",
"path_or_uri",
")",
"db",
"=",
"sa",
".",
"create_en... | Initialize a database.
:param database_path: The absolute path to the database to initialize. | [
"Initialize",
"a",
"database",
"."
] | python | test | 39.777778 |
appliedsec/pygeoip | pygeoip/__init__.py | https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L553-L562 | def record_by_name(self, hostname):
"""
Returns dictionary with city data containing `country_code`, `country_name`,
`region`, `city`, `postal_code`, `latitude`, `longitude`, `dma_code`,
`metro_code`, `area_code`, `region_code` and `time_zone`.
:arg hostname: Hostname (e.g. exam... | [
"def",
"record_by_name",
"(",
"self",
",",
"hostname",
")",
":",
"addr",
"=",
"self",
".",
"_gethostbyname",
"(",
"hostname",
")",
"return",
"self",
".",
"record_by_addr",
"(",
"addr",
")"
] | Returns dictionary with city data containing `country_code`, `country_name`,
`region`, `city`, `postal_code`, `latitude`, `longitude`, `dma_code`,
`metro_code`, `area_code`, `region_code` and `time_zone`.
:arg hostname: Hostname (e.g. example.com) | [
"Returns",
"dictionary",
"with",
"city",
"data",
"containing",
"country_code",
"country_name",
"region",
"city",
"postal_code",
"latitude",
"longitude",
"dma_code",
"metro_code",
"area_code",
"region_code",
"and",
"time_zone",
"."
] | python | valid | 41.7 |
fake-name/ChromeController | ChromeController/Generator/Generated.py | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L5150-L5168 | def ServiceWorker_setForceUpdateOnPageLoad(self, forceUpdateOnPageLoad):
"""
Function path: ServiceWorker.setForceUpdateOnPageLoad
Domain: ServiceWorker
Method name: setForceUpdateOnPageLoad
Parameters:
Required arguments:
'forceUpdateOnPageLoad' (type: boolean) -> No description
No return v... | [
"def",
"ServiceWorker_setForceUpdateOnPageLoad",
"(",
"self",
",",
"forceUpdateOnPageLoad",
")",
":",
"assert",
"isinstance",
"(",
"forceUpdateOnPageLoad",
",",
"(",
"bool",
",",
")",
")",
",",
"\"Argument 'forceUpdateOnPageLoad' must be of type '['bool']'. Received type: '%s'\... | Function path: ServiceWorker.setForceUpdateOnPageLoad
Domain: ServiceWorker
Method name: setForceUpdateOnPageLoad
Parameters:
Required arguments:
'forceUpdateOnPageLoad' (type: boolean) -> No description
No return value. | [
"Function",
"path",
":",
"ServiceWorker",
".",
"setForceUpdateOnPageLoad",
"Domain",
":",
"ServiceWorker",
"Method",
"name",
":",
"setForceUpdateOnPageLoad",
"Parameters",
":",
"Required",
"arguments",
":",
"forceUpdateOnPageLoad",
"(",
"type",
":",
"boolean",
")",
"-... | python | train | 34.789474 |
sckott/pygbif | pygbif/utils/wkt_rewind.py | https://github.com/sckott/pygbif/blob/bf54f2920bc46d97d7e2e1b0c8059e5878f3c5ab/pygbif/utils/wkt_rewind.py#L6-L36 | def wkt_rewind(x, digits = None):
'''
reverse WKT winding order
:param x: [str] WKT string
:param digits: [int] number of digits after decimal to use for the return string.
by default, we use the mean number of digits in your string.
:return: a string
Usage::
from py... | [
"def",
"wkt_rewind",
"(",
"x",
",",
"digits",
"=",
"None",
")",
":",
"z",
"=",
"wkt",
".",
"loads",
"(",
"x",
")",
"if",
"digits",
"is",
"None",
":",
"coords",
"=",
"z",
"[",
"'coordinates'",
"]",
"nums",
"=",
"__flatten",
"(",
"coords",
")",
"de... | reverse WKT winding order
:param x: [str] WKT string
:param digits: [int] number of digits after decimal to use for the return string.
by default, we use the mean number of digits in your string.
:return: a string
Usage::
from pygbif import wkt_rewind
x = 'POLYGON((1... | [
"reverse",
"WKT",
"winding",
"order"
] | python | train | 30.709677 |
profitbricks/profitbricks-sdk-python | profitbricks/client.py | https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1084-L1108 | def get_nic(self, datacenter_id, server_id, nic_id, depth=1):
"""
Retrieves a NIC by its ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str`... | [
"def",
"get_nic",
"(",
"self",
",",
"datacenter_id",
",",
"server_id",
",",
"nic_id",
",",
"depth",
"=",
"1",
")",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/datacenters/%s/servers/%s/nics/%s?depth=%s'",
"%",
"(",
"datacenter_id",
",",
"serve... | Retrieves a NIC by its ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param nic_id: The unique ID of the NIC.
:type nic_i... | [
"Retrieves",
"a",
"NIC",
"by",
"its",
"ID",
"."
] | python | valid | 29.44 |
invinst/ResponseBot | responsebot/responsebot_client.py | https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L249-L256 | def get_list(self, list_id):
"""
Get info of specified list
:param list_id: list ID number
:return: :class:`~responsebot.models.List` object
"""
return List(tweepy_list_to_json(self._client.get_list(list_id=list_id))) | [
"def",
"get_list",
"(",
"self",
",",
"list_id",
")",
":",
"return",
"List",
"(",
"tweepy_list_to_json",
"(",
"self",
".",
"_client",
".",
"get_list",
"(",
"list_id",
"=",
"list_id",
")",
")",
")"
] | Get info of specified list
:param list_id: list ID number
:return: :class:`~responsebot.models.List` object | [
"Get",
"info",
"of",
"specified",
"list"
] | python | train | 32.375 |
thefactory/marathon-python | marathon/client.py | https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L67-L74 | def _parse_response(response, clazz, is_list=False, resource_name=None):
"""Parse a Marathon response into an object or list of objects."""
target = response.json()[
resource_name] if resource_name else response.json()
if is_list:
return [clazz.from_json(resource) for res... | [
"def",
"_parse_response",
"(",
"response",
",",
"clazz",
",",
"is_list",
"=",
"False",
",",
"resource_name",
"=",
"None",
")",
":",
"target",
"=",
"response",
".",
"json",
"(",
")",
"[",
"resource_name",
"]",
"if",
"resource_name",
"else",
"response",
".",... | Parse a Marathon response into an object or list of objects. | [
"Parse",
"a",
"Marathon",
"response",
"into",
"an",
"object",
"or",
"list",
"of",
"objects",
"."
] | python | train | 48.25 |
tjomasc/snekbol | snekbol/document.py | https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L460-L481 | def _extend_module_definitions(self, graph):
"""
Using collected module definitions extend linkages
"""
for mod_id in self._modules:
mod_identity = self._get_triplet_value(graph, URIRef(mod_id), SBOL.module)
modules = []
for mod in graph.triples((mod_i... | [
"def",
"_extend_module_definitions",
"(",
"self",
",",
"graph",
")",
":",
"for",
"mod_id",
"in",
"self",
".",
"_modules",
":",
"mod_identity",
"=",
"self",
".",
"_get_triplet_value",
"(",
"graph",
",",
"URIRef",
"(",
"mod_id",
")",
",",
"SBOL",
".",
"modul... | Using collected module definitions extend linkages | [
"Using",
"collected",
"module",
"definitions",
"extend",
"linkages"
] | python | train | 58 |
SmileyChris/easy-thumbnails | easy_thumbnails/utils.py | https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L111-L137 | def exif_orientation(im):
"""
Rotate and/or flip an image to respect the image's EXIF orientation data.
"""
try:
exif = im._getexif()
except Exception:
# There are many ways that _getexif fails, we're just going to blanket
# cover them all.
exif = None
if exif:
... | [
"def",
"exif_orientation",
"(",
"im",
")",
":",
"try",
":",
"exif",
"=",
"im",
".",
"_getexif",
"(",
")",
"except",
"Exception",
":",
"# There are many ways that _getexif fails, we're just going to blanket",
"# cover them all.",
"exif",
"=",
"None",
"if",
"exif",
":... | Rotate and/or flip an image to respect the image's EXIF orientation data. | [
"Rotate",
"and",
"/",
"or",
"flip",
"an",
"image",
"to",
"respect",
"the",
"image",
"s",
"EXIF",
"orientation",
"data",
"."
] | python | train | 35.888889 |
openstack/horizon | horizon/tables/views.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/views.py#L290-L314 | def get_filters(self, filters=None, filters_map=None):
"""Converts a string given by the user into a valid api filter value.
:filters: Default filter values.
{'filter1': filter_value, 'filter2': filter_value}
:filters_map: mapping between user input and valid api filter values.
... | [
"def",
"get_filters",
"(",
"self",
",",
"filters",
"=",
"None",
",",
"filters_map",
"=",
"None",
")",
":",
"filters",
"=",
"filters",
"or",
"{",
"}",
"filters_map",
"=",
"filters_map",
"or",
"{",
"}",
"filter_action",
"=",
"self",
".",
"table",
".",
"_... | Converts a string given by the user into a valid api filter value.
:filters: Default filter values.
{'filter1': filter_value, 'filter2': filter_value}
:filters_map: mapping between user input and valid api filter values.
{'filter_name':{_("true_value"):True, _("false_value"):Fal... | [
"Converts",
"a",
"string",
"given",
"by",
"the",
"user",
"into",
"a",
"valid",
"api",
"filter",
"value",
"."
] | python | train | 49.44 |
jakebasile/reap | reap/api/admin.py | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L209-L216 | def task_assignments(self):
'''Retrieves all tasks currently assigned to this project.'''
url = str.format(
'projects/{}/task_assignments',
self.id
)
response = self.hv.get_request(url)
return [TaskAssignment(self.hv, tj['task_assignment']) for tj in respo... | [
"def",
"task_assignments",
"(",
"self",
")",
":",
"url",
"=",
"str",
".",
"format",
"(",
"'projects/{}/task_assignments'",
",",
"self",
".",
"id",
")",
"response",
"=",
"self",
".",
"hv",
".",
"get_request",
"(",
"url",
")",
"return",
"[",
"TaskAssignment"... | Retrieves all tasks currently assigned to this project. | [
"Retrieves",
"all",
"tasks",
"currently",
"assigned",
"to",
"this",
"project",
"."
] | python | train | 39.625 |
saltstack/salt | salt/modules/dracr.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L67-L101 | def __execute_cmd(command, host=None,
admin_username=None, admin_password=None,
module=None):
'''
Execute rac commands
'''
if module:
# -a takes 'server' or 'switch' to represent all servers
# or all switches in a chassis. Allow
# user to say ... | [
"def",
"__execute_cmd",
"(",
"command",
",",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"if",
"module",
":",
"# -a takes 'server' or 'switch' to represent all servers",
"# or a... | Execute rac commands | [
"Execute",
"rac",
"commands"
] | python | train | 37.942857 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/monitoring.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/monitoring.py#L916-L932 | def publish_topology_description_changed(self, previous_description,
new_description, topology_id):
"""Publish a TopologyDescriptionChangedEvent to all topology listeners.
:Parameters:
- `previous_description`: The previous topology description.
... | [
"def",
"publish_topology_description_changed",
"(",
"self",
",",
"previous_description",
",",
"new_description",
",",
"topology_id",
")",
":",
"event",
"=",
"TopologyDescriptionChangedEvent",
"(",
"previous_description",
",",
"new_description",
",",
"topology_id",
")",
"f... | Publish a TopologyDescriptionChangedEvent to all topology listeners.
:Parameters:
- `previous_description`: The previous topology description.
- `new_description`: The new topology description.
- `topology_id`: A unique identifier for the topology this server
is a part of. | [
"Publish",
"a",
"TopologyDescriptionChangedEvent",
"to",
"all",
"topology",
"listeners",
"."
] | python | train | 47.647059 |
jjjake/iamine | iamine/core.py | https://github.com/jjjake/iamine/blob/f1fc123a5b40b2247c537382368d38bd744eebe0/iamine/core.py#L85-L93 | def get_global_rate_limit(self):
"""Get the global rate limit per client.
:rtype: int
:returns: The global rate limit for each client.
"""
r = urllib.request.urlopen('https://archive.org/metadata/iamine-rate-limiter')
j = json.loads(r.read().decode('utf-8'))
retu... | [
"def",
"get_global_rate_limit",
"(",
"self",
")",
":",
"r",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"'https://archive.org/metadata/iamine-rate-limiter'",
")",
"j",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"read",
"(",
")",
".",
"decode",
"(",
... | Get the global rate limit per client.
:rtype: int
:returns: The global rate limit for each client. | [
"Get",
"the",
"global",
"rate",
"limit",
"per",
"client",
"."
] | python | train | 41 |
treycucco/bidon | bidon/data_table.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L87-L94 | def is_cell_empty(self, cell):
"""Checks if the cell is empty."""
if cell is None:
return True
elif self._is_cell_empty:
return self._is_cell_empty(cell)
else:
return cell is None | [
"def",
"is_cell_empty",
"(",
"self",
",",
"cell",
")",
":",
"if",
"cell",
"is",
"None",
":",
"return",
"True",
"elif",
"self",
".",
"_is_cell_empty",
":",
"return",
"self",
".",
"_is_cell_empty",
"(",
"cell",
")",
"else",
":",
"return",
"cell",
"is",
"... | Checks if the cell is empty. | [
"Checks",
"if",
"the",
"cell",
"is",
"empty",
"."
] | python | train | 25.75 |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L471-L484 | def _loadBatch(self, item, batch):
"""
Loads the batch of items for this tree based on the inputed batch item.
:param item | <XBatchItem>
batch | <orb.RecordSet>
"""
if self.isThreadEnabled() and batch.isThreadEnabled():
self... | [
"def",
"_loadBatch",
"(",
"self",
",",
"item",
",",
"batch",
")",
":",
"if",
"self",
".",
"isThreadEnabled",
"(",
")",
"and",
"batch",
".",
"isThreadEnabled",
"(",
")",
":",
"self",
".",
"loadBatchRequested",
".",
"emit",
"(",
"batch",
")",
"self",
"."... | Loads the batch of items for this tree based on the inputed batch item.
:param item | <XBatchItem>
batch | <orb.RecordSet> | [
"Loads",
"the",
"batch",
"of",
"items",
"for",
"this",
"tree",
"based",
"on",
"the",
"inputed",
"batch",
"item",
".",
":",
"param",
"item",
"|",
"<XBatchItem",
">",
"batch",
"|",
"<orb",
".",
"RecordSet",
">"
] | python | train | 40.428571 |
holgern/pyedflib | pyedflib/edfwriter.py | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L383-L396 | def setStartdatetime(self, recording_start_time):
"""
Sets the recording start Time
Parameters
----------
recording_start_time: datetime object
Sets the recording start Time
"""
if isinstance(recording_start_time,datetime):
self.recording_... | [
"def",
"setStartdatetime",
"(",
"self",
",",
"recording_start_time",
")",
":",
"if",
"isinstance",
"(",
"recording_start_time",
",",
"datetime",
")",
":",
"self",
".",
"recording_start_time",
"=",
"recording_start_time",
"else",
":",
"self",
".",
"recording_start_ti... | Sets the recording start Time
Parameters
----------
recording_start_time: datetime object
Sets the recording start Time | [
"Sets",
"the",
"recording",
"start",
"Time"
] | python | train | 34.5 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L3633-L3791 | def update(self, fontsize=0.0, text_color=None, border_color=None, fill_color=None, rotate=-1):
"""Update the appearance of an annotation."""
if self.type[0] == ANNOT_WIDGET:
print("Use updateWidget method for form fields.")
return False
val = _fitz.Annot_update(self, f... | [
"def",
"update",
"(",
"self",
",",
"fontsize",
"=",
"0.0",
",",
"text_color",
"=",
"None",
",",
"border_color",
"=",
"None",
",",
"fill_color",
"=",
"None",
",",
"rotate",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"type",
"[",
"0",
"]",
"==",
"... | Update the appearance of an annotation. | [
"Update",
"the",
"appearance",
"of",
"an",
"annotation",
"."
] | python | train | 42.773585 |
enricobacis/wos | wos/client.py | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L278-L305 | def citedReferencesRetrieve(self, queryId, count=100, offset=1,
retrieveParameters=None):
"""The citedReferencesRetrieve operation submits a query returned by a
previous citedReferences operation.
This operation is useful for overcoming the retrieval limit of 100... | [
"def",
"citedReferencesRetrieve",
"(",
"self",
",",
"queryId",
",",
"count",
"=",
"100",
",",
"offset",
"=",
"1",
",",
"retrieveParameters",
"=",
"None",
")",
":",
"return",
"self",
".",
"_search",
".",
"service",
".",
"citedReferencesRetrieve",
"(",
"queryI... | The citedReferencesRetrieve operation submits a query returned by a
previous citedReferences operation.
This operation is useful for overcoming the retrieval limit of 100
records per query. For example, a citedReferences operation may find
106 cited references, as revealed by the conten... | [
"The",
"citedReferencesRetrieve",
"operation",
"submits",
"a",
"query",
"returned",
"by",
"a",
"previous",
"citedReferences",
"operation",
"."
] | python | train | 50.035714 |
pyviz/holoviews | holoviews/element/raster.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/element/raster.py#L119-L169 | def sample(self, samples=[], **sample_values):
"""
Sample the Raster along one or both of its dimensions,
returning a reduced dimensionality type, which is either
a ItemTable, Curve or Scatter. If two dimension samples
and a new_xaxis is provided the sample will be the value
... | [
"def",
"sample",
"(",
"self",
",",
"samples",
"=",
"[",
"]",
",",
"*",
"*",
"sample_values",
")",
":",
"if",
"isinstance",
"(",
"samples",
",",
"tuple",
")",
":",
"X",
",",
"Y",
"=",
"samples",
"samples",
"=",
"zip",
"(",
"X",
",",
"Y",
")",
"p... | Sample the Raster along one or both of its dimensions,
returning a reduced dimensionality type, which is either
a ItemTable, Curve or Scatter. If two dimension samples
and a new_xaxis is provided the sample will be the value
of the sampled unit indexed by the value in the new_xaxis
... | [
"Sample",
"the",
"Raster",
"along",
"one",
"or",
"both",
"of",
"its",
"dimensions",
"returning",
"a",
"reduced",
"dimensionality",
"type",
"which",
"is",
"either",
"a",
"ItemTable",
"Curve",
"or",
"Scatter",
".",
"If",
"two",
"dimension",
"samples",
"and",
"... | python | train | 47.54902 |
tensorflow/probability | tensorflow_probability/python/distributions/half_normal.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/half_normal.py#L180-L196 | def _kl_half_normal_half_normal(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default i... | [
"def",
"_kl_half_normal_half_normal",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_half_normal_half_normal\"",
")",
":",
"# Consistent with",
"# http://www.mast.queensu.ca/~communications/Papers/gil-ms... | Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default is "kl_half_normal_half_normal".
Returns:
Batchwi... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"a",
"||",
"b",
")",
"with",
"a",
"and",
"b",
"HalfNormal",
"."
] | python | test | 38.588235 |
juju/charm-helpers | charmhelpers/contrib/ssl/service.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ssl/service.py#L95-L116 | def _init_ca(self):
"""Generate the root ca's cert and key.
"""
if not exists(path_join(self.ca_dir, 'ca.cnf')):
with open(path_join(self.ca_dir, 'ca.cnf'), 'w') as fh:
fh.write(
CA_CONF_TEMPLATE % (self.get_conf_variables()))
if not exist... | [
"def",
"_init_ca",
"(",
"self",
")",
":",
"if",
"not",
"exists",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'ca.cnf'",
")",
")",
":",
"with",
"open",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'ca.cnf'",
")",
",",
"'w'",
")",
"as"... | Generate the root ca's cert and key. | [
"Generate",
"the",
"root",
"ca",
"s",
"cert",
"and",
"key",
"."
] | python | train | 46.409091 |
bunq/sdk_python | bunq/sdk/util.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/util.py#L35-L58 | def __generate_new_sandbox_user():
"""
:rtype: endpoint.SandboxUser
"""
url = ApiEnvironmentType.SANDBOX.uri_base + __ENDPOINT_SANDBOX_USER
headers = {
ApiClient.HEADER_REQUEST_ID: __UNIQUE_REQUEST_ID,
ApiClient.HEADER_CACHE_CONTROL: ApiClient._CACHE_CONTROL_NONE,
ApiClient... | [
"def",
"__generate_new_sandbox_user",
"(",
")",
":",
"url",
"=",
"ApiEnvironmentType",
".",
"SANDBOX",
".",
"uri_base",
"+",
"__ENDPOINT_SANDBOX_USER",
"headers",
"=",
"{",
"ApiClient",
".",
"HEADER_REQUEST_ID",
":",
"__UNIQUE_REQUEST_ID",
",",
"ApiClient",
".",
"HE... | :rtype: endpoint.SandboxUser | [
":",
"rtype",
":",
"endpoint",
".",
"SandboxUser"
] | python | train | 37.125 |
hsolbrig/PyShEx | pyshex/shex_evaluator.py | https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/shex_evaluator.py#L264-L289 | def genargs(prog: Optional[str] = None) -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser(prog)
parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options")
parser.add_argument("shex", help="ShEx specification... | [
"def",
"genargs",
"(",
"prog",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"ArgumentParser",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
")",
"parser",
".",
"add_argument",
"(",
"\"rdf\"",
",",
"help",
"=",
"\"Input RDF file or SPARQL en... | Create a command line parser
:return: parser | [
"Create",
"a",
"command",
"line",
"parser",
":",
"return",
":",
"parser"
] | python | train | 74.423077 |
bitesofcode/projexui | projexui/widgets/xenumbox.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xenumbox.py#L80-L98 | def currentValue(self):
"""
Returns the current value for the widget. If this widget is checkable
then the bitor value for all checked items is returned, otherwise, the
selected value is returned.
:return <int>
"""
enum = self.enum()
... | [
"def",
"currentValue",
"(",
"self",
")",
":",
"enum",
"=",
"self",
".",
"enum",
"(",
")",
"if",
"(",
"self",
".",
"isCheckable",
"(",
")",
")",
":",
"value",
"=",
"0",
"for",
"i",
"in",
"self",
".",
"checkedIndexes",
"(",
")",
":",
"value",
"|=",... | Returns the current value for the widget. If this widget is checkable
then the bitor value for all checked items is returned, otherwise, the
selected value is returned.
:return <int> | [
"Returns",
"the",
"current",
"value",
"for",
"the",
"widget",
".",
"If",
"this",
"widget",
"is",
"checkable",
"then",
"the",
"bitor",
"value",
"for",
"all",
"checked",
"items",
"is",
"returned",
"otherwise",
"the",
"selected",
"value",
"is",
"returned",
".",... | python | train | 34.473684 |
Gandi/gandi.cli | gandi/cli/commands/disk.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/disk.py#L91-L111 | def info(gandi, resource):
""" Display information about a disk.
Resource can be a disk name or ID
"""
output_keys = ['name', 'state', 'size', 'type', 'id', 'dc', 'vm',
'profile', 'kernel', 'cmdline']
resource = sorted(tuple(set(resource)))
vms = dict([(vm['id'], vm) for vm ... | [
"def",
"info",
"(",
"gandi",
",",
"resource",
")",
":",
"output_keys",
"=",
"[",
"'name'",
",",
"'state'",
",",
"'size'",
",",
"'type'",
",",
"'id'",
",",
"'dc'",
",",
"'vm'",
",",
"'profile'",
",",
"'kernel'",
",",
"'cmdline'",
"]",
"resource",
"=",
... | Display information about a disk.
Resource can be a disk name or ID | [
"Display",
"information",
"about",
"a",
"disk",
"."
] | python | train | 29.809524 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L112-L118 | def items(self):
"""Yield the async reuslts for the context."""
for key, task in self._tasks:
if not (task and task.result):
yield key, None
else:
yield key, json.loads(task.result)["payload"] | [
"def",
"items",
"(",
"self",
")",
":",
"for",
"key",
",",
"task",
"in",
"self",
".",
"_tasks",
":",
"if",
"not",
"(",
"task",
"and",
"task",
".",
"result",
")",
":",
"yield",
"key",
",",
"None",
"else",
":",
"yield",
"key",
",",
"json",
".",
"l... | Yield the async reuslts for the context. | [
"Yield",
"the",
"async",
"reuslts",
"for",
"the",
"context",
"."
] | python | train | 36.857143 |
dps/simplescheduler | simplescheduler/scheduler.py | https://github.com/dps/simplescheduler/blob/d633549a8b78d5c1ff37419f4970835f1c6a5947/simplescheduler/scheduler.py#L73-L77 | def schedule_in(self, job, timedelta):
""" Schedule job to run at datetime.timedelta from now."""
now = long(self._now() * 1e6)
when = now + timedelta.total_seconds() * 1e6
self.schedule(job, when) | [
"def",
"schedule_in",
"(",
"self",
",",
"job",
",",
"timedelta",
")",
":",
"now",
"=",
"long",
"(",
"self",
".",
"_now",
"(",
")",
"*",
"1e6",
")",
"when",
"=",
"now",
"+",
"timedelta",
".",
"total_seconds",
"(",
")",
"*",
"1e6",
"self",
".",
"sc... | Schedule job to run at datetime.timedelta from now. | [
"Schedule",
"job",
"to",
"run",
"at",
"datetime",
".",
"timedelta",
"from",
"now",
"."
] | python | train | 45 |
DataONEorg/d1_python | lib_common/src/d1_common/util.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L55-L77 | def get_content_type(content_type):
"""Extract the MIME type value from a content type string.
Removes any subtype and parameter values that may be present in the string.
Args:
content_type: str
String with content type and optional subtype and parameter fields.
Returns:
str: Stri... | [
"def",
"get_content_type",
"(",
"content_type",
")",
":",
"m",
"=",
"email",
".",
"message",
".",
"Message",
"(",
")",
"m",
"[",
"'Content-Type'",
"]",
"=",
"content_type",
"return",
"m",
".",
"get_content_type",
"(",
")"
] | Extract the MIME type value from a content type string.
Removes any subtype and parameter values that may be present in the string.
Args:
content_type: str
String with content type and optional subtype and parameter fields.
Returns:
str: String with only content type
Example:
... | [
"Extract",
"the",
"MIME",
"type",
"value",
"from",
"a",
"content",
"type",
"string",
"."
] | python | train | 24 |
CamDavidsonPilon/lifelines | lifelines/fitters/cox_time_varying_fitter.py | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/cox_time_varying_fitter.py#L707-L757 | def plot(self, columns=None, **errorbar_kwargs):
"""
Produces a visual representation of the coefficients, including their standard errors and magnitudes.
Parameters
----------
columns : list, optional
specify a subset of the columns to plot
errorbar_kwargs:
... | [
"def",
"plot",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"errorbar_kwargs",
")",
":",
"from",
"matplotlib",
"import",
"pyplot",
"as",
"plt",
"ax",
"=",
"errorbar_kwargs",
".",
"pop",
"(",
"\"ax\"",
",",
"None",
")",
"or",
"plt",
".",
"... | Produces a visual representation of the coefficients, including their standard errors and magnitudes.
Parameters
----------
columns : list, optional
specify a subset of the columns to plot
errorbar_kwargs:
pass in additional plotting commands to matplotlib errorb... | [
"Produces",
"a",
"visual",
"representation",
"of",
"the",
"coefficients",
"including",
"their",
"standard",
"errors",
"and",
"magnitudes",
"."
] | python | train | 34.509804 |
clalancette/pycdlib | pycdlib/dr.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/dr.py#L644-L660 | def change_existence(self, is_hidden):
# type: (bool) -> None
'''
Change the ISO9660 existence flag of this Directory Record.
Parameters:
is_hidden - True if this Directory Record should be hidden, False otherwise.
Returns:
Nothing.
'''
if not s... | [
"def",
"change_existence",
"(",
"self",
",",
"is_hidden",
")",
":",
"# type: (bool) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'Directory Record not yet initialized'",
")",
"if",
"is_hidden",
... | Change the ISO9660 existence flag of this Directory Record.
Parameters:
is_hidden - True if this Directory Record should be hidden, False otherwise.
Returns:
Nothing. | [
"Change",
"the",
"ISO9660",
"existence",
"flag",
"of",
"this",
"Directory",
"Record",
"."
] | python | train | 34.647059 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_hardware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_hardware.py#L135-L145 | def hardware_flexport_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
flexport = ET.SubElement(hardware, "flexport")
id = ET.SubElement(flexport, "id")... | [
"def",
"hardware_flexport_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hardware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hardware\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 39.636364 |
spyder-ide/spyder | spyder/plugins/console/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/plugin.py#L193-L198 | def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.focus_changed.connect(self.main.plugin_focus_changed)
self.main.add_dockwidget(self)
# Connecting the following signal once the dockwidget has been created:
self.shell.exception_occurred.connect(se... | [
"def",
"register_plugin",
"(",
"self",
")",
":",
"self",
".",
"focus_changed",
".",
"connect",
"(",
"self",
".",
"main",
".",
"plugin_focus_changed",
")",
"self",
".",
"main",
".",
"add_dockwidget",
"(",
"self",
")",
"# Connecting the following signal once the doc... | Register plugin in Spyder's main window | [
"Register",
"plugin",
"in",
"Spyder",
"s",
"main",
"window"
] | python | train | 56.166667 |
Esri/ArcREST | src/arcrest/common/symbology.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/symbology.py#L314-L328 | def value(self):
"""gets the color value"""
if self._outline is None:
return {
"type" : self._type,
"style" : self._style,
"color" : self._color.value,
}
else:
return {
"type" : self._type,
... | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_outline",
"is",
"None",
":",
"return",
"{",
"\"type\"",
":",
"self",
".",
"_type",
",",
"\"style\"",
":",
"self",
".",
"_style",
",",
"\"color\"",
":",
"self",
".",
"_color",
".",
"value",
... | gets the color value | [
"gets",
"the",
"color",
"value"
] | python | train | 29.666667 |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2089-L2111 | def download_needed(self, response, outfile, quiet=True):
""" determine if a download is needed based on timestamp. Return True
if needed (remote is newer) or False if local is newest.
Parameters
==========
response: the response from the API
outfile:... | [
"def",
"download_needed",
"(",
"self",
",",
"response",
",",
"outfile",
",",
"quiet",
"=",
"True",
")",
":",
"try",
":",
"remote_date",
"=",
"datetime",
".",
"strptime",
"(",
"response",
".",
"headers",
"[",
"'Last-Modified'",
"]",
",",
"'%a, %d %b %Y %X %Z'... | determine if a download is needed based on timestamp. Return True
if needed (remote is newer) or False if local is newest.
Parameters
==========
response: the response from the API
outfile: the output file to write to
quiet: suppress verbose outpu... | [
"determine",
"if",
"a",
"download",
"is",
"needed",
"based",
"on",
"timestamp",
".",
"Return",
"True",
"if",
"needed",
"(",
"remote",
"is",
"newer",
")",
"or",
"False",
"if",
"local",
"is",
"newest",
".",
"Parameters",
"==========",
"response",
":",
"the",... | python | train | 45.304348 |
shonenada/flask-rbac | flask_rbac/__init__.py | https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L100-L107 | def is_denied(self, role, method, resource):
"""Check wherther role is denied to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked.
"""
return (role, method, resource) in self._denied | [
"def",
"is_denied",
"(",
"self",
",",
"role",
",",
"method",
",",
"resource",
")",
":",
"return",
"(",
"role",
",",
"method",
",",
"resource",
")",
"in",
"self",
".",
"_denied"
] | Check wherther role is denied to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked. | [
"Check",
"wherther",
"role",
"is",
"denied",
"to",
"access",
"resource"
] | python | valid | 38.25 |
jstitch/MambuPy | MambuPy/rest/mambubranch.py | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambubranch.py#L78-L106 | def convertDict2Attrs(self, *args, **kwargs):
"""The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Branch object for each one, initializing them
one at a time, and changing the attrs attribute (which just
... | [
"def",
"convertDict2Attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"n",
",",
"b",
"in",
"enumerate",
"(",
"self",
".",
"attrs",
")",
":",
"# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!",
"try",
":",... | The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Branch object for each one, initializing them
one at a time, and changing the attrs attribute (which just
holds a list of plain dictionaries) with a MambuB... | [
"The",
"trick",
"for",
"iterable",
"Mambu",
"Objects",
"comes",
"here",
":"
] | python | train | 45.896552 |
novopl/peltak | src/peltak/core/log.py | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/log.py#L41-L51 | def err(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Per step status messages
Use this locally in a command definition to highlight more important
information.
"""
if len(args) or len(kw):
msg = msg.format(*args, **kw)
shell.cprint('-- <31>{}<0>'.format(msg)) | [
"def",
"err",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# type: (str, *Any, **Any) -> None",
"if",
"len",
"(",
"args",
")",
"or",
"len",
"(",
"kw",
")",
":",
"msg",
"=",
"msg",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
... | Per step status messages
Use this locally in a command definition to highlight more important
information. | [
"Per",
"step",
"status",
"messages"
] | python | train | 27.272727 |
materialsproject/pymatgen | pymatgen/analysis/local_env.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/local_env.py#L1041-L1052 | def get_max_bond_distance(self, el1_sym, el2_sym):
"""
Use Jmol algorithm to determine bond length from atomic parameters
Args:
el1_sym: (str) symbol of atom 1
el2_sym: (str) symbol of atom 2
Returns: (float) max bond length
"""
return sqrt(
... | [
"def",
"get_max_bond_distance",
"(",
"self",
",",
"el1_sym",
",",
"el2_sym",
")",
":",
"return",
"sqrt",
"(",
"(",
"self",
".",
"el_radius",
"[",
"el1_sym",
"]",
"+",
"self",
".",
"el_radius",
"[",
"el2_sym",
"]",
"+",
"self",
".",
"tol",
")",
"**",
... | Use Jmol algorithm to determine bond length from atomic parameters
Args:
el1_sym: (str) symbol of atom 1
el2_sym: (str) symbol of atom 2
Returns: (float) max bond length | [
"Use",
"Jmol",
"algorithm",
"to",
"determine",
"bond",
"length",
"from",
"atomic",
"parameters",
"Args",
":",
"el1_sym",
":",
"(",
"str",
")",
"symbol",
"of",
"atom",
"1",
"el2_sym",
":",
"(",
"str",
")",
"symbol",
"of",
"atom",
"2"
] | python | train | 32.083333 |
crytic/slither | slither/core/declarations/function.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L537-L543 | def signature_str(self):
"""
str: func_name(type1,type2) returns (type3)
Return the function signature as a str (contains the return values)
"""
name, parameters, returnVars = self.signature
return name+'('+','.join(parameters)+') returns('+','.join(returnVars)+')... | [
"def",
"signature_str",
"(",
"self",
")",
":",
"name",
",",
"parameters",
",",
"returnVars",
"=",
"self",
".",
"signature",
"return",
"name",
"+",
"'('",
"+",
"','",
".",
"join",
"(",
"parameters",
")",
"+",
"') returns('",
"+",
"','",
".",
"join",
"("... | str: func_name(type1,type2) returns (type3)
Return the function signature as a str (contains the return values) | [
"str",
":",
"func_name",
"(",
"type1",
"type2",
")",
"returns",
"(",
"type3",
")",
"Return",
"the",
"function",
"signature",
"as",
"a",
"str",
"(",
"contains",
"the",
"return",
"values",
")"
] | python | train | 45 |
MisterY/price-database | pricedb/cli.py | https://github.com/MisterY/price-database/blob/b4fd366b7763891c690fe3000b8840e656da023e/pricedb/cli.py#L30-L56 | def add(symbol: str, date, value, currency: str):
""" Add individual price """
symbol = symbol.upper()
currency = currency.upper()
app = PriceDbApplication()
price = PriceModel()
# security = SecuritySymbol("", "")
price.symbol.parse(symbol)
# price.symbol.mnemonic = price.symbol.mnemo... | [
"def",
"add",
"(",
"symbol",
":",
"str",
",",
"date",
",",
"value",
",",
"currency",
":",
"str",
")",
":",
"symbol",
"=",
"symbol",
".",
"upper",
"(",
")",
"currency",
"=",
"currency",
".",
"upper",
"(",
")",
"app",
"=",
"PriceDbApplication",
"(",
... | Add individual price | [
"Add",
"individual",
"price"
] | python | test | 27.407407 |
pkgw/pwkit | pwkit/synphot.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/synphot.py#L292-L305 | def pivot_wavelength(self):
"""Get the bandpass' pivot wavelength.
Unlike calc_pivot_wavelength(), this function will use a cached
value if available.
"""
wl = self.registry._pivot_wavelengths.get((self.telescope, self.band))
if wl is not None:
return wl
... | [
"def",
"pivot_wavelength",
"(",
"self",
")",
":",
"wl",
"=",
"self",
".",
"registry",
".",
"_pivot_wavelengths",
".",
"get",
"(",
"(",
"self",
".",
"telescope",
",",
"self",
".",
"band",
")",
")",
"if",
"wl",
"is",
"not",
"None",
":",
"return",
"wl",... | Get the bandpass' pivot wavelength.
Unlike calc_pivot_wavelength(), this function will use a cached
value if available. | [
"Get",
"the",
"bandpass",
"pivot",
"wavelength",
"."
] | python | train | 31.642857 |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py#L282-L290 | def _opcode_set(*names):
"""Return a set of opcodes by the names in `names`."""
s = set()
for name in names:
try:
s.add(_opcode(name))
except KeyError:
pass
return s | [
"def",
"_opcode_set",
"(",
"*",
"names",
")",
":",
"s",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"names",
":",
"try",
":",
"s",
".",
"add",
"(",
"_opcode",
"(",
"name",
")",
")",
"except",
"KeyError",
":",
"pass",
"return",
"s"
] | Return a set of opcodes by the names in `names`. | [
"Return",
"a",
"set",
"of",
"opcodes",
"by",
"the",
"names",
"in",
"names",
"."
] | python | test | 23.666667 |
leancloud/python-sdk | leancloud/object_.py | https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/object_.py#L145-L179 | def destroy_all(cls, objs):
"""
在一个请求中 destroy 多个 leancloud.Object 对象实例。
:param objs: 需要 destroy 的对象
:type objs: list
"""
if not objs:
return
if any(x.is_new() for x in objs):
raise ValueError("Could not destroy unsaved object")
d... | [
"def",
"destroy_all",
"(",
"cls",
",",
"objs",
")",
":",
"if",
"not",
"objs",
":",
"return",
"if",
"any",
"(",
"x",
".",
"is_new",
"(",
")",
"for",
"x",
"in",
"objs",
")",
":",
"raise",
"ValueError",
"(",
"\"Could not destroy unsaved object\"",
")",
"d... | 在一个请求中 destroy 多个 leancloud.Object 对象实例。
:param objs: 需要 destroy 的对象
:type objs: list | [
"在一个请求中",
"destroy",
"多个",
"leancloud",
".",
"Object",
"对象实例。"
] | python | train | 31.342857 |
lorien/grab | grab/transport/curl.py | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L134-L158 | def body_processor(self, chunk):
"""
Process body of response.
"""
if self.config_nobody:
self.curl.grab_callback_interrupted = True
return 0
bytes_read = len(chunk)
self.response_body_bytes_read += bytes_read
if self.body_file:
... | [
"def",
"body_processor",
"(",
"self",
",",
"chunk",
")",
":",
"if",
"self",
".",
"config_nobody",
":",
"self",
".",
"curl",
".",
"grab_callback_interrupted",
"=",
"True",
"return",
"0",
"bytes_read",
"=",
"len",
"(",
"chunk",
")",
"self",
".",
"response_bo... | Process body of response. | [
"Process",
"body",
"of",
"response",
"."
] | python | train | 32.36 |
Microsoft/nni | src/sdk/pynni/nni/gridsearch_tuner/gridsearch_tuner.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/gridsearch_tuner/gridsearch_tuner.py#L59-L94 | def json2paramater(self, ss_spec):
'''
generate all possible configs for hyperparameters from hyperparameter space.
ss_spec: hyperparameter space
'''
if isinstance(ss_spec, dict):
if '_type' in ss_spec.keys():
_type = ss_spec['_type']
_... | [
"def",
"json2paramater",
"(",
"self",
",",
"ss_spec",
")",
":",
"if",
"isinstance",
"(",
"ss_spec",
",",
"dict",
")",
":",
"if",
"'_type'",
"in",
"ss_spec",
".",
"keys",
"(",
")",
":",
"_type",
"=",
"ss_spec",
"[",
"'_type'",
"]",
"_value",
"=",
"ss_... | generate all possible configs for hyperparameters from hyperparameter space.
ss_spec: hyperparameter space | [
"generate",
"all",
"possible",
"configs",
"for",
"hyperparameters",
"from",
"hyperparameter",
"space",
".",
"ss_spec",
":",
"hyperparameter",
"space"
] | python | train | 42.194444 |
pmacosta/peng | peng/wave_core.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_core.py#L87-L97 | def _homogenize_waves(wave_a, wave_b):
"""
Generate combined independent variable vector.
The combination is from two waveforms and the (possibly interpolated)
dependent variable vectors of these two waveforms
"""
indep_vector = _get_indep_vector(wave_a, wave_b)
dep_vector_a = _interp_dep_v... | [
"def",
"_homogenize_waves",
"(",
"wave_a",
",",
"wave_b",
")",
":",
"indep_vector",
"=",
"_get_indep_vector",
"(",
"wave_a",
",",
"wave_b",
")",
"dep_vector_a",
"=",
"_interp_dep_vector",
"(",
"wave_a",
",",
"indep_vector",
")",
"dep_vector_b",
"=",
"_interp_dep_v... | Generate combined independent variable vector.
The combination is from two waveforms and the (possibly interpolated)
dependent variable vectors of these two waveforms | [
"Generate",
"combined",
"independent",
"variable",
"vector",
"."
] | python | test | 41 |
tanghaibao/goatools | goatools/go_enrichment.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_enrichment.py#L453-L464 | def prt_txt(prt, goea_results, prtfmt=None, **kws):
"""Print GOEA results in text format."""
objprt = PrtFmt()
if prtfmt is None:
flds = ['GO', 'NS', 'p_uncorrected',
'ratio_in_study', 'ratio_in_pop', 'depth', 'name', 'study_items']
prtfmt = objprt.get... | [
"def",
"prt_txt",
"(",
"prt",
",",
"goea_results",
",",
"prtfmt",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"objprt",
"=",
"PrtFmt",
"(",
")",
"if",
"prtfmt",
"is",
"None",
":",
"flds",
"=",
"[",
"'GO'",
",",
"'NS'",
",",
"'p_uncorrected'",
",",... | Print GOEA results in text format. | [
"Print",
"GOEA",
"results",
"in",
"text",
"format",
"."
] | python | train | 48.083333 |
PMEAL/OpenPNM | openpnm/materials/VoronoiFibers.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/materials/VoronoiFibers.py#L955-L995 | def _rotate_and_chop(self, verts, normal, axis=[0, 0, 1]):
r"""
Method to rotate a set of vertices (or coords) to align with an axis
points must be coplanar and normal must be given
Chops axis coord to give vertices back in 2D
Used to prepare verts for printing or calculating con... | [
"def",
"_rotate_and_chop",
"(",
"self",
",",
"verts",
",",
"normal",
",",
"axis",
"=",
"[",
"0",
",",
"0",
",",
"1",
"]",
")",
":",
"xaxis",
"=",
"[",
"1",
",",
"0",
",",
"0",
"]",
"yaxis",
"=",
"[",
"0",
",",
"1",
",",
"0",
"]",
"zaxis",
... | r"""
Method to rotate a set of vertices (or coords) to align with an axis
points must be coplanar and normal must be given
Chops axis coord to give vertices back in 2D
Used to prepare verts for printing or calculating convex hull in order
to arrange them in hull order for calcula... | [
"r",
"Method",
"to",
"rotate",
"a",
"set",
"of",
"vertices",
"(",
"or",
"coords",
")",
"to",
"align",
"with",
"an",
"axis",
"points",
"must",
"be",
"coplanar",
"and",
"normal",
"must",
"be",
"given",
"Chops",
"axis",
"coord",
"to",
"give",
"vertices",
... | python | train | 36.146341 |
saltstack/salt | salt/modules/vsphere.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4917-L4957 | def assign_default_storage_policy_to_datastore(policy, datastore,
service_instance=None):
'''
Assigns a storage policy as the default policy to a datastore.
policy
Name of the policy to assign.
datastore
Name of the datastore to assign.
... | [
"def",
"assign_default_storage_policy_to_datastore",
"(",
"policy",
",",
"datastore",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Assigning policy %s to datastore %s'",
",",
"policy",
",",
"datastore",
")",
"profile_manager",
"=",
"salt... | Assigns a storage policy as the default policy to a datastore.
policy
Name of the policy to assign.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.Service... | [
"Assigns",
"a",
"storage",
"policy",
"as",
"the",
"default",
"policy",
"to",
"a",
"datastore",
"."
] | python | train | 38.512195 |
sci-bots/serial-device | serial_device/mqtt.py | https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L162-L180 | def _serial_close(self, port):
'''
Handle close request.
Parameters
----------
port : str
Device name/port.
'''
if port in self.open_devices:
try:
self.open_devices[port].close()
except Exception as exception:
... | [
"def",
"_serial_close",
"(",
"self",
",",
"port",
")",
":",
"if",
"port",
"in",
"self",
".",
"open_devices",
":",
"try",
":",
"self",
".",
"open_devices",
"[",
"port",
"]",
".",
"close",
"(",
")",
"except",
"Exception",
"as",
"exception",
":",
"logger"... | Handle close request.
Parameters
----------
port : str
Device name/port. | [
"Handle",
"close",
"request",
"."
] | python | train | 28.263158 |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L329-L333 | def near_to_position(self, position, max_distance):
'''Returns true iff the record is within max_distance of the given position.
Note: chromosome name not checked, so that's up to you to do first.'''
end = self.ref_end_pos()
return self.POS <= position <= end or abs(position - self.POS) ... | [
"def",
"near_to_position",
"(",
"self",
",",
"position",
",",
"max_distance",
")",
":",
"end",
"=",
"self",
".",
"ref_end_pos",
"(",
")",
"return",
"self",
".",
"POS",
"<=",
"position",
"<=",
"end",
"or",
"abs",
"(",
"position",
"-",
"self",
".",
"POS"... | Returns true iff the record is within max_distance of the given position.
Note: chromosome name not checked, so that's up to you to do first. | [
"Returns",
"true",
"iff",
"the",
"record",
"is",
"within",
"max_distance",
"of",
"the",
"given",
"position",
".",
"Note",
":",
"chromosome",
"name",
"not",
"checked",
"so",
"that",
"s",
"up",
"to",
"you",
"to",
"do",
"first",
"."
] | python | train | 74 |
s0md3v/Photon | plugins/exporter.py | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/exporter.py#L6-L24 | def exporter(directory, method, datasets):
"""Export the results."""
if method.lower() == 'json':
# Convert json_dict to a JSON styled string
json_string = json.dumps(datasets, indent=4)
savefile = open('{}/exported.json'.format(directory), 'w+')
savefile.write(json_string)
... | [
"def",
"exporter",
"(",
"directory",
",",
"method",
",",
"datasets",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'json'",
":",
"# Convert json_dict to a JSON styled string",
"json_string",
"=",
"json",
".",
"dumps",
"(",
"datasets",
",",
"indent",... | Export the results. | [
"Export",
"the",
"results",
"."
] | python | train | 40.210526 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.