repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
sampottinger/pycotracer | pycotracer/mongo_aggregator.py | https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L200-L213 | def insert_loan_entries(database, entries):
"""Insert a set of records of a loan report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The loans collection will be
used fr... | [
"def",
"insert_loan_entries",
"(",
"database",
",",
"entries",
")",
":",
"entries",
"=",
"map",
"(",
"clean_entry",
",",
"entries",
")",
"database",
".",
"loans",
".",
"insert",
"(",
"entries",
",",
"continue_on_error",
"=",
"True",
")"
] | Insert a set of records of a loan report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The loans collection will be
used from this database.
@type db: pymongo.database.Da... | [
"Insert",
"a",
"set",
"of",
"records",
"of",
"a",
"loan",
"report",
"in",
"the",
"provided",
"database",
"."
] | python | train |
Miserlou/Zappa | zappa/core.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2076-L2096 | def delete_stack(self, name, wait=False):
"""
Delete the CF stack managed by Zappa.
"""
try:
stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
except: # pragma: no cover
print('No Zappa stack named {0}'.format(name))
return Fa... | [
"def",
"delete_stack",
"(",
"self",
",",
"name",
",",
"wait",
"=",
"False",
")",
":",
"try",
":",
"stack",
"=",
"self",
".",
"cf_client",
".",
"describe_stacks",
"(",
"StackName",
"=",
"name",
")",
"[",
"'Stacks'",
"]",
"[",
"0",
"]",
"except",
":",
... | Delete the CF stack managed by Zappa. | [
"Delete",
"the",
"CF",
"stack",
"managed",
"by",
"Zappa",
"."
] | python | train |
IAMconsortium/pyam | pyam/core.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1334-L1338 | def _aggregate(df, by):
"""Aggregate `df` by specified column(s), return indexed `pd.Series`"""
by = [by] if isstr(by) else by
cols = [c for c in list(df.columns) if c not in ['value'] + by]
return df.groupby(cols).sum()['value'] | [
"def",
"_aggregate",
"(",
"df",
",",
"by",
")",
":",
"by",
"=",
"[",
"by",
"]",
"if",
"isstr",
"(",
"by",
")",
"else",
"by",
"cols",
"=",
"[",
"c",
"for",
"c",
"in",
"list",
"(",
"df",
".",
"columns",
")",
"if",
"c",
"not",
"in",
"[",
"'val... | Aggregate `df` by specified column(s), return indexed `pd.Series` | [
"Aggregate",
"df",
"by",
"specified",
"column",
"(",
"s",
")",
"return",
"indexed",
"pd",
".",
"Series"
] | python | train |
UCL-INGI/INGInious | inginious/frontend/template_helper.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L148-L151 | def _generic_hook(self, name, **kwargs):
""" A generic hook that links the TemplateHelper with PluginManager """
entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None]
return "\n".join(entries) | [
"def",
"_generic_hook",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"entries",
"=",
"[",
"entry",
"for",
"entry",
"in",
"self",
".",
"_plugin_manager",
".",
"call_hook",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"if",
"entry",
"is",... | A generic hook that links the TemplateHelper with PluginManager | [
"A",
"generic",
"hook",
"that",
"links",
"the",
"TemplateHelper",
"with",
"PluginManager"
] | python | train |
jsommers/switchyard | switchyard/lib/packet/packet.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/packet/packet.py#L29-L40 | def to_bytes(self):
'''
Returns serialized bytes object representing all headers/
payloads in this packet'''
rawlist = []
i = len(self._headers)-1
while i >= 0:
self._headers[i].pre_serialize(b''.join(rawlist), self, i)
rawlist.insert(0, self._head... | [
"def",
"to_bytes",
"(",
"self",
")",
":",
"rawlist",
"=",
"[",
"]",
"i",
"=",
"len",
"(",
"self",
".",
"_headers",
")",
"-",
"1",
"while",
"i",
">=",
"0",
":",
"self",
".",
"_headers",
"[",
"i",
"]",
".",
"pre_serialize",
"(",
"b''",
".",
"join... | Returns serialized bytes object representing all headers/
payloads in this packet | [
"Returns",
"serialized",
"bytes",
"object",
"representing",
"all",
"headers",
"/",
"payloads",
"in",
"this",
"packet"
] | python | train |
jmoiron/johnny-cache | johnny/cache.py | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L178-L183 | def gen_multi_key(self, values, db='default'):
"""Takes a list of generations (not table keys) and returns a key."""
db = settings.DB_CACHE_KEYS[db]
if db and len(db) > 100:
db = db[0:68] + self.gen_key(db[68:])
return '%s_%s_multi_%s' % (self.prefix, db, self.gen_key(*values... | [
"def",
"gen_multi_key",
"(",
"self",
",",
"values",
",",
"db",
"=",
"'default'",
")",
":",
"db",
"=",
"settings",
".",
"DB_CACHE_KEYS",
"[",
"db",
"]",
"if",
"db",
"and",
"len",
"(",
"db",
")",
">",
"100",
":",
"db",
"=",
"db",
"[",
"0",
":",
"... | Takes a list of generations (not table keys) and returns a key. | [
"Takes",
"a",
"list",
"of",
"generations",
"(",
"not",
"table",
"keys",
")",
"and",
"returns",
"a",
"key",
"."
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/val.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L420-L507 | def content_val(self, ymldata=None, messages=None):
"""Validates the Command Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc."""
self._ymlproc = YAMLProcessor(self._ymlfile, False)
# Turn off the YAML Proce... | [
"def",
"content_val",
"(",
"self",
",",
"ymldata",
"=",
"None",
",",
"messages",
"=",
"None",
")",
":",
"self",
".",
"_ymlproc",
"=",
"YAMLProcessor",
"(",
"self",
".",
"_ymlfile",
",",
"False",
")",
"# Turn off the YAML Processor",
"log",
".",
"debug",
"(... | Validates the Command Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc. | [
"Validates",
"the",
"Command",
"Dictionary",
"to",
"ensure",
"the",
"contents",
"for",
"each",
"of",
"the",
"fields",
"meets",
"specific",
"criteria",
"regarding",
"the",
"expected",
"types",
"byte",
"ranges",
"etc",
"."
] | python | train |
pyvisa/pyvisa | pyvisa/rname.py | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/rname.py#L416-L488 | def filter(resources, query):
"""Filter a list of resources according to a query expression.
The search criteria specified in the query parameter has two parts:
1. a VISA regular expression over a resource string.
2. optional logical expression over attribute values
(not implemented in thi... | [
"def",
"filter",
"(",
"resources",
",",
"query",
")",
":",
"if",
"'{'",
"in",
"query",
":",
"query",
",",
"_",
"=",
"query",
".",
"split",
"(",
"'{'",
")",
"logger",
".",
"warning",
"(",
"'optional part of the query expression not supported. '",
"'See filter2'... | Filter a list of resources according to a query expression.
The search criteria specified in the query parameter has two parts:
1. a VISA regular expression over a resource string.
2. optional logical expression over attribute values
(not implemented in this function, see below).
.. note:... | [
"Filter",
"a",
"list",
"of",
"resources",
"according",
"to",
"a",
"query",
"expression",
"."
] | python | train |
Stewori/pytypes | pytypes/type_util.py | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L533-L536 | def is_builtin_type(tp):
"""Checks if the given type is a builtin one.
"""
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | [
"def",
"is_builtin_type",
"(",
"tp",
")",
":",
"return",
"hasattr",
"(",
"__builtins__",
",",
"tp",
".",
"__name__",
")",
"and",
"tp",
"is",
"getattr",
"(",
"__builtins__",
",",
"tp",
".",
"__name__",
")"
] | Checks if the given type is a builtin one. | [
"Checks",
"if",
"the",
"given",
"type",
"is",
"a",
"builtin",
"one",
"."
] | python | train |
inasafe/inasafe | safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py#L223-L229 | def clear(self):
"""Clear current state."""
# Adapted from http://stackoverflow.com/a/13103617/1198772
for i in reversed(list(range(self.kwExtraKeywordsGridLayout.count()))):
self.kwExtraKeywordsGridLayout.itemAt(i).widget().setParent(None)
self.parameters = []
self.p... | [
"def",
"clear",
"(",
"self",
")",
":",
"# Adapted from http://stackoverflow.com/a/13103617/1198772",
"for",
"i",
"in",
"reversed",
"(",
"list",
"(",
"range",
"(",
"self",
".",
"kwExtraKeywordsGridLayout",
".",
"count",
"(",
")",
")",
")",
")",
":",
"self",
"."... | Clear current state. | [
"Clear",
"current",
"state",
"."
] | python | train |
python-diamond/Diamond | src/diamond/handler/logentries_diamond.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/logentries_diamond.py#L70-L83 | def _send(self):
"""
Convert message to a json object and send to Lognetries
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
topic, value, timestamp = str(metric).split()
msg = json.dumps({"event": {topic: value}})
req = urllib... | [
"def",
"_send",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"queue",
")",
">",
"0",
":",
"metric",
"=",
"self",
".",
"queue",
".",
"popleft",
"(",
")",
"topic",
",",
"value",
",",
"timestamp",
"=",
"str",
"(",
"metric",
")",
".",
"... | Convert message to a json object and send to Lognetries | [
"Convert",
"message",
"to",
"a",
"json",
"object",
"and",
"send",
"to",
"Lognetries"
] | python | train |
nccgroup/opinel | opinel/utils/credentials.py | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L311-L319 | def read_profile_from_environment_variables():
"""
Read profiles from env
:return:
"""
role_arn = os.environ.get('AWS_ROLE_ARN', None)
external_id = os.environ.get('AWS_EXTERNAL_ID', None)
return role_arn, external_id | [
"def",
"read_profile_from_environment_variables",
"(",
")",
":",
"role_arn",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_ROLE_ARN'",
",",
"None",
")",
"external_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_EXTERNAL_ID'",
",",
"None",
")",
"re... | Read profiles from env
:return: | [
"Read",
"profiles",
"from",
"env"
] | python | train |
SeattleTestbed/seash | seash_modules.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/seash_modules.py#L450-L478 | def enable_modules_from_last_session(seashcommanddict):
"""
Enable every module that isn't marked as disabled in the modules folder.
This function is meant to be called when seash is initializing and nowhere
else. A module is marked as disabled when there is a modulename.disabled
file.
"""
successfully_... | [
"def",
"enable_modules_from_last_session",
"(",
"seashcommanddict",
")",
":",
"successfully_enabled_modules",
"=",
"[",
"]",
"modules_to_enable",
"=",
"get_enabled_modules",
"(",
")",
"for",
"modulename",
"in",
"modules_to_enable",
":",
"# There are no bad side effects to sea... | Enable every module that isn't marked as disabled in the modules folder.
This function is meant to be called when seash is initializing and nowhere
else. A module is marked as disabled when there is a modulename.disabled
file. | [
"Enable",
"every",
"module",
"that",
"isn",
"t",
"marked",
"as",
"disabled",
"in",
"the",
"modules",
"folder",
".",
"This",
"function",
"is",
"meant",
"to",
"be",
"called",
"when",
"seash",
"is",
"initializing",
"and",
"nowhere",
"else",
".",
"A",
"module"... | python | train |
dwavesystems/dwave_networkx | dwave_networkx/algorithms/independent_set.py | https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/independent_set.py#L24-L95 | def maximum_weighted_independent_set(G, weight=None, sampler=None, lagrange=2.0, **sampler_args):
"""Returns an approximate maximum weighted independent set.
Defines a QUBO with ground states corresponding to a
maximum weighted independent set and uses the sampler to sample
from it.
An independent... | [
"def",
"maximum_weighted_independent_set",
"(",
"G",
",",
"weight",
"=",
"None",
",",
"sampler",
"=",
"None",
",",
"lagrange",
"=",
"2.0",
",",
"*",
"*",
"sampler_args",
")",
":",
"# Get a QUBO representation of the problem",
"Q",
"=",
"maximum_weighted_independent_... | Returns an approximate maximum weighted independent set.
Defines a QUBO with ground states corresponding to a
maximum weighted independent set and uses the sampler to sample
from it.
An independent set is a set of nodes such that the subgraph
of G induced by these nodes contains no edges. A maximu... | [
"Returns",
"an",
"approximate",
"maximum",
"weighted",
"independent",
"set",
"."
] | python | train |
sastrarobotics/pyHerkulex | herkulex.py | https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L848-L868 | def set_servo_angle(self, goalangle, goaltime, led):
""" Sets the servo angle (in degrees)
Enable torque using torque_on function before calling this
Args:
goalangle (int): The desired angle in degrees, range -150 to 150
goaltime (int): the time taken to move from prese... | [
"def",
"set_servo_angle",
"(",
"self",
",",
"goalangle",
",",
"goaltime",
",",
"led",
")",
":",
"if",
"(",
"self",
".",
"servomodel",
"==",
"0x06",
")",
"or",
"(",
"self",
".",
"servomodel",
"==",
"0x04",
")",
":",
"goalposition",
"=",
"scale",
"(",
... | Sets the servo angle (in degrees)
Enable torque using torque_on function before calling this
Args:
goalangle (int): The desired angle in degrees, range -150 to 150
goaltime (int): the time taken to move from present
position to goalposition
led (int): t... | [
"Sets",
"the",
"servo",
"angle",
"(",
"in",
"degrees",
")"
] | python | train |
ArduPilot/MAVProxy | MAVProxy/tools/MAVExplorer.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/tools/MAVExplorer.py#L364-L406 | def save_graph(graphdef):
'''save a graph as XML'''
if graphdef.filename is None:
if 'HOME' in os.environ:
dname = os.path.join(os.environ['HOME'], '.mavproxy')
if os.path.exists(dname):
mp_util.mkdir_p(dname)
graphdef.filename = os.path.join(dname... | [
"def",
"save_graph",
"(",
"graphdef",
")",
":",
"if",
"graphdef",
".",
"filename",
"is",
"None",
":",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"dname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
",",... | save a graph as XML | [
"save",
"a",
"graph",
"as",
"XML"
] | python | train |
twisted/txaws | txaws/ec2/client.py | https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/ec2/client.py#L389-L401 | def describe_snapshots(self, *snapshot_ids):
"""Describe available snapshots.
TODO: ownerSet, restorableBySet
"""
snapshot_set = {}
for pos, snapshot_id in enumerate(snapshot_ids):
snapshot_set["SnapshotId.%d" % (pos + 1)] = snapshot_id
query = self.query_fac... | [
"def",
"describe_snapshots",
"(",
"self",
",",
"*",
"snapshot_ids",
")",
":",
"snapshot_set",
"=",
"{",
"}",
"for",
"pos",
",",
"snapshot_id",
"in",
"enumerate",
"(",
"snapshot_ids",
")",
":",
"snapshot_set",
"[",
"\"SnapshotId.%d\"",
"%",
"(",
"pos",
"+",
... | Describe available snapshots.
TODO: ownerSet, restorableBySet | [
"Describe",
"available",
"snapshots",
"."
] | python | train |
jsommers/switchyard | switchyard/lib/socket/socketemu.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/socket/socketemu.py#L393-L399 | def recv(self, buffersize, flags=0):
'''
Receive data on the socket. The buffersize and flags
arguments are currently ignored. Only returns the data.
'''
_,_,data = self._recv(buffersize)
return data | [
"def",
"recv",
"(",
"self",
",",
"buffersize",
",",
"flags",
"=",
"0",
")",
":",
"_",
",",
"_",
",",
"data",
"=",
"self",
".",
"_recv",
"(",
"buffersize",
")",
"return",
"data"
] | Receive data on the socket. The buffersize and flags
arguments are currently ignored. Only returns the data. | [
"Receive",
"data",
"on",
"the",
"socket",
".",
"The",
"buffersize",
"and",
"flags",
"arguments",
"are",
"currently",
"ignored",
".",
"Only",
"returns",
"the",
"data",
"."
] | python | train |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L1935-L1947 | def remove_component(self, component, **kwargs):
"""
[NOT IMPLEMENTED]
Remove a 'component' from the bundle
:raises NotImplementedError: because this isn't implemented yet
"""
# NOTE: run_checks will check if an entry is in the hierarchy but has no parameters
kw... | [
"def",
"remove_component",
"(",
"self",
",",
"component",
",",
"*",
"*",
"kwargs",
")",
":",
"# NOTE: run_checks will check if an entry is in the hierarchy but has no parameters",
"kwargs",
"[",
"'component'",
"]",
"=",
"component",
"# NOTE: we do not remove from 'model' by def... | [NOT IMPLEMENTED]
Remove a 'component' from the bundle
:raises NotImplementedError: because this isn't implemented yet | [
"[",
"NOT",
"IMPLEMENTED",
"]"
] | python | train |
corpusops/pdbclone | lib/pdb_clone/attach.py | https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/attach.py#L503-L519 | def spawn_gdb(pid, address=DFLT_ADDRESS, gdb='gdb', verbose=False,
ctx=None, proc_iut=None):
"""Spawn gdb and attach to a process."""
parent, child = socket.socketpair()
proc = Popen([gdb, '--interpreter=mi', '-nx'],
bufsize=0, stdin=child, stdout=child, stderr=STDOUT)
... | [
"def",
"spawn_gdb",
"(",
"pid",
",",
"address",
"=",
"DFLT_ADDRESS",
",",
"gdb",
"=",
"'gdb'",
",",
"verbose",
"=",
"False",
",",
"ctx",
"=",
"None",
",",
"proc_iut",
"=",
"None",
")",
":",
"parent",
",",
"child",
"=",
"socket",
".",
"socketpair",
"(... | Spawn gdb and attach to a process. | [
"Spawn",
"gdb",
"and",
"attach",
"to",
"a",
"process",
"."
] | python | train |
awslabs/sockeye | sockeye/training.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/training.py#L322-L328 | def prepare_batch(self, batch: mx.io.DataBatch):
"""
Pre-fetches the next mini-batch.
:param batch: The mini-batch to prepare.
"""
self.module.prepare(batch) | [
"def",
"prepare_batch",
"(",
"self",
",",
"batch",
":",
"mx",
".",
"io",
".",
"DataBatch",
")",
":",
"self",
".",
"module",
".",
"prepare",
"(",
"batch",
")"
] | Pre-fetches the next mini-batch.
:param batch: The mini-batch to prepare. | [
"Pre",
"-",
"fetches",
"the",
"next",
"mini",
"-",
"batch",
"."
] | python | train |
saltstack/salt | salt/daemons/masterapi.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/masterapi.py#L91-L130 | def clean_fsbackend(opts):
'''
Clean out the old fileserver backends
'''
# Clear remote fileserver backend caches so they get recreated
for backend in ('git', 'hg', 'svn'):
if backend in opts['fileserver_backend']:
env_cache = os.path.join(
opts['cachedir'],
... | [
"def",
"clean_fsbackend",
"(",
"opts",
")",
":",
"# Clear remote fileserver backend caches so they get recreated",
"for",
"backend",
"in",
"(",
"'git'",
",",
"'hg'",
",",
"'svn'",
")",
":",
"if",
"backend",
"in",
"opts",
"[",
"'fileserver_backend'",
"]",
":",
"env... | Clean out the old fileserver backends | [
"Clean",
"out",
"the",
"old",
"fileserver",
"backends"
] | python | train |
singularityhub/sregistry-cli | sregistry/main/__template__/query.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/__template__/query.py#L46-L73 | def search_all(self):
'''a "show all" search that doesn't require a query'''
# This should be your apis url for a search
url = '...'
# paginte get is what it sounds like, and what you want for multiple
# pages of results
results = self._paginate_get(url)
if len(results) == 0:
b... | [
"def",
"search_all",
"(",
"self",
")",
":",
"# This should be your apis url for a search",
"url",
"=",
"'...'",
"# paginte get is what it sounds like, and what you want for multiple",
"# pages of results",
"results",
"=",
"self",
".",
"_paginate_get",
"(",
"url",
")",
"if",
... | a "show all" search that doesn't require a query | [
"a",
"show",
"all",
"search",
"that",
"doesn",
"t",
"require",
"a",
"query"
] | python | test |
prompt-toolkit/pyvim | pyvim/commands/commands.py | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/commands/commands.py#L422-L428 | def color_scheme(editor, variables):
"""
Go to one of the open buffers.
"""
colorscheme = variables.get('colorscheme')
if colorscheme:
editor.use_colorscheme(colorscheme) | [
"def",
"color_scheme",
"(",
"editor",
",",
"variables",
")",
":",
"colorscheme",
"=",
"variables",
".",
"get",
"(",
"'colorscheme'",
")",
"if",
"colorscheme",
":",
"editor",
".",
"use_colorscheme",
"(",
"colorscheme",
")"
] | Go to one of the open buffers. | [
"Go",
"to",
"one",
"of",
"the",
"open",
"buffers",
"."
] | python | train |
joestump/python-oauth2 | oauth2/__init__.py | https://github.com/joestump/python-oauth2/blob/b94f69b1ad195513547924e380d9265133e995fa/oauth2/__init__.py#L393-L405 | def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(v)) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k... | [
"def",
"to_header",
"(",
"self",
",",
"realm",
"=",
"''",
")",
":",
"oauth_params",
"=",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"'oauth_'",
")",
")",
"stringy... | Serialize as a header for an HTTPAuth request. | [
"Serialize",
"as",
"a",
"header",
"for",
"an",
"HTTPAuth",
"request",
"."
] | python | train |
PetrochukM/PyTorch-NLP | examples/snli/util.py | https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/examples/snli/util.py#L10-L24 | def makedirs(name):
"""helper function for python 2 and 3 to call os.makedirs()
avoiding an error if the directory to be created already exists"""
import os, errno
try:
os.makedirs(name)
except OSError as ex:
if ex.errno == errno.EEXIST and os.path.isdir(name):
# ign... | [
"def",
"makedirs",
"(",
"name",
")",
":",
"import",
"os",
",",
"errno",
"try",
":",
"os",
".",
"makedirs",
"(",
"name",
")",
"except",
"OSError",
"as",
"ex",
":",
"if",
"ex",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
"... | helper function for python 2 and 3 to call os.makedirs()
avoiding an error if the directory to be created already exists | [
"helper",
"function",
"for",
"python",
"2",
"and",
"3",
"to",
"call",
"os",
".",
"makedirs",
"()",
"avoiding",
"an",
"error",
"if",
"the",
"directory",
"to",
"be",
"created",
"already",
"exists"
] | python | train |
pymc-devs/pymc | pymc/distributions.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L957-L965 | def rcategorical(p, size=None):
"""
Categorical random variates.
"""
out = flib.rcat(p, np.random.random(size=size))
if sum(out.shape) == 1:
return out.squeeze()
else:
return out | [
"def",
"rcategorical",
"(",
"p",
",",
"size",
"=",
"None",
")",
":",
"out",
"=",
"flib",
".",
"rcat",
"(",
"p",
",",
"np",
".",
"random",
".",
"random",
"(",
"size",
"=",
"size",
")",
")",
"if",
"sum",
"(",
"out",
".",
"shape",
")",
"==",
"1"... | Categorical random variates. | [
"Categorical",
"random",
"variates",
"."
] | python | train |
spacetelescope/synphot_refactor | synphot/models.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/models.py#L193-L214 | def sampleset(self, step=0.01, minimal=False):
"""Return ``x`` array that samples the feature.
Parameters
----------
step : float
Distance of first and last points w.r.t. bounding box.
minimal : bool
Only return the minimal points needed to define the bo... | [
"def",
"sampleset",
"(",
"self",
",",
"step",
"=",
"0.01",
",",
"minimal",
"=",
"False",
")",
":",
"w1",
",",
"w2",
"=",
"self",
".",
"bounding_box",
"if",
"self",
".",
"_n_models",
"==",
"1",
":",
"w",
"=",
"self",
".",
"_calc_sampleset",
"(",
"w1... | Return ``x`` array that samples the feature.
Parameters
----------
step : float
Distance of first and last points w.r.t. bounding box.
minimal : bool
Only return the minimal points needed to define the box;
i.e., box edges and a point outside on each... | [
"Return",
"x",
"array",
"that",
"samples",
"the",
"feature",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/runsnakerun/runsnake.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/runsnakerun/runsnake.py#L729-L747 | def SaveState( self, config_parser ):
"""Retrieve window state to be restored on the next run..."""
if not config_parser.has_section( 'window' ):
config_parser.add_section( 'window' )
if self.IsMaximized():
config_parser.set( 'window', 'maximized', str(True))
else... | [
"def",
"SaveState",
"(",
"self",
",",
"config_parser",
")",
":",
"if",
"not",
"config_parser",
".",
"has_section",
"(",
"'window'",
")",
":",
"config_parser",
".",
"add_section",
"(",
"'window'",
")",
"if",
"self",
".",
"IsMaximized",
"(",
")",
":",
"confi... | Retrieve window state to be restored on the next run... | [
"Retrieve",
"window",
"state",
"to",
"be",
"restored",
"on",
"the",
"next",
"run",
"..."
] | python | train |
RIPE-NCC/ripe-atlas-cousteau | ripe/atlas/cousteau/stream.py | https://github.com/RIPE-NCC/ripe-atlas-cousteau/blob/ffee2556aaa4df86525b88c269bb098de11678ec/ripe/atlas/cousteau/stream.py#L167-L175 | def timeout(self, seconds=None):
"""
Times out all streams after n seconds or wait forever if seconds is
None
"""
if seconds is None:
self.socketIO.wait()
else:
self.socketIO.wait(seconds=seconds) | [
"def",
"timeout",
"(",
"self",
",",
"seconds",
"=",
"None",
")",
":",
"if",
"seconds",
"is",
"None",
":",
"self",
".",
"socketIO",
".",
"wait",
"(",
")",
"else",
":",
"self",
".",
"socketIO",
".",
"wait",
"(",
"seconds",
"=",
"seconds",
")"
] | Times out all streams after n seconds or wait forever if seconds is
None | [
"Times",
"out",
"all",
"streams",
"after",
"n",
"seconds",
"or",
"wait",
"forever",
"if",
"seconds",
"is",
"None"
] | python | train |
vberlier/nbtlib | nbtlib/tag.py | https://github.com/vberlier/nbtlib/blob/9c9d58b5c4a530b0f1ffd76dda176f00406c3547/nbtlib/tag.py#L124-L128 | def write_string(value, buff, byteorder='big'):
"""Write a string to a file-like object."""
data = value.encode('utf-8')
write_numeric(USHORT, len(data), buff, byteorder)
buff.write(data) | [
"def",
"write_string",
"(",
"value",
",",
"buff",
",",
"byteorder",
"=",
"'big'",
")",
":",
"data",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"write_numeric",
"(",
"USHORT",
",",
"len",
"(",
"data",
")",
",",
"buff",
",",
"byteorder",
")",
"b... | Write a string to a file-like object. | [
"Write",
"a",
"string",
"to",
"a",
"file",
"-",
"like",
"object",
"."
] | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_wp.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L787-L810 | def savecsv(self, filename):
'''save waypoints to a file in human-readable CSV file'''
f = open(filename, mode='w')
headers = ["Seq", "Frame", "Cmd", "P1", "P2", "P3", "P4", "X", "Y", "Z"]
print(self.csv_line(headers))
f.write(self.csv_line(headers) + "\n")
for w in self.... | [
"def",
"savecsv",
"(",
"self",
",",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"mode",
"=",
"'w'",
")",
"headers",
"=",
"[",
"\"Seq\"",
",",
"\"Frame\"",
",",
"\"Cmd\"",
",",
"\"P1\"",
",",
"\"P2\"",
",",
"\"P3\"",
",",
"\"P4\"",
... | save waypoints to a file in human-readable CSV file | [
"save",
"waypoints",
"to",
"a",
"file",
"in",
"human",
"-",
"readable",
"CSV",
"file"
] | python | train |
abseil/abseil-py | absl/flags/_validators.py | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L424-L450 | def mark_bool_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is True.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one flag must be True. Otherwise,... | [
"def",
"mark_bool_flags_as_mutual_exclusive",
"(",
"flag_names",
",",
"required",
"=",
"False",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"for",
"flag_name",
"in",
"flag_names",
":",
"if",
"not",
"flag_values",
"[",
"flag_name",
"]",
".",
... | Ensures that only one flag among flag_names is True.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one flag must be True. Otherwise, at most
one flag can be True, and it is valid for all flags to be False.
flag_values: flags.FlagValues, optional FlagValues instance... | [
"Ensures",
"that",
"only",
"one",
"flag",
"among",
"flag_names",
"is",
"True",
"."
] | python | train |
shoebot/shoebot | lib/web/wikipedia.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L634-L644 | def convert_pre(self, markup):
""" Substitutes <pre> to Wikipedia markup by adding a space at the start of a line.
"""
for m in re.findall(self.re["preformatted"], markup):
markup = markup.replace(m, m.replace("\n", "\n "))
markup = re.sub("<pre.*?>\n{0,... | [
"def",
"convert_pre",
"(",
"self",
",",
"markup",
")",
":",
"for",
"m",
"in",
"re",
".",
"findall",
"(",
"self",
".",
"re",
"[",
"\"preformatted\"",
"]",
",",
"markup",
")",
":",
"markup",
"=",
"markup",
".",
"replace",
"(",
"m",
",",
"m",
".",
"... | Substitutes <pre> to Wikipedia markup by adding a space at the start of a line. | [
"Substitutes",
"<pre",
">",
"to",
"Wikipedia",
"markup",
"by",
"adding",
"a",
"space",
"at",
"the",
"start",
"of",
"a",
"line",
"."
] | python | valid |
saltstack/salt | salt/modules/influxdbmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdbmod.py#L114-L134 | def create_db(name, **client_args):
'''
Create a database.
name
Name of the database to create.
CLI Example:
.. code-block:: bash
salt '*' influxdb.create_db <name>
'''
if db_exists(name, **client_args):
log.info('DB \'%s\' already exists', name)
return Fa... | [
"def",
"create_db",
"(",
"name",
",",
"*",
"*",
"client_args",
")",
":",
"if",
"db_exists",
"(",
"name",
",",
"*",
"*",
"client_args",
")",
":",
"log",
".",
"info",
"(",
"'DB \\'%s\\' already exists'",
",",
"name",
")",
"return",
"False",
"client",
"=",
... | Create a database.
name
Name of the database to create.
CLI Example:
.. code-block:: bash
salt '*' influxdb.create_db <name> | [
"Create",
"a",
"database",
"."
] | python | train |
phaethon/kamene | kamene/plist.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/plist.py#L377-L388 | def pdfdump(self, filename = None, **kargs):
"""Creates a PDF file with a psdump of every packet
filename: name of the file to write to. If empty, a temporary file is used and
conf.prog.pdfreader is called"""
d = self._dump_document(**kargs)
if filename is None:
... | [
"def",
"pdfdump",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"d",
"=",
"self",
".",
"_dump_document",
"(",
"*",
"*",
"kargs",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"get_temp_file",
"(",
"autoext"... | Creates a PDF file with a psdump of every packet
filename: name of the file to write to. If empty, a temporary file is used and
conf.prog.pdfreader is called | [
"Creates",
"a",
"PDF",
"file",
"with",
"a",
"psdump",
"of",
"every",
"packet",
"filename",
":",
"name",
"of",
"the",
"file",
"to",
"write",
"to",
".",
"If",
"empty",
"a",
"temporary",
"file",
"is",
"used",
"and",
"conf",
".",
"prog",
".",
"pdfreader",
... | python | train |
minhhoit/yacms | yacms/pages/context_processors.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/context_processors.py#L4-L20 | def page(request):
"""
Adds the current page to the template context and runs its
``set_helper`` method. This was previously part of
``PageMiddleware``, but moved to a context processor so that
we could assign these template context variables without
the middleware depending on Django's ``Templa... | [
"def",
"page",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"page",
"=",
"getattr",
"(",
"request",
",",
"\"page\"",
",",
"None",
")",
"if",
"isinstance",
"(",
"page",
",",
"Page",
")",
":",
"# set_helpers has always expected the current template contex... | Adds the current page to the template context and runs its
``set_helper`` method. This was previously part of
``PageMiddleware``, but moved to a context processor so that
we could assign these template context variables without
the middleware depending on Django's ``TemplateResponse``. | [
"Adds",
"the",
"current",
"page",
"to",
"the",
"template",
"context",
"and",
"runs",
"its",
"set_helper",
"method",
".",
"This",
"was",
"previously",
"part",
"of",
"PageMiddleware",
"but",
"moved",
"to",
"a",
"context",
"processor",
"so",
"that",
"we",
"coul... | python | train |
oceanprotocol/squid-py | squid_py/ocean/ocean_templates.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_templates.py#L18-L40 | def propose(self, template_address, account):
"""
Propose a new template.
:param template_address: Address of the template contract, str
:param account: account proposing the template, Account
:return: bool
"""
try:
proposed = self._keeper.template_ma... | [
"def",
"propose",
"(",
"self",
",",
"template_address",
",",
"account",
")",
":",
"try",
":",
"proposed",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"propose_template",
"(",
"template_address",
",",
"account",
")",
"return",
"proposed",
"except... | Propose a new template.
:param template_address: Address of the template contract, str
:param account: account proposing the template, Account
:return: bool | [
"Propose",
"a",
"new",
"template",
"."
] | python | train |
mushkevych/scheduler | workers/abstract_mongo_worker.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/workers/abstract_mongo_worker.py#L27-L47 | def _flush_aggregated_objects(self):
""" method inserts aggregated objects into MongoDB
:return number_of_aggregated_objects """
if len(self.aggregated_objects) == 0:
# nothing to do
return 0
number_of_aggregated_objects = len(self.aggregated_objects)
... | [
"def",
"_flush_aggregated_objects",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"aggregated_objects",
")",
"==",
"0",
":",
"# nothing to do",
"return",
"0",
"number_of_aggregated_objects",
"=",
"len",
"(",
"self",
".",
"aggregated_objects",
")",
"self"... | method inserts aggregated objects into MongoDB
:return number_of_aggregated_objects | [
"method",
"inserts",
"aggregated",
"objects",
"into",
"MongoDB",
":",
"return",
"number_of_aggregated_objects"
] | python | train |
angr/angr | angr/knowledge_plugins/variables/variable_manager.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/knowledge_plugins/variables/variable_manager.py#L125-L168 | def make_phi_node(self, block_addr, *variables):
"""
Create a phi variable for variables at block `block_addr`.
:param int block_addr: The address of the current block.
:param variables: Variables that the phi variable represents.
:return: The created phi v... | [
"def",
"make_phi_node",
"(",
"self",
",",
"block_addr",
",",
"*",
"variables",
")",
":",
"existing_phis",
"=",
"set",
"(",
")",
"non_phis",
"=",
"set",
"(",
")",
"for",
"var",
"in",
"variables",
":",
"if",
"self",
".",
"is_phi_variable",
"(",
"var",
")... | Create a phi variable for variables at block `block_addr`.
:param int block_addr: The address of the current block.
:param variables: Variables that the phi variable represents.
:return: The created phi variable. | [
"Create",
"a",
"phi",
"variable",
"for",
"variables",
"at",
"block",
"block_addr",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/summary.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/summary.py#L240-L266 | def _repr(o, verbosity=1):
"""Get meaning object representation.
This function should be used when the simple str(o) output would result in
too general data. E.g. "<type 'instance'" is less meaningful than
"instance: Foo".
Keyword arguments:
verbosity -- if True the first row is treated as a t... | [
"def",
"_repr",
"(",
"o",
",",
"verbosity",
"=",
"1",
")",
":",
"res",
"=",
"\"\"",
"t",
"=",
"type",
"(",
"o",
")",
"if",
"(",
"verbosity",
"==",
"0",
")",
"or",
"(",
"t",
"not",
"in",
"representations",
")",
":",
"res",
"=",
"str",
"(",
"t"... | Get meaning object representation.
This function should be used when the simple str(o) output would result in
too general data. E.g. "<type 'instance'" is less meaningful than
"instance: Foo".
Keyword arguments:
verbosity -- if True the first row is treated as a table header | [
"Get",
"meaning",
"object",
"representation",
"."
] | python | train |
apache/airflow | airflow/hooks/hive_hooks.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/hive_hooks.py#L641-L680 | def _get_max_partition_from_part_specs(part_specs, partition_key, filter_map):
"""
Helper method to get max partition of partitions with partition_key
from part specs. key:value pair in filter_map will be used to
filter out partitions.
:param part_specs: list of partition specs.... | [
"def",
"_get_max_partition_from_part_specs",
"(",
"part_specs",
",",
"partition_key",
",",
"filter_map",
")",
":",
"if",
"not",
"part_specs",
":",
"return",
"None",
"# Assuming all specs have the same keys.",
"if",
"partition_key",
"not",
"in",
"part_specs",
"[",
"0",
... | Helper method to get max partition of partitions with partition_key
from part specs. key:value pair in filter_map will be used to
filter out partitions.
:param part_specs: list of partition specs.
:type part_specs: list
:param partition_key: partition key name.
:type par... | [
"Helper",
"method",
"to",
"get",
"max",
"partition",
"of",
"partitions",
"with",
"partition_key",
"from",
"part",
"specs",
".",
"key",
":",
"value",
"pair",
"in",
"filter_map",
"will",
"be",
"used",
"to",
"filter",
"out",
"partitions",
"."
] | python | test |
tensorflow/tensor2tensor | tensor2tensor/data_generators/text_problems.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L621-L627 | def text2text_distill_iterator(source_txt_path, target_txt_path,
distill_txt_path):
"""Yield dicts for Text2TextProblem.generate_samples from lines of files."""
for inputs, targets, dist_targets in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path),
... | [
"def",
"text2text_distill_iterator",
"(",
"source_txt_path",
",",
"target_txt_path",
",",
"distill_txt_path",
")",
":",
"for",
"inputs",
",",
"targets",
",",
"dist_targets",
"in",
"zip",
"(",
"txt_line_iterator",
"(",
"source_txt_path",
")",
",",
"txt_line_iterator",
... | Yield dicts for Text2TextProblem.generate_samples from lines of files. | [
"Yield",
"dicts",
"for",
"Text2TextProblem",
".",
"generate_samples",
"from",
"lines",
"of",
"files",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/internal/distribution_util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1274-L1320 | def pick_vector(cond, true_vector, false_vector, name="pick_vector"):
"""Picks possibly different length row `Tensor`s based on condition.
Value `Tensor`s should have exactly one dimension.
If `cond` is a python Boolean or `tf.constant` then either `true_vector` or
`false_vector` is immediately returned. I.e.... | [
"def",
"pick_vector",
"(",
"cond",
",",
"true_vector",
",",
"false_vector",
",",
"name",
"=",
"\"pick_vector\"",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"cond",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"cond",
","... | Picks possibly different length row `Tensor`s based on condition.
Value `Tensor`s should have exactly one dimension.
If `cond` is a python Boolean or `tf.constant` then either `true_vector` or
`false_vector` is immediately returned. I.e., no graph nodes are created and
no validation happens.
Args:
cond... | [
"Picks",
"possibly",
"different",
"length",
"row",
"Tensor",
"s",
"based",
"on",
"condition",
"."
] | python | test |
NORDUnet/python-norduniclient | norduniclient/core.py | https://github.com/NORDUnet/python-norduniclient/blob/ee5084a6f45caac614b4fda4a023749ca52f786c/norduniclient/core.py#L508-L537 | def get_indexed_node(manager, prop, value, node_type='Node', lookup_func='CONTAINS', legacy=True):
"""
:param manager: Neo4jDBSessionManager
:param prop: Indexed property
:param value: Indexed value
:param node_type: Label used for index
:param lookup_func: STARTS WITH | CONTAINS | ENDS WITH
... | [
"def",
"get_indexed_node",
"(",
"manager",
",",
"prop",
",",
"value",
",",
"node_type",
"=",
"'Node'",
",",
"lookup_func",
"=",
"'CONTAINS'",
",",
"legacy",
"=",
"True",
")",
":",
"q",
"=",
"\"\"\"\n MATCH (n:{label})\n WHERE LOWER(n.{prop}) {lookup_func... | :param manager: Neo4jDBSessionManager
:param prop: Indexed property
:param value: Indexed value
:param node_type: Label used for index
:param lookup_func: STARTS WITH | CONTAINS | ENDS WITH
:param legacy: Backwards compatibility
:type manager: Neo4jDBSessionManager
:type prop: str
:type... | [
":",
"param",
"manager",
":",
"Neo4jDBSessionManager",
":",
"param",
"prop",
":",
"Indexed",
"property",
":",
"param",
"value",
":",
"Indexed",
"value",
":",
"param",
"node_type",
":",
"Label",
"used",
"for",
"index",
":",
"param",
"lookup_func",
":",
"START... | python | train |
googleapis/google-cloud-python | storage/google/cloud/storage/notification.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/notification.py#L111-L133 | def from_api_repr(cls, resource, bucket):
"""Construct an instance from the JSON repr returned by the server.
See: https://cloud.google.com/storage/docs/json_api/v1/notifications
:type resource: dict
:param resource: JSON repr of the notification
:type bucket: :class:`google.c... | [
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
",",
"bucket",
")",
":",
"topic_path",
"=",
"resource",
".",
"get",
"(",
"\"topic\"",
")",
"if",
"topic_path",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Resource has no topic\"",
")",
"name",
",",
... | Construct an instance from the JSON repr returned by the server.
See: https://cloud.google.com/storage/docs/json_api/v1/notifications
:type resource: dict
:param resource: JSON repr of the notification
:type bucket: :class:`google.cloud.storage.bucket.Bucket`
:param bucket: Bu... | [
"Construct",
"an",
"instance",
"from",
"the",
"JSON",
"repr",
"returned",
"by",
"the",
"server",
"."
] | python | train |
pandas-dev/pandas | pandas/core/indexes/base.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1487-L1541 | def droplevel(self, level=0):
"""
Return index with requested level(s) removed.
If resulting index has only 1 level left, the result will be
of Index type, not MultiIndex.
.. versionadded:: 0.23.1 (support for non-MultiIndex)
Parameters
----------
level... | [
"def",
"droplevel",
"(",
"self",
",",
"level",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"level",
"=",
"[",
"level",
"]",
"levnums",
"=",
"sorted",
"(",
"self",
".",
"_get_level_numb... | Return index with requested level(s) removed.
If resulting index has only 1 level left, the result will be
of Index type, not MultiIndex.
.. versionadded:: 0.23.1 (support for non-MultiIndex)
Parameters
----------
level : int, str, or list-like, default 0
I... | [
"Return",
"index",
"with",
"requested",
"level",
"(",
"s",
")",
"removed",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/configfiles.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L171-L199 | def get_config_parameter(config: ConfigParser,
section: str,
param: str,
fn: Callable[[Any], Any],
default: Any) -> Any:
"""
Fetch parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:... | [
"def",
"get_config_parameter",
"(",
"config",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"param",
":",
"str",
",",
"fn",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
",",
"default",
":",
"Any",
")",
"->",
"Any",
":",
"try",
":... | Fetch parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
fn: function to apply to string parameter (e.g. ``int``)
default: default value
Returns:
... | [
"Fetch",
"parameter",
"from",
"configparser",
".",
"INI",
"file",
"."
] | python | train |
edx/XBlock | xblock/scorable.py | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L34-L55 | def rescore(self, only_if_higher):
"""
Calculate a new raw score and save it to the block. If only_if_higher
is True and the score didn't improve, keep the existing score.
Raises a TypeError if the block cannot be scored.
Raises a ValueError if the user has not yet completed th... | [
"def",
"rescore",
"(",
"self",
",",
"only_if_higher",
")",
":",
"_",
"=",
"self",
".",
"runtime",
".",
"service",
"(",
"self",
",",
"'i18n'",
")",
".",
"ugettext",
"if",
"not",
"self",
".",
"allows_rescore",
"(",
")",
":",
"raise",
"TypeError",
"(",
... | Calculate a new raw score and save it to the block. If only_if_higher
is True and the score didn't improve, keep the existing score.
Raises a TypeError if the block cannot be scored.
Raises a ValueError if the user has not yet completed the problem.
May also raise other errors in self... | [
"Calculate",
"a",
"new",
"raw",
"score",
"and",
"save",
"it",
"to",
"the",
"block",
".",
"If",
"only_if_higher",
"is",
"True",
"and",
"the",
"score",
"didn",
"t",
"improve",
"keep",
"the",
"existing",
"score",
"."
] | python | train |
gwpy/gwpy | gwpy/segments/flag.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1186-L1253 | def query_dqsegdb(cls, flags, *args, **kwargs):
"""Query the advanced LIGO DQSegDB for a list of flags.
Parameters
----------
flags : `iterable`
A list of flag names for which to query.
*args
Either, two `float`-like numbers indicating the
GP... | [
"def",
"query_dqsegdb",
"(",
"cls",
",",
"flags",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# check on_error flag",
"on_error",
"=",
"kwargs",
".",
"pop",
"(",
"'on_error'",
",",
"'raise'",
")",
".",
"lower",
"(",
")",
"if",
"on_error",
"no... | Query the advanced LIGO DQSegDB for a list of flags.
Parameters
----------
flags : `iterable`
A list of flag names for which to query.
*args
Either, two `float`-like numbers indicating the
GPS [start, stop) interval, or a `SegmentList`
de... | [
"Query",
"the",
"advanced",
"LIGO",
"DQSegDB",
"for",
"a",
"list",
"of",
"flags",
"."
] | python | train |
Galarzaa90/tibia.py | tibiapy/world.py | https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/tibiapy/world.py#L371-L392 | def _parse_tables(cls, parsed_content):
"""
Parses the information tables found in a world's information page.
Parameters
----------
parsed_content: :class:`bs4.BeautifulSoup`
A :class:`BeautifulSoup` object containing all the content.
Returns
------... | [
"def",
"_parse_tables",
"(",
"cls",
",",
"parsed_content",
")",
":",
"tables",
"=",
"parsed_content",
".",
"find_all",
"(",
"'div'",
",",
"attrs",
"=",
"{",
"'class'",
":",
"'TableContainer'",
"}",
")",
"output",
"=",
"OrderedDict",
"(",
")",
"for",
"table... | Parses the information tables found in a world's information page.
Parameters
----------
parsed_content: :class:`bs4.BeautifulSoup`
A :class:`BeautifulSoup` object containing all the content.
Returns
-------
:class:`OrderedDict`[:class:`str`, :class:`list`[:... | [
"Parses",
"the",
"information",
"tables",
"found",
"in",
"a",
"world",
"s",
"information",
"page",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/xmppstringprep.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L182-L189 | def check_unassigned(self, data):
"""Checks for unassigned character codes."""
for char in data:
for lookup in self.unassigned:
if lookup(char):
raise StringprepError("Unassigned character: {0!r}"
... | [
"def",
"check_unassigned",
"(",
"self",
",",
"data",
")",
":",
"for",
"char",
"in",
"data",
":",
"for",
"lookup",
"in",
"self",
".",
"unassigned",
":",
"if",
"lookup",
"(",
"char",
")",
":",
"raise",
"StringprepError",
"(",
"\"Unassigned character: {0!r}\"",... | Checks for unassigned character codes. | [
"Checks",
"for",
"unassigned",
"character",
"codes",
"."
] | python | valid |
thunder-project/thunder | thunder/readers.py | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/readers.py#L437-L472 | def getkeys(self, path, filename=None, directories=False, recursive=False):
"""
Get matching keys for a path
"""
from .utils import connection_with_anon, connection_with_gs
parse = BotoClient.parse_query(path)
scheme = parse[0]
bucket_name = parse[1]
key... | [
"def",
"getkeys",
"(",
"self",
",",
"path",
",",
"filename",
"=",
"None",
",",
"directories",
"=",
"False",
",",
"recursive",
"=",
"False",
")",
":",
"from",
".",
"utils",
"import",
"connection_with_anon",
",",
"connection_with_gs",
"parse",
"=",
"BotoClient... | Get matching keys for a path | [
"Get",
"matching",
"keys",
"for",
"a",
"path"
] | python | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/cybrowser.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/cybrowser.py#L42-L59 | def show(self, wid=None, text=None, title=None, url=None, verbose=False):
"""
Launch an HTML browser in the Results Panel.
:param wid: Window ID
:param text: HTML text
:param title: Window Title
:param url: URL
:param verbose: print more
"""
PARA... | [
"def",
"show",
"(",
"self",
",",
"wid",
"=",
"None",
",",
"text",
"=",
"None",
",",
"title",
"=",
"None",
",",
"url",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"PARAMS",
"=",
"{",
"}",
"for",
"p",
",",
"v",
"in",
"zip",
"(",
"[",
... | Launch an HTML browser in the Results Panel.
:param wid: Window ID
:param text: HTML text
:param title: Window Title
:param url: URL
:param verbose: print more | [
"Launch",
"an",
"HTML",
"browser",
"in",
"the",
"Results",
"Panel",
"."
] | python | train |
tkf/rash | rash/cli.py | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/cli.py#L31-L64 | def get_parser(commands):
"""
Generate argument parser given a list of subcommand specifications.
:type commands: list of (str, function, function)
:arg commands:
Each element must be a tuple ``(name, adder, runner)``.
:param name: subcommand
:param adder: a function takes ... | [
"def",
"get_parser",
"(",
"commands",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"Formatter",
",",
"description",
"=",
"__doc__",
",",
"epilog",
"=",
"EPILOG",
",",
")",
"subparsers",
"=",
"parser",
".",
"add_sub... | Generate argument parser given a list of subcommand specifications.
:type commands: list of (str, function, function)
:arg commands:
Each element must be a tuple ``(name, adder, runner)``.
:param name: subcommand
:param adder: a function takes one object which is an instance
... | [
"Generate",
"argument",
"parser",
"given",
"a",
"list",
"of",
"subcommand",
"specifications",
"."
] | python | train |
google/openhtf | openhtf/core/measurements.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L260-L276 | def validate(self):
"""Validate this measurement and update its 'outcome' field."""
# PASS if all our validators return True, otherwise FAIL.
try:
if all(v(self.measured_value.value) for v in self.validators):
self.outcome = Outcome.PASS
else:
self.outcome = Outcome.FAIL
re... | [
"def",
"validate",
"(",
"self",
")",
":",
"# PASS if all our validators return True, otherwise FAIL.",
"try",
":",
"if",
"all",
"(",
"v",
"(",
"self",
".",
"measured_value",
".",
"value",
")",
"for",
"v",
"in",
"self",
".",
"validators",
")",
":",
"self",
".... | Validate this measurement and update its 'outcome' field. | [
"Validate",
"this",
"measurement",
"and",
"update",
"its",
"outcome",
"field",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/stats.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L467-L536 | def counter(self, key, value, timestamp=None):
"""Set a counter value
If the inner key does not exist is is created
:param key: counter to update
:type key: str
:param value: counter value
:type value: float
:return: An alignak_stat brok if broks are enabled els... | [
"def",
"counter",
"(",
"self",
",",
"key",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"_min",
",",
"_max",
",",
"count",
",",
"_sum",
"=",
"self",
".",
"stats",
".",
"get",
"(",
"key",
",",
"(",
"None",
",",
"None",
",",
"0",
",",
... | Set a counter value
If the inner key does not exist is is created
:param key: counter to update
:type key: str
:param value: counter value
:type value: float
:return: An alignak_stat brok if broks are enabled else None | [
"Set",
"a",
"counter",
"value"
] | python | train |
tulsawebdevs/django-multi-gtfs | multigtfs/models/base.py | https://github.com/tulsawebdevs/django-multi-gtfs/blob/8c442bfb67e87566c24a7364d8fa0aacd4a0a652/multigtfs/models/base.py#L303-L410 | def export_txt(cls, feed):
'''Export records as a GTFS comma-separated file'''
objects = cls.objects.in_feed(feed)
# If no records, return None
if not objects.exists():
return
# Get the columns used in the dataset
column_map = objects.populated_column_map()
... | [
"def",
"export_txt",
"(",
"cls",
",",
"feed",
")",
":",
"objects",
"=",
"cls",
".",
"objects",
".",
"in_feed",
"(",
"feed",
")",
"# If no records, return None",
"if",
"not",
"objects",
".",
"exists",
"(",
")",
":",
"return",
"# Get the columns used in the data... | Export records as a GTFS comma-separated file | [
"Export",
"records",
"as",
"a",
"GTFS",
"comma",
"-",
"separated",
"file"
] | python | train |
tjomasc/snekbol | snekbol/document.py | https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L263-L268 | def _get_triplet_value(self, graph, identity, rdf_type):
"""
Get a value from an RDF triple
"""
value = graph.value(subject=identity, predicate=rdf_type)
return value.toPython() if value is not None else value | [
"def",
"_get_triplet_value",
"(",
"self",
",",
"graph",
",",
"identity",
",",
"rdf_type",
")",
":",
"value",
"=",
"graph",
".",
"value",
"(",
"subject",
"=",
"identity",
",",
"predicate",
"=",
"rdf_type",
")",
"return",
"value",
".",
"toPython",
"(",
")"... | Get a value from an RDF triple | [
"Get",
"a",
"value",
"from",
"an",
"RDF",
"triple"
] | python | train |
gmr/tinman | tinman/application.py | https://github.com/gmr/tinman/blob/98f0acd15a228d752caa1864cdf02aaa3d492a9f/tinman/application.py#L55-L77 | def log_request(self, handler):
"""Writes a completed HTTP request to the logs.
By default writes to the tinman.application LOGGER. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary as
'log_fu... | [
"def",
"log_request",
"(",
"self",
",",
"handler",
")",
":",
"if",
"config",
".",
"LOG_FUNCTION",
"in",
"self",
".",
"settings",
":",
"self",
".",
"settings",
"[",
"config",
".",
"LOG_FUNCTION",
"]",
"(",
"handler",
")",
"return",
"if",
"handler",
".",
... | Writes a completed HTTP request to the logs.
By default writes to the tinman.application LOGGER. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary as
'log_function'.
:param tornado.web.Reques... | [
"Writes",
"a",
"completed",
"HTTP",
"request",
"to",
"the",
"logs",
"."
] | python | train |
yyuu/botornado | boto/vpc/__init__.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/vpc/__init__.py#L489-L524 | def get_all_subnets(self, subnet_ids=None, filters=None):
"""
Retrieve information about your Subnets. You can filter results to
return information only about those Subnets that match your search
parameters. Otherwise, all Subnets associated with your account
are returned.
... | [
"def",
"get_all_subnets",
"(",
"self",
",",
"subnet_ids",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"subnet_ids",
":",
"self",
".",
"build_list_params",
"(",
"params",
",",
"subnet_ids",
",",
"'SubnetId'",
")",
"i... | Retrieve information about your Subnets. You can filter results to
return information only about those Subnets that match your search
parameters. Otherwise, all Subnets associated with your account
are returned.
:type subnet_ids: list
:param subnet_ids: A list of strings with ... | [
"Retrieve",
"information",
"about",
"your",
"Subnets",
".",
"You",
"can",
"filter",
"results",
"to",
"return",
"information",
"only",
"about",
"those",
"Subnets",
"that",
"match",
"your",
"search",
"parameters",
".",
"Otherwise",
"all",
"Subnets",
"associated",
... | python | train |
apache/incubator-mxnet | python/mxnet/module/bucketing_module.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/bucketing_module.py#L289-L352 | def bind(self, data_shapes, label_shapes=None, for_training=True,
inputs_need_grad=False, force_rebind=False, shared_module=None,
grad_req='write'):
"""Binding for a `BucketingModule` means setting up the buckets and binding the
executor for the default bucket key. Executors co... | [
"def",
"bind",
"(",
"self",
",",
"data_shapes",
",",
"label_shapes",
"=",
"None",
",",
"for_training",
"=",
"True",
",",
"inputs_need_grad",
"=",
"False",
",",
"force_rebind",
"=",
"False",
",",
"shared_module",
"=",
"None",
",",
"grad_req",
"=",
"'write'",
... | Binding for a `BucketingModule` means setting up the buckets and binding the
executor for the default bucket key. Executors corresponding to other keys are
bound afterwards with `switch_bucket`.
Parameters
----------
data_shapes : list of (str, tuple)
This should cor... | [
"Binding",
"for",
"a",
"BucketingModule",
"means",
"setting",
"up",
"the",
"buckets",
"and",
"binding",
"the",
"executor",
"for",
"the",
"default",
"bucket",
"key",
".",
"Executors",
"corresponding",
"to",
"other",
"keys",
"are",
"bound",
"afterwards",
"with",
... | python | train |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/file_utils.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/file_utils.py#L102-L124 | def LockFile(path, blocking=False):
"""Interface to flock-based file locking to prevent concurrent executions.
Args:
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Yields:
None, yields when a lock on the file is obtained.
Raises:
IO... | [
"def",
"LockFile",
"(",
"path",
",",
"blocking",
"=",
"False",
")",
":",
"fd",
"=",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_CREAT",
")",
"try",
":",
"Lock",
"(",
"fd",
",",
"path",
",",
"blocking",
")",
"yield",
"finally",
":",
"try",
... | Interface to flock-based file locking to prevent concurrent executions.
Args:
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Yields:
None, yields when a lock on the file is obtained.
Raises:
IOError, raised from flock locking operatio... | [
"Interface",
"to",
"flock",
"-",
"based",
"file",
"locking",
"to",
"prevent",
"concurrent",
"executions",
"."
] | python | train |
creare-com/pydem | pydem/processing_manager.py | https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L665-L709 | def process(self, index=None):
"""
This will completely process a directory of elevation tiles (as
supplied in the constructor). Both phases of the calculation, the
single tile and edge resolution phases are run.
Parameters
-----------
index : int/slice (optional... | [
"def",
"process",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"# Round 0 of twi processing, process the magnitude and directions of",
"# slopes",
"print",
"\"Starting slope calculation round\"",
"self",
".",
"process_twi",
"(",
"index",
",",
"do_edges",
"=",
"False"... | This will completely process a directory of elevation tiles (as
supplied in the constructor). Both phases of the calculation, the
single tile and edge resolution phases are run.
Parameters
-----------
index : int/slice (optional)
Default None - processes all tiles in... | [
"This",
"will",
"completely",
"process",
"a",
"directory",
"of",
"elevation",
"tiles",
"(",
"as",
"supplied",
"in",
"the",
"constructor",
")",
".",
"Both",
"phases",
"of",
"the",
"calculation",
"the",
"single",
"tile",
"and",
"edge",
"resolution",
"phases",
... | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/ext/_bundled/png.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L845-L929 | def filter_scanline(type, line, fo, prev=None):
"""Apply a scanline filter to a scanline. `type` specifies the
filter type (0 to 4); `line` specifies the current (unfiltered)
scanline as a sequence of bytes; `prev` specifies the previous
(unfiltered) scanline as a sequence of bytes. `fo` specifies the
... | [
"def",
"filter_scanline",
"(",
"type",
",",
"line",
",",
"fo",
",",
"prev",
"=",
"None",
")",
":",
"assert",
"0",
"<=",
"type",
"<",
"5",
"# The output array. Which, pathetically, we extend one-byte at a",
"# time (fortunately this is linear).",
"out",
"=",
"array",
... | Apply a scanline filter to a scanline. `type` specifies the
filter type (0 to 4); `line` specifies the current (unfiltered)
scanline as a sequence of bytes; `prev` specifies the previous
(unfiltered) scanline as a sequence of bytes. `fo` specifies the
filter offset; normally this is size of a pixel in ... | [
"Apply",
"a",
"scanline",
"filter",
"to",
"a",
"scanline",
".",
"type",
"specifies",
"the",
"filter",
"type",
"(",
"0",
"to",
"4",
")",
";",
"line",
"specifies",
"the",
"current",
"(",
"unfiltered",
")",
"scanline",
"as",
"a",
"sequence",
"of",
"bytes",
... | python | train |
saltstack/salt | salt/modules/rabbitmq.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L132-L143 | def _safe_output(line):
'''
Looks for rabbitmqctl warning, or general formatting, strings that aren't
intended to be parsed as output.
Returns a boolean whether the line can be parsed as rabbitmqctl output.
'''
return not any([
line.startswith('Listing') and line.endswith('...'),
... | [
"def",
"_safe_output",
"(",
"line",
")",
":",
"return",
"not",
"any",
"(",
"[",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"line",
".",
"endswith",
"(",
"'...'",
")",
",",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"'\\t'",
... | Looks for rabbitmqctl warning, or general formatting, strings that aren't
intended to be parsed as output.
Returns a boolean whether the line can be parsed as rabbitmqctl output. | [
"Looks",
"for",
"rabbitmqctl",
"warning",
"or",
"general",
"formatting",
"strings",
"that",
"aren",
"t",
"intended",
"to",
"be",
"parsed",
"as",
"output",
".",
"Returns",
"a",
"boolean",
"whether",
"the",
"line",
"can",
"be",
"parsed",
"as",
"rabbitmqctl",
"... | python | train |
glut23/webvtt-py | webvtt/segmenter.py | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/segmenter.py#L73-L95 | def segment(self, webvtt, output='', seconds=SECONDS, mpegts=MPEGTS):
"""Segments the captions based on a number of seconds."""
if isinstance(webvtt, str):
# if a string is supplied we parse the file
captions = WebVTT().read(webvtt).captions
elif not self._validate_webvtt... | [
"def",
"segment",
"(",
"self",
",",
"webvtt",
",",
"output",
"=",
"''",
",",
"seconds",
"=",
"SECONDS",
",",
"mpegts",
"=",
"MPEGTS",
")",
":",
"if",
"isinstance",
"(",
"webvtt",
",",
"str",
")",
":",
"# if a string is supplied we parse the file",
"captions"... | Segments the captions based on a number of seconds. | [
"Segments",
"the",
"captions",
"based",
"on",
"a",
"number",
"of",
"seconds",
"."
] | python | train |
ArchiveTeam/wpull | wpull/processor/rule.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L378-L385 | def get_wait_time(self, item_session: ItemSession, error=None):
'''Return the wait time in seconds between requests.'''
seconds = self._waiter.get()
try:
return self.hook_dispatcher.call(PluginFunctions.wait_time, seconds,
item_session, er... | [
"def",
"get_wait_time",
"(",
"self",
",",
"item_session",
":",
"ItemSession",
",",
"error",
"=",
"None",
")",
":",
"seconds",
"=",
"self",
".",
"_waiter",
".",
"get",
"(",
")",
"try",
":",
"return",
"self",
".",
"hook_dispatcher",
".",
"call",
"(",
"Pl... | Return the wait time in seconds between requests. | [
"Return",
"the",
"wait",
"time",
"in",
"seconds",
"between",
"requests",
"."
] | python | train |
elliterate/capybara.py | capybara/window.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/window.py#L106-L118 | def resize_to(self, width, height):
"""
Resizes the window to the given dimensions.
If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.
Args:
width... | [
"def",
"resize_to",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"self",
".",
"driver",
".",
"resize_window_to",
"(",
"self",
".",
"handle",
",",
"width",
",",
"height",
")"
] | Resizes the window to the given dimensions.
If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.
Args:
width (int): The new window width in pixels.
heig... | [
"Resizes",
"the",
"window",
"to",
"the",
"given",
"dimensions",
"."
] | python | test |
log2timeline/dftimewolf | dftimewolf/lib/collectors/grr_hosts.py | https://github.com/log2timeline/dftimewolf/blob/45f898476a288d73c4256ae8e3836a2a4848c0d7/dftimewolf/lib/collectors/grr_hosts.py#L257-L287 | def setup(self,
hosts, artifacts, extra_artifacts, use_tsk,
reason, grr_server_url, grr_username, grr_password, approvers=None,
verify=True):
"""Initializes a GRR artifact collector.
Args:
hosts: Comma-separated list of hostnames to launch the flow on.
artifacts:... | [
"def",
"setup",
"(",
"self",
",",
"hosts",
",",
"artifacts",
",",
"extra_artifacts",
",",
"use_tsk",
",",
"reason",
",",
"grr_server_url",
",",
"grr_username",
",",
"grr_password",
",",
"approvers",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"super... | Initializes a GRR artifact collector.
Args:
hosts: Comma-separated list of hostnames to launch the flow on.
artifacts: list of GRR-defined artifacts.
extra_artifacts: list of GRR-defined artifacts to append.
use_tsk: toggle for use_tsk flag on GRR flow.
reason: justification for GRR a... | [
"Initializes",
"a",
"GRR",
"artifact",
"collector",
"."
] | python | train |
juju/python-libjuju | juju/client/_client7.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client7.py#L1411-L1424 | async def SetInstanceInfo(self, machines):
'''
machines : typing.Sequence[~InstanceInfo]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Provisioner',
request='SetInstanceInfo',
... | [
"async",
"def",
"SetInstanceInfo",
"(",
"self",
",",
"machines",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Provisioner'",
",",
"request",
"=",
"'SetInstanceInfo'",
",",
"version",
"=",
... | machines : typing.Sequence[~InstanceInfo]
Returns -> typing.Sequence[~ErrorResult] | [
"machines",
":",
"typing",
".",
"Sequence",
"[",
"~InstanceInfo",
"]",
"Returns",
"-",
">",
"typing",
".",
"Sequence",
"[",
"~ErrorResult",
"]"
] | python | train |
cprogrammer1994/GLWindow | GLWindow/__init__.py | https://github.com/cprogrammer1994/GLWindow/blob/521e18fcbc15e88d3c1f3547aa313c3a07386ee5/GLWindow/__init__.py#L243-L248 | def viewport(self) -> Tuple[int, int, int, int]:
'''
tuple: The viewport of the window.
'''
return self.wnd.viewport | [
"def",
"viewport",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
"]",
":",
"return",
"self",
".",
"wnd",
".",
"viewport"
] | tuple: The viewport of the window. | [
"tuple",
":",
"The",
"viewport",
"of",
"the",
"window",
"."
] | python | train |
cltrudeau/django-awl | awl/waelsteng.py | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L232-L245 | def field_value(self, admin_model, instance, field_name):
"""Returns the value displayed in the column on the web interface for
a given instance.
:param admin_model:
Instance of a :class:`admin.ModelAdmin` object that is responsible
for displaying the change list
... | [
"def",
"field_value",
"(",
"self",
",",
"admin_model",
",",
"instance",
",",
"field_name",
")",
":",
"_",
",",
"_",
",",
"value",
"=",
"lookup_field",
"(",
"field_name",
",",
"instance",
",",
"admin_model",
")",
"return",
"value"
] | Returns the value displayed in the column on the web interface for
a given instance.
:param admin_model:
Instance of a :class:`admin.ModelAdmin` object that is responsible
for displaying the change list
:param instance:
Object instance that is the row in the ... | [
"Returns",
"the",
"value",
"displayed",
"in",
"the",
"column",
"on",
"the",
"web",
"interface",
"for",
"a",
"given",
"instance",
"."
] | python | valid |
njsmith/colorspacious | colorspacious/ciecam02.py | https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/ciecam02.py#L143-L252 | def XYZ100_to_CIECAM02(self, XYZ100, on_negative_A="raise"):
"""Computes CIECAM02 appearance correlates for the given tristimulus
value(s) XYZ (normalized to be on the 0-100 scale).
Example: ``vc.XYZ100_to_CIECAM02([30.0, 45.5, 21.0])``
:param XYZ100: An array-like of tristimulus value... | [
"def",
"XYZ100_to_CIECAM02",
"(",
"self",
",",
"XYZ100",
",",
"on_negative_A",
"=",
"\"raise\"",
")",
":",
"#### Argument checking",
"XYZ100",
"=",
"np",
".",
"asarray",
"(",
"XYZ100",
",",
"dtype",
"=",
"float",
")",
"if",
"XYZ100",
".",
"shape",
"[",
"-"... | Computes CIECAM02 appearance correlates for the given tristimulus
value(s) XYZ (normalized to be on the 0-100 scale).
Example: ``vc.XYZ100_to_CIECAM02([30.0, 45.5, 21.0])``
:param XYZ100: An array-like of tristimulus values. These should be
given on the 0-100 scale, not the 0-1 scale... | [
"Computes",
"CIECAM02",
"appearance",
"correlates",
"for",
"the",
"given",
"tristimulus",
"value",
"(",
"s",
")",
"XYZ",
"(",
"normalized",
"to",
"be",
"on",
"the",
"0",
"-",
"100",
"scale",
")",
"."
] | python | train |
zibertscrem/hexdi | hexdi/__init__.py | https://github.com/zibertscrem/hexdi/blob/4875598299c53f984f2bb1b37060fd42bb7aba84/hexdi/__init__.py#L89-L96 | def bind_transient(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype):
"""
shortcut for bind_type with PerResolveLifeTimeManager on root container
:param type_to_bind: type that will be resolved by accessor
:param accessor: accessor for resolving object
"""
hexdi.core.get_root_cont... | [
"def",
"bind_transient",
"(",
"type_to_bind",
":",
"hexdi",
".",
"core",
".",
"restype",
",",
"accessor",
":",
"hexdi",
".",
"core",
".",
"clstype",
")",
":",
"hexdi",
".",
"core",
".",
"get_root_container",
"(",
")",
".",
"bind_type",
"(",
"type_to_bind",... | shortcut for bind_type with PerResolveLifeTimeManager on root container
:param type_to_bind: type that will be resolved by accessor
:param accessor: accessor for resolving object | [
"shortcut",
"for",
"bind_type",
"with",
"PerResolveLifeTimeManager",
"on",
"root",
"container"
] | python | train |
pypa/pipenv | pipenv/vendor/click/termui.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/termui.py#L261-L351 | def progressbar(iterable=None, length=None, label=None, show_eta=True,
show_percent=None, show_pos=False,
item_show_func=None, fill_char='#', empty_char='-',
bar_template='%(label)s [%(bar)s] %(info)s',
info_sep=' ', width=36, file=None, color=None):
... | [
"def",
"progressbar",
"(",
"iterable",
"=",
"None",
",",
"length",
"=",
"None",
",",
"label",
"=",
"None",
",",
"show_eta",
"=",
"True",
",",
"show_percent",
"=",
"None",
",",
"show_pos",
"=",
"False",
",",
"item_show_func",
"=",
"None",
",",
"fill_char"... | This function creates an iterable context manager that can be used
to iterate over something while showing a progress bar. It will
either iterate over the `iterable` or `length` items (that are counted
up). While iteration happens, this function will print a rendered
progress bar to the given `file` (... | [
"This",
"function",
"creates",
"an",
"iterable",
"context",
"manager",
"that",
"can",
"be",
"used",
"to",
"iterate",
"over",
"something",
"while",
"showing",
"a",
"progress",
"bar",
".",
"It",
"will",
"either",
"iterate",
"over",
"the",
"iterable",
"or",
"le... | python | train |
aewallin/allantools | allantools/allantools.py | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/allantools.py#L568-L660 | def totdev(data, rate=1.0, data_type="phase", taus=None):
""" Total deviation.
Better confidence at long averages for Allan.
.. math::
\\sigma^2_{TOTDEV}( m\\tau_0 ) = { 1 \\over 2 (m\\tau_0)^2 (N-2) }
\\sum_{i=2}^{N-1} ( {x}^*_{i-m} - 2x^*_{i} + x^*_{i+m} )^2
Where :math:`x^... | [
"def",
"totdev",
"(",
"data",
",",
"rate",
"=",
"1.0",
",",
"data_type",
"=",
"\"phase\"",
",",
"taus",
"=",
"None",
")",
":",
"phase",
"=",
"input_to_phase",
"(",
"data",
",",
"rate",
",",
"data_type",
")",
"(",
"phase",
",",
"m",
",",
"taus_used",
... | Total deviation.
Better confidence at long averages for Allan.
.. math::
\\sigma^2_{TOTDEV}( m\\tau_0 ) = { 1 \\over 2 (m\\tau_0)^2 (N-2) }
\\sum_{i=2}^{N-1} ( {x}^*_{i-m} - 2x^*_{i} + x^*_{i+m} )^2
Where :math:`x^*_i` is a new time-series of length :math:`3N-4`
derived from ... | [
"Total",
"deviation",
".",
"Better",
"confidence",
"at",
"long",
"averages",
"for",
"Allan",
"."
] | python | train |
O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/utils/utils.py#L1084-L1106 | def any(self, *, collection, attribute, word, func=None, operation=None):
""" Performs a filter with the OData 'any' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will transform to a filte... | [
"def",
"any",
"(",
"self",
",",
"*",
",",
"collection",
",",
"attribute",
",",
"word",
",",
"func",
"=",
"None",
",",
"operation",
"=",
"None",
")",
":",
"return",
"self",
".",
"iterable",
"(",
"'any'",
",",
"collection",
"=",
"collection",
",",
"att... | Performs a filter with the OData 'any' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will transform to a filter such as:
emailAddresses/any(a:a/address eq 'george@best.com')
:par... | [
"Performs",
"a",
"filter",
"with",
"the",
"OData",
"any",
"keyword",
"on",
"the",
"collection"
] | python | train |
ray-project/ray | python/ray/experimental/streaming/streaming.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L585-L600 | def sum(self, attribute_selector, state_keeper=None):
"""Applies a rolling sum operator to the stream.
Attributes:
sum_attribute_index (int): The index of the attribute to sum
(assuming tuple records).
"""
op = Operator(
_generate_uuid(),
... | [
"def",
"sum",
"(",
"self",
",",
"attribute_selector",
",",
"state_keeper",
"=",
"None",
")",
":",
"op",
"=",
"Operator",
"(",
"_generate_uuid",
"(",
")",
",",
"OpType",
".",
"Sum",
",",
"\"Sum\"",
",",
"_sum",
",",
"other",
"=",
"attribute_selector",
","... | Applies a rolling sum operator to the stream.
Attributes:
sum_attribute_index (int): The index of the attribute to sum
(assuming tuple records). | [
"Applies",
"a",
"rolling",
"sum",
"operator",
"to",
"the",
"stream",
"."
] | python | train |
ibelie/typy | typy/google/protobuf/text_format.py | https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L739-L759 | def _SkipFieldValue(tokenizer):
"""Skips over a field value.
Args:
tokenizer: A tokenizer to parse the field name and values.
Raises:
ParseError: In case an invalid field value is found.
"""
# String/bytes tokens can come in multiple adjacent string literals.
# If we can consume one, consume as ma... | [
"def",
"_SkipFieldValue",
"(",
"tokenizer",
")",
":",
"# String/bytes tokens can come in multiple adjacent string literals.",
"# If we can consume one, consume as many as we can.",
"if",
"tokenizer",
".",
"TryConsumeByteString",
"(",
")",
":",
"while",
"tokenizer",
".",
"TryConsu... | Skips over a field value.
Args:
tokenizer: A tokenizer to parse the field name and values.
Raises:
ParseError: In case an invalid field value is found. | [
"Skips",
"over",
"a",
"field",
"value",
"."
] | python | valid |
xeroc/python-graphenelib | graphenebase/memo.py | https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/memo.py#L72-L92 | def encode_memo(priv, pub, nonce, message):
""" Encode a message with a shared secret between Alice and Bob
:param PrivateKey priv: Private Key (of Alice)
:param PublicKey pub: Public Key (of Bob)
:param int nonce: Random nonce
:param str message: Memo message
:return: Encry... | [
"def",
"encode_memo",
"(",
"priv",
",",
"pub",
",",
"nonce",
",",
"message",
")",
":",
"shared_secret",
"=",
"get_shared_secret",
"(",
"priv",
",",
"pub",
")",
"aes",
"=",
"init_aes",
"(",
"shared_secret",
",",
"nonce",
")",
"\" Checksum \"",
"raw",
"=",
... | Encode a message with a shared secret between Alice and Bob
:param PrivateKey priv: Private Key (of Alice)
:param PublicKey pub: Public Key (of Bob)
:param int nonce: Random nonce
:param str message: Memo message
:return: Encrypted message
:rtype: hex | [
"Encode",
"a",
"message",
"with",
"a",
"shared",
"secret",
"between",
"Alice",
"and",
"Bob"
] | python | valid |
pyviz/holoviews | holoviews/core/dimension.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/dimension.py#L379-L383 | def pprint_label(self):
"The pretty-printed label string for the Dimension"
unit = ('' if self.unit is None
else type(self.unit)(self.unit_format).format(unit=self.unit))
return bytes_to_unicode(self.label) + bytes_to_unicode(unit) | [
"def",
"pprint_label",
"(",
"self",
")",
":",
"unit",
"=",
"(",
"''",
"if",
"self",
".",
"unit",
"is",
"None",
"else",
"type",
"(",
"self",
".",
"unit",
")",
"(",
"self",
".",
"unit_format",
")",
".",
"format",
"(",
"unit",
"=",
"self",
".",
"uni... | The pretty-printed label string for the Dimension | [
"The",
"pretty",
"-",
"printed",
"label",
"string",
"for",
"the",
"Dimension"
] | python | train |
onicagroup/runway | runway/tfenv.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/tfenv.py#L76-L87 | def get_available_tf_versions(include_prerelease=False):
"""Return available Terraform versions."""
tf_releases = json.loads(
requests.get('https://releases.hashicorp.com/index.json').text
)['terraform']
tf_versions = sorted([k # descending
for k, _v in tf_releases['ve... | [
"def",
"get_available_tf_versions",
"(",
"include_prerelease",
"=",
"False",
")",
":",
"tf_releases",
"=",
"json",
".",
"loads",
"(",
"requests",
".",
"get",
"(",
"'https://releases.hashicorp.com/index.json'",
")",
".",
"text",
")",
"[",
"'terraform'",
"]",
"tf_ve... | Return available Terraform versions. | [
"Return",
"available",
"Terraform",
"versions",
"."
] | python | train |
LuminosoInsight/langcodes | langcodes/__init__.py | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L730-L817 | def find_name(tagtype: str, name: str, language: {str, 'Language', None}=None):
"""
Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français... | [
"def",
"find_name",
"(",
"tagtype",
":",
"str",
",",
"name",
":",
"str",
",",
"language",
":",
"{",
"str",
",",
"'Language'",
",",
"None",
"}",
"=",
"None",
")",
":",
"# No matter what form of language we got, normalize it to a single",
"# language subtag",
"if",
... | Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français", or
"francés".
Occasionally, names are ambiguous in a way that can be resolved by... | [
"Find",
"the",
"subtag",
"of",
"a",
"particular",
"tagtype",
"that",
"has",
"the",
"given",
"name",
"."
] | python | train |
jobovy/galpy | galpy/potential/KuzminKutuzovStaeckelPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/KuzminKutuzovStaeckelPotential.py#L195-L224 | def _Rzderiv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t- time
OUTP... | [
"def",
"_Rzderiv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"l",
",",
"n",
"=",
"bovy_coords",
".",
"Rz_to_lambdanu",
"(",
"R",
",",
"z",
",",
"ac",
"=",
"self",
".",
"_ac",
",",
"Delta",
"=",
"... | NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t- time
OUTPUT:
d2phi/dR/dz
HISTORY:
... | [
"NAME",
":",
"_Rzderiv",
"PURPOSE",
":",
"evaluate",
"the",
"mixed",
"R",
"z",
"derivative",
"for",
"this",
"potential",
"INPUT",
":",
"R",
"-",
"Galactocentric",
"cylindrical",
"radius",
"z",
"-",
"vertical",
"height",
"phi",
"-",
"azimuth",
"t",
"-",
"ti... | python | train |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1278-L1283 | def get_file_privilege(self, source):
'''Get privileges of a local file'''
try:
return str(oct(os.stat(source).st_mode)[-3:])
except Exception as e:
raise Failure('Could not get stat for %s, error_message = %s', source, e) | [
"def",
"get_file_privilege",
"(",
"self",
",",
"source",
")",
":",
"try",
":",
"return",
"str",
"(",
"oct",
"(",
"os",
".",
"stat",
"(",
"source",
")",
".",
"st_mode",
")",
"[",
"-",
"3",
":",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"rai... | Get privileges of a local file | [
"Get",
"privileges",
"of",
"a",
"local",
"file"
] | python | test |
tobami/littlechef | littlechef/chef.py | https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L431-L474 | def _configure_node():
"""Exectutes chef-solo to apply roles and recipes to a node"""
print("")
msg = "Cooking..."
if env.parallel:
msg = "[{0}]: {1}".format(env.host_string, msg)
print(msg)
# Backup last report
with settings(hide('stdout', 'warnings', 'running'), warn_only=True):
... | [
"def",
"_configure_node",
"(",
")",
":",
"print",
"(",
"\"\"",
")",
"msg",
"=",
"\"Cooking...\"",
"if",
"env",
".",
"parallel",
":",
"msg",
"=",
"\"[{0}]: {1}\"",
".",
"format",
"(",
"env",
".",
"host_string",
",",
"msg",
")",
"print",
"(",
"msg",
")",... | Exectutes chef-solo to apply roles and recipes to a node | [
"Exectutes",
"chef",
"-",
"solo",
"to",
"apply",
"roles",
"and",
"recipes",
"to",
"a",
"node"
] | python | train |
quantopian/pyfolio | pyfolio/plotting.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L712-L836 | def plot_rolling_returns(returns,
factor_returns=None,
live_start_date=None,
logy=False,
cone_std=None,
legend_loc='best',
volatility_match=False,
... | [
"def",
"plot_rolling_returns",
"(",
"returns",
",",
"factor_returns",
"=",
"None",
",",
"live_start_date",
"=",
"None",
",",
"logy",
"=",
"False",
",",
"cone_std",
"=",
"None",
",",
"legend_loc",
"=",
"'best'",
",",
"volatility_match",
"=",
"False",
",",
"co... | Plots cumulative rolling returns versus some benchmarks'.
Backtest returns are in green, and out-of-sample (live trading)
returns are in red.
Additionally, a non-parametric cone plot may be added to the
out-of-sample returns region.
Parameters
----------
returns : pd.Series
Daily ... | [
"Plots",
"cumulative",
"rolling",
"returns",
"versus",
"some",
"benchmarks",
"."
] | python | valid |
apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L64-L83 | def _add_docstring(format_dict):
"""
Format a doc-string on the fly.
@arg format_dict: A dictionary to format the doc-strings
Example:
@add_docstring({'context': __doc_string_context})
def predict(x):
'''
{context}
>> model.predict(data)
'... | [
"def",
"_add_docstring",
"(",
"format_dict",
")",
":",
"def",
"add_docstring_context",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"wr... | Format a doc-string on the fly.
@arg format_dict: A dictionary to format the doc-strings
Example:
@add_docstring({'context': __doc_string_context})
def predict(x):
'''
{context}
>> model.predict(data)
'''
return x | [
"Format",
"a",
"doc",
"-",
"string",
"on",
"the",
"fly",
".",
"@arg",
"format_dict",
":",
"A",
"dictionary",
"to",
"format",
"the",
"doc",
"-",
"strings",
"Example",
":"
] | python | train |
Microsoft/botbuilder-python | libraries/botframework-connector/azure_bdist_wheel.py | https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/azure_bdist_wheel.py#L368-L448 | def egg2dist(self, egginfo_path, distinfo_path):
"""Convert an .egg-info directory into a .dist-info directory"""
def adios(p):
"""Appropriately delete directory, file or link."""
if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
shutil.rmtree(p... | [
"def",
"egg2dist",
"(",
"self",
",",
"egginfo_path",
",",
"distinfo_path",
")",
":",
"def",
"adios",
"(",
"p",
")",
":",
"\"\"\"Appropriately delete directory, file or link.\"\"\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
"and",
"not",
"os",
"... | Convert an .egg-info directory into a .dist-info directory | [
"Convert",
"an",
".",
"egg",
"-",
"info",
"directory",
"into",
"a",
".",
"dist",
"-",
"info",
"directory"
] | python | test |
ahwillia/tensortools | tensortools/visualization.py | https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/visualization.py#L116-L245 | def plot_factors(U, plots='line', fig=None, axes=None, scatter_kw=dict(),
line_kw=dict(), bar_kw=dict(), **kwargs):
"""Plots a KTensor.
Note: Each keyword option is broadcast to all modes of the KTensor. For
example, if `U` is a 3rd-order tensor (i.e. `U.ndim == 3`) then
`plot_factors(... | [
"def",
"plot_factors",
"(",
"U",
",",
"plots",
"=",
"'line'",
",",
"fig",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"scatter_kw",
"=",
"dict",
"(",
")",
",",
"line_kw",
"=",
"dict",
"(",
")",
",",
"bar_kw",
"=",
"dict",
"(",
")",
",",
"*",
"*... | Plots a KTensor.
Note: Each keyword option is broadcast to all modes of the KTensor. For
example, if `U` is a 3rd-order tensor (i.e. `U.ndim == 3`) then
`plot_factors(U, plots=['line','bar','scatter'])` plots all factors for the
first mode as a line plot, the second as a bar plot, and the third mode as... | [
"Plots",
"a",
"KTensor",
"."
] | python | train |
ucsb-cs/submit | submit/models.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/models.py#L488-L497 | def recent_submissions(self):
"""Generate a list of the most recent submissions for each user.
Only yields a submission for a user if they've made one.
"""
for group in self.groups:
submission = Submission.most_recent_submission(self, group)
if submission:
... | [
"def",
"recent_submissions",
"(",
"self",
")",
":",
"for",
"group",
"in",
"self",
".",
"groups",
":",
"submission",
"=",
"Submission",
".",
"most_recent_submission",
"(",
"self",
",",
"group",
")",
"if",
"submission",
":",
"yield",
"submission"
] | Generate a list of the most recent submissions for each user.
Only yields a submission for a user if they've made one. | [
"Generate",
"a",
"list",
"of",
"the",
"most",
"recent",
"submissions",
"for",
"each",
"user",
"."
] | python | train |
andycasey/sick | sick/models/base.py | https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L82-L115 | def save(self, filename, clobber=False, **kwargs):
"""
Save the model configuration to a YAML-formatted file.
:param filename:
The filename to save the model configuration to.
:type filename:
str
:param clobber: [optional]
Clobber the filena... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"clobber",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
"and",
"not",
"clobber",
":",
"raise",
"IOError",
"(",
"\"filename {} already ex... | Save the model configuration to a YAML-formatted file.
:param filename:
The filename to save the model configuration to.
:type filename:
str
:param clobber: [optional]
Clobber the filename if it already exists.
:type clobber:
bool
... | [
"Save",
"the",
"model",
"configuration",
"to",
"a",
"YAML",
"-",
"formatted",
"file",
"."
] | python | train |
trailofbits/manticore | manticore/core/workspace.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L119-L129 | def save_stream(self, key, binary=False):
"""
Return a managed file-like object into which the calling code can write
arbitrary data.
:param key:
:return: A managed stream-like object
"""
s = io.BytesIO() if binary else io.StringIO()
yield s
self.... | [
"def",
"save_stream",
"(",
"self",
",",
"key",
",",
"binary",
"=",
"False",
")",
":",
"s",
"=",
"io",
".",
"BytesIO",
"(",
")",
"if",
"binary",
"else",
"io",
".",
"StringIO",
"(",
")",
"yield",
"s",
"self",
".",
"save_value",
"(",
"key",
",",
"s"... | Return a managed file-like object into which the calling code can write
arbitrary data.
:param key:
:return: A managed stream-like object | [
"Return",
"a",
"managed",
"file",
"-",
"like",
"object",
"into",
"which",
"the",
"calling",
"code",
"can",
"write",
"arbitrary",
"data",
"."
] | python | valid |
saltstack/salt | salt/utils/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vmware.py#L2927-L2944 | def _check_disks_in_diskgroup(disk_group, cache_disk_id, capacity_disk_ids):
'''
Checks that the disks in a disk group are as expected and raises
CheckError exceptions if the check fails
'''
if not disk_group.ssd.canonicalName == cache_disk_id:
raise salt.exceptions.ArgumentValueError(
... | [
"def",
"_check_disks_in_diskgroup",
"(",
"disk_group",
",",
"cache_disk_id",
",",
"capacity_disk_ids",
")",
":",
"if",
"not",
"disk_group",
".",
"ssd",
".",
"canonicalName",
"==",
"cache_disk_id",
":",
"raise",
"salt",
".",
"exceptions",
".",
"ArgumentValueError",
... | Checks that the disks in a disk group are as expected and raises
CheckError exceptions if the check fails | [
"Checks",
"that",
"the",
"disks",
"in",
"a",
"disk",
"group",
"are",
"as",
"expected",
"and",
"raises",
"CheckError",
"exceptions",
"if",
"the",
"check",
"fails"
] | python | train |
authomatic/authomatic | authomatic/core.py | https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L434-L440 | def _signature(self, *parts):
"""
Creates signature for the session.
"""
signature = hmac.new(six.b(self.secret), digestmod=hashlib.sha1)
signature.update(six.b('|'.join(parts)))
return signature.hexdigest() | [
"def",
"_signature",
"(",
"self",
",",
"*",
"parts",
")",
":",
"signature",
"=",
"hmac",
".",
"new",
"(",
"six",
".",
"b",
"(",
"self",
".",
"secret",
")",
",",
"digestmod",
"=",
"hashlib",
".",
"sha1",
")",
"signature",
".",
"update",
"(",
"six",
... | Creates signature for the session. | [
"Creates",
"signature",
"for",
"the",
"session",
"."
] | python | test |
Tinche/cattrs | src/cattr/multistrategy_dispatch.py | https://github.com/Tinche/cattrs/blob/481bc9bdb69b2190d699b54f331c8c5c075506d5/src/cattr/multistrategy_dispatch.py#L46-L52 | def register_func_list(self, func_and_handler):
""" register a function to determine if the handle
should be used for the type
"""
for func, handler in func_and_handler:
self._function_dispatch.register(func, handler)
self.dispatch.cache_clear() | [
"def",
"register_func_list",
"(",
"self",
",",
"func_and_handler",
")",
":",
"for",
"func",
",",
"handler",
"in",
"func_and_handler",
":",
"self",
".",
"_function_dispatch",
".",
"register",
"(",
"func",
",",
"handler",
")",
"self",
".",
"dispatch",
".",
"ca... | register a function to determine if the handle
should be used for the type | [
"register",
"a",
"function",
"to",
"determine",
"if",
"the",
"handle",
"should",
"be",
"used",
"for",
"the",
"type"
] | python | train |
python-cmd2/cmd2 | cmd2/utils.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L322-L324 | def getvalue(self) -> str:
"""Get the internal contents as a str"""
return self.buffer.byte_buf.decode(encoding=self.encoding, errors=self.errors) | [
"def",
"getvalue",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"buffer",
".",
"byte_buf",
".",
"decode",
"(",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"self",
".",
"errors",
")"
] | Get the internal contents as a str | [
"Get",
"the",
"internal",
"contents",
"as",
"a",
"str"
] | python | train |
Clinical-Genomics/scout | scout/parse/hpo.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/parse/hpo.py#L42-L64 | def parse_hpo_disease(hpo_line):
"""Parse hpo disease line
Args:
hpo_line(str)
"""
hpo_line = hpo_line.rstrip().split('\t')
hpo_info = {}
disease = hpo_line[0].split(':')
hpo_info['source'] = disease[0]
hpo_info['disease_nr'] = int(disease[1])
hpo_info['hgnc... | [
"def",
"parse_hpo_disease",
"(",
"hpo_line",
")",
":",
"hpo_line",
"=",
"hpo_line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"hpo_info",
"=",
"{",
"}",
"disease",
"=",
"hpo_line",
"[",
"0",
"]",
".",
"split",
"(",
"':'",
")",
"hpo_in... | Parse hpo disease line
Args:
hpo_line(str) | [
"Parse",
"hpo",
"disease",
"line",
"Args",
":",
"hpo_line",
"(",
"str",
")"
] | python | test |
carljm/django-adminfiles | adminfiles/flickr.py | https://github.com/carljm/django-adminfiles/blob/b01dc7be266305d575c11d5ff9a37ccac04a78c2/adminfiles/flickr.py#L436-L441 | def _general_getattr(self, var):
"""Generic get attribute function."""
if getattr(self, "_%s__%s" % (self.__class__.__name__, var)) is None \
and not self.__loaded:
self._load_properties()
return getattr(self, "_%s__%s" % (self.__class__.__name__, var)) | [
"def",
"_general_getattr",
"(",
"self",
",",
"var",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"\"_%s__%s\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"var",
")",
")",
"is",
"None",
"and",
"not",
"self",
".",
"__loaded",
":",
"self... | Generic get attribute function. | [
"Generic",
"get",
"attribute",
"function",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.