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 |
|---|---|---|---|---|---|---|---|---|
nwilming/ocupy | ocupy/measures.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L199-L212 | def nss_model(prediction, fm):
"""
wraps nss functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Fixations that define the actuals
"""
(r_y, r_x) = calc_resize_factor(prediction, fm.image_size)
fix = ((np.arr... | [
"def",
"nss_model",
"(",
"prediction",
",",
"fm",
")",
":",
"(",
"r_y",
",",
"r_x",
")",
"=",
"calc_resize_factor",
"(",
"prediction",
",",
"fm",
".",
"image_size",
")",
"fix",
"=",
"(",
"(",
"np",
".",
"array",
"(",
"fm",
".",
"y",
"-",
"1",
")"... | wraps nss functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Fixations that define the actuals | [
"wraps",
"nss",
"functionality",
"for",
"model",
"evaluation"
] | python | train |
iotile/coretools | iotileemulate/iotile/emulate/virtual/peripheral_tile.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/peripheral_tile.py#L127-L140 | def restore_state(self, state):
"""Restore the current state of this emulated object.
Args:
state (dict): A previously dumped state produced by dump_state.
"""
super(EmulatedPeripheralTile, self).restore_state(state)
self.debug_mode = state.get('debug_mode', False)... | [
"def",
"restore_state",
"(",
"self",
",",
"state",
")",
":",
"super",
"(",
"EmulatedPeripheralTile",
",",
"self",
")",
".",
"restore_state",
"(",
"state",
")",
"self",
".",
"debug_mode",
"=",
"state",
".",
"get",
"(",
"'debug_mode'",
",",
"False",
")",
"... | Restore the current state of this emulated object.
Args:
state (dict): A previously dumped state produced by dump_state. | [
"Restore",
"the",
"current",
"state",
"of",
"this",
"emulated",
"object",
"."
] | python | train |
googledatalab/pydatalab | google/datalab/storage/_object.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L175-L188 | def metadata(self):
"""Retrieves metadata about the object.
Returns:
An ObjectMetadata instance with information about this object.
Raises:
Exception if there was an error requesting the object's metadata.
"""
if self._info is None:
try:
self._info = self._api.objects_get(... | [
"def",
"metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_info",
"is",
"None",
":",
"try",
":",
"self",
".",
"_info",
"=",
"self",
".",
"_api",
".",
"objects_get",
"(",
"self",
".",
"_bucket",
",",
"self",
".",
"_key",
")",
"except",
"Exceptio... | Retrieves metadata about the object.
Returns:
An ObjectMetadata instance with information about this object.
Raises:
Exception if there was an error requesting the object's metadata. | [
"Retrieves",
"metadata",
"about",
"the",
"object",
"."
] | python | train |
Rapptz/discord.py | discord/ext/commands/core.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1430-L1453 | def bot_has_any_role(*items):
"""Similar to :func:`.has_any_role` except checks if the bot itself has
any of the roles listed.
This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
... | [
"def",
"bot_has_any_role",
"(",
"*",
"items",
")",
":",
"def",
"predicate",
"(",
"ctx",
")",
":",
"ch",
"=",
"ctx",
".",
"channel",
"if",
"not",
"isinstance",
"(",
"ch",
",",
"discord",
".",
"abc",
".",
"GuildChannel",
")",
":",
"raise",
"NoPrivateMess... | Similar to :func:`.has_any_role` except checks if the bot itself has
any of the roles listed.
This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.CheckFailure... | [
"Similar",
"to",
":",
"func",
":",
".",
"has_any_role",
"except",
"checks",
"if",
"the",
"bot",
"itself",
"has",
"any",
"of",
"the",
"roles",
"listed",
"."
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/ssl/list.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/list.py#L24-L42 | def cli(env, status, sortby):
"""List SSL certificates."""
manager = SoftLayer.SSLManager(env.client)
certificates = manager.list_certs(status)
table = formatting.Table(['id',
'common_name',
'days_until_expire',
... | [
"def",
"cli",
"(",
"env",
",",
"status",
",",
"sortby",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"SSLManager",
"(",
"env",
".",
"client",
")",
"certificates",
"=",
"manager",
".",
"list_certs",
"(",
"status",
")",
"table",
"=",
"formatting",
".",
"T... | List SSL certificates. | [
"List",
"SSL",
"certificates",
"."
] | python | train |
sdispater/pendulum | pendulum/formatting/formatter.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/formatting/formatter.py#L232-L261 | def format(self, dt, fmt, locale=None):
"""
Formats a DateTime instance with a given format and locale.
:param dt: The instance to format
:type dt: pendulum.DateTime
:param fmt: The format to use
:type fmt: str
:param locale: The locale to use
:type loc... | [
"def",
"format",
"(",
"self",
",",
"dt",
",",
"fmt",
",",
"locale",
"=",
"None",
")",
":",
"if",
"not",
"locale",
":",
"locale",
"=",
"pendulum",
".",
"get_locale",
"(",
")",
"locale",
"=",
"Locale",
".",
"load",
"(",
"locale",
")",
"result",
"=",
... | Formats a DateTime instance with a given format and locale.
:param dt: The instance to format
:type dt: pendulum.DateTime
:param fmt: The format to use
:type fmt: str
:param locale: The locale to use
:type locale: str or Locale or None
:rtype: str | [
"Formats",
"a",
"DateTime",
"instance",
"with",
"a",
"given",
"format",
"and",
"locale",
"."
] | python | train |
quantmind/pulsar | pulsar/utils/pylib/websocket.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/websocket.py#L136-L138 | def continuation(self, body=None, final=True):
'''return a `continuation` :class:`Frame`.'''
return self.encode(body, opcode=0, final=final) | [
"def",
"continuation",
"(",
"self",
",",
"body",
"=",
"None",
",",
"final",
"=",
"True",
")",
":",
"return",
"self",
".",
"encode",
"(",
"body",
",",
"opcode",
"=",
"0",
",",
"final",
"=",
"final",
")"
] | return a `continuation` :class:`Frame`. | [
"return",
"a",
"continuation",
":",
"class",
":",
"Frame",
"."
] | python | train |
LettError/MutatorMath | Lib/mutatorMath/objects/location.py | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/location.py#L204-L238 | def asString(self, strict=False):
"""
Return the location as a string.
::
>>> l = Location(pop=1, snap=(-100.0, -200))
>>> l.asString()
'pop:1, snap:(-100.000,-200.000)'
"""
if len(self.keys())==0:
return "origin"
v... | [
"def",
"asString",
"(",
"self",
",",
"strict",
"=",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"keys",
"(",
")",
")",
"==",
"0",
":",
"return",
"\"origin\"",
"v",
"=",
"[",
"]",
"n",
"=",
"[",
"]",
"try",
":",
"for",
"name",
",",
"valu... | Return the location as a string.
::
>>> l = Location(pop=1, snap=(-100.0, -200))
>>> l.asString()
'pop:1, snap:(-100.000,-200.000)' | [
"Return",
"the",
"location",
"as",
"a",
"string",
".",
"::",
">>>",
"l",
"=",
"Location",
"(",
"pop",
"=",
"1",
"snap",
"=",
"(",
"-",
"100",
".",
"0",
"-",
"200",
"))",
">>>",
"l",
".",
"asString",
"()",
"pop",
":",
"1",
"snap",
":",
"(",
"-... | python | train |
fermiPy/fermipy | fermipy/config.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/config.py#L269-L291 | def create(cls, configfile):
"""Create a configuration dictionary from a yaml config file.
This function will first populate the dictionary with defaults
taken from pre-defined configuration files. The configuration
dictionary is then updated with the user-defined configuration
... | [
"def",
"create",
"(",
"cls",
",",
"configfile",
")",
":",
"# populate config dictionary with an initial set of values",
"# config_logging = ConfigManager.load('logging.yaml')",
"config",
"=",
"{",
"}",
"if",
"config",
"[",
"'fileio'",
"]",
"[",
"'outdir'",
"]",
"is",
"N... | Create a configuration dictionary from a yaml config file.
This function will first populate the dictionary with defaults
taken from pre-defined configuration files. The configuration
dictionary is then updated with the user-defined configuration
file. Any settings defined by the user ... | [
"Create",
"a",
"configuration",
"dictionary",
"from",
"a",
"yaml",
"config",
"file",
".",
"This",
"function",
"will",
"first",
"populate",
"the",
"dictionary",
"with",
"defaults",
"taken",
"from",
"pre",
"-",
"defined",
"configuration",
"files",
".",
"The",
"c... | python | train |
CivicSpleen/ambry | ambry/orm/dataset.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L649-L680 | def rows(self):
"""Return configuration in a form that can be used to reconstitute a
Metadata object. Returns all of the rows for a dataset.
This is distinct from get_config_value, which returns the value
for the library.
"""
from ambry.orm import Config as SAConfig
... | [
"def",
"rows",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
"import",
"Config",
"as",
"SAConfig",
"from",
"sqlalchemy",
"import",
"or_",
"rows",
"=",
"[",
"]",
"configs",
"=",
"self",
".",
"dataset",
".",
"session",
".",
"query",
"(",
"SAConfig"... | Return configuration in a form that can be used to reconstitute a
Metadata object. Returns all of the rows for a dataset.
This is distinct from get_config_value, which returns the value
for the library. | [
"Return",
"configuration",
"in",
"a",
"form",
"that",
"can",
"be",
"used",
"to",
"reconstitute",
"a",
"Metadata",
"object",
".",
"Returns",
"all",
"of",
"the",
"rows",
"for",
"a",
"dataset",
"."
] | python | train |
Iotic-Labs/py-IoticAgent | src/IoticAgent/Core/Client.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1324-L1356 | def __dispatch_msg(self, message):
"""Verify the signature and update RequestEvents / perform callbacks
Note messages with an invalid wrapper, invalid hash, invalid sequence number or unexpected clientRef
will be sent to debug_bad callback.
"""
msg = self.__validate_decode_msg(m... | [
"def",
"__dispatch_msg",
"(",
"self",
",",
"message",
")",
":",
"msg",
"=",
"self",
".",
"__validate_decode_msg",
"(",
"message",
")",
"if",
"msg",
":",
"msg",
",",
"seqnum",
"=",
"msg",
"else",
":",
"self",
".",
"__fire_callback",
"(",
"_CB_DEBUG_BAD",
... | Verify the signature and update RequestEvents / perform callbacks
Note messages with an invalid wrapper, invalid hash, invalid sequence number or unexpected clientRef
will be sent to debug_bad callback. | [
"Verify",
"the",
"signature",
"and",
"update",
"RequestEvents",
"/",
"perform",
"callbacks"
] | python | train |
lltk/lltk | lltk/scraping.py | https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L19-L29 | def register(scraper):
''' Registers a scraper to make it available for the generic scraping interface. '''
global scrapers
language = scraper('').language
if not language:
raise Exception('No language specified for your scraper.')
if scrapers.has_key(language):
scrapers[language].append(scraper)
else:
scr... | [
"def",
"register",
"(",
"scraper",
")",
":",
"global",
"scrapers",
"language",
"=",
"scraper",
"(",
"''",
")",
".",
"language",
"if",
"not",
"language",
":",
"raise",
"Exception",
"(",
"'No language specified for your scraper.'",
")",
"if",
"scrapers",
".",
"h... | Registers a scraper to make it available for the generic scraping interface. | [
"Registers",
"a",
"scraper",
"to",
"make",
"it",
"available",
"for",
"the",
"generic",
"scraping",
"interface",
"."
] | python | train |
django-parler/django-parler | parler/models.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L445-L557 | def _get_translated_model(self, language_code=None, use_fallback=False, auto_create=False, meta=None):
"""
Fetch the translated fields model.
"""
if self._parler_meta is None:
raise ImproperlyConfigured("No translation is assigned to the current model!")
if self._tran... | [
"def",
"_get_translated_model",
"(",
"self",
",",
"language_code",
"=",
"None",
",",
"use_fallback",
"=",
"False",
",",
"auto_create",
"=",
"False",
",",
"meta",
"=",
"None",
")",
":",
"if",
"self",
".",
"_parler_meta",
"is",
"None",
":",
"raise",
"Imprope... | Fetch the translated fields model. | [
"Fetch",
"the",
"translated",
"fields",
"model",
"."
] | python | train |
mamrhein/specification | specification/_extd_ast_expr.py | https://github.com/mamrhein/specification/blob/a4c09a0d286cda7a04e8a189f12e23edd97f64ea/specification/_extd_ast_expr.py#L205-L208 | def visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str:
"""Return tuple representation of `node`s elements."""
elems = (self.visit(elt) for elt in node.elts)
return f"({', '.join(elems)}{')' if len(node.elts) != 1 else ',)'}" | [
"def",
"visit_Tuple",
"(",
"self",
",",
"node",
":",
"AST",
",",
"dfltChaining",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"elems",
"=",
"(",
"self",
".",
"visit",
"(",
"elt",
")",
"for",
"elt",
"in",
"node",
".",
"elts",
")",
"return",
"f... | Return tuple representation of `node`s elements. | [
"Return",
"tuple",
"representation",
"of",
"node",
"s",
"elements",
"."
] | python | train |
sernst/cauldron | cauldron/environ/systems.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/systems.py#L76-L108 | def get_system_data() -> typing.Union[None, dict]:
"""
Returns information about the system in which Cauldron is running.
If the information cannot be found, None is returned instead.
:return:
Dictionary containing information about the Cauldron system, whic
includes:
* name
... | [
"def",
"get_system_data",
"(",
")",
"->",
"typing",
".",
"Union",
"[",
"None",
",",
"dict",
"]",
":",
"site_packages",
"=",
"get_site_packages",
"(",
")",
"path_prefixes",
"=",
"[",
"(",
"'[SP]'",
",",
"p",
")",
"for",
"p",
"in",
"site_packages",
"]",
... | Returns information about the system in which Cauldron is running.
If the information cannot be found, None is returned instead.
:return:
Dictionary containing information about the Cauldron system, whic
includes:
* name
* location
* version | [
"Returns",
"information",
"about",
"the",
"system",
"in",
"which",
"Cauldron",
"is",
"running",
".",
"If",
"the",
"information",
"cannot",
"be",
"found",
"None",
"is",
"returned",
"instead",
"."
] | python | train |
TheGhouls/oct | oct/results/report.py | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L99-L105 | def compile_results(self):
"""Compile all results for the current test
"""
self._init_dataframes()
self.total_transactions = len(self.main_results['raw'])
self._init_dates() | [
"def",
"compile_results",
"(",
"self",
")",
":",
"self",
".",
"_init_dataframes",
"(",
")",
"self",
".",
"total_transactions",
"=",
"len",
"(",
"self",
".",
"main_results",
"[",
"'raw'",
"]",
")",
"self",
".",
"_init_dates",
"(",
")"
] | Compile all results for the current test | [
"Compile",
"all",
"results",
"for",
"the",
"current",
"test"
] | python | train |
tanghaibao/jcvi | jcvi/formats/fasta.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1572-L1621 | def some(args):
"""
%prog some fastafile listfile outfastafile
generate a subset of fastafile, based on a list
"""
p = OptionParser(some.__doc__)
p.add_option("--exclude", default=False, action="store_true",
help="Output sequences not in the list file [default: %default]")
p.add... | [
"def",
"some",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"some",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--exclude\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Output sequences not in... | %prog some fastafile listfile outfastafile
generate a subset of fastafile, based on a list | [
"%prog",
"some",
"fastafile",
"listfile",
"outfastafile"
] | python | train |
CalebBell/fluids | fluids/drag.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/drag.py#L1260-L1414 | def integrate_drag_sphere(D, rhop, rho, mu, t, V=0, Method=None,
distance=False):
r'''Integrates the velocity and distance traveled by a particle moving
at a speed which will converge to its terminal velocity.
Performs an integration of the following expression for acceleration:
... | [
"def",
"integrate_drag_sphere",
"(",
"D",
",",
"rhop",
",",
"rho",
",",
"mu",
",",
"t",
",",
"V",
"=",
"0",
",",
"Method",
"=",
"None",
",",
"distance",
"=",
"False",
")",
":",
"laminar_initial",
"=",
"Reynolds",
"(",
"V",
"=",
"V",
",",
"rho",
"... | r'''Integrates the velocity and distance traveled by a particle moving
at a speed which will converge to its terminal velocity.
Performs an integration of the following expression for acceleration:
.. math::
a = \frac{g(\rho_p-\rho_f)}{\rho_p} - \frac{3C_D \rho_f u^2}{4D \rho_p}
Parameters
... | [
"r",
"Integrates",
"the",
"velocity",
"and",
"distance",
"traveled",
"by",
"a",
"particle",
"moving",
"at",
"a",
"speed",
"which",
"will",
"converge",
"to",
"its",
"terminal",
"velocity",
"."
] | python | train |
shimpe/pyvectortween | vectortween/TimeConversion.py | https://github.com/shimpe/pyvectortween/blob/aff071180474739060ec2d3102c39c8e73510988/vectortween/TimeConversion.py#L19-L27 | def hms2frame(hms, fps):
"""
:param hms: a string, e.g. "01:23:15" for one hour, 23 minutes 15 seconds
:param fps: framerate
:return: frame number
"""
import time
t = time.strptime(hms, "%H:%M:%S")
return (t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec) ... | [
"def",
"hms2frame",
"(",
"hms",
",",
"fps",
")",
":",
"import",
"time",
"t",
"=",
"time",
".",
"strptime",
"(",
"hms",
",",
"\"%H:%M:%S\"",
")",
"return",
"(",
"t",
".",
"tm_hour",
"*",
"60",
"*",
"60",
"+",
"t",
".",
"tm_min",
"*",
"60",
"+",
... | :param hms: a string, e.g. "01:23:15" for one hour, 23 minutes 15 seconds
:param fps: framerate
:return: frame number | [
":",
"param",
"hms",
":",
"a",
"string",
"e",
".",
"g",
".",
"01",
":",
"23",
":",
"15",
"for",
"one",
"hour",
"23",
"minutes",
"15",
"seconds",
":",
"param",
"fps",
":",
"framerate",
":",
"return",
":",
"frame",
"number"
] | python | train |
DataBiosphere/toil | src/toil/batchSystems/abstractBatchSystem.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/abstractBatchSystem.py#L283-L297 | def workerCleanup(info):
"""
Cleans up the worker node on batch system shutdown. Also see :meth:`supportsWorkerCleanup`.
:param WorkerCleanupInfo info: A named tuple consisting of all the relevant information
for cleaning up the worker.
"""
assert isinstance(info,... | [
"def",
"workerCleanup",
"(",
"info",
")",
":",
"assert",
"isinstance",
"(",
"info",
",",
"WorkerCleanupInfo",
")",
"workflowDir",
"=",
"Toil",
".",
"getWorkflowDir",
"(",
"info",
".",
"workflowID",
",",
"info",
".",
"workDir",
")",
"workflowDirContents",
"=",
... | Cleans up the worker node on batch system shutdown. Also see :meth:`supportsWorkerCleanup`.
:param WorkerCleanupInfo info: A named tuple consisting of all the relevant information
for cleaning up the worker. | [
"Cleans",
"up",
"the",
"worker",
"node",
"on",
"batch",
"system",
"shutdown",
".",
"Also",
"see",
":",
"meth",
":",
"supportsWorkerCleanup",
"."
] | python | train |
disqus/nose-performance | src/noseperf/wrappers/django.py | https://github.com/disqus/nose-performance/blob/916c8bd7fe7f30e4b7cba24a79a4157fd7889ec2/src/noseperf/wrappers/django.py#L55-L77 | def execute(self, operation, parameters=()):
"""
Wraps execute method to record the query, execution duration and
stackframe.
"""
__traceback_hide__ = True # NOQ
# Time the exection of the query
start = time.time()
try:
return self.cursor.ex... | [
"def",
"execute",
"(",
"self",
",",
"operation",
",",
"parameters",
"=",
"(",
")",
")",
":",
"__traceback_hide__",
"=",
"True",
"# NOQ",
"# Time the exection of the query",
"start",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"return",
"self",
".",
"cu... | Wraps execute method to record the query, execution duration and
stackframe. | [
"Wraps",
"execute",
"method",
"to",
"record",
"the",
"query",
"execution",
"duration",
"and",
"stackframe",
"."
] | python | train |
RLBot/RLBot | src/main/python/rlbot/gui/qt_root.py | https://github.com/RLBot/RLBot/blob/3f9b6bec8b9baf4dcfff0f6cf3103c8744ac6234/src/main/python/rlbot/gui/qt_root.py#L747-L756 | def update_match_settings(self):
"""
Sets all match setting widgets to the values in the overall config
:return:
"""
self.mode_type_combobox.setCurrentText(self.overall_config.get(MATCH_CONFIGURATION_HEADER, GAME_MODE))
self.map_type_combobox.setCurrentText(self.overall_c... | [
"def",
"update_match_settings",
"(",
"self",
")",
":",
"self",
".",
"mode_type_combobox",
".",
"setCurrentText",
"(",
"self",
".",
"overall_config",
".",
"get",
"(",
"MATCH_CONFIGURATION_HEADER",
",",
"GAME_MODE",
")",
")",
"self",
".",
"map_type_combobox",
".",
... | Sets all match setting widgets to the values in the overall config
:return: | [
"Sets",
"all",
"match",
"setting",
"widgets",
"to",
"the",
"values",
"in",
"the",
"overall",
"config",
":",
"return",
":"
] | python | train |
bwhite/hadoopy | hadoopy/_freeze.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_freeze.py#L156-L188 | def freeze(script_path, target_dir='frozen', **kw):
"""Wraps pyinstaller and provides an easy to use interface
Args:
script_path: Absolute path to python script to be frozen.
Returns:
List of freeze commands ran
Raises:
subprocess.CalledProcessError: Freeze error.
OSEr... | [
"def",
"freeze",
"(",
"script_path",
",",
"target_dir",
"=",
"'frozen'",
",",
"*",
"*",
"kw",
")",
":",
"cmds",
"=",
"[",
"]",
"freeze_start_time",
"=",
"time",
".",
"time",
"(",
")",
"logging",
".",
"debug",
"(",
"'/\\\\%s%s Output%s/\\\\'",
"%",
"(",
... | Wraps pyinstaller and provides an easy to use interface
Args:
script_path: Absolute path to python script to be frozen.
Returns:
List of freeze commands ran
Raises:
subprocess.CalledProcessError: Freeze error.
OSError: Freeze not found. | [
"Wraps",
"pyinstaller",
"and",
"provides",
"an",
"easy",
"to",
"use",
"interface"
] | python | train |
blue-yonder/tsfresh | tsfresh/feature_extraction/extraction.py | https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/feature_extraction/extraction.py#L252-L335 | def _do_extraction(df, column_id, column_value, column_kind,
default_fc_parameters, kind_to_fc_parameters,
n_jobs, chunk_size, disable_progressbar, distributor):
"""
Wrapper around the _do_extraction_on_chunk, which calls it on all chunks in the data frame.
A chunk is a... | [
"def",
"_do_extraction",
"(",
"df",
",",
"column_id",
",",
"column_value",
",",
"column_kind",
",",
"default_fc_parameters",
",",
"kind_to_fc_parameters",
",",
"n_jobs",
",",
"chunk_size",
",",
"disable_progressbar",
",",
"distributor",
")",
":",
"data_in_chunks",
"... | Wrapper around the _do_extraction_on_chunk, which calls it on all chunks in the data frame.
A chunk is a subset of the data, with a given kind and id - so a single time series.
The data is separated out into those single time series and the _do_extraction_on_chunk is
called on each of them. The results are... | [
"Wrapper",
"around",
"the",
"_do_extraction_on_chunk",
"which",
"calls",
"it",
"on",
"all",
"chunks",
"in",
"the",
"data",
"frame",
".",
"A",
"chunk",
"is",
"a",
"subset",
"of",
"the",
"data",
"with",
"a",
"given",
"kind",
"and",
"id",
"-",
"so",
"a",
... | python | train |
tarmstrong/nbdiff | nbdiff/merge.py | https://github.com/tarmstrong/nbdiff/blob/3fdfb89f94fc0f4821bc04999ddf53b34d882ab9/nbdiff/merge.py#L46-L177 | def notebook_merge(local, base, remote, check_modified=False):
"""Unify three notebooks into a single notebook with merge metadata.
The result of this function is a valid notebook that can be loaded
by the IPython Notebook front-end. This function adds additional
cell metadata that the front-end Javasc... | [
"def",
"notebook_merge",
"(",
"local",
",",
"base",
",",
"remote",
",",
"check_modified",
"=",
"False",
")",
":",
"local_cells",
"=",
"get_cells",
"(",
"local",
")",
"base_cells",
"=",
"get_cells",
"(",
"base",
")",
"remote_cells",
"=",
"get_cells",
"(",
"... | Unify three notebooks into a single notebook with merge metadata.
The result of this function is a valid notebook that can be loaded
by the IPython Notebook front-end. This function adds additional
cell metadata that the front-end Javascript uses to render the merge.
Parameters
----------
loca... | [
"Unify",
"three",
"notebooks",
"into",
"a",
"single",
"notebook",
"with",
"merge",
"metadata",
"."
] | python | train |
walkr/nanoservice | benchmarks/bench_req_rep_raw.py | https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/benchmarks/bench_req_rep_raw.py#L24-L39 | def bench(client, n):
""" Benchmark n requests """
items = list(range(n))
# Time client publish operations
# ------------------------------
started = time.time()
msg = b'x'
for i in items:
client.socket.send(msg)
res = client.socket.recv()
assert msg == res
durat... | [
"def",
"bench",
"(",
"client",
",",
"n",
")",
":",
"items",
"=",
"list",
"(",
"range",
"(",
"n",
")",
")",
"# Time client publish operations",
"# ------------------------------",
"started",
"=",
"time",
".",
"time",
"(",
")",
"msg",
"=",
"b'x'",
"for",
"i"... | Benchmark n requests | [
"Benchmark",
"n",
"requests"
] | python | train |
brentp/cruzdb | cruzdb/__init__.py | https://github.com/brentp/cruzdb/blob/9068d46e25952f4a929dde0242beb31fa4c7e89a/cruzdb/__init__.py#L94-L110 | def mirror(self, tables, dest_url):
"""
miror a set of `tables` from `dest_url`
Returns a new Genome object
Parameters
----------
tables : list
an iterable of tables
dest_url: str
a dburl string, e.g. 'sqlite:///local.db'
"""
... | [
"def",
"mirror",
"(",
"self",
",",
"tables",
",",
"dest_url",
")",
":",
"from",
"mirror",
"import",
"mirror",
"return",
"mirror",
"(",
"self",
",",
"tables",
",",
"dest_url",
")"
] | miror a set of `tables` from `dest_url`
Returns a new Genome object
Parameters
----------
tables : list
an iterable of tables
dest_url: str
a dburl string, e.g. 'sqlite:///local.db' | [
"miror",
"a",
"set",
"of",
"tables",
"from",
"dest_url"
] | python | train |
IndicoDataSolutions/IndicoIo-python | indicoio/pdf/pdf_extraction.py | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/pdf/pdf_extraction.py#L6-L35 | def pdf_extraction(pdf, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a pdf, returns the text and metadata associated with the given pdf.
PDFs may be provided as base64 encoded data or as a filepath.
Base64 image data and formatted table is optionally returned by setting
... | [
"def",
"pdf_extraction",
"(",
"pdf",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pdf",
"=",
"pdf_preprocess",
"(",
"pdf",
",",
"batch",
"=",
"b... | Given a pdf, returns the text and metadata associated with the given pdf.
PDFs may be provided as base64 encoded data or as a filepath.
Base64 image data and formatted table is optionally returned by setting
`images=True` or `tables=True`.
Example usage:
.. code-block:: python
>>> from ind... | [
"Given",
"a",
"pdf",
"returns",
"the",
"text",
"and",
"metadata",
"associated",
"with",
"the",
"given",
"pdf",
".",
"PDFs",
"may",
"be",
"provided",
"as",
"base64",
"encoded",
"data",
"or",
"as",
"a",
"filepath",
".",
"Base64",
"image",
"data",
"and",
"f... | python | train |
welbornprod/colr | colr/__main__.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L333-L344 | def list_known_codes(s, unique=True, rgb_mode=False):
""" Find and print all known escape codes in a string,
using get_known_codes.
"""
total = 0
for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode):
total += 1
print(codedesc)
plural = 'code' if total == 1 els... | [
"def",
"list_known_codes",
"(",
"s",
",",
"unique",
"=",
"True",
",",
"rgb_mode",
"=",
"False",
")",
":",
"total",
"=",
"0",
"for",
"codedesc",
"in",
"get_known_codes",
"(",
"s",
",",
"unique",
"=",
"unique",
",",
"rgb_mode",
"=",
"rgb_mode",
")",
":",... | Find and print all known escape codes in a string,
using get_known_codes. | [
"Find",
"and",
"print",
"all",
"known",
"escape",
"codes",
"in",
"a",
"string",
"using",
"get_known_codes",
"."
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/cluster/eval_server/launch_eval.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/eval_server/launch_eval.py#L33-L88 | def launch_eval_job(tag, m1_path, m2_path, job_name, completions):
"""Launches an evaluator job.
tag: name for this eval job (used as top level folder name)
m1_path, m2_path: full gs:// paths to the .pb files to match up
job_name: string, appended to the container, used to differentiate the job
name... | [
"def",
"launch_eval_job",
"(",
"tag",
",",
"m1_path",
",",
"m2_path",
",",
"job_name",
",",
"completions",
")",
":",
"print",
"(",
")",
"if",
"not",
"re",
".",
"match",
"(",
"r'[a-z0-9-]*$'",
",",
"tag",
",",
"re",
".",
"I",
")",
":",
"print",
"(",
... | Launches an evaluator job.
tag: name for this eval job (used as top level folder name)
m1_path, m2_path: full gs:// paths to the .pb files to match up
job_name: string, appended to the container, used to differentiate the job
names (e.g. 'minigo-cc-evaluator-v5-123-v7-456')
completions: the number o... | [
"Launches",
"an",
"evaluator",
"job",
".",
"tag",
":",
"name",
"for",
"this",
"eval",
"job",
"(",
"used",
"as",
"top",
"level",
"folder",
"name",
")",
"m1_path",
"m2_path",
":",
"full",
"gs",
":",
"//",
"paths",
"to",
"the",
".",
"pb",
"files",
"to",... | python | train |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L279-L309 | def bed2interval(align_file, bed, out_file=None):
"""Converts a bed file to an interval file for use with some of the
Picard tools by grabbing the header from the alignment file, reording
the bed file columns and gluing them together.
align_file can be in BAM or SAM format.
bed needs to be in bed12... | [
"def",
"bed2interval",
"(",
"align_file",
",",
"bed",
",",
"out_file",
"=",
"None",
")",
":",
"import",
"pysam",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"align_file",
")",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
... | Converts a bed file to an interval file for use with some of the
Picard tools by grabbing the header from the alignment file, reording
the bed file columns and gluing them together.
align_file can be in BAM or SAM format.
bed needs to be in bed12 format:
http://genome.ucsc.edu/FAQ/FAQformat.html#fo... | [
"Converts",
"a",
"bed",
"file",
"to",
"an",
"interval",
"file",
"for",
"use",
"with",
"some",
"of",
"the",
"Picard",
"tools",
"by",
"grabbing",
"the",
"header",
"from",
"the",
"alignment",
"file",
"reording",
"the",
"bed",
"file",
"columns",
"and",
"gluing... | python | train |
RI-imaging/ODTbrain | odtbrain/_preproc.py | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_preproc.py#L60-L102 | def sinogram_as_radon(uSin, align=True):
r"""Compute the phase from a complex wave field sinogram
This step is essential when using the ray approximation before
computation of the refractive index with the inverse Radon
transform.
Parameters
----------
uSin: 2d or 3d complex ndarray
... | [
"def",
"sinogram_as_radon",
"(",
"uSin",
",",
"align",
"=",
"True",
")",
":",
"ndims",
"=",
"len",
"(",
"uSin",
".",
"shape",
")",
"if",
"ndims",
"==",
"2",
":",
"# unwrapping is very important",
"phiR",
"=",
"np",
".",
"unwrap",
"(",
"np",
".",
"angle... | r"""Compute the phase from a complex wave field sinogram
This step is essential when using the ray approximation before
computation of the refractive index with the inverse Radon
transform.
Parameters
----------
uSin: 2d or 3d complex ndarray
The background-corrected sinogram of the co... | [
"r",
"Compute",
"the",
"phase",
"from",
"a",
"complex",
"wave",
"field",
"sinogram"
] | python | train |
bububa/pyTOP | pyTOP/packages/requests/api.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/api.py#L17-L66 | def request(method, url,
params=None,
data=None,
headers=None,
cookies=None,
files=None,
auth=None,
timeout=None,
allow_redirects=False,
proxies=None,
hooks=None,
return_response=True,
prefetch=False,
config=None):
"""Constructs and sends a :class:`Request <Reques... | [
"def",
"request",
"(",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"files",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"a... | Constructs and sends a :class:`Request <Request>`.
Returns :class:`Response <Response>` object.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Re... | [
"Constructs",
"and",
"sends",
"a",
":",
"class",
":",
"Request",
"<Request",
">",
".",
"Returns",
":",
"class",
":",
"Response",
"<Response",
">",
"object",
"."
] | python | train |
tanghaibao/jcvi | jcvi/formats/fastq.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fastq.py#L721-L749 | def trim(args):
"""
%prog trim fastqfile
Wraps `fastx_trimmer` to trim from begin or end of reads.
"""
p = OptionParser(trim.__doc__)
p.add_option("-f", dest="first", default=0, type="int",
help="First base to keep. Default is 1.")
p.add_option("-l", dest="last", default=0, type... | [
"def",
"trim",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"trim",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"-f\"",
",",
"dest",
"=",
"\"first\"",
",",
"default",
"=",
"0",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Firs... | %prog trim fastqfile
Wraps `fastx_trimmer` to trim from begin or end of reads. | [
"%prog",
"trim",
"fastqfile"
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/color/color_space.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L39-L43 | def _rgb_to_hex(rgbs):
"""Convert rgb to hex triplet"""
rgbs, n_dim = _check_color_dim(rgbs)
return np.array(['#%02x%02x%02x' % tuple((255*rgb[:3]).astype(np.uint8))
for rgb in rgbs], '|U7') | [
"def",
"_rgb_to_hex",
"(",
"rgbs",
")",
":",
"rgbs",
",",
"n_dim",
"=",
"_check_color_dim",
"(",
"rgbs",
")",
"return",
"np",
".",
"array",
"(",
"[",
"'#%02x%02x%02x'",
"%",
"tuple",
"(",
"(",
"255",
"*",
"rgb",
"[",
":",
"3",
"]",
")",
".",
"astyp... | Convert rgb to hex triplet | [
"Convert",
"rgb",
"to",
"hex",
"triplet"
] | python | train |
xflr6/graphviz | graphviz/backend.py | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/backend.py#L230-L242 | def view(filepath):
"""Open filepath with its default viewing application (platform-specific).
Args:
filepath: Path to the file to open in viewer.
Raises:
RuntimeError: If the current platform is not supported.
"""
try:
view_func = getattr(view, PLATFORM)
except Attribut... | [
"def",
"view",
"(",
"filepath",
")",
":",
"try",
":",
"view_func",
"=",
"getattr",
"(",
"view",
",",
"PLATFORM",
")",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"'platform %r not supported'",
"%",
"PLATFORM",
")",
"view_func",
"(",
"filepat... | Open filepath with its default viewing application (platform-specific).
Args:
filepath: Path to the file to open in viewer.
Raises:
RuntimeError: If the current platform is not supported. | [
"Open",
"filepath",
"with",
"its",
"default",
"viewing",
"application",
"(",
"platform",
"-",
"specific",
")",
"."
] | python | train |
Genida/archan | src/archan/analysis.py | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/analysis.py#L120-L125 | def successful(self):
"""Property to tell if the run was successful: no failures."""
for result in self.results:
if result.code == ResultCode.FAILED:
return False
return True | [
"def",
"successful",
"(",
"self",
")",
":",
"for",
"result",
"in",
"self",
".",
"results",
":",
"if",
"result",
".",
"code",
"==",
"ResultCode",
".",
"FAILED",
":",
"return",
"False",
"return",
"True"
] | Property to tell if the run was successful: no failures. | [
"Property",
"to",
"tell",
"if",
"the",
"run",
"was",
"successful",
":",
"no",
"failures",
"."
] | python | train |
cuihantao/andes | andes/models/agc.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/agc.py#L169-L178 | def switch(self):
"""Switch if time for eAgc has come"""
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
'Extended ACE <{}> act... | [
"def",
"switch",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"system",
".",
"dae",
".",
"t",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"self",
".",
"n",
")",
":",
"if",
"t",
">=",
"self",
".",
"tl",
"[",
"idx",
"]",
":",
"if",
"self",
... | Switch if time for eAgc has come | [
"Switch",
"if",
"time",
"for",
"eAgc",
"has",
"come"
] | python | train |
square/pylink | pylink/jlink.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3949-L3980 | def strace_read(self, num_instructions):
"""Reads and returns a number of instructions captured by STRACE.
The number of instructions must be a non-negative value of at most
``0x10000`` (``65536``).
Args:
self (JLink): the ``JLink`` instance.
num_instructions (int):... | [
"def",
"strace_read",
"(",
"self",
",",
"num_instructions",
")",
":",
"if",
"num_instructions",
"<",
"0",
"or",
"num_instructions",
">",
"0x10000",
":",
"raise",
"ValueError",
"(",
"'Invalid instruction count.'",
")",
"buf",
"=",
"(",
"ctypes",
".",
"c_uint32",
... | Reads and returns a number of instructions captured by STRACE.
The number of instructions must be a non-negative value of at most
``0x10000`` (``65536``).
Args:
self (JLink): the ``JLink`` instance.
num_instructions (int): number of instructions to fetch.
Returns:
... | [
"Reads",
"and",
"returns",
"a",
"number",
"of",
"instructions",
"captured",
"by",
"STRACE",
"."
] | python | train |
seomoz/qless-py | qless/workers/serial.py | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/serial.py#L24-L43 | def run(self):
'''Run jobs, popping one after another'''
# Register our signal handlers
self.signals()
with self.listener():
for job in self.jobs():
# If there was no job to be had, we should sleep a little bit
if not job:
... | [
"def",
"run",
"(",
"self",
")",
":",
"# Register our signal handlers",
"self",
".",
"signals",
"(",
")",
"with",
"self",
".",
"listener",
"(",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
"(",
")",
":",
"# If there was no job to be had, we should sleep a... | Run jobs, popping one after another | [
"Run",
"jobs",
"popping",
"one",
"after",
"another"
] | python | train |
quodlibet/mutagen | mutagen/_senf/_stdlib.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_stdlib.py#L135-L154 | def expandvars(path):
"""
Args:
path (pathlike): A path to expand
Returns:
`fsnative`
Like :func:`python:os.path.expandvars` but supports unicode under Windows
+ Python 2 and always returns a `fsnative`.
"""
path = path2fsn(path)
def repl_func(match):
return en... | [
"def",
"expandvars",
"(",
"path",
")",
":",
"path",
"=",
"path2fsn",
"(",
"path",
")",
"def",
"repl_func",
"(",
"match",
")",
":",
"return",
"environ",
".",
"get",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"0",
"... | Args:
path (pathlike): A path to expand
Returns:
`fsnative`
Like :func:`python:os.path.expandvars` but supports unicode under Windows
+ Python 2 and always returns a `fsnative`. | [
"Args",
":",
"path",
"(",
"pathlike",
")",
":",
"A",
"path",
"to",
"expand",
"Returns",
":",
"fsnative"
] | python | train |
dropbox/stone | stone/backends/python_rsrc/stone_serializers.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/python_rsrc/stone_serializers.py#L118-L170 | def encode_sub(self, validator, value):
# type: (bv.Validator, typing.Any) -> typing.Any
"""
Callback intended to be called by other ``encode`` methods to
delegate encoding of sub-values. Arguments have the same semantics
as with the ``encode`` method.
"""
if isi... | [
"def",
"encode_sub",
"(",
"self",
",",
"validator",
",",
"value",
")",
":",
"# type: (bv.Validator, typing.Any) -> typing.Any",
"if",
"isinstance",
"(",
"validator",
",",
"bv",
".",
"List",
")",
":",
"# Because Lists are mutable, we always validate them during",
"# serial... | Callback intended to be called by other ``encode`` methods to
delegate encoding of sub-values. Arguments have the same semantics
as with the ``encode`` method. | [
"Callback",
"intended",
"to",
"be",
"called",
"by",
"other",
"encode",
"methods",
"to",
"delegate",
"encoding",
"of",
"sub",
"-",
"values",
".",
"Arguments",
"have",
"the",
"same",
"semantics",
"as",
"with",
"the",
"encode",
"method",
"."
] | python | train |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L613-L620 | def load(cls, cache_key, deserializer, key_attr):
"""
Load the persisted cache and return a new instance of this class.
"""
items = unitdata.kv().get(cache_key) or []
return cls(cache_key,
[deserializer(item) for item in items],
key_attr) | [
"def",
"load",
"(",
"cls",
",",
"cache_key",
",",
"deserializer",
",",
"key_attr",
")",
":",
"items",
"=",
"unitdata",
".",
"kv",
"(",
")",
".",
"get",
"(",
"cache_key",
")",
"or",
"[",
"]",
"return",
"cls",
"(",
"cache_key",
",",
"[",
"deserializer"... | Load the persisted cache and return a new instance of this class. | [
"Load",
"the",
"persisted",
"cache",
"and",
"return",
"a",
"new",
"instance",
"of",
"this",
"class",
"."
] | python | train |
byt3bl33d3r/CrackMapExec | cme/helpers/powershell.py | https://github.com/byt3bl33d3r/CrackMapExec/blob/333f1c4e06884e85b2776459963ef85d182aba8e/cme/helpers/powershell.py#L242-L392 | def invoke_obfuscation(scriptString):
# Add letters a-z with random case to $RandomDelimiters.
alphabet = ''.join(choice([i.upper(), i]) for i in ascii_lowercase)
# Create list of random dxelimiters called randomDelimiters.
# Avoid using . * ' " [ ] ( ) etc. as delimiters as these will cause problems ... | [
"def",
"invoke_obfuscation",
"(",
"scriptString",
")",
":",
"# Add letters a-z with random case to $RandomDelimiters.",
"alphabet",
"=",
"''",
".",
"join",
"(",
"choice",
"(",
"[",
"i",
".",
"upper",
"(",
")",
",",
"i",
"]",
")",
"for",
"i",
"in",
"ascii_lower... | # Array to store all selected PowerShell execution flags.
powerShellFlags = []
noProfile = '-nop'
nonInteractive = '-noni'
windowStyle = '-w'
# Build the PowerShell execution flags by randomly selecting execution flags substrings and randomizing the order.
# This is to prevent Blue Team from p... | [
"#",
"Array",
"to",
"store",
"all",
"selected",
"PowerShell",
"execution",
"flags",
".",
"powerShellFlags",
"=",
"[]"
] | python | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L537-L545 | def prepend_path_variable_command(variable, paths):
"""
Returns a command that prepends the given paths to the named path variable on
the current platform.
"""
assert isinstance(variable, basestring)
assert is_iterable_typed(paths, basestring)
return path_variable_setting_command(
... | [
"def",
"prepend_path_variable_command",
"(",
"variable",
",",
"paths",
")",
":",
"assert",
"isinstance",
"(",
"variable",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"paths",
",",
"basestring",
")",
"return",
"path_variable_setting_command",
"(",
"va... | Returns a command that prepends the given paths to the named path variable on
the current platform. | [
"Returns",
"a",
"command",
"that",
"prepends",
"the",
"given",
"paths",
"to",
"the",
"named",
"path",
"variable",
"on",
"the",
"current",
"platform",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/repository/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/objects.py#L290-L316 | def get_source_id(self):
"""Gets the ``Resource Id`` of the source of this asset.
The source is the original owner of the copyright of this asset
and may differ from the creator of this asset. The source for a
published book written by Margaret Mitchell would be Macmillan.
The s... | [
"def",
"get_source_id",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.Resource.get_avatar_id_template",
"if",
"not",
"bool",
"(",
"self",
".",
"_my_map",
"[",
"'sourceId'",
"]",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'this Asse... | Gets the ``Resource Id`` of the source of this asset.
The source is the original owner of the copyright of this asset
and may differ from the creator of this asset. The source for a
published book written by Margaret Mitchell would be Macmillan.
The source for an unpublished painting by... | [
"Gets",
"the",
"Resource",
"Id",
"of",
"the",
"source",
"of",
"this",
"asset",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/projects/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/plugin.py#L389-L396 | def get_project_filenames(self):
"""Get the list of recent filenames of a project"""
recent_files = []
if self.current_active_project:
recent_files = self.current_active_project.get_recent_files()
elif self.latest_project:
recent_files = self.latest_project.... | [
"def",
"get_project_filenames",
"(",
"self",
")",
":",
"recent_files",
"=",
"[",
"]",
"if",
"self",
".",
"current_active_project",
":",
"recent_files",
"=",
"self",
".",
"current_active_project",
".",
"get_recent_files",
"(",
")",
"elif",
"self",
".",
"latest_pr... | Get the list of recent filenames of a project | [
"Get",
"the",
"list",
"of",
"recent",
"filenames",
"of",
"a",
"project"
] | python | train |
pmacosta/peng | peng/wave_functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1959-L1986 | def wint(wave):
r"""
Convert a waveform's dependent variable vector to integer.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.... | [
"def",
"wint",
"(",
"wave",
")",
":",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"TypeError",
",",
"\"Cannot convert complex to integer\"",
",",
"wave",
".",
"_dep_vector",
".",
"dtype",
".",
"name",
".",
"startswith",
"(",
"\"complex\"",
")",
",",
")",
"ret... | r"""
Convert a waveform's dependent variable vector to integer.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_function... | [
"r",
"Convert",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"to",
"integer",
"."
] | python | test |
senaite/senaite.core | bika/lims/content/calculation.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/calculation.py#L215-L228 | def setFormula(self, Formula=None):
"""Set the Dependent Services from the text of the calculation Formula
"""
bsc = getToolByName(self, 'bika_setup_catalog')
if Formula is None:
self.setDependentServices(None)
self.getField('Formula').set(self, Formula)
e... | [
"def",
"setFormula",
"(",
"self",
",",
"Formula",
"=",
"None",
")",
":",
"bsc",
"=",
"getToolByName",
"(",
"self",
",",
"'bika_setup_catalog'",
")",
"if",
"Formula",
"is",
"None",
":",
"self",
".",
"setDependentServices",
"(",
"None",
")",
"self",
".",
"... | Set the Dependent Services from the text of the calculation Formula | [
"Set",
"the",
"Dependent",
"Services",
"from",
"the",
"text",
"of",
"the",
"calculation",
"Formula"
] | python | train |
crytic/pyevmasm | pyevmasm/evmasm.py | https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L220-L225 | def bytes(self):
""" Encoded instruction """
b = [bytes([self._opcode])]
for offset in reversed(range(self.operand_size)):
b.append(bytes([(self.operand >> offset * 8) & 0xff]))
return b''.join(b) | [
"def",
"bytes",
"(",
"self",
")",
":",
"b",
"=",
"[",
"bytes",
"(",
"[",
"self",
".",
"_opcode",
"]",
")",
"]",
"for",
"offset",
"in",
"reversed",
"(",
"range",
"(",
"self",
".",
"operand_size",
")",
")",
":",
"b",
".",
"append",
"(",
"bytes",
... | Encoded instruction | [
"Encoded",
"instruction"
] | python | valid |
cidrblock/modelsettings | modelsettings/__init__.py | https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L220-L228 | def generate_env(self):
""" Generate sample environment variables
"""
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in (dict, list):
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
value = f"{self... | [
"def",
"generate_env",
"(",
"self",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"list",
"(",
"self",
".",
"spec",
".",
"keys",
"(",
")",
")",
")",
":",
"if",
"self",
".",
"spec",
"[",
"key",
"]",
"[",
"'type'",
"]",
"in",
"(",
"dict",
",",
"... | Generate sample environment variables | [
"Generate",
"sample",
"environment",
"variables"
] | python | train |
EntilZha/PyFunctional | functional/pipeline.py | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1467-L1495 | def to_file(self, path, delimiter=None, mode='wt', buffering=-1, encoding=None, errors=None,
newline=None, compresslevel=9, format=None, check=-1, preset=None, filters=None,
compression=None):
"""
Saves the sequence to a file by executing str(self) which becomes str(self.... | [
"def",
"to_file",
"(",
"self",
",",
"path",
",",
"delimiter",
"=",
"None",
",",
"mode",
"=",
"'wt'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"compresslevel",
"=",
... | Saves the sequence to a file by executing str(self) which becomes str(self.to_list()). If
delimiter is defined will instead execute self.make_string(delimiter)
:param path: path to write file
:param delimiter: if defined, will call make_string(delimiter) and save that to file.
:param mo... | [
"Saves",
"the",
"sequence",
"to",
"a",
"file",
"by",
"executing",
"str",
"(",
"self",
")",
"which",
"becomes",
"str",
"(",
"self",
".",
"to_list",
"()",
")",
".",
"If",
"delimiter",
"is",
"defined",
"will",
"instead",
"execute",
"self",
".",
"make_string... | python | train |
PmagPy/PmagPy | pmagpy/convert_2_magic.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/convert_2_magic.py#L5098-L5357 | def jr6_txt(mag_file, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
user="", specnum=1, samp_con='1', location='unknown', lat='', lon='',
noave=False, vol... | [
"def",
"jr6_txt",
"(",
"mag_file",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"meas_file",
"=",
"\"measurements.txt\"",
",",
"spec_file",
"=",
"\"specimens.txt\"",
",",
"samp_file",
"=",
"\"samples.txt\"",
",",
"site_file",
"=",
"\"s... | Converts JR6 .txt format files to MagIC measurements format files.
Parameters
----------
mag_file : str
input file name
dir_path : str
working directory, default "."
input_dir_path : str
input file directory IF different from dir_path, default ""
meas_file : str
... | [
"Converts",
"JR6",
".",
"txt",
"format",
"files",
"to",
"MagIC",
"measurements",
"format",
"files",
"."
] | python | train |
jtwhite79/pyemu | pyemu/pst/pst_utils.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_utils.py#L546-L575 | def pst_from_io_files(tpl_files,in_files,ins_files,out_files,pst_filename=None):
""" generate a new pyemu.Pst instance from model interface files. This
function is emulated in the Pst.from_io_files() class method.
Parameters
----------
tpl_files : (list)
template file names
in_files : ... | [
"def",
"pst_from_io_files",
"(",
"tpl_files",
",",
"in_files",
",",
"ins_files",
",",
"out_files",
",",
"pst_filename",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"pst_from_io_files has moved to pyemu.helpers and is also \"",
"+",
"\"now avaiable as a Pst clas... | generate a new pyemu.Pst instance from model interface files. This
function is emulated in the Pst.from_io_files() class method.
Parameters
----------
tpl_files : (list)
template file names
in_files : (list)
model input file names
ins_files : (list)
instruction file nam... | [
"generate",
"a",
"new",
"pyemu",
".",
"Pst",
"instance",
"from",
"model",
"interface",
"files",
".",
"This",
"function",
"is",
"emulated",
"in",
"the",
"Pst",
".",
"from_io_files",
"()",
"class",
"method",
"."
] | python | train |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3241-L3246 | def all_dims(self):
"""The dimensions for each of the arrays in this list"""
return [
_get_dims(arr) if not isinstance(arr, ArrayList) else
arr.all_dims
for arr in self] | [
"def",
"all_dims",
"(",
"self",
")",
":",
"return",
"[",
"_get_dims",
"(",
"arr",
")",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"ArrayList",
")",
"else",
"arr",
".",
"all_dims",
"for",
"arr",
"in",
"self",
"]"
] | The dimensions for each of the arrays in this list | [
"The",
"dimensions",
"for",
"each",
"of",
"the",
"arrays",
"in",
"this",
"list"
] | python | train |
Aluriak/bubble-tools | bubbletools/converter.py | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/converter.py#L16-L20 | def bubble_to_dot(bblfile:str, dotfile:str=None, render:bool=False,
oriented:bool=False):
"""Write in dotfile a graph equivalent to those depicted in bubble file"""
tree = BubbleTree.from_bubble_file(bblfile, oriented=bool(oriented))
return tree_to_dot(tree, dotfile, render=render) | [
"def",
"bubble_to_dot",
"(",
"bblfile",
":",
"str",
",",
"dotfile",
":",
"str",
"=",
"None",
",",
"render",
":",
"bool",
"=",
"False",
",",
"oriented",
":",
"bool",
"=",
"False",
")",
":",
"tree",
"=",
"BubbleTree",
".",
"from_bubble_file",
"(",
"bblfi... | Write in dotfile a graph equivalent to those depicted in bubble file | [
"Write",
"in",
"dotfile",
"a",
"graph",
"equivalent",
"to",
"those",
"depicted",
"in",
"bubble",
"file"
] | python | train |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/viewport.py | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L84-L98 | def get_orientation(width, height):
# type: (int, int) -> Orientation
"""Get viewport orientation from given width and height.
:type width: int
:type height: int
:return: viewport orientation enum
:rtype: Orientation
"""
if width > height:
return Orientation.LANDSCAPE
elif w... | [
"def",
"get_orientation",
"(",
"width",
",",
"height",
")",
":",
"# type: (int, int) -> Orientation",
"if",
"width",
">",
"height",
":",
"return",
"Orientation",
".",
"LANDSCAPE",
"elif",
"width",
"<",
"height",
":",
"return",
"Orientation",
".",
"PORTRAIT",
"el... | Get viewport orientation from given width and height.
:type width: int
:type height: int
:return: viewport orientation enum
:rtype: Orientation | [
"Get",
"viewport",
"orientation",
"from",
"given",
"width",
"and",
"height",
"."
] | python | train |
maxalbert/tohu | tohu/v6/custom_generator/utils.py | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/utils.py#L11-L54 | def make_tohu_items_class(clsname, attr_names):
"""
Parameters
----------
clsname: string
Name of the class to be created
attr_names: list of strings
Names of the attributes of the class to be created
"""
item_cls = attr.make_class(clsname, {name: attr.ib() for name in attr... | [
"def",
"make_tohu_items_class",
"(",
"clsname",
",",
"attr_names",
")",
":",
"item_cls",
"=",
"attr",
".",
"make_class",
"(",
"clsname",
",",
"{",
"name",
":",
"attr",
".",
"ib",
"(",
")",
"for",
"name",
"in",
"attr_names",
"}",
",",
"repr",
"=",
"Fals... | Parameters
----------
clsname: string
Name of the class to be created
attr_names: list of strings
Names of the attributes of the class to be created | [
"Parameters",
"----------",
"clsname",
":",
"string",
"Name",
"of",
"the",
"class",
"to",
"be",
"created"
] | python | train |
chriskiehl/Gooey | gooey/gui/processor.py | https://github.com/chriskiehl/Gooey/blob/e598573c6519b953e0ccfc1f3663f827f8cd7e22/gooey/gui/processor.py#L60-L72 | def _forward_stdout(self, process):
'''
Reads the stdout of `process` and forwards lines and progress
to any interested subscribers
'''
while True:
line = process.stdout.readline()
if not line:
break
pub.send_message(ev... | [
"def",
"_forward_stdout",
"(",
"self",
",",
"process",
")",
":",
"while",
"True",
":",
"line",
"=",
"process",
".",
"stdout",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"pub",
".",
"send_message",
"(",
"events",
".",
"CONSOLE_UPDATE",
... | Reads the stdout of `process` and forwards lines and progress
to any interested subscribers | [
"Reads",
"the",
"stdout",
"of",
"process",
"and",
"forwards",
"lines",
"and",
"progress",
"to",
"any",
"interested",
"subscribers"
] | python | train |
bintoro/overloading.py | overloading.py | https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L755-L769 | def is_void(func):
"""
Determines if a function is a void function, i.e., one whose body contains
nothing but a docstring or an ellipsis. A void function can be used to introduce
an overloaded function without actually registering an implementation.
"""
try:
source = dedent(inspect.getso... | [
"def",
"is_void",
"(",
"func",
")",
":",
"try",
":",
"source",
"=",
"dedent",
"(",
"inspect",
".",
"getsource",
"(",
"func",
")",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"return",
"False",
"fdef",
"=",
"next",
"(",
"ast",
".",
"ite... | Determines if a function is a void function, i.e., one whose body contains
nothing but a docstring or an ellipsis. A void function can be used to introduce
an overloaded function without actually registering an implementation. | [
"Determines",
"if",
"a",
"function",
"is",
"a",
"void",
"function",
"i",
".",
"e",
".",
"one",
"whose",
"body",
"contains",
"nothing",
"but",
"a",
"docstring",
"or",
"an",
"ellipsis",
".",
"A",
"void",
"function",
"can",
"be",
"used",
"to",
"introduce",
... | python | train |
not-na/peng3d | peng3d/model.py | https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/model.py#L888-L898 | def ensureModelData(self,obj):
"""
Ensures that the given ``obj`` has been initialized to be used with this model.
If the object is found to not be initialized, it will be initialized.
"""
if not hasattr(obj,"_modeldata"):
self.create(obj,cache=True)
... | [
"def",
"ensureModelData",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"\"_modeldata\"",
")",
":",
"self",
".",
"create",
"(",
"obj",
",",
"cache",
"=",
"True",
")",
"if",
"\"_modelcache\"",
"not",
"in",
"obj",
".",
"_m... | Ensures that the given ``obj`` has been initialized to be used with this model.
If the object is found to not be initialized, it will be initialized. | [
"Ensures",
"that",
"the",
"given",
"obj",
"has",
"been",
"initialized",
"to",
"be",
"used",
"with",
"this",
"model",
".",
"If",
"the",
"object",
"is",
"found",
"to",
"not",
"be",
"initialized",
"it",
"will",
"be",
"initialized",
"."
] | python | test |
Azure/azure-sdk-for-python | azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py#L1685-L1702 | def start_roles(self, service_name, deployment_name, role_names):
'''
Starts the specified virtual machines.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
role_names:
The names of the roles, as an enumerab... | [
"def",
"start_roles",
"(",
"self",
",",
"service_name",
",",
"deployment_name",
",",
"role_names",
")",
":",
"_validate_not_none",
"(",
"'service_name'",
",",
"service_name",
")",
"_validate_not_none",
"(",
"'deployment_name'",
",",
"deployment_name",
")",
"_validate_... | Starts the specified virtual machines.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
role_names:
The names of the roles, as an enumerable of strings. | [
"Starts",
"the",
"specified",
"virtual",
"machines",
"."
] | python | test |
foxx/peewee-extras | peewee_extras.py | https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L359-L370 | def retrieve(self, cursor):
"""
Retrieve items from query
"""
assert isinstance(cursor, dict), "expected cursor type 'dict'"
# look for record in query
query = self.get_query()
assert isinstance(query, peewee.Query)
query
return query.get(**curso... | [
"def",
"retrieve",
"(",
"self",
",",
"cursor",
")",
":",
"assert",
"isinstance",
"(",
"cursor",
",",
"dict",
")",
",",
"\"expected cursor type 'dict'\"",
"# look for record in query",
"query",
"=",
"self",
".",
"get_query",
"(",
")",
"assert",
"isinstance",
"(",... | Retrieve items from query | [
"Retrieve",
"items",
"from",
"query"
] | python | valid |
vladsaveliev/TargQC | targqc/qualimap/runner.py | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/qualimap/runner.py#L97-L143 | def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report):
""" 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in sample... | [
"def",
"run_multisample_qualimap",
"(",
"output_dir",
",",
"work_dir",
",",
"samples",
",",
"targqc_full_report",
")",
":",
"plots_dirpath",
"=",
"join",
"(",
"output_dir",
",",
"'plots'",
")",
"individual_report_fpaths",
"=",
"[",
"s",
".",
"qualimap_html_fpath",
... | 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots | [
"1",
".",
"Generates",
"Qualimap2",
"plots",
"and",
"put",
"into",
"plots_dirpath",
"2",
".",
"Adds",
"records",
"to",
"targqc_full_report",
".",
"plots"
] | python | train |
coursera-dl/coursera-dl | coursera/utils.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L274-L291 | def extend_supplement_links(destination, source):
"""
Extends (merges) destination dictionary with supplement_links
from source dictionary. Values are expected to be lists, or any
data structure that has `extend` method.
@param destination: Destination dictionary that will be extended.
@type de... | [
"def",
"extend_supplement_links",
"(",
"destination",
",",
"source",
")",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"source",
")",
":",
"if",
"key",
"not",
"in",
"destination",
":",
"destination",
"[",
"key",
"]",
"=",
"value",
"else",
":"... | Extends (merges) destination dictionary with supplement_links
from source dictionary. Values are expected to be lists, or any
data structure that has `extend` method.
@param destination: Destination dictionary that will be extended.
@type destination: @see CourseraOnDemand._extract_links_from_text
... | [
"Extends",
"(",
"merges",
")",
"destination",
"dictionary",
"with",
"supplement_links",
"from",
"source",
"dictionary",
".",
"Values",
"are",
"expected",
"to",
"be",
"lists",
"or",
"any",
"data",
"structure",
"that",
"has",
"extend",
"method",
"."
] | python | train |
HPCC-Cloud-Computing/CAL | calplus/v1/network/resources/network.py | https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/v1/network/resources/network.py#L9-L25 | def index(self, req, drivers):
"""List all network
List all of netowrks on some special cloud
with:
:Param req
:Type object Request
"""
result = []
for driver in drivers:
result.append(driver.list_network(req.params))
data = {
... | [
"def",
"index",
"(",
"self",
",",
"req",
",",
"drivers",
")",
":",
"result",
"=",
"[",
"]",
"for",
"driver",
"in",
"drivers",
":",
"result",
".",
"append",
"(",
"driver",
".",
"list_network",
"(",
"req",
".",
"params",
")",
")",
"data",
"=",
"{",
... | List all network
List all of netowrks on some special cloud
with:
:Param req
:Type object Request | [
"List",
"all",
"network",
"List",
"all",
"of",
"netowrks",
"on",
"some",
"special",
"cloud",
"with",
":",
":",
"Param",
"req",
":",
"Type",
"object",
"Request"
] | python | train |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3490-L3508 | def onMarkedSeen(
self, threads=None, seen_ts=None, ts=None, metadata=None, msg=None
):
"""
Called when the client is listening, and the client has successfully marked threads as seen
:param threads: The threads that were marked
:param author_id: The ID of the person who cha... | [
"def",
"onMarkedSeen",
"(",
"self",
",",
"threads",
"=",
"None",
",",
"seen_ts",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"msg",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"Marked messages as seen in threads {} at {}s\... | Called when the client is listening, and the client has successfully marked threads as seen
:param threads: The threads that were marked
:param author_id: The ID of the person who changed the emoji
:param seen_ts: A timestamp of when the threads were seen
:param ts: A timestamp of the a... | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"the",
"client",
"has",
"successfully",
"marked",
"threads",
"as",
"seen"
] | python | train |
fatiando/pooch | pooch/core.py | https://github.com/fatiando/pooch/blob/fc38601d2d32809b4df75d0715922025740c869a/pooch/core.py#L343-L388 | def _download_file(self, fname):
"""
Download a file from the remote data storage to the local storage.
Used by :meth:`~pooch.Pooch.fetch` to do the actual downloading.
Parameters
----------
fname : str
The file name (relative to the *base_url* of the remote... | [
"def",
"_download_file",
"(",
"self",
",",
"fname",
")",
":",
"destination",
"=",
"self",
".",
"abspath",
"/",
"fname",
"source",
"=",
"self",
".",
"get_url",
"(",
"fname",
")",
"# Stream the file to a temporary so that we can safely check its hash before",
"# overwri... | Download a file from the remote data storage to the local storage.
Used by :meth:`~pooch.Pooch.fetch` to do the actual downloading.
Parameters
----------
fname : str
The file name (relative to the *base_url* of the remote data storage) to
fetch from the local st... | [
"Download",
"a",
"file",
"from",
"the",
"remote",
"data",
"storage",
"to",
"the",
"local",
"storage",
"."
] | python | train |
yashbathia/freeport | setup.py | https://github.com/yashbathia/freeport/blob/ea9bda56f40cde903e21aab23c1c792d28a6f663/setup.py#L76-L84 | def origin(self):
"""
Return the fetch url for the git origin
:return:
"""
for item in os.popen('git remote -v'):
split_item = item.strip().split()
if split_item[0] == 'origin' and split_item[-1] == '(push)':
return split_item[1] | [
"def",
"origin",
"(",
"self",
")",
":",
"for",
"item",
"in",
"os",
".",
"popen",
"(",
"'git remote -v'",
")",
":",
"split_item",
"=",
"item",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"if",
"split_item",
"[",
"0",
"]",
"==",
"'origin'",
"and"... | Return the fetch url for the git origin
:return: | [
"Return",
"the",
"fetch",
"url",
"for",
"the",
"git",
"origin",
":",
"return",
":"
] | python | train |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/config_map.py | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L176-L181 | def itervalues(self):
"Returns an iterator over the values of ConfigMap."
return chain(self._pb.StringMap.values(),
self._pb.IntMap.values(),
self._pb.FloatMap.values(),
self._pb.BoolMap.values()) | [
"def",
"itervalues",
"(",
"self",
")",
":",
"return",
"chain",
"(",
"self",
".",
"_pb",
".",
"StringMap",
".",
"values",
"(",
")",
",",
"self",
".",
"_pb",
".",
"IntMap",
".",
"values",
"(",
")",
",",
"self",
".",
"_pb",
".",
"FloatMap",
".",
"va... | Returns an iterator over the values of ConfigMap. | [
"Returns",
"an",
"iterator",
"over",
"the",
"values",
"of",
"ConfigMap",
"."
] | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/rbridge_id/maps/email/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/rbridge_id/maps/email/__init__.py#L92-L113 | def _set_email_list(self, v, load=False):
"""
Setter method for email_list, mapped from YANG variable /rbridge_id/maps/email/email_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_email_list is considered as a private
method. Backends looking to populate t... | [
"def",
"_set_email_list",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | Setter method for email_list, mapped from YANG variable /rbridge_id/maps/email/email_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_email_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set... | [
"Setter",
"method",
"for",
"email_list",
"mapped",
"from",
"YANG",
"variable",
"/",
"rbridge_id",
"/",
"maps",
"/",
"email",
"/",
"email_list",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",... | python | train |
merll/docker-map | dockermap/map/config/__init__.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/config/__init__.py#L159-L191 | def update_from_obj(self, obj, copy=False):
"""
Updates this configuration object from another.
See :meth:`ConfigurationObject.update` for details.
:param obj: Values to update the ConfigurationObject with.
:type obj: ConfigurationObject
:param copy: Copies lists and di... | [
"def",
"update_from_obj",
"(",
"self",
",",
"obj",
",",
"copy",
"=",
"False",
")",
":",
"obj",
".",
"clean",
"(",
")",
"obj_config",
"=",
"obj",
".",
"_config",
"all_props",
"=",
"self",
".",
"__class__",
".",
"CONFIG_PROPERTIES",
"if",
"copy",
":",
"f... | Updates this configuration object from another.
See :meth:`ConfigurationObject.update` for details.
:param obj: Values to update the ConfigurationObject with.
:type obj: ConfigurationObject
:param copy: Copies lists and dictionaries.
:type copy: bool | [
"Updates",
"this",
"configuration",
"object",
"from",
"another",
"."
] | python | train |
rodionovd/machobot | machobot/dylib.py | https://github.com/rodionovd/machobot/blob/60e10b63c2538a73dc8ec3ce636b3ed5bf09f524/machobot/dylib.py#L31-L79 | def macho_dependencies_list(target_path, header_magic=None):
""" Generates a list of libraries the given Mach-O file depends on.
In that list a single library is represented by its "install path": for some
libraries it would be a full file path, and for others it would be a relative
path (sometimes with dyld templ... | [
"def",
"macho_dependencies_list",
"(",
"target_path",
",",
"header_magic",
"=",
"None",
")",
":",
"MachODeprendencies",
"=",
"namedtuple",
"(",
"\"MachODeprendecies\"",
",",
"\"weak strong\"",
")",
"# Convert the magic value into macholib representation if needed",
"if",
"isi... | Generates a list of libraries the given Mach-O file depends on.
In that list a single library is represented by its "install path": for some
libraries it would be a full file path, and for others it would be a relative
path (sometimes with dyld templates like @executable_path or @rpath in it).
Note: I don't know ... | [
"Generates",
"a",
"list",
"of",
"libraries",
"the",
"given",
"Mach",
"-",
"O",
"file",
"depends",
"on",
"."
] | python | train |
ktbyers/netmiko | netmiko/utilities.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/utilities.py#L158-L179 | def write_bytes(out_data, encoding="ascii"):
"""Write Python2 and Python3 compatible byte stream."""
if sys.version_info[0] >= 3:
if isinstance(out_data, type("")):
if encoding == "utf-8":
return out_data.encode("utf-8")
else:
return out_data.encod... | [
"def",
"write_bytes",
"(",
"out_data",
",",
"encoding",
"=",
"\"ascii\"",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">=",
"3",
":",
"if",
"isinstance",
"(",
"out_data",
",",
"type",
"(",
"\"\"",
")",
")",
":",
"if",
"encoding",
"==",... | Write Python2 and Python3 compatible byte stream. | [
"Write",
"Python2",
"and",
"Python3",
"compatible",
"byte",
"stream",
"."
] | python | train |
contentful/contentful-management.py | contentful_management/client_proxy.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client_proxy.py#L56-L78 | def create(self, resource_id=None, attributes=None):
"""
Creates a resource with the given ID (optional) and attributes.
"""
if attributes is None:
attributes = {}
result = None
if not resource_id:
result = self.client._post(
self... | [
"def",
"create",
"(",
"self",
",",
"resource_id",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"if",
"attributes",
"is",
"None",
":",
"attributes",
"=",
"{",
"}",
"result",
"=",
"None",
"if",
"not",
"resource_id",
":",
"result",
"=",
"self",
... | Creates a resource with the given ID (optional) and attributes. | [
"Creates",
"a",
"resource",
"with",
"the",
"given",
"ID",
"(",
"optional",
")",
"and",
"attributes",
"."
] | python | train |
mbj4668/pyang | pyang/grammar.py | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/grammar.py#L799-L828 | def sort_canonical(keyword, stmts):
"""Sort all `stmts` in the canonical order defined by `keyword`.
Return the sorted list. The `stmt` list is not modified.
If `keyword` does not have a canonical order, the list is returned
as is.
"""
try:
(_arg_type, subspec) = stmt_map[keyword]
... | [
"def",
"sort_canonical",
"(",
"keyword",
",",
"stmts",
")",
":",
"try",
":",
"(",
"_arg_type",
",",
"subspec",
")",
"=",
"stmt_map",
"[",
"keyword",
"]",
"except",
"KeyError",
":",
"return",
"stmts",
"res",
"=",
"[",
"]",
"# keep the order of data definition... | Sort all `stmts` in the canonical order defined by `keyword`.
Return the sorted list. The `stmt` list is not modified.
If `keyword` does not have a canonical order, the list is returned
as is. | [
"Sort",
"all",
"stmts",
"in",
"the",
"canonical",
"order",
"defined",
"by",
"keyword",
".",
"Return",
"the",
"sorted",
"list",
".",
"The",
"stmt",
"list",
"is",
"not",
"modified",
".",
"If",
"keyword",
"does",
"not",
"have",
"a",
"canonical",
"order",
"t... | python | train |
raphaelm/python-fints | fints/client.py | https://github.com/raphaelm/python-fints/blob/fee55ae37d3182d0adb40507d4acb98b06057e4a/fints/client.py#L1151-L1167 | def send_tan(self, challenge: NeedTANResponse, tan: str):
"""
Sends a TAN to confirm a pending operation.
:param challenge: NeedTANResponse to respond to
:param tan: TAN value
:return: Currently no response
"""
with self._get_dialog() as dialog:
tan_... | [
"def",
"send_tan",
"(",
"self",
",",
"challenge",
":",
"NeedTANResponse",
",",
"tan",
":",
"str",
")",
":",
"with",
"self",
".",
"_get_dialog",
"(",
")",
"as",
"dialog",
":",
"tan_seg",
"=",
"self",
".",
"_get_tan_segment",
"(",
"challenge",
".",
"comman... | Sends a TAN to confirm a pending operation.
:param challenge: NeedTANResponse to respond to
:param tan: TAN value
:return: Currently no response | [
"Sends",
"a",
"TAN",
"to",
"confirm",
"a",
"pending",
"operation",
"."
] | python | train |
kevinconway/daemons | daemons/startstop/simple.py | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/startstop/simple.py#L24-L49 | def start(self):
"""Start the process with daemonization.
If the process is already started this call should exit with code
ALREADY_RUNNING. Otherwise it must call the 'daemonize' method and then
call 'run'.
"""
if self.pid is not None:
LOG.error(
... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"pid",
"is",
"not",
"None",
":",
"LOG",
".",
"error",
"(",
"\"The process is already running with pid {0}.\"",
".",
"format",
"(",
"self",
".",
"pid",
")",
")",
"sys",
".",
"exit",
"(",
"exit",
... | Start the process with daemonization.
If the process is already started this call should exit with code
ALREADY_RUNNING. Otherwise it must call the 'daemonize' method and then
call 'run'. | [
"Start",
"the",
"process",
"with",
"daemonization",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py#L75-L93 | def _find_cmd(cmd):
"""Find the full path to a .bat or .exe using the win32api module."""
try:
from win32api import SearchPath
except ImportError:
raise ImportError('you need to have pywin32 installed for this to work')
else:
PATH = os.environ['PATH']
extensions = ['.exe'... | [
"def",
"_find_cmd",
"(",
"cmd",
")",
":",
"try",
":",
"from",
"win32api",
"import",
"SearchPath",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'you need to have pywin32 installed for this to work'",
")",
"else",
":",
"PATH",
"=",
"os",
".",
"environ... | Find the full path to a .bat or .exe using the win32api module. | [
"Find",
"the",
"full",
"path",
"to",
"a",
".",
"bat",
"or",
".",
"exe",
"using",
"the",
"win32api",
"module",
"."
] | python | test |
Games-and-Simulations/sc-docker | scbw/docker_utils.py | https://github.com/Games-and-Simulations/sc-docker/blob/1d7adb9b5839783655564afc4bbcd204a0055dcb/scbw/docker_utils.py#L145-L164 | def check_dockermachine() -> bool:
"""
Checks that docker-machine is available on the computer
:raises FileNotFoundError if docker-machine is not present
"""
logger.debug("checking docker-machine presence")
# noinspection PyBroadException
try:
out = subprocess \
.check_o... | [
"def",
"check_dockermachine",
"(",
")",
"->",
"bool",
":",
"logger",
".",
"debug",
"(",
"\"checking docker-machine presence\"",
")",
"# noinspection PyBroadException",
"try",
":",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"docker-machine\"",
",",
"\... | Checks that docker-machine is available on the computer
:raises FileNotFoundError if docker-machine is not present | [
"Checks",
"that",
"docker",
"-",
"machine",
"is",
"available",
"on",
"the",
"computer"
] | python | train |
c0fec0de/anytree | anytree/importer/jsonimporter.py | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/importer/jsonimporter.py#L64-L66 | def read(self, filehandle):
"""Read JSON from `filehandle`."""
return self.__import(json.load(filehandle, **self.kwargs)) | [
"def",
"read",
"(",
"self",
",",
"filehandle",
")",
":",
"return",
"self",
".",
"__import",
"(",
"json",
".",
"load",
"(",
"filehandle",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
")"
] | Read JSON from `filehandle`. | [
"Read",
"JSON",
"from",
"filehandle",
"."
] | python | train |
Hironsan/anago | anago/layers.py | https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/layers.py#L363-L376 | def get_energy(self, y_true, input_energy, mask):
"""Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3
"""
input_energy = K.sum(input_energy * y_true, 2) # (B, T)
chain_energy = K.sum(K.dot(y_true[:, :-1, :], self.chain_kernel) * y_true[:, 1:, :], 2) # (B, T-1)
... | [
"def",
"get_energy",
"(",
"self",
",",
"y_true",
",",
"input_energy",
",",
"mask",
")",
":",
"input_energy",
"=",
"K",
".",
"sum",
"(",
"input_energy",
"*",
"y_true",
",",
"2",
")",
"# (B, T)",
"chain_energy",
"=",
"K",
".",
"sum",
"(",
"K",
".",
"do... | Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3 | [
"Energy",
"=",
"a1",
"y1",
"+",
"u1",
"y1",
"+",
"y1",
"U",
"y2",
"+",
"u2",
"y2",
"+",
"y2",
"U",
"y3",
"+",
"u3",
"y3",
"+",
"an",
"y3"
] | python | train |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L266-L308 | def draw_samples(self, sequences, n_samples, random_state=None):
"""Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
... | [
"def",
"draw_samples",
"(",
"self",
",",
"sequences",
",",
"n_samples",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"seq",
",",
"collections",
".",
"Iterable",
")",
"for",
"seq",
"in",
"sequences",
"]",
... | Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
n_samples : int
How many samples to return for any given state... | [
"Sample",
"conformations",
"for",
"a",
"sequences",
"of",
"states",
"."
] | python | train |
jciskey/pygraph | pygraph/predefined_graphs.py | https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/predefined_graphs.py#L24-L37 | def build_wheel_graph(num_nodes):
"""Builds a wheel graph with the specified number of nodes.
Ref: http://mathworld.wolfram.com/WheelGraph.html"""
# The easiest way to build a wheel graph is to build
# C_n-1 and then add a hub node and spoke edges
graph = build_cycle_graph(num_nodes - 1)
cyc... | [
"def",
"build_wheel_graph",
"(",
"num_nodes",
")",
":",
"# The easiest way to build a wheel graph is to build",
"# C_n-1 and then add a hub node and spoke edges",
"graph",
"=",
"build_cycle_graph",
"(",
"num_nodes",
"-",
"1",
")",
"cycle_graph_vertices",
"=",
"graph",
".",
"g... | Builds a wheel graph with the specified number of nodes.
Ref: http://mathworld.wolfram.com/WheelGraph.html | [
"Builds",
"a",
"wheel",
"graph",
"with",
"the",
"specified",
"number",
"of",
"nodes",
".",
"Ref",
":",
"http",
":",
"//",
"mathworld",
".",
"wolfram",
".",
"com",
"/",
"WheelGraph",
".",
"html"
] | python | train |
RedHatInsights/insights-core | insights/parsers/grub_conf.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/grub_conf.py#L447-L460 | def _parse_title(line_iter, cur_line, conf):
"""
Parse "title" in grub v1 config
"""
title = []
conf['title'].append(title)
title.append(('title_name', cur_line.split('title', 1)[1].strip()))
while (True):
line = next(line_iter)
if line.startswith("title "):
retur... | [
"def",
"_parse_title",
"(",
"line_iter",
",",
"cur_line",
",",
"conf",
")",
":",
"title",
"=",
"[",
"]",
"conf",
"[",
"'title'",
"]",
".",
"append",
"(",
"title",
")",
"title",
".",
"append",
"(",
"(",
"'title_name'",
",",
"cur_line",
".",
"split",
"... | Parse "title" in grub v1 config | [
"Parse",
"title",
"in",
"grub",
"v1",
"config"
] | python | train |
edx/xblock-utils | xblockutils/studio_editable.py | https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L443-L450 | def get_nested_blocks_spec(self):
"""
Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface
"""
return [
block_spec if isinstance(block_spec, NestedXBlockSpec) else NestedXBlockSpec(block_spec)
for block_spec in self.allowed_nested_b... | [
"def",
"get_nested_blocks_spec",
"(",
"self",
")",
":",
"return",
"[",
"block_spec",
"if",
"isinstance",
"(",
"block_spec",
",",
"NestedXBlockSpec",
")",
"else",
"NestedXBlockSpec",
"(",
"block_spec",
")",
"for",
"block_spec",
"in",
"self",
".",
"allowed_nested_bl... | Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface | [
"Converts",
"allowed_nested_blocks",
"items",
"to",
"NestedXBlockSpec",
"to",
"provide",
"common",
"interface"
] | python | train |
persephone-tools/persephone | persephone/datasets/na.py | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L267-L289 | def prepare_labels(label_type, org_xml_dir=ORG_XML_DIR, label_dir=LABEL_DIR):
""" Prepare the neural network output targets."""
if not os.path.exists(os.path.join(label_dir, "TEXT")):
os.makedirs(os.path.join(label_dir, "TEXT"))
if not os.path.exists(os.path.join(label_dir, "WORDLIST")):
os... | [
"def",
"prepare_labels",
"(",
"label_type",
",",
"org_xml_dir",
"=",
"ORG_XML_DIR",
",",
"label_dir",
"=",
"LABEL_DIR",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"label_dir",
",",
"\"TEXT\"",
")",
... | Prepare the neural network output targets. | [
"Prepare",
"the",
"neural",
"network",
"output",
"targets",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1477-L1534 | def submit_files(self, halt_on_error=True):
"""Submit Files for Documents and Reports to ThreatConnect API.
Critical Errors
* There is insufficient document storage allocated to this account.
Args:
halt_on_error (bool, default:True): If True any exception will raise an err... | [
"def",
"submit_files",
"(",
"self",
",",
"halt_on_error",
"=",
"True",
")",
":",
"# check global setting for override",
"if",
"self",
".",
"halt_on_file_error",
"is",
"not",
"None",
":",
"halt_on_error",
"=",
"self",
".",
"halt_on_file_error",
"upload_status",
"=",
... | Submit Files for Documents and Reports to ThreatConnect API.
Critical Errors
* There is insufficient document storage allocated to this account.
Args:
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
dict: The upload stat... | [
"Submit",
"Files",
"for",
"Documents",
"and",
"Reports",
"to",
"ThreatConnect",
"API",
"."
] | python | train |
nathan-hoad/aiomanhole | aiomanhole/__init__.py | https://github.com/nathan-hoad/aiomanhole/blob/a13394c79e1878cde67aa2637ae5664df468ed04/aiomanhole/__init__.py#L99-L107 | def run_command(self, codeobj):
"""Execute a compiled code object, and write the output back to the client."""
try:
value, stdout = yield from self.attempt_exec(codeobj, self.namespace)
except Exception:
yield from self.send_exception()
return
else:
... | [
"def",
"run_command",
"(",
"self",
",",
"codeobj",
")",
":",
"try",
":",
"value",
",",
"stdout",
"=",
"yield",
"from",
"self",
".",
"attempt_exec",
"(",
"codeobj",
",",
"self",
".",
"namespace",
")",
"except",
"Exception",
":",
"yield",
"from",
"self",
... | Execute a compiled code object, and write the output back to the client. | [
"Execute",
"a",
"compiled",
"code",
"object",
"and",
"write",
"the",
"output",
"back",
"to",
"the",
"client",
"."
] | python | train |
mitsei/dlkit | dlkit/handcar/repository/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/managers.py#L2979-L3002 | def get_repository_lookup_session(self, proxy, *args, **kwargs):
"""Gets the repository lookup session.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.RepositoryLookupSession) - a
RepositoryLookupSession
raise: OperationFailed - unable to complete re... | [
"def",
"get_repository_lookup_session",
"(",
"self",
",",
"proxy",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"supports_repository_lookup",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"i... | Gets the repository lookup session.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.RepositoryLookupSession) - a
RepositoryLookupSession
raise: OperationFailed - unable to complete request
raise: Unimplemented - supports_repository_lookup() is false
... | [
"Gets",
"the",
"repository",
"lookup",
"session",
"."
] | python | train |
tensorpack/tensorpack | tensorpack/models/regularize.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L103-L141 | def regularize_cost_from_collection(name='regularize_cost'):
"""
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
... | [
"def",
"regularize_cost_from_collection",
"(",
"name",
"=",
"'regularize_cost'",
")",
":",
"ctx",
"=",
"get_current_tower_context",
"(",
")",
"if",
"not",
"ctx",
".",
"is_training",
":",
"# TODO Currently cannot build the wd_cost correctly at inference,",
"# because ths vs_na... | Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
tf.Tensor: a scalar, the total regularization cost. | [
"Get",
"the",
"cost",
"from",
"the",
"regularizers",
"in",
"tf",
".",
"GraphKeys",
".",
"REGULARIZATION_LOSSES",
".",
"If",
"in",
"replicated",
"mode",
"will",
"only",
"regularize",
"variables",
"created",
"within",
"the",
"current",
"tower",
"."
] | python | train |
persandstrom/python-verisure | verisure/__main__.py | https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/__main__.py#L22-L31 | def print_result(overview, *names):
""" Print the result of a verisure request """
if names:
for name in names:
toprint = overview
for part in name.split('/'):
toprint = toprint[part]
print(json.dumps(toprint, indent=4, separators=(',', ': ')))
els... | [
"def",
"print_result",
"(",
"overview",
",",
"*",
"names",
")",
":",
"if",
"names",
":",
"for",
"name",
"in",
"names",
":",
"toprint",
"=",
"overview",
"for",
"part",
"in",
"name",
".",
"split",
"(",
"'/'",
")",
":",
"toprint",
"=",
"toprint",
"[",
... | Print the result of a verisure request | [
"Print",
"the",
"result",
"of",
"a",
"verisure",
"request"
] | python | train |
sigmaris/python-gssapi | gssapi/creds.py | https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/creds.py#L266-L293 | def export(self):
"""
Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The serialized token representation ... | [
"def",
"export",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"C",
",",
"'gss_export_cred'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"The GSSAPI implementation does not support gss_export_cred\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"... | Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The serialized token representation of this credential.
:rtype: by... | [
"Serializes",
"this",
"credential",
"into",
"a",
"byte",
"string",
"which",
"can",
"be",
"passed",
"to",
":",
"meth",
":",
"imprt",
"in",
"another",
"process",
"in",
"order",
"to",
"deserialize",
"the",
"byte",
"string",
"back",
"into",
"a",
"credential",
... | python | test |
NerdWalletOSS/savage | src/savage/utils.py | https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/utils.py#L22-L48 | def get_bind_processor(column_type, dialect):
"""
Returns a bind processor for a column type and dialect, with special handling
for JSON/JSONB column types to return dictionaries instead of serialized JSON strings.
NOTE: This is a workaround for https://github.com/NerdWalletOSS/savage/issues/8
:pa... | [
"def",
"get_bind_processor",
"(",
"column_type",
",",
"dialect",
")",
":",
"if",
"column_type",
".",
"compile",
"(",
"dialect",
")",
"not",
"in",
"{",
"'JSON'",
",",
"'JSONB'",
"}",
":",
"# For non-JSON/JSONB column types, return the column type's bind processor",
"re... | Returns a bind processor for a column type and dialect, with special handling
for JSON/JSONB column types to return dictionaries instead of serialized JSON strings.
NOTE: This is a workaround for https://github.com/NerdWalletOSS/savage/issues/8
:param column_type: :py:class:`~sqlalchemy.sql.type_api.TypeE... | [
"Returns",
"a",
"bind",
"processor",
"for",
"a",
"column",
"type",
"and",
"dialect",
"with",
"special",
"handling",
"for",
"JSON",
"/",
"JSONB",
"column",
"types",
"to",
"return",
"dictionaries",
"instead",
"of",
"serialized",
"JSON",
"strings",
"."
] | python | train |
jaraco/jaraco.util | jaraco/util/dice.py | https://github.com/jaraco/jaraco.util/blob/f21071c64f165a5cf844db15e39356e1a47f4b02/jaraco/util/dice.py#L32-L42 | def do_dice_roll():
"""
Roll n-sided dice and return each result and the total
"""
options = get_options()
dice = Dice(options.sides)
rolls = [dice.roll() for n in range(options.number)]
for roll in rolls:
print('rolled', roll)
if options.number > 1:
print('total', sum(rolls)) | [
"def",
"do_dice_roll",
"(",
")",
":",
"options",
"=",
"get_options",
"(",
")",
"dice",
"=",
"Dice",
"(",
"options",
".",
"sides",
")",
"rolls",
"=",
"[",
"dice",
".",
"roll",
"(",
")",
"for",
"n",
"in",
"range",
"(",
"options",
".",
"number",
")",
... | Roll n-sided dice and return each result and the total | [
"Roll",
"n",
"-",
"sided",
"dice",
"and",
"return",
"each",
"result",
"and",
"the",
"total"
] | python | test |
tornadoweb/tornado | tornado/httputil.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L212-L229 | def parse(cls, headers: str) -> "HTTPHeaders":
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
.. versionchanged:: 5... | [
"def",
"parse",
"(",
"cls",
",",
"headers",
":",
"str",
")",
"->",
"\"HTTPHeaders\"",
":",
"h",
"=",
"cls",
"(",
")",
"for",
"line",
"in",
"_CRLF_RE",
".",
"split",
"(",
"headers",
")",
":",
"if",
"line",
":",
"h",
".",
"parse_line",
"(",
"line",
... | Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
.. versionchanged:: 5.1
Raises `HTTPInputError` on malformed header... | [
"Returns",
"a",
"dictionary",
"from",
"HTTP",
"header",
"text",
"."
] | python | train |
juju/python-libjuju | juju/client/_client1.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client1.py#L598-L611 | async def GetChanges(self, yaml):
'''
yaml : str
Returns -> typing.Union[typing.Sequence[~BundleChange], typing.Sequence[str]]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Bundle',
request='GetChanges',
v... | [
"async",
"def",
"GetChanges",
"(",
"self",
",",
"yaml",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Bundle'",
",",
"request",
"=",
"'GetChanges'",
",",
"version",
"=",
"1",
",",
"par... | yaml : str
Returns -> typing.Union[typing.Sequence[~BundleChange], typing.Sequence[str]] | [
"yaml",
":",
"str",
"Returns",
"-",
">",
"typing",
".",
"Union",
"[",
"typing",
".",
"Sequence",
"[",
"~BundleChange",
"]",
"typing",
".",
"Sequence",
"[",
"str",
"]]"
] | python | train |
Jammy2211/PyAutoLens | autolens/data/array/util/grid_util.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/grid_util.py#L83-L126 | def regular_grid_1d_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin=(0.0, 0.0)):
"""Compute the (y,x) arc second coordinates at the centre of every pixel of an array of shape (rows, columns).
Coordinates are defined from the top-left corner, such that the first pixel at location [0, 0] has negat... | [
"def",
"regular_grid_1d_from_shape_pixel_scales_and_origin",
"(",
"shape",
",",
"pixel_scales",
",",
"origin",
"=",
"(",
"0.0",
",",
"0.0",
")",
")",
":",
"regular_grid_1d",
"=",
"np",
".",
"zeros",
"(",
"(",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",... | Compute the (y,x) arc second coordinates at the centre of every pixel of an array of shape (rows, columns).
Coordinates are defined from the top-left corner, such that the first pixel at location [0, 0] has negative x \
and y values in arc seconds.
The regular grid is returned on an array of shape (total_... | [
"Compute",
"the",
"(",
"y",
"x",
")",
"arc",
"second",
"coordinates",
"at",
"the",
"centre",
"of",
"every",
"pixel",
"of",
"an",
"array",
"of",
"shape",
"(",
"rows",
"columns",
")",
"."
] | python | valid |
noahbenson/neuropythy | neuropythy/optimize/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/optimize/core.py#L1153-L1165 | def sign(f=Ellipsis):
'''
sign() yields a potential function equivalent to the sign of the input.
sign(f) yields the sign of the potential function f.
Note that sign has a derivative of 0 at all points; this is not mathematically correct, but it is
useful for the purposes of numerical methods. If y... | [
"def",
"sign",
"(",
"f",
"=",
"Ellipsis",
")",
":",
"f",
"=",
"to_potential",
"(",
"f",
")",
"if",
"is_const_potential",
"(",
"f",
")",
":",
"return",
"const_potential",
"(",
"np",
".",
"sign",
"(",
"f",
".",
"c",
")",
")",
"elif",
"is_identity_poten... | sign() yields a potential function equivalent to the sign of the input.
sign(f) yields the sign of the potential function f.
Note that sign has a derivative of 0 at all points; this is not mathematically correct, but it is
useful for the purposes of numerical methods. If you want traditional behavior, it i... | [
"sign",
"()",
"yields",
"a",
"potential",
"function",
"equivalent",
"to",
"the",
"sign",
"of",
"the",
"input",
".",
"sign",
"(",
"f",
")",
"yields",
"the",
"sign",
"of",
"the",
"potential",
"function",
"f",
"."
] | python | train |
cmcqueen/simplerandom | python/python2/simplerandom/random/_random_py.py | https://github.com/cmcqueen/simplerandom/blob/3f19ffdfeaa8256986adf7173f08c1c719164d01/python/python2/simplerandom/random/_random_py.py#L44-L59 | def seed(self, x=None, *args):
"""For consistent cross-platform seeding, provide an integer seed.
"""
if x is None:
# Use same random seed code copied from Python's random.Random
try:
x = long(_hexlify(_urandom(16)), 16)
except NotImplementedEr... | [
"def",
"seed",
"(",
"self",
",",
"x",
"=",
"None",
",",
"*",
"args",
")",
":",
"if",
"x",
"is",
"None",
":",
"# Use same random seed code copied from Python's random.Random",
"try",
":",
"x",
"=",
"long",
"(",
"_hexlify",
"(",
"_urandom",
"(",
"16",
")",
... | For consistent cross-platform seeding, provide an integer seed. | [
"For",
"consistent",
"cross",
"-",
"platform",
"seeding",
"provide",
"an",
"integer",
"seed",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.