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 |
|---|---|---|---|---|---|---|---|---|
nats-io/asyncio-nats | nats/aio/client.py | https://github.com/nats-io/asyncio-nats/blob/39e840be0b12ce326edac0bba69aeb1be930dcb8/nats/aio/client.py#L478-L585 | def subscribe(self, subject,
queue="",
cb=None,
future=None,
max_msgs=0,
is_async=False,
pending_msgs_limit=DEFAULT_SUB_PENDING_MSGS_LIMIT,
pending_bytes_limit=DEFAULT_SUB_PENDING_BYTES_LIMIT,
... | [
"def",
"subscribe",
"(",
"self",
",",
"subject",
",",
"queue",
"=",
"\"\"",
",",
"cb",
"=",
"None",
",",
"future",
"=",
"None",
",",
"max_msgs",
"=",
"0",
",",
"is_async",
"=",
"False",
",",
"pending_msgs_limit",
"=",
"DEFAULT_SUB_PENDING_MSGS_LIMIT",
",",... | Takes a subject string and optional queue string to send a SUB cmd,
and a callback which to which messages (Msg) will be dispatched to
be processed sequentially by default. | [
"Takes",
"a",
"subject",
"string",
"and",
"optional",
"queue",
"string",
"to",
"send",
"a",
"SUB",
"cmd",
"and",
"a",
"callback",
"which",
"to",
"which",
"messages",
"(",
"Msg",
")",
"will",
"be",
"dispatched",
"to",
"be",
"processed",
"sequentially",
"by"... | python | test |
fastai/fastai | fastai/callbacks/tensorboard.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L345-L357 | def write(self)->None:
"Writes model gradient statistics to Tensorboard."
if len(self.gradients) == 0: return
norms = [x.data.norm() for x in self.gradients]
self._write_avg_norm(norms=norms)
self._write_median_norm(norms=norms)
self._write_max_norm(norms=norms)
s... | [
"def",
"write",
"(",
"self",
")",
"->",
"None",
":",
"if",
"len",
"(",
"self",
".",
"gradients",
")",
"==",
"0",
":",
"return",
"norms",
"=",
"[",
"x",
".",
"data",
".",
"norm",
"(",
")",
"for",
"x",
"in",
"self",
".",
"gradients",
"]",
"self",... | Writes model gradient statistics to Tensorboard. | [
"Writes",
"model",
"gradient",
"statistics",
"to",
"Tensorboard",
"."
] | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_param.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_param.py#L405-L410 | def check_new_target_system(self):
'''handle a new target_system'''
sysid = self.get_sysid()
if sysid in self.pstate:
return
self.add_new_target_system(sysid) | [
"def",
"check_new_target_system",
"(",
"self",
")",
":",
"sysid",
"=",
"self",
".",
"get_sysid",
"(",
")",
"if",
"sysid",
"in",
"self",
".",
"pstate",
":",
"return",
"self",
".",
"add_new_target_system",
"(",
"sysid",
")"
] | handle a new target_system | [
"handle",
"a",
"new",
"target_system"
] | python | train |
swharden/SWHLab | doc/oldcode/swhlab/core/common.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L213-L218 | def html_temp_launch(html):
"""given text, make it a temporary HTML file and launch it."""
fname = tempfile.gettempdir()+"/swhlab/temp.html"
with open(fname,'w') as f:
f.write(html)
webbrowser.open(fname) | [
"def",
"html_temp_launch",
"(",
"html",
")",
":",
"fname",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"+",
"\"/swhlab/temp.html\"",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"html",
")",
"webbrowser",
"."... | given text, make it a temporary HTML file and launch it. | [
"given",
"text",
"make",
"it",
"a",
"temporary",
"HTML",
"file",
"and",
"launch",
"it",
"."
] | python | valid |
kubernetes-client/python | kubernetes/client/apis/core_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L5188-L5209 | def connect_put_node_proxy_with_path(self, name, path, **kwargs):
"""
connect PUT requests to proxy of Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_node_proxy_with_path(... | [
"def",
"connect_put_node_proxy_with_path",
"(",
"self",
",",
"name",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".... | connect PUT requests to proxy of Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_re... | [
"connect",
"PUT",
"requests",
"to",
"proxy",
"of",
"Node",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thre... | python | train |
numba/llvmlite | llvmlite/ir/values.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L161-L166 | def literal_struct(cls, elems):
"""
Construct a literal structure constant made of the given members.
"""
tys = [el.type for el in elems]
return cls(types.LiteralStructType(tys), elems) | [
"def",
"literal_struct",
"(",
"cls",
",",
"elems",
")",
":",
"tys",
"=",
"[",
"el",
".",
"type",
"for",
"el",
"in",
"elems",
"]",
"return",
"cls",
"(",
"types",
".",
"LiteralStructType",
"(",
"tys",
")",
",",
"elems",
")"
] | Construct a literal structure constant made of the given members. | [
"Construct",
"a",
"literal",
"structure",
"constant",
"made",
"of",
"the",
"given",
"members",
"."
] | python | train |
bapakode/OmMongo | ommongo/fields/fields.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/fields.py#L588-L591 | def unwrap(self, value, session=None):
''' Validates ``value`` and unwraps it with ``ComputedField.computed_type``'''
self.validate_unwrap(value)
return self.computed_type.unwrap(value, session=session) | [
"def",
"unwrap",
"(",
"self",
",",
"value",
",",
"session",
"=",
"None",
")",
":",
"self",
".",
"validate_unwrap",
"(",
"value",
")",
"return",
"self",
".",
"computed_type",
".",
"unwrap",
"(",
"value",
",",
"session",
"=",
"session",
")"
] | Validates ``value`` and unwraps it with ``ComputedField.computed_type`` | [
"Validates",
"value",
"and",
"unwraps",
"it",
"with",
"ComputedField",
".",
"computed_type"
] | python | train |
edx/edx-organizations | organizations/data.py | https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/data.py#L53-L61 | def _activate_organization(organization):
"""
Activates an inactivated (soft-deleted) organization as well as any inactive relationships
"""
[_activate_organization_course_relationship(record) for record
in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=False)]
... | [
"def",
"_activate_organization",
"(",
"organization",
")",
":",
"[",
"_activate_organization_course_relationship",
"(",
"record",
")",
"for",
"record",
"in",
"internal",
".",
"OrganizationCourse",
".",
"objects",
".",
"filter",
"(",
"organization_id",
"=",
"organizati... | Activates an inactivated (soft-deleted) organization as well as any inactive relationships | [
"Activates",
"an",
"inactivated",
"(",
"soft",
"-",
"deleted",
")",
"organization",
"as",
"well",
"as",
"any",
"inactive",
"relationships"
] | python | valid |
PlaidWeb/Publ | publ/queries.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L145-L157 | def where_entry_date(query, datespec):
""" Where clause for entries which match a textual date spec
datespec -- The date spec to check for, in YYYY[[-]MM[[-]DD]] format
"""
date, interval, _ = utils.parse_date(datespec)
start_date, end_date = date.span(interval)
return orm.select(
e fo... | [
"def",
"where_entry_date",
"(",
"query",
",",
"datespec",
")",
":",
"date",
",",
"interval",
",",
"_",
"=",
"utils",
".",
"parse_date",
"(",
"datespec",
")",
"start_date",
",",
"end_date",
"=",
"date",
".",
"span",
"(",
"interval",
")",
"return",
"orm",
... | Where clause for entries which match a textual date spec
datespec -- The date spec to check for, in YYYY[[-]MM[[-]DD]] format | [
"Where",
"clause",
"for",
"entries",
"which",
"match",
"a",
"textual",
"date",
"spec"
] | python | train |
mediawiki-utilities/python-mwtypes | mwtypes/files/functions.py | https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/files/functions.py#L118-L129 | def writer(path):
"""
Creates a compressed file writer from for a path with a specified
compression type.
"""
filename, extension = extract_extension(path)
if extension in FILE_WRITERS:
writer_func = FILE_WRITERS[extension]
return writer_func(path)
else:
raise Runtime... | [
"def",
"writer",
"(",
"path",
")",
":",
"filename",
",",
"extension",
"=",
"extract_extension",
"(",
"path",
")",
"if",
"extension",
"in",
"FILE_WRITERS",
":",
"writer_func",
"=",
"FILE_WRITERS",
"[",
"extension",
"]",
"return",
"writer_func",
"(",
"path",
"... | Creates a compressed file writer from for a path with a specified
compression type. | [
"Creates",
"a",
"compressed",
"file",
"writer",
"from",
"for",
"a",
"path",
"with",
"a",
"specified",
"compression",
"type",
"."
] | python | train |
saltstack/salt | salt/modules/libcloud_storage.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L242-L286 | def download_object(container_name, object_name, destination_path, profile,
overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs):
'''
Download an object to the specified destination path.
:param container_name: Container name
:type container_name: ``str``
:para... | [
"def",
"download_object",
"(",
"container_name",
",",
"object_name",
",",
"destination_path",
",",
"profile",
",",
"overwrite_existing",
"=",
"False",
",",
"delete_on_failure",
"=",
"True",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"conn",
"=",
"_get_driver",
... | Download an object to the specified destination path.
:param container_name: Container name
:type container_name: ``str``
:param object_name: Object name
:type object_name: ``str``
:param destination_path: Full path to a file or a directory where the
incoming fil... | [
"Download",
"an",
"object",
"to",
"the",
"specified",
"destination",
"path",
"."
] | python | train |
KelSolaar/Umbra | umbra/ui/widgets/notification_QLabel.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/notification_QLabel.py#L735-L742 | def __fade_in(self):
"""
Starts the Widget fade in.
"""
self.__timer.stop()
self.__vector = self.__fade_speed
self.__timer.start() | [
"def",
"__fade_in",
"(",
"self",
")",
":",
"self",
".",
"__timer",
".",
"stop",
"(",
")",
"self",
".",
"__vector",
"=",
"self",
".",
"__fade_speed",
"self",
".",
"__timer",
".",
"start",
"(",
")"
] | Starts the Widget fade in. | [
"Starts",
"the",
"Widget",
"fade",
"in",
"."
] | python | train |
waqasbhatti/astrobase | astrobase/fakelcs/recovery.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L1950-L2064 | def parallel_periodicvar_recovery(simbasedir,
period_tolerance=1.0e-3,
liststartind=None,
listmaxobjects=None,
nworkers=None):
'''This is a parallel driver for `periodicvar_recover... | [
"def",
"parallel_periodicvar_recovery",
"(",
"simbasedir",
",",
"period_tolerance",
"=",
"1.0e-3",
",",
"liststartind",
"=",
"None",
",",
"listmaxobjects",
"=",
"None",
",",
"nworkers",
"=",
"None",
")",
":",
"# figure out the periodfinding pickles directory",
"pfpkldir... | This is a parallel driver for `periodicvar_recovery`.
Parameters
----------
simbasedir : str
The base directory where all of the fake LCs and period-finding results
are.
period_tolerance : float
The maximum difference that this function will consider between an
actual ... | [
"This",
"is",
"a",
"parallel",
"driver",
"for",
"periodicvar_recovery",
"."
] | python | valid |
fermiPy/fermipy | fermipy/gtanalysis.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L4982-L5001 | def model_counts_spectrum(self, name, logemin, logemax, weighted=False):
"""Return the model counts spectrum of a source.
Parameters
----------
name : str
Source name.
"""
# EAC, we need this b/c older version of the ST don't have the right signature
... | [
"def",
"model_counts_spectrum",
"(",
"self",
",",
"name",
",",
"logemin",
",",
"logemax",
",",
"weighted",
"=",
"False",
")",
":",
"# EAC, we need this b/c older version of the ST don't have the right signature",
"try",
":",
"cs",
"=",
"np",
".",
"array",
"(",
"self... | Return the model counts spectrum of a source.
Parameters
----------
name : str
Source name. | [
"Return",
"the",
"model",
"counts",
"spectrum",
"of",
"a",
"source",
"."
] | python | train |
chrisspen/dtree | dtree.py | https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1028-L1037 | def get_gain(self, attr_name):
"""
Calculates the information gain from splitting on the given attribute.
"""
subset_entropy = 0.0
for value in iterkeys(self._attr_value_counts[attr_name]):
value_prob = self.get_value_prob(attr_name, value)
e = self.get_en... | [
"def",
"get_gain",
"(",
"self",
",",
"attr_name",
")",
":",
"subset_entropy",
"=",
"0.0",
"for",
"value",
"in",
"iterkeys",
"(",
"self",
".",
"_attr_value_counts",
"[",
"attr_name",
"]",
")",
":",
"value_prob",
"=",
"self",
".",
"get_value_prob",
"(",
"att... | Calculates the information gain from splitting on the given attribute. | [
"Calculates",
"the",
"information",
"gain",
"from",
"splitting",
"on",
"the",
"given",
"attribute",
"."
] | python | train |
saltstack/salt | salt/modules/bcache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L211-L264 | def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_m... | [
"def",
"back_make",
"(",
"dev",
",",
"cache_mode",
"=",
"'writeback'",
",",
"force",
"=",
"False",
",",
"attach",
"=",
"True",
",",
"bucket_size",
"=",
"None",
")",
":",
"# pylint: disable=too-many-return-statements",
"cache",
"=",
"uuid",
"(",
")",
"if",
"n... | Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
... | [
"Create",
"a",
"backing",
"device",
"for",
"attachment",
"to",
"a",
"set",
".",
"Because",
"the",
"block",
"size",
"must",
"be",
"the",
"same",
"a",
"cache",
"set",
"already",
"needs",
"to",
"exist",
"."
] | python | train |
edx/django-user-tasks | user_tasks/tasks.py | https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/tasks.py#L74-L95 | def status(self):
"""
Get the :py:class:`~user_tasks.models.UserTaskStatus` model instance for this UserTaskMixin.
"""
task_id = self.request.id
try:
# Most calls are for existing objects, don't waste time
# preparing creation arguments unless necessary
... | [
"def",
"status",
"(",
"self",
")",
":",
"task_id",
"=",
"self",
".",
"request",
".",
"id",
"try",
":",
"# Most calls are for existing objects, don't waste time",
"# preparing creation arguments unless necessary",
"return",
"UserTaskStatus",
".",
"objects",
".",
"get",
"... | Get the :py:class:`~user_tasks.models.UserTaskStatus` model instance for this UserTaskMixin. | [
"Get",
"the",
":",
"py",
":",
"class",
":",
"~user_tasks",
".",
"models",
".",
"UserTaskStatus",
"model",
"instance",
"for",
"this",
"UserTaskMixin",
"."
] | python | train |
apache/incubator-heron | heron/tools/tracker/src/python/handlers/machineshandler.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/machineshandler.py#L58-L103 | def get(self):
""" get method """
clusters = self.get_arguments(constants.PARAM_CLUSTER)
environs = self.get_arguments(constants.PARAM_ENVIRON)
topology_names = self.get_arguments(constants.PARAM_TOPOLOGY)
ret = {}
if len(topology_names) > 1:
if not clusters:
message = "Missing a... | [
"def",
"get",
"(",
"self",
")",
":",
"clusters",
"=",
"self",
".",
"get_arguments",
"(",
"constants",
".",
"PARAM_CLUSTER",
")",
"environs",
"=",
"self",
".",
"get_arguments",
"(",
"constants",
".",
"PARAM_ENVIRON",
")",
"topology_names",
"=",
"self",
".",
... | get method | [
"get",
"method"
] | python | valid |
cggh/scikit-allel | allel/stats/selection.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/selection.py#L661-L736 | def xpnsl(h1, h2, use_threads=True):
"""Cross-population version of the NSL statistic.
Parameters
----------
h1 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the first population.
h2 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for th... | [
"def",
"xpnsl",
"(",
"h1",
",",
"h2",
",",
"use_threads",
"=",
"True",
")",
":",
"# check inputs",
"h1",
"=",
"asarray_ndim",
"(",
"h1",
",",
"2",
")",
"check_integer_dtype",
"(",
"h1",
")",
"h2",
"=",
"asarray_ndim",
"(",
"h2",
",",
"2",
")",
"check... | Cross-population version of the NSL statistic.
Parameters
----------
h1 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the first population.
h2 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the second population.
use_threads : bool,... | [
"Cross",
"-",
"population",
"version",
"of",
"the",
"NSL",
"statistic",
"."
] | python | train |
jgrassler/mkdocs-pandoc | mkdocs_pandoc/filters/tables.py | https://github.com/jgrassler/mkdocs-pandoc/blob/11edfb90830325dca85bd0369bb8e2da8d6815b3/mkdocs_pandoc/filters/tables.py#L60-L169 | def convert_table(self, block):
""""Converts a table to grid table format"""
lines_orig = block.split('\n')
lines_orig.pop() # Remove extra newline at end of block
widest_cell = [] # Will hold the width of the widest cell for each column
widest_word = [] # Will hold the width of ... | [
"def",
"convert_table",
"(",
"self",
",",
"block",
")",
":",
"lines_orig",
"=",
"block",
".",
"split",
"(",
"'\\n'",
")",
"lines_orig",
".",
"pop",
"(",
")",
"# Remove extra newline at end of block",
"widest_cell",
"=",
"[",
"]",
"# Will hold the width of the wide... | Converts a table to grid table format | [
"Converts",
"a",
"table",
"to",
"grid",
"table",
"format"
] | python | train |
bram85/topydo | topydo/ui/columns/CommandLineWidget.py | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/CommandLineWidget.py#L63-L76 | def _history_move(self, p_step):
"""
Changes current value of the command-line to the value obtained from
history_tmp list with index calculated by addition of p_step to the
current position in the command history (history_pos attribute).
Also saves value of the command-line (be... | [
"def",
"_history_move",
"(",
"self",
",",
"p_step",
")",
":",
"if",
"len",
"(",
"self",
".",
"history",
")",
">",
"0",
":",
"# don't pollute real history - use temporary storage",
"self",
".",
"history_tmp",
"[",
"self",
".",
"history_pos",
"]",
"=",
"self",
... | Changes current value of the command-line to the value obtained from
history_tmp list with index calculated by addition of p_step to the
current position in the command history (history_pos attribute).
Also saves value of the command-line (before changing it) to history_tmp
for potentia... | [
"Changes",
"current",
"value",
"of",
"the",
"command",
"-",
"line",
"to",
"the",
"value",
"obtained",
"from",
"history_tmp",
"list",
"with",
"index",
"calculated",
"by",
"addition",
"of",
"p_step",
"to",
"the",
"current",
"position",
"in",
"the",
"command",
... | python | train |
Esri/ArcREST | src/arcrest/manageorg/_portals.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_portals.py#L91-L100 | def portal(self, portalID=None):
"""returns a specific reference to a portal"""
if portalID is None:
portalID = self.portalSelf.id
url = "%s/%s" % (self.root, portalID)
return Portal(url=url,
securityHandler=self._securityHandler,
proxy_url... | [
"def",
"portal",
"(",
"self",
",",
"portalID",
"=",
"None",
")",
":",
"if",
"portalID",
"is",
"None",
":",
"portalID",
"=",
"self",
".",
"portalSelf",
".",
"id",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"root",
",",
"portalID",
")",
"return",
... | returns a specific reference to a portal | [
"returns",
"a",
"specific",
"reference",
"to",
"a",
"portal"
] | python | train |
solvebio/solvebio-python | solvebio/cli/credentials.py | https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/cli/credentials.py#L76-L93 | def get_credentials():
"""
Returns the user's stored API key if a valid credentials file is found.
Raises CredentialsError if no valid credentials file is found.
"""
try:
netrc_path = netrc.path()
auths = netrc(netrc_path).authenticators(
urlparse(solvebio.api_host).netlo... | [
"def",
"get_credentials",
"(",
")",
":",
"try",
":",
"netrc_path",
"=",
"netrc",
".",
"path",
"(",
")",
"auths",
"=",
"netrc",
"(",
"netrc_path",
")",
".",
"authenticators",
"(",
"urlparse",
"(",
"solvebio",
".",
"api_host",
")",
".",
"netloc",
")",
"e... | Returns the user's stored API key if a valid credentials file is found.
Raises CredentialsError if no valid credentials file is found. | [
"Returns",
"the",
"user",
"s",
"stored",
"API",
"key",
"if",
"a",
"valid",
"credentials",
"file",
"is",
"found",
".",
"Raises",
"CredentialsError",
"if",
"no",
"valid",
"credentials",
"file",
"is",
"found",
"."
] | python | test |
nok/sklearn-porter | sklearn_porter/estimator/classifier/AdaBoostClassifier/__init__.py | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/AdaBoostClassifier/__init__.py#L199-L254 | def create_branches(self, left_nodes, right_nodes, threshold,
value, features, node, depth, init=False):
"""
Parse and port a single tree estimator.
Parameters
----------
:param left_nodes : object
The left children node.
:param right_... | [
"def",
"create_branches",
"(",
"self",
",",
"left_nodes",
",",
"right_nodes",
",",
"threshold",
",",
"value",
",",
"features",
",",
"node",
",",
"depth",
",",
"init",
"=",
"False",
")",
":",
"out",
"=",
"''",
"if",
"threshold",
"[",
"node",
"]",
"!=",
... | Parse and port a single tree estimator.
Parameters
----------
:param left_nodes : object
The left children node.
:param right_nodes : object
The left children node.
:param threshold : object
The decision threshold.
:param value : objec... | [
"Parse",
"and",
"port",
"a",
"single",
"tree",
"estimator",
"."
] | python | train |
ciena/afkak | afkak/kafkacodec.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L250-L265 | def decode_produce_response(cls, data):
"""
Decode bytes to a ProduceResponse
:param bytes data: bytes to decode
:returns: iterable of `afkak.common.ProduceResponse`
"""
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0)
for _i in range(num_to... | [
"def",
"decode_produce_response",
"(",
"cls",
",",
"data",
")",
":",
"(",
"(",
"correlation_id",
",",
"num_topics",
")",
",",
"cur",
")",
"=",
"relative_unpack",
"(",
"'>ii'",
",",
"data",
",",
"0",
")",
"for",
"_i",
"in",
"range",
"(",
"num_topics",
"... | Decode bytes to a ProduceResponse
:param bytes data: bytes to decode
:returns: iterable of `afkak.common.ProduceResponse` | [
"Decode",
"bytes",
"to",
"a",
"ProduceResponse"
] | python | train |
pybel/pybel | src/pybel/struct/summary/edge_summary.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/edge_summary.py#L24-L35 | def iter_annotation_value_pairs(graph) -> Iterable[Tuple[str, str]]:
"""Iterate over the key/value pairs, with duplicates, for each annotation used in a BEL graph.
:param pybel.BELGraph graph: A BEL graph
"""
return (
(key, value)
for _, _, data in graph.edges(data=True)
if ANNO... | [
"def",
"iter_annotation_value_pairs",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"return",
"(",
"(",
"key",
",",
"value",
")",
"for",
"_",
",",
"_",
",",
"data",
"in",
"graph",
".",
"edges",
"(",
"data... | Iterate over the key/value pairs, with duplicates, for each annotation used in a BEL graph.
:param pybel.BELGraph graph: A BEL graph | [
"Iterate",
"over",
"the",
"key",
"/",
"value",
"pairs",
"with",
"duplicates",
"for",
"each",
"annotation",
"used",
"in",
"a",
"BEL",
"graph",
"."
] | python | train |
wheerd/multiset | multiset.py | https://github.com/wheerd/multiset/blob/1f002397096edae3da32d004e3159345a476999c/multiset.py#L222-L256 | def union(self, *others):
r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities.
>>> ms = Multiset('aab')
>>> sorted(ms.union('bc'))
['a', 'a', 'b', 'c']
You can also use the ``|`` operator for the same effect. However, the ope... | [
"def",
"union",
"(",
"self",
",",
"*",
"others",
")",
":",
"result",
"=",
"self",
".",
"__copy__",
"(",
")",
"_elements",
"=",
"result",
".",
"_elements",
"_total",
"=",
"result",
".",
"_total",
"for",
"other",
"in",
"map",
"(",
"self",
".",
"_as_map... | r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities.
>>> ms = Multiset('aab')
>>> sorted(ms.union('bc'))
['a', 'a', 'b', 'c']
You can also use the ``|`` operator for the same effect. However, the operator version
will only ac... | [
"r",
"Return",
"a",
"new",
"multiset",
"with",
"all",
"elements",
"from",
"the",
"multiset",
"and",
"the",
"others",
"with",
"maximal",
"multiplicities",
"."
] | python | train |
gwpy/gwpy | gwpy/signal/qtransform.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/qtransform.py#L482-L583 | def interpolate(self, tres="<default>", fres="<default>", logf=False,
outseg=None):
"""Interpolate this `QGram` over a regularly-gridded spectrogram
Parameters
----------
tres : `float`, optional
desired time resolution (seconds) of output `Spectrogram`,
... | [
"def",
"interpolate",
"(",
"self",
",",
"tres",
"=",
"\"<default>\"",
",",
"fres",
"=",
"\"<default>\"",
",",
"logf",
"=",
"False",
",",
"outseg",
"=",
"None",
")",
":",
"from",
"scipy",
".",
"interpolate",
"import",
"(",
"interp2d",
",",
"InterpolatedUniv... | Interpolate this `QGram` over a regularly-gridded spectrogram
Parameters
----------
tres : `float`, optional
desired time resolution (seconds) of output `Spectrogram`,
default is `abs(outseg) / 1000.`
fres : `float`, `int`, `None`, optional
desired f... | [
"Interpolate",
"this",
"QGram",
"over",
"a",
"regularly",
"-",
"gridded",
"spectrogram"
] | python | train |
rigetti/pyquil | pyquil/magic.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/magic.py#L64-L102 | def _if_statement(test, if_function, else_function) -> None:
"""
Evaluate an if statement within a @magicquil block.
If the test value is a Quil Addr then unwind it into quil code equivalent to an if then statement using jumps. Both
sides of the if statement need to be evaluated and placed into separat... | [
"def",
"_if_statement",
"(",
"test",
",",
"if_function",
",",
"else_function",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"test",
",",
"Addr",
")",
":",
"token",
"=",
"_program_context",
".",
"set",
"(",
"Program",
"(",
")",
")",
"if_function",
"("... | Evaluate an if statement within a @magicquil block.
If the test value is a Quil Addr then unwind it into quil code equivalent to an if then statement using jumps. Both
sides of the if statement need to be evaluated and placed into separate Programs, which is why we create new
program contexts for their eva... | [
"Evaluate",
"an",
"if",
"statement",
"within",
"a",
"@magicquil",
"block",
"."
] | python | train |
saltstack/salt | salt/modules/zabbix.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1894-L1951 | def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the... | [
"def",
"usermacro_get",
"(",
"macro",
"=",
"None",
",",
"hostids",
"=",
"None",
",",
"templateids",
"=",
"None",
",",
"hostmacroids",
"=",
"None",
",",
"globalmacroids",
"=",
"None",
",",
"globalmacro",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
... | Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmac... | [
"Retrieve",
"user",
"macros",
"according",
"to",
"the",
"given",
"parameters",
"."
] | python | train |
raamana/mrivis | mrivis/base.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/base.py#L1067-L1079 | def _set_roi_mask(self, roi_mask):
"""Sets a new ROI mask."""
if isinstance(roi_mask,
np.ndarray): # not (roi_mask is None or roi_mask=='auto'):
self._verify_shape_compatibility(roi_mask, 'ROI set')
self.roi_mask = roi_mask
self.roi_list = np.... | [
"def",
"_set_roi_mask",
"(",
"self",
",",
"roi_mask",
")",
":",
"if",
"isinstance",
"(",
"roi_mask",
",",
"np",
".",
"ndarray",
")",
":",
"# not (roi_mask is None or roi_mask=='auto'):",
"self",
".",
"_verify_shape_compatibility",
"(",
"roi_mask",
",",
"'ROI set'",
... | Sets a new ROI mask. | [
"Sets",
"a",
"new",
"ROI",
"mask",
"."
] | python | train |
techdragon/python-check-pypi-name | src/check_pypi_name/__init__.py | https://github.com/techdragon/python-check-pypi-name/blob/2abfa98878755ed9073b4f5448f4380f88e3e8f3/src/check_pypi_name/__init__.py#L7-L86 | def check_pypi_name(pypi_package_name, pypi_registry_host=None):
"""
Check if a package name exists on pypi.
TODO: Document the Registry URL construction.
It may not be obvious how pypi_package_name and pypi_registry_host are used
I'm appending the simple HTTP API parts of the registry stan... | [
"def",
"check_pypi_name",
"(",
"pypi_package_name",
",",
"pypi_registry_host",
"=",
"None",
")",
":",
"if",
"pypi_registry_host",
"is",
"None",
":",
"pypi_registry_host",
"=",
"'pypi.python.org'",
"# Just a helpful reminder why this bytearray size was chosen.",
"# ... | Check if a package name exists on pypi.
TODO: Document the Registry URL construction.
It may not be obvious how pypi_package_name and pypi_registry_host are used
I'm appending the simple HTTP API parts of the registry standard specification.
It will return True if the package name, or any equi... | [
"Check",
"if",
"a",
"package",
"name",
"exists",
"on",
"pypi",
"."
] | python | test |
Alignak-monitoring-contrib/alignak-backend-client | alignak_backend_client/backend_client.py | https://github.com/Alignak-monitoring-contrib/alignak-backend-client/blob/1e21f6ce703e66984d1f9b20fe7866460ab50b39/alignak_backend_client/backend_client.py#L441-L458 | def file_dump(self, data, filename): # pylint: disable=no-self-use
"""
Dump the data to a JSON formatted file
:param data: data to be dumped
:param filename: name of the file to use. Only the file name, not the full path!
:return: dumped file absolute file name
"""
... | [
"def",
"file_dump",
"(",
"self",
",",
"data",
",",
"filename",
")",
":",
"# pylint: disable=no-self-use",
"dump",
"=",
"json",
".",
"dumps",
"(",
"data",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"sort_keys",
"... | Dump the data to a JSON formatted file
:param data: data to be dumped
:param filename: name of the file to use. Only the file name, not the full path!
:return: dumped file absolute file name | [
"Dump",
"the",
"data",
"to",
"a",
"JSON",
"formatted",
"file",
":",
"param",
"data",
":",
"data",
"to",
"be",
"dumped",
":",
"param",
"filename",
":",
"name",
"of",
"the",
"file",
"to",
"use",
".",
"Only",
"the",
"file",
"name",
"not",
"the",
"full",... | python | test |
zetaops/zengine | zengine/management_commands.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/management_commands.py#L44-L92 | def run(self):
"""
Creates new permissions.
"""
from pyoko.lib.utils import get_object_from_path
from zengine.config import settings
model = get_object_from_path(settings.PERMISSION_MODEL)
perm_provider = get_object_from_path(settings.PERMISSION_PROVIDER)
... | [
"def",
"run",
"(",
"self",
")",
":",
"from",
"pyoko",
".",
"lib",
".",
"utils",
"import",
"get_object_from_path",
"from",
"zengine",
".",
"config",
"import",
"settings",
"model",
"=",
"get_object_from_path",
"(",
"settings",
".",
"PERMISSION_MODEL",
")",
"perm... | Creates new permissions. | [
"Creates",
"new",
"permissions",
"."
] | python | train |
openvax/varcode | varcode/effects/mutate.py | https://github.com/openvax/varcode/blob/981633db45ca2b31f76c06894a7360ea5d70a9b8/varcode/effects/mutate.py#L62-L87 | def substitute(sequence, offset, ref, alt):
"""Mutate a sequence by substituting given `alt` at instead of `ref` at the
given `position`.
Parameters
----------
sequence : sequence
String of amino acids or DNA bases
offset : int
Base 0 offset from start of `sequence`
ref : ... | [
"def",
"substitute",
"(",
"sequence",
",",
"offset",
",",
"ref",
",",
"alt",
")",
":",
"n_ref",
"=",
"len",
"(",
"ref",
")",
"sequence_ref",
"=",
"sequence",
"[",
"offset",
":",
"offset",
"+",
"n_ref",
"]",
"assert",
"str",
"(",
"sequence_ref",
")",
... | Mutate a sequence by substituting given `alt` at instead of `ref` at the
given `position`.
Parameters
----------
sequence : sequence
String of amino acids or DNA bases
offset : int
Base 0 offset from start of `sequence`
ref : sequence or str
What do we expect to find a... | [
"Mutate",
"a",
"sequence",
"by",
"substituting",
"given",
"alt",
"at",
"instead",
"of",
"ref",
"at",
"the",
"given",
"position",
"."
] | python | train |
sveetch/boussole | boussole/watcher.py | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/watcher.py#L143-L161 | def compile_dependencies(self, sourcepath, include_self=False):
"""
Apply compile on all dependencies
Args:
sourcepath (string): Sass source path to compile to its
destination using project settings.
Keyword Arguments:
include_self (bool): If ``T... | [
"def",
"compile_dependencies",
"(",
"self",
",",
"sourcepath",
",",
"include_self",
"=",
"False",
")",
":",
"items",
"=",
"self",
".",
"inspector",
".",
"parents",
"(",
"sourcepath",
")",
"# Also add the current event related path",
"if",
"include_self",
":",
"ite... | Apply compile on all dependencies
Args:
sourcepath (string): Sass source path to compile to its
destination using project settings.
Keyword Arguments:
include_self (bool): If ``True`` the given sourcepath is add to
items to compile, else only its... | [
"Apply",
"compile",
"on",
"all",
"dependencies"
] | python | train |
pybel/pybel | src/pybel/canonicalize.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L178-L183 | def _unset_annotation_to_str(keys: List[str]) -> str:
"""Return an unset annotation string."""
if len(keys) == 1:
return 'UNSET {}'.format(list(keys)[0])
return 'UNSET {{{}}}'.format(', '.join('{}'.format(key) for key in keys)) | [
"def",
"_unset_annotation_to_str",
"(",
"keys",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
":",
"return",
"'UNSET {}'",
".",
"format",
"(",
"list",
"(",
"keys",
")",
"[",
"0",
"]",
")",
"return",
... | Return an unset annotation string. | [
"Return",
"an",
"unset",
"annotation",
"string",
"."
] | python | train |
pri22296/beautifultable | beautifultable/rows.py | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/rows.py#L65-L99 | def _clamp_string(self, row_item, column_index, delimiter=''):
"""Clamp `row_item` to fit in column referred by column_index.
This method considers padding and appends the delimiter if `row_item`
needs to be truncated.
Parameters
----------
row_item: str
Str... | [
"def",
"_clamp_string",
"(",
"self",
",",
"row_item",
",",
"column_index",
",",
"delimiter",
"=",
"''",
")",
":",
"width",
"=",
"(",
"self",
".",
"_table",
".",
"column_widths",
"[",
"column_index",
"]",
"-",
"self",
".",
"_table",
".",
"left_padding_width... | Clamp `row_item` to fit in column referred by column_index.
This method considers padding and appends the delimiter if `row_item`
needs to be truncated.
Parameters
----------
row_item: str
String which should be clamped.
column_index: int
Index ... | [
"Clamp",
"row_item",
"to",
"fit",
"in",
"column",
"referred",
"by",
"column_index",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_2_00/keychain/key/accept_lifetime/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_2_00/keychain/key/accept_lifetime/__init__.py#L127-L148 | def _set_start_time(self, v, load=False):
"""
Setter method for start_time, mapped from YANG variable /keychain/key/accept_lifetime/start_time (time-format-start)
If this variable is read-only (config: false) in the
source YANG file, then _set_start_time is considered as a private
method. Backends l... | [
"def",
"_set_start_time",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | Setter method for start_time, mapped from YANG variable /keychain/key/accept_lifetime/start_time (time-format-start)
If this variable is read-only (config: false) in the
source YANG file, then _set_start_time is considered as a private
method. Backends looking to populate this variable should
do so via ... | [
"Setter",
"method",
"for",
"start_time",
"mapped",
"from",
"YANG",
"variable",
"/",
"keychain",
"/",
"key",
"/",
"accept_lifetime",
"/",
"start_time",
"(",
"time",
"-",
"format",
"-",
"start",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
... | python | train |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L4686-L4697 | def addContext(self, layer, hiddenLayerName = 'hidden', verbosity = 0):
"""
Adds a context layer. Necessary to keep self.contextLayers dictionary up to date.
"""
# better not add context layer first if using sweep() without mapInput
SRN.add(self, layer, verbosity)
if hid... | [
"def",
"addContext",
"(",
"self",
",",
"layer",
",",
"hiddenLayerName",
"=",
"'hidden'",
",",
"verbosity",
"=",
"0",
")",
":",
"# better not add context layer first if using sweep() without mapInput",
"SRN",
".",
"add",
"(",
"self",
",",
"layer",
",",
"verbosity",
... | Adds a context layer. Necessary to keep self.contextLayers dictionary up to date. | [
"Adds",
"a",
"context",
"layer",
".",
"Necessary",
"to",
"keep",
"self",
".",
"contextLayers",
"dictionary",
"up",
"to",
"date",
"."
] | python | train |
intelligenia/modeltranslation | modeltranslation/models.py | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L206-L216 | def _load_source_object(self):
"""
Loads related object in a dynamic attribute and returns it.
"""
if hasattr(self, "source_obj"):
self.source_text = getattr(self.source_obj, self.field)
return self.source_obj
self._load_source_model()
self.source_obj = self.source_model.objects.get(id=self.object_id... | [
"def",
"_load_source_object",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"source_obj\"",
")",
":",
"self",
".",
"source_text",
"=",
"getattr",
"(",
"self",
".",
"source_obj",
",",
"self",
".",
"field",
")",
"return",
"self",
".",
"source... | Loads related object in a dynamic attribute and returns it. | [
"Loads",
"related",
"object",
"in",
"a",
"dynamic",
"attribute",
"and",
"returns",
"it",
"."
] | python | train |
Rapptz/discord.py | discord/message.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L566-L601 | async def delete(self, *, delay=None):
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1.0
... | [
"async",
"def",
"delete",
"(",
"self",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"if",
"delay",
"is",
"not",
"None",
":",
"async",
"def",
"delete",
"(",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"delay",
",",
"loop",
"=",
"self",
".",... | |coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1.0
Added the new ``delay`` keyword-only pa... | [
"|coro|"
] | python | train |
yahoo/TensorFlowOnSpark | tensorflowonspark/dfutil.py | https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/dfutil.py#L134-L168 | def infer_schema(example, binary_features=[]):
"""Given a tf.train.Example, infer the Spark DataFrame schema (StructFields).
Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to
disambiguate these types for Spark DataFrames DTypes (StringType and BinaryType), so we requ... | [
"def",
"infer_schema",
"(",
"example",
",",
"binary_features",
"=",
"[",
"]",
")",
":",
"def",
"_infer_sql_type",
"(",
"k",
",",
"v",
")",
":",
"# special handling for binary features",
"if",
"k",
"in",
"binary_features",
":",
"return",
"BinaryType",
"(",
")",... | Given a tf.train.Example, infer the Spark DataFrame schema (StructFields).
Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to
disambiguate these types for Spark DataFrames DTypes (StringType and BinaryType), so we require a "hint"
from the caller in the ``binary_featu... | [
"Given",
"a",
"tf",
".",
"train",
".",
"Example",
"infer",
"the",
"Spark",
"DataFrame",
"schema",
"(",
"StructFields",
")",
"."
] | python | train |
openego/ding0 | ding0/grid/mv_grid/util/data_input.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/grid/mv_grid/util/data_input.py#L312-L376 | def _parse_tsplib(f):
"""Parses a TSPLIB file descriptor and returns a dict containing the problem definition"""
line = ''
specs = {}
used_specs = ['NAME', 'COMMENT', 'DIMENSION', 'CAPACITY', 'TYPE', 'EDGE_WEIGHT_TYPE']
used_data = ['DEMAND_SECTION', 'DEPOT_SECTION']
# Parse specs part
fo... | [
"def",
"_parse_tsplib",
"(",
"f",
")",
":",
"line",
"=",
"''",
"specs",
"=",
"{",
"}",
"used_specs",
"=",
"[",
"'NAME'",
",",
"'COMMENT'",
",",
"'DIMENSION'",
",",
"'CAPACITY'",
",",
"'TYPE'",
",",
"'EDGE_WEIGHT_TYPE'",
"]",
"used_data",
"=",
"[",
"'DEMA... | Parses a TSPLIB file descriptor and returns a dict containing the problem definition | [
"Parses",
"a",
"TSPLIB",
"file",
"descriptor",
"and",
"returns",
"a",
"dict",
"containing",
"the",
"problem",
"definition"
] | python | train |
ray-project/ray | python/ray/experimental/array/distributed/core.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/core.py#L58-L68 | def assemble(self):
"""Assemble an array from a distributed array of object IDs."""
first_block = ray.get(self.objectids[(0, ) * self.ndim])
dtype = first_block.dtype
result = np.zeros(self.shape, dtype=dtype)
for index in np.ndindex(*self.num_blocks):
lower = DistArr... | [
"def",
"assemble",
"(",
"self",
")",
":",
"first_block",
"=",
"ray",
".",
"get",
"(",
"self",
".",
"objectids",
"[",
"(",
"0",
",",
")",
"*",
"self",
".",
"ndim",
"]",
")",
"dtype",
"=",
"first_block",
".",
"dtype",
"result",
"=",
"np",
".",
"zer... | Assemble an array from a distributed array of object IDs. | [
"Assemble",
"an",
"array",
"from",
"a",
"distributed",
"array",
"of",
"object",
"IDs",
"."
] | python | train |
zarr-developers/zarr | zarr/hierarchy.py | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L458-L496 | def visitvalues(self, func):
"""Run ``func`` on each object.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
... | [
"def",
"visitvalues",
"(",
"self",
",",
"func",
")",
":",
"def",
"_visit",
"(",
"obj",
")",
":",
"yield",
"obj",
"keys",
"=",
"sorted",
"(",
"getattr",
"(",
"obj",
",",
"\"keys\"",
",",
"lambda",
":",
"[",
"]",
")",
"(",
")",
")",
"for",
"k",
"... | Run ``func`` on each object.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>... | [
"Run",
"func",
"on",
"each",
"object",
"."
] | python | train |
senseobservationsystems/commonsense-python-lib | senseapi.py | https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L392-L410 | def AuthenticateOauth (self, oauth_token_key, oauth_token_secret, oauth_consumer_key, oauth_consumer_secret):
"""
Authenticate using Oauth
@param oauth_token_key (string) - A valid oauth token key obtained from CommonSense
@param oauth_token_secret (string) ... | [
"def",
"AuthenticateOauth",
"(",
"self",
",",
"oauth_token_key",
",",
"oauth_token_secret",
",",
"oauth_consumer_key",
",",
"oauth_consumer_secret",
")",
":",
"self",
".",
"__oauth_consumer__",
"=",
"oauth",
".",
"OAuthConsumer",
"(",
"str",
"(",
"oauth_consumer_key",... | Authenticate using Oauth
@param oauth_token_key (string) - A valid oauth token key obtained from CommonSense
@param oauth_token_secret (string) - A valid oauth token secret obtained from CommonSense
@param oauth_consumer_key (string) - A valid oauth consumer key obta... | [
"Authenticate",
"using",
"Oauth"
] | python | train |
linkhub-sdk/popbill.py | popbill/htTaxinvoiceService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/htTaxinvoiceService.py#L71-L85 | def getJobState(self, CorpNum, JobID, UserID=None):
""" 수집 상태 확인
args
CorpNum : 팝빌회원 사업자번호
JobID : 작업아이디
UserID : 팝빌회원 아이디
return
수집 상태 정보
raise
PopbillException
"""
if JobID == No... | [
"def",
"getJobState",
"(",
"self",
",",
"CorpNum",
",",
"JobID",
",",
"UserID",
"=",
"None",
")",
":",
"if",
"JobID",
"==",
"None",
"or",
"len",
"(",
"JobID",
")",
"!=",
"18",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"작업아이디(jobID)... | 수집 상태 확인
args
CorpNum : 팝빌회원 사업자번호
JobID : 작업아이디
UserID : 팝빌회원 아이디
return
수집 상태 정보
raise
PopbillException | [
"수집",
"상태",
"확인",
"args",
"CorpNum",
":",
"팝빌회원",
"사업자번호",
"JobID",
":",
"작업아이디",
"UserID",
":",
"팝빌회원",
"아이디",
"return",
"수집",
"상태",
"정보",
"raise",
"PopbillException"
] | python | train |
bitesofcode/projexui | projexui/widgets/xcalendarwidget/xcalendaritem.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendaritem.py#L261-L334 | def rebuildDay( self ):
"""
Rebuilds the current item in day mode.
"""
scene = self.scene()
if ( not scene ):
return
# calculate the base information
start_date = self.dateStart()
end_date = self.dateEnd()
min_date... | [
"def",
"rebuildDay",
"(",
"self",
")",
":",
"scene",
"=",
"self",
".",
"scene",
"(",
")",
"if",
"(",
"not",
"scene",
")",
":",
"return",
"# calculate the base information\r",
"start_date",
"=",
"self",
".",
"dateStart",
"(",
")",
"end_date",
"=",
"self",
... | Rebuilds the current item in day mode. | [
"Rebuilds",
"the",
"current",
"item",
"in",
"day",
"mode",
"."
] | python | train |
ishepard/pydriller | pydriller/git_repository.py | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L302-L318 | def get_commits_modified_file(self, filepath: str) -> List[str]:
"""
Given a filepath, returns all the commits that modified this file
(following renames).
:param str filepath: path to the file
:return: the list of commits' hash
"""
path = str(Path(filepath))
... | [
"def",
"get_commits_modified_file",
"(",
"self",
",",
"filepath",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"path",
"=",
"str",
"(",
"Path",
"(",
"filepath",
")",
")",
"commits",
"=",
"[",
"]",
"try",
":",
"commits",
"=",
"self",
".",
"g... | Given a filepath, returns all the commits that modified this file
(following renames).
:param str filepath: path to the file
:return: the list of commits' hash | [
"Given",
"a",
"filepath",
"returns",
"all",
"the",
"commits",
"that",
"modified",
"this",
"file",
"(",
"following",
"renames",
")",
"."
] | python | train |
MoseleyBioinformaticsLab/ctfile | ctfile/ctfile.py | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/ctfile.py#L1144-L1155 | def default(self, o):
"""Default encoder.
:param o: Atom or Bond instance.
:type o: :class:`~ctfile.ctfile.Atom` or :class:`~ctfile.ctfile.Bond`.
:return: Dictionary that contains information required for atom and bond block of ``Ctab``.
:rtype: :py:class:`collections.OrderedDic... | [
"def",
"default",
"(",
"self",
",",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"Atom",
")",
"or",
"isinstance",
"(",
"o",
",",
"Bond",
")",
":",
"return",
"o",
".",
"_ctab_data",
"else",
":",
"return",
"o",
".",
"__dict__"
] | Default encoder.
:param o: Atom or Bond instance.
:type o: :class:`~ctfile.ctfile.Atom` or :class:`~ctfile.ctfile.Bond`.
:return: Dictionary that contains information required for atom and bond block of ``Ctab``.
:rtype: :py:class:`collections.OrderedDict` | [
"Default",
"encoder",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L635-L654 | def get_executor(self, create=1):
"""Fetch the action executor for this node. Create one if
there isn't already one, and requested to do so."""
try:
executor = self.executor
except AttributeError:
if not create:
raise
try:
... | [
"def",
"get_executor",
"(",
"self",
",",
"create",
"=",
"1",
")",
":",
"try",
":",
"executor",
"=",
"self",
".",
"executor",
"except",
"AttributeError",
":",
"if",
"not",
"create",
":",
"raise",
"try",
":",
"act",
"=",
"self",
".",
"builder",
".",
"a... | Fetch the action executor for this node. Create one if
there isn't already one, and requested to do so. | [
"Fetch",
"the",
"action",
"executor",
"for",
"this",
"node",
".",
"Create",
"one",
"if",
"there",
"isn",
"t",
"already",
"one",
"and",
"requested",
"to",
"do",
"so",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/tools/qi/qi.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L249-L287 | def choi_to_rauli(choi, order=1):
"""
Convert a Choi-matrix to a Pauli-basis superoperator.
Note that this function assumes that the Choi-matrix
is defined in the standard column-stacking convention
and is normalized to have trace 1. For a channel E this
is defined as: choi = (I \\otimes E)(bel... | [
"def",
"choi_to_rauli",
"(",
"choi",
",",
"order",
"=",
"1",
")",
":",
"if",
"order",
"==",
"0",
":",
"order",
"=",
"'weight'",
"elif",
"order",
"==",
"1",
":",
"order",
"=",
"'tensor'",
"# get number of qubits'",
"num_qubits",
"=",
"int",
"(",
"np",
"... | Convert a Choi-matrix to a Pauli-basis superoperator.
Note that this function assumes that the Choi-matrix
is defined in the standard column-stacking convention
and is normalized to have trace 1. For a channel E this
is defined as: choi = (I \\otimes E)(bell_state).
The resulting 'rauli' R acts on... | [
"Convert",
"a",
"Choi",
"-",
"matrix",
"to",
"a",
"Pauli",
"-",
"basis",
"superoperator",
"."
] | python | test |
spotify/pyschema | pyschema/core.py | https://github.com/spotify/pyschema/blob/7e6c3934150bcb040c628d74ace6caf5fcf867df/pyschema/core.py#L512-L522 | def from_json_compatible(schema, dct):
"Load from json-encodable"
kwargs = {}
for key in dct:
field_type = schema._fields.get(key)
if field_type is None:
raise ParseError("Unexpected field encountered in line for record %s: %s" % (schema.__name__, key))
kwargs[key] = fie... | [
"def",
"from_json_compatible",
"(",
"schema",
",",
"dct",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"key",
"in",
"dct",
":",
"field_type",
"=",
"schema",
".",
"_fields",
".",
"get",
"(",
"key",
")",
"if",
"field_type",
"is",
"None",
":",
"raise",
"Pa... | Load from json-encodable | [
"Load",
"from",
"json",
"-",
"encodable"
] | python | test |
Jaymon/endpoints | endpoints/utils.py | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/utils.py#L211-L244 | def _sort(self, a, b):
'''
sort the headers according to rfc 2616 so when __iter__ is called, the accept media types are
in order from most preferred to least preferred
'''
ret = 0
# first we check q, higher values win:
if a[1] != b[1]:
ret = cmp(a[1]... | [
"def",
"_sort",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"ret",
"=",
"0",
"# first we check q, higher values win:",
"if",
"a",
"[",
"1",
"]",
"!=",
"b",
"[",
"1",
"]",
":",
"ret",
"=",
"cmp",
"(",
"a",
"[",
"1",
"]",
",",
"b",
"[",
"1",
"]"... | sort the headers according to rfc 2616 so when __iter__ is called, the accept media types are
in order from most preferred to least preferred | [
"sort",
"the",
"headers",
"according",
"to",
"rfc",
"2616",
"so",
"when",
"__iter__",
"is",
"called",
"the",
"accept",
"media",
"types",
"are",
"in",
"order",
"from",
"most",
"preferred",
"to",
"least",
"preferred"
] | python | train |
Microsoft/nni | tools/nni_cmd/launcher.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L142-L155 | def set_trial_config(experiment_config, port, config_file_name):
'''set trial configuration'''
request_data = dict()
request_data['trial_config'] = experiment_config['trial']
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
if check_response(response):
... | [
"def",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"request_data",
"=",
"dict",
"(",
")",
"request_data",
"[",
"'trial_config'",
"]",
"=",
"experiment_config",
"[",
"'trial'",
"]",
"response",
"=",
"rest_put",
"(... | set trial configuration | [
"set",
"trial",
"configuration"
] | python | train |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/datacite.py | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/datacite.py#L120-L142 | def serialize_oaipmh(self, pid, record):
"""Serialize a single record for OAI-PMH."""
root = etree.Element(
'oai_datacite',
nsmap={
None: 'http://schema.datacite.org/oai/oai-1.0/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
... | [
"def",
"serialize_oaipmh",
"(",
"self",
",",
"pid",
",",
"record",
")",
":",
"root",
"=",
"etree",
".",
"Element",
"(",
"'oai_datacite'",
",",
"nsmap",
"=",
"{",
"None",
":",
"'http://schema.datacite.org/oai/oai-1.0/'",
",",
"'xsi'",
":",
"'http://www.w3.org/200... | Serialize a single record for OAI-PMH. | [
"Serialize",
"a",
"single",
"record",
"for",
"OAI",
"-",
"PMH",
"."
] | python | train |
ecell/ecell4 | ecell4/util/viz.py | https://github.com/ecell/ecell4/blob/a4a1229661c39b2059adbbacae9090e5ba664e01/ecell4/util/viz.py#L802-L825 | def generate_html(keywords, tmpl_path, package_name='ecell4.util'):
"""
Generate static html file from JSON model and its own id.
Parameters
----------
model : dict
JSON model from which ecell4.viz generates a plot.
model_id : string
Unique id for the plot.
Returns
----... | [
"def",
"generate_html",
"(",
"keywords",
",",
"tmpl_path",
",",
"package_name",
"=",
"'ecell4.util'",
")",
":",
"from",
"jinja2",
"import",
"Template",
"import",
"pkgutil",
"template",
"=",
"Template",
"(",
"pkgutil",
".",
"get_data",
"(",
"package_name",
",",
... | Generate static html file from JSON model and its own id.
Parameters
----------
model : dict
JSON model from which ecell4.viz generates a plot.
model_id : string
Unique id for the plot.
Returns
-------
html :
A HTML object | [
"Generate",
"static",
"html",
"file",
"from",
"JSON",
"model",
"and",
"its",
"own",
"id",
"."
] | python | train |
heronotears/lazyxml | lazyxml/parser.py | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L160-L169 | def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
... | [
"def",
"get_node",
"(",
"self",
",",
"element",
")",
":",
"ns",
",",
"tag",
"=",
"self",
".",
"split_namespace",
"(",
"element",
".",
"tag",
")",
"return",
"{",
"'tag'",
":",
"tag",
",",
"'value'",
":",
"(",
"element",
".",
"text",
"or",
"''",
")",... | r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict | [
"r",
"Get",
"node",
"info",
"."
] | python | train |
pypa/setuptools | setuptools/msvc.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/msvc.py#L494-L522 | def find_available_vc_vers(self):
"""
Find all available Microsoft Visual C++ versions.
"""
ms = self.ri.microsoft
vckeys = (self.ri.vc, self.ri.vc_for_python, self.ri.vs)
vc_vers = []
for hkey in self.ri.HKEYS:
for key in vckeys:
try:
... | [
"def",
"find_available_vc_vers",
"(",
"self",
")",
":",
"ms",
"=",
"self",
".",
"ri",
".",
"microsoft",
"vckeys",
"=",
"(",
"self",
".",
"ri",
".",
"vc",
",",
"self",
".",
"ri",
".",
"vc_for_python",
",",
"self",
".",
"ri",
".",
"vs",
")",
"vc_vers... | Find all available Microsoft Visual C++ versions. | [
"Find",
"all",
"available",
"Microsoft",
"Visual",
"C",
"++",
"versions",
"."
] | python | train |
wdecoster/nanoget | nanoget/nanoget.py | https://github.com/wdecoster/nanoget/blob/fb7306220e261849b96785fab02dd2f35a0e3b60/nanoget/nanoget.py#L85-L97 | def combine_dfs(dfs, names, method):
"""Combine dataframes.
Combination is either done simple by just concatenating the DataFrames
or performs tracking by adding the name of the dataset as a column."""
if method == "track":
res = list()
for df, identifier in zip(dfs, names):
... | [
"def",
"combine_dfs",
"(",
"dfs",
",",
"names",
",",
"method",
")",
":",
"if",
"method",
"==",
"\"track\"",
":",
"res",
"=",
"list",
"(",
")",
"for",
"df",
",",
"identifier",
"in",
"zip",
"(",
"dfs",
",",
"names",
")",
":",
"df",
"[",
"\"dataset\""... | Combine dataframes.
Combination is either done simple by just concatenating the DataFrames
or performs tracking by adding the name of the dataset as a column. | [
"Combine",
"dataframes",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/glow_ops.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L1222-L1245 | def scale_gaussian_prior(name, z, logscale_factor=3.0, trainable=True):
"""Returns N(s^i * z^i, std^i) where s^i and std^i are pre-component.
s^i is a learnable parameter with identity initialization.
std^i is optionally learnable with identity initialization.
Args:
name: variable scope.
z: input_tens... | [
"def",
"scale_gaussian_prior",
"(",
"name",
",",
"z",
",",
"logscale_factor",
"=",
"3.0",
",",
"trainable",
"=",
"True",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"z_shape",
"=",
"... | Returns N(s^i * z^i, std^i) where s^i and std^i are pre-component.
s^i is a learnable parameter with identity initialization.
std^i is optionally learnable with identity initialization.
Args:
name: variable scope.
z: input_tensor
logscale_factor: equivalent to scaling up the learning_rate by a facto... | [
"Returns",
"N",
"(",
"s^i",
"*",
"z^i",
"std^i",
")",
"where",
"s^i",
"and",
"std^i",
"are",
"pre",
"-",
"component",
"."
] | python | train |
mommermi/callhorizons | callhorizons/callhorizons.py | https://github.com/mommermi/callhorizons/blob/fdd7ad9e87cac107c1b7f88e594d118210da3b1a/callhorizons/callhorizons.py#L372-L386 | def set_discreteepochs(self, discreteepochs):
"""Set a list of discrete epochs, epochs have to be given as Julian
Dates
:param discreteepochs: array_like
list or 1D array of floats or strings
:return: None
:example: >>> import callhorizons
>>> ceres ... | [
"def",
"set_discreteepochs",
"(",
"self",
",",
"discreteepochs",
")",
":",
"if",
"not",
"isinstance",
"(",
"discreteepochs",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"discreteepochs",
"=",
"[",
"discreteepochs",
"]",
"self",
".",
"discre... | Set a list of discrete epochs, epochs have to be given as Julian
Dates
:param discreteepochs: array_like
list or 1D array of floats or strings
:return: None
:example: >>> import callhorizons
>>> ceres = callhorizons.query('Ceres')
>>> ceres... | [
"Set",
"a",
"list",
"of",
"discrete",
"epochs",
"epochs",
"have",
"to",
"be",
"given",
"as",
"Julian",
"Dates"
] | python | train |
apache/airflow | airflow/bin/cli.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/bin/cli.py#L763-L868 | def restart_workers(gunicorn_master_proc, num_workers_expected, master_timeout):
"""
Runs forever, monitoring the child processes of @gunicorn_master_proc and
restarting workers occasionally.
Each iteration of the loop traverses one edge of this state transition
diagram, where each state (node) repr... | [
"def",
"restart_workers",
"(",
"gunicorn_master_proc",
",",
"num_workers_expected",
",",
"master_timeout",
")",
":",
"def",
"wait_until_true",
"(",
"fn",
",",
"timeout",
"=",
"0",
")",
":",
"\"\"\"\n Sleeps until fn is true\n \"\"\"",
"t",
"=",
"time",
"... | Runs forever, monitoring the child processes of @gunicorn_master_proc and
restarting workers occasionally.
Each iteration of the loop traverses one edge of this state transition
diagram, where each state (node) represents
[ num_ready_workers_running / num_workers_running ]. We expect most time to
be... | [
"Runs",
"forever",
"monitoring",
"the",
"child",
"processes",
"of"
] | python | test |
ciena/afkak | afkak/kafkacodec.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L610-L621 | def create_snappy_message(message_set):
"""
Construct a Snappy-compressed message containing multiple messages
The given messages will be encoded, compressed, and sent as a single atomic
message to Kafka.
:param list message_set: a list of :class:`Message` instances
"""
encoded_message_set... | [
"def",
"create_snappy_message",
"(",
"message_set",
")",
":",
"encoded_message_set",
"=",
"KafkaCodec",
".",
"_encode_message_set",
"(",
"message_set",
")",
"snapped",
"=",
"snappy_encode",
"(",
"encoded_message_set",
")",
"return",
"Message",
"(",
"0",
",",
"CODEC_... | Construct a Snappy-compressed message containing multiple messages
The given messages will be encoded, compressed, and sent as a single atomic
message to Kafka.
:param list message_set: a list of :class:`Message` instances | [
"Construct",
"a",
"Snappy",
"-",
"compressed",
"message",
"containing",
"multiple",
"messages"
] | python | train |
pazz/alot | alot/buffers/thread.py | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/buffers/thread.py#L267-L278 | def focus_property(self, prop, direction):
"""does a walk in the given direction and focuses the
first message tree that matches the given property"""
newpos = self.get_selected_mid()
newpos = direction(newpos)
while newpos is not None:
MT = self._tree[newpos]
... | [
"def",
"focus_property",
"(",
"self",
",",
"prop",
",",
"direction",
")",
":",
"newpos",
"=",
"self",
".",
"get_selected_mid",
"(",
")",
"newpos",
"=",
"direction",
"(",
"newpos",
")",
"while",
"newpos",
"is",
"not",
"None",
":",
"MT",
"=",
"self",
"."... | does a walk in the given direction and focuses the
first message tree that matches the given property | [
"does",
"a",
"walk",
"in",
"the",
"given",
"direction",
"and",
"focuses",
"the",
"first",
"message",
"tree",
"that",
"matches",
"the",
"given",
"property"
] | python | train |
westonplatter/fast_arrow | fast_arrow/resources/option.py | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option.py#L44-L62 | def fetch_list(cls, client, ids):
"""
fetch instruments by ids
"""
results = []
request_url = "https://api.robinhood.com/options/instruments/"
for _ids in chunked_list(ids, 50):
params = {"ids": ",".join(_ids)}
data = client.get(request_url, para... | [
"def",
"fetch_list",
"(",
"cls",
",",
"client",
",",
"ids",
")",
":",
"results",
"=",
"[",
"]",
"request_url",
"=",
"\"https://api.robinhood.com/options/instruments/\"",
"for",
"_ids",
"in",
"chunked_list",
"(",
"ids",
",",
"50",
")",
":",
"params",
"=",
"{"... | fetch instruments by ids | [
"fetch",
"instruments",
"by",
"ids"
] | python | train |
saltstack/salt | salt/modules/lxc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2706-L2733 | def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set... | [
"def",
"set_parameter",
"(",
"name",
",",
"parameter",
",",
"value",
",",
"path",
"=",
"None",
")",
":",
"if",
"not",
"exists",
"(",
"name",
",",
"path",
"=",
"path",
")",
":",
"return",
"None",
"cmd",
"=",
"'lxc-cgroup'",
"if",
"path",
":",
"cmd",
... | Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value | [
"Set",
"the",
"value",
"of",
"a",
"cgroup",
"parameter",
"for",
"a",
"container",
"."
] | python | train |
dcos/shakedown | shakedown/dcos/__init__.py | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/__init__.py#L114-L130 | def authenticate(username, password):
"""Authenticate with a DC/OS cluster and return an ACS token.
return: ACS token
"""
url = _gen_url('acs/api/v1/auth/login')
creds = {
'uid': username,
'password': password
}
response = dcos.http.request('post', url, json=creds)
if ... | [
"def",
"authenticate",
"(",
"username",
",",
"password",
")",
":",
"url",
"=",
"_gen_url",
"(",
"'acs/api/v1/auth/login'",
")",
"creds",
"=",
"{",
"'uid'",
":",
"username",
",",
"'password'",
":",
"password",
"}",
"response",
"=",
"dcos",
".",
"http",
".",... | Authenticate with a DC/OS cluster and return an ACS token.
return: ACS token | [
"Authenticate",
"with",
"a",
"DC",
"/",
"OS",
"cluster",
"and",
"return",
"an",
"ACS",
"token",
".",
"return",
":",
"ACS",
"token"
] | python | train |
opendatateam/udata | udata/frontend/markdown.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/markdown.py#L40-L59 | def nofollow_callback(attrs, new=False):
"""
Turn relative links into external ones and avoid `nofollow` for us,
otherwise add `nofollow`.
That callback is not splitted in order to parse the URL only once.
"""
parsed_url = urlparse(attrs[(None, 'href')])
if parsed_url.netloc in ('', current... | [
"def",
"nofollow_callback",
"(",
"attrs",
",",
"new",
"=",
"False",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"attrs",
"[",
"(",
"None",
",",
"'href'",
")",
"]",
")",
"if",
"parsed_url",
".",
"netloc",
"in",
"(",
"''",
",",
"current_app",
".",
"c... | Turn relative links into external ones and avoid `nofollow` for us,
otherwise add `nofollow`.
That callback is not splitted in order to parse the URL only once. | [
"Turn",
"relative",
"links",
"into",
"external",
"ones",
"and",
"avoid",
"nofollow",
"for",
"us"
] | python | train |
pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/ef09f28b858b7ffcd2627ce6a4dc618183a6bc8a/ffn/core.py#L1223-L1235 | def calc_cagr(prices):
"""
Calculates the `CAGR (compound annual growth rate) <https://www.investopedia.com/terms/c/cagr.asp>`_ for a given price series.
Args:
* prices (pandas.Series): A Series of prices.
Returns:
* float -- cagr.
"""
start = prices.index[0]
end = prices.i... | [
"def",
"calc_cagr",
"(",
"prices",
")",
":",
"start",
"=",
"prices",
".",
"index",
"[",
"0",
"]",
"end",
"=",
"prices",
".",
"index",
"[",
"-",
"1",
"]",
"return",
"(",
"prices",
".",
"iloc",
"[",
"-",
"1",
"]",
"/",
"prices",
".",
"iloc",
"[",... | Calculates the `CAGR (compound annual growth rate) <https://www.investopedia.com/terms/c/cagr.asp>`_ for a given price series.
Args:
* prices (pandas.Series): A Series of prices.
Returns:
* float -- cagr. | [
"Calculates",
"the",
"CAGR",
"(",
"compound",
"annual",
"growth",
"rate",
")",
"<https",
":",
"//",
"www",
".",
"investopedia",
".",
"com",
"/",
"terms",
"/",
"c",
"/",
"cagr",
".",
"asp",
">",
"_",
"for",
"a",
"given",
"price",
"series",
"."
] | python | train |
PGower/PyCanvas | pycanvas/apis/discussion_topics.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/discussion_topics.py#L19-L72 | def list_discussion_topics_courses(self, course_id, exclude_context_module_locked_topics=None, include=None, only_announcements=None, order_by=None, scope=None, search_term=None):
"""
List discussion topics.
Returns the paginated list of discussion topics for this course or group.
... | [
"def",
"list_discussion_topics_courses",
"(",
"self",
",",
"course_id",
",",
"exclude_context_module_locked_topics",
"=",
"None",
",",
"include",
"=",
"None",
",",
"only_announcements",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"... | List discussion topics.
Returns the paginated list of discussion topics for this course or group. | [
"List",
"discussion",
"topics",
".",
"Returns",
"the",
"paginated",
"list",
"of",
"discussion",
"topics",
"for",
"this",
"course",
"or",
"group",
"."
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/dtype.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dtype.py#L535-L541 | def evrs(self):
"""Getter EVRs dictionary"""
if self._evrs is None:
import ait.core.evr as evr
self._evrs = evr.getDefaultDict()
return self._evrs | [
"def",
"evrs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_evrs",
"is",
"None",
":",
"import",
"ait",
".",
"core",
".",
"evr",
"as",
"evr",
"self",
".",
"_evrs",
"=",
"evr",
".",
"getDefaultDict",
"(",
")",
"return",
"self",
".",
"_evrs"
] | Getter EVRs dictionary | [
"Getter",
"EVRs",
"dictionary"
] | python | train |
boto/s3transfer | s3transfer/download.py | https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/download.py#L488-L547 | def _main(self, client, bucket, key, fileobj, extra_args, callbacks,
max_attempts, download_output_manager, io_chunksize,
start_index=0, bandwidth_limiter=None):
"""Downloads an object and places content into io queue
:param client: The client to use when calling GetObject
... | [
"def",
"_main",
"(",
"self",
",",
"client",
",",
"bucket",
",",
"key",
",",
"fileobj",
",",
"extra_args",
",",
"callbacks",
",",
"max_attempts",
",",
"download_output_manager",
",",
"io_chunksize",
",",
"start_index",
"=",
"0",
",",
"bandwidth_limiter",
"=",
... | Downloads an object and places content into io queue
:param client: The client to use when calling GetObject
:param bucket: The bucket to download from
:param key: The key to download from
:param fileobj: The file handle to write content to
:param exta_args: Any extra arguements... | [
"Downloads",
"an",
"object",
"and",
"places",
"content",
"into",
"io",
"queue"
] | python | test |
econ-ark/HARK | HARK/core.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/core.py#L973-L1008 | def solve(self):
'''
"Solves" the market by finding a "dynamic rule" that governs the aggregate
market state such that when agents believe in these dynamics, their actions
collectively generate the same dynamic rule.
Parameters
----------
None
Returns
... | [
"def",
"solve",
"(",
"self",
")",
":",
"go",
"=",
"True",
"max_loops",
"=",
"self",
".",
"max_loops",
"# Failsafe against infinite solution loop",
"completed_loops",
"=",
"0",
"old_dynamics",
"=",
"None",
"while",
"go",
":",
"# Loop until the dynamic process converges... | "Solves" the market by finding a "dynamic rule" that governs the aggregate
market state such that when agents believe in these dynamics, their actions
collectively generate the same dynamic rule.
Parameters
----------
None
Returns
-------
None | [
"Solves",
"the",
"market",
"by",
"finding",
"a",
"dynamic",
"rule",
"that",
"governs",
"the",
"aggregate",
"market",
"state",
"such",
"that",
"when",
"agents",
"believe",
"in",
"these",
"dynamics",
"their",
"actions",
"collectively",
"generate",
"the",
"same",
... | python | train |
amadev/doan | doan/dataset.py | https://github.com/amadev/doan/blob/5adfa983ac547007a688fe7517291a432919aa3e/doan/dataset.py#L150-L157 | def r_num(obj):
"""Read list of numbers."""
if isinstance(obj, (list, tuple)):
it = iter
else:
it = LinesIterator
dataset = Dataset([Dataset.FLOAT])
return dataset.load(it(obj)) | [
"def",
"r_num",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"it",
"=",
"iter",
"else",
":",
"it",
"=",
"LinesIterator",
"dataset",
"=",
"Dataset",
"(",
"[",
"Dataset",
".",
"FLOAT",
"]",
")... | Read list of numbers. | [
"Read",
"list",
"of",
"numbers",
"."
] | python | train |
openthread/openthread | tools/harness-thci/OpenThread_WpanCtl.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread_WpanCtl.py#L933-L956 | def getMAC(self, bType=MacType.RandomMac):
"""get one specific type of MAC address
currently OpenThreadWpan only supports Random MAC address
Args:
bType: indicate which kind of MAC address is required
Returns:
specific type of MAC address
"""
... | [
"def",
"getMAC",
"(",
"self",
",",
"bType",
"=",
"MacType",
".",
"RandomMac",
")",
":",
"print",
"'%s call getMAC'",
"%",
"self",
".",
"port",
"# if power down happens, return extended address assigned previously",
"if",
"self",
".",
"isPowerDown",
":",
"macAddr64",
... | get one specific type of MAC address
currently OpenThreadWpan only supports Random MAC address
Args:
bType: indicate which kind of MAC address is required
Returns:
specific type of MAC address | [
"get",
"one",
"specific",
"type",
"of",
"MAC",
"address",
"currently",
"OpenThreadWpan",
"only",
"supports",
"Random",
"MAC",
"address"
] | python | train |
dask/dask-ml | dask_ml/model_selection/_search.py | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_search.py#L921-L956 | def compute_n_splits(cv, X, y=None, groups=None):
"""Return the number of splits.
Parameters
----------
cv : BaseCrossValidator
X, y, groups : array_like, dask object, or None
Returns
-------
n_splits : int
"""
if not any(is_dask_collection(i) for i in (X, y, groups)):
... | [
"def",
"compute_n_splits",
"(",
"cv",
",",
"X",
",",
"y",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"is_dask_collection",
"(",
"i",
")",
"for",
"i",
"in",
"(",
"X",
",",
"y",
",",
"groups",
")",
")",
":",
"retu... | Return the number of splits.
Parameters
----------
cv : BaseCrossValidator
X, y, groups : array_like, dask object, or None
Returns
-------
n_splits : int | [
"Return",
"the",
"number",
"of",
"splits",
"."
] | python | train |
chrisjrn/registrasion | registrasion/controllers/invoice.py | https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/controllers/invoice.py#L361-L378 | def update_validity(self):
''' Voids this invoice if the attached cart is no longer valid because
the cart revision has changed, or the reservations have expired. '''
is_valid = self._invoice_matches_cart()
cart = self.invoice.cart
if self.invoice.is_unpaid and is_valid and cart... | [
"def",
"update_validity",
"(",
"self",
")",
":",
"is_valid",
"=",
"self",
".",
"_invoice_matches_cart",
"(",
")",
"cart",
"=",
"self",
".",
"invoice",
".",
"cart",
"if",
"self",
".",
"invoice",
".",
"is_unpaid",
"and",
"is_valid",
"and",
"cart",
":",
"tr... | Voids this invoice if the attached cart is no longer valid because
the cart revision has changed, or the reservations have expired. | [
"Voids",
"this",
"invoice",
"if",
"the",
"attached",
"cart",
"is",
"no",
"longer",
"valid",
"because",
"the",
"cart",
"revision",
"has",
"changed",
"or",
"the",
"reservations",
"have",
"expired",
"."
] | python | test |
eandersson/amqpstorm | amqpstorm/message.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L373-L390 | def _try_decode_dict(self, content):
"""Decode content of a dictionary.
:param dict content:
:return:
"""
result = dict()
for key, value in content.items():
key = try_utf8_decode(key)
if isinstance(value, dict):
result[key] = self.... | [
"def",
"_try_decode_dict",
"(",
"self",
",",
"content",
")",
":",
"result",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"content",
".",
"items",
"(",
")",
":",
"key",
"=",
"try_utf8_decode",
"(",
"key",
")",
"if",
"isinstance",
"(",
"val... | Decode content of a dictionary.
:param dict content:
:return: | [
"Decode",
"content",
"of",
"a",
"dictionary",
"."
] | python | train |
openvax/mhctools | mhctools/common.py | https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/common.py#L24-L35 | def seq_to_str(obj, sep=","):
"""
Given a sequence convert it to a comma separated string.
If, however, the argument is a single object, return its string
representation.
"""
if isinstance(obj, string_classes):
return obj
elif isinstance(obj, (list, tuple)):
return sep.join([... | [
"def",
"seq_to_str",
"(",
"obj",
",",
"sep",
"=",
"\",\"",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"string_classes",
")",
":",
"return",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"sep",
... | Given a sequence convert it to a comma separated string.
If, however, the argument is a single object, return its string
representation. | [
"Given",
"a",
"sequence",
"convert",
"it",
"to",
"a",
"comma",
"separated",
"string",
".",
"If",
"however",
"the",
"argument",
"is",
"a",
"single",
"object",
"return",
"its",
"string",
"representation",
"."
] | python | valid |
LonamiWebs/Telethon | telethon/tl/custom/dialog.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/dialog.py#L99-L112 | async def delete(self):
"""
Deletes the dialog from your dialog list. If you own the
channel this won't destroy it, only delete it from the list.
"""
if self.is_channel:
await self._client(functions.channels.LeaveChannelRequest(
self.input_entity))
... | [
"async",
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_channel",
":",
"await",
"self",
".",
"_client",
"(",
"functions",
".",
"channels",
".",
"LeaveChannelRequest",
"(",
"self",
".",
"input_entity",
")",
")",
"else",
":",
"if",
"self",
... | Deletes the dialog from your dialog list. If you own the
channel this won't destroy it, only delete it from the list. | [
"Deletes",
"the",
"dialog",
"from",
"your",
"dialog",
"list",
".",
"If",
"you",
"own",
"the",
"channel",
"this",
"won",
"t",
"destroy",
"it",
"only",
"delete",
"it",
"from",
"the",
"list",
"."
] | python | train |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L86-L108 | def ramp_function(data_type, attr, fname, xinstfeature, xNNifeature):
""" Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds
that indicate the max difference before a score of 1 is given, as well a min difference befo... | [
"def",
"ramp_function",
"(",
"data_type",
",",
"attr",
",",
"fname",
",",
"xinstfeature",
",",
"xNNifeature",
")",
":",
"diff",
"=",
"0",
"mmdiff",
"=",
"attr",
"[",
"fname",
"]",
"[",
"3",
"]",
"# Max/Min range of values for target feature\r",
"rawfd",
"=",
... | Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds
that indicate the max difference before a score of 1 is given, as well a min difference before a score of 0 is given, and any in the middle get a
score that is the no... | [
"Our",
"own",
"user",
"simplified",
"variation",
"of",
"the",
"ramp",
"function",
"suggested",
"by",
"Hong",
"1994",
"1997",
".",
"Hong",
"s",
"method",
"requires",
"the",
"user",
"to",
"specifiy",
"two",
"thresholds",
"that",
"indicate",
"the",
"max",
"diff... | python | train |
googlecolab/jupyter_http_over_ws | jupyter_http_over_ws/handlers.py | https://github.com/googlecolab/jupyter_http_over_ws/blob/21fe278cae6fca4e6c92f92d6d786fae8fdea9b1/jupyter_http_over_ws/handlers.py#L76-L101 | def _validate_min_version(min_version):
"""Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the err... | [
"def",
"_validate_min_version",
"(",
"min_version",
")",
":",
"if",
"min_version",
"is",
"not",
"None",
":",
"try",
":",
"parsed_min_version",
"=",
"version",
".",
"StrictVersion",
"(",
"min_version",
")",
"except",
"ValueError",
":",
"return",
"ExtensionVersionRe... | Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the error_reason field will be non-empty. | [
"Validates",
"the",
"extension",
"version",
"matches",
"the",
"requested",
"version",
"."
] | python | train |
kalbhor/MusicTools | musictools/musictools.py | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L166-L173 | def revert_metadata(files):
"""
Removes all tags from a mp3 file
"""
for file_path in files:
tags = EasyMP3(file_path)
tags.delete()
tags.save() | [
"def",
"revert_metadata",
"(",
"files",
")",
":",
"for",
"file_path",
"in",
"files",
":",
"tags",
"=",
"EasyMP3",
"(",
"file_path",
")",
"tags",
".",
"delete",
"(",
")",
"tags",
".",
"save",
"(",
")"
] | Removes all tags from a mp3 file | [
"Removes",
"all",
"tags",
"from",
"a",
"mp3",
"file"
] | python | train |
google/prettytensor | prettytensor/pretty_tensor_methods.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_methods.py#L37-L111 | def _infer_unknown_dims(old_shape, shape_spec):
"""Attempts to replace DIM_REST (if present) with a value.
Because of `pt.DIM_SAME`, this has more information to compute a shape value
than the default reshape's shape function.
Args:
old_shape: The current shape of the Tensor as a list.
shape_spec: A s... | [
"def",
"_infer_unknown_dims",
"(",
"old_shape",
",",
"shape_spec",
")",
":",
"# To compute the dimension of an unknown, we need to track which of the values",
"# from old_shape are not copied for the numerator and any values specified as",
"# integers for the denominator.",
"#",
"# After the... | Attempts to replace DIM_REST (if present) with a value.
Because of `pt.DIM_SAME`, this has more information to compute a shape value
than the default reshape's shape function.
Args:
old_shape: The current shape of the Tensor as a list.
shape_spec: A shape spec, see `pt.reshape`.
Returns:
A list de... | [
"Attempts",
"to",
"replace",
"DIM_REST",
"(",
"if",
"present",
")",
"with",
"a",
"value",
"."
] | python | train |
royi1000/py-libhdate | hdate/date.py | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/date.py#L137-L142 | def hebrew_date(self):
"""Return the hebrew date string."""
return u"{} {} {}".format(
hebrew_number(self.hdate.day, hebrew=self.hebrew), # Day
htables.MONTHS[self.hdate.month - 1][self.hebrew], # Month
hebrew_number(self.hdate.year, hebrew=self.hebrew)) | [
"def",
"hebrew_date",
"(",
"self",
")",
":",
"return",
"u\"{} {} {}\"",
".",
"format",
"(",
"hebrew_number",
"(",
"self",
".",
"hdate",
".",
"day",
",",
"hebrew",
"=",
"self",
".",
"hebrew",
")",
",",
"# Day",
"htables",
".",
"MONTHS",
"[",
"self",
"."... | Return the hebrew date string. | [
"Return",
"the",
"hebrew",
"date",
"string",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/editor/panels/linenumber.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/linenumber.py#L114-L134 | def mouseMoveEvent(self, event):
"""Override Qt method.
Show code analisis, if left button pressed select lines.
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
block = self.editor.document().findBlockByNumber(line_number-1)
data = block.userData()
... | [
"def",
"mouseMoveEvent",
"(",
"self",
",",
"event",
")",
":",
"line_number",
"=",
"self",
".",
"editor",
".",
"get_linenumber_from_mouse_event",
"(",
"event",
")",
"block",
"=",
"self",
".",
"editor",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",... | Override Qt method.
Show code analisis, if left button pressed select lines. | [
"Override",
"Qt",
"method",
"."
] | python | train |
PrefPy/prefpy | prefpy/gmmra.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmmra.py#L66-L78 | def _adj(self, k):
"""
Description:
Adjacent breaking
Paramters:
k: not used
"""
G = np.zeros((self.m, self.m))
for i in range(self.m):
for j in range(self.m):
if i == j+1 or j == i+1:
G[i]... | [
"def",
"_adj",
"(",
"self",
",",
"k",
")",
":",
"G",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"m",
",",
"self",
".",
"m",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"m",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",... | Description:
Adjacent breaking
Paramters:
k: not used | [
"Description",
":",
"Adjacent",
"breaking",
"Paramters",
":",
"k",
":",
"not",
"used"
] | python | train |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1401-L1497 | def autoresponds(self, matcher, *args, **kwargs):
"""Send a canned reply to all matching client requests.
``matcher`` is a `Matcher` or a command name, or an instance of
`OpInsert`, `OpQuery`, etc.
>>> s = MockupDB()
>>> port = s.run()
>>>
>>> from pymon... | [
"def",
"autoresponds",
"(",
"self",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_insert_responder",
"(",
"\"top\"",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Send a canned reply to all matching client requests.
``matcher`` is a `Matcher` or a command name, or an instance of
`OpInsert`, `OpQuery`, etc.
>>> s = MockupDB()
>>> port = s.run()
>>>
>>> from pymongo import MongoClient
>>> client = MongoClient(s.uri)... | [
"Send",
"a",
"canned",
"reply",
"to",
"all",
"matching",
"client",
"requests",
".",
"matcher",
"is",
"a",
"Matcher",
"or",
"a",
"command",
"name",
"or",
"an",
"instance",
"of",
"OpInsert",
"OpQuery",
"etc",
"."
] | python | train |
Microsoft/botbuilder-python | libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py | https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py#L36-L47 | def add_step(self, step):
"""
Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`.
"""
if not step:
raise TypeError('WaterfallDialog.add_step(): step cannot be None.')
self.... | [
"def",
"add_step",
"(",
"self",
",",
"step",
")",
":",
"if",
"not",
"step",
":",
"raise",
"TypeError",
"(",
"'WaterfallDialog.add_step(): step cannot be None.'",
")",
"self",
".",
"_steps",
".",
"append",
"(",
"step",
")",
"return",
"self"
] | Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`. | [
"Adds",
"a",
"new",
"step",
"to",
"the",
"waterfall",
".",
":",
"param",
"step",
":",
"Step",
"to",
"add",
":",
"return",
":",
"Waterfall",
"dialog",
"for",
"fluent",
"calls",
"to",
"add_step",
"()",
"."
] | python | test |
oscarbranson/latools | latools/latools.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/latools.py#L3822-L3918 | def export_traces(self, outdir=None, focus_stage=None, analytes=None,
samples=None, subset='All_Analyses', filt=False, zip_archive=False):
"""
Function to export raw data.
Parameters
----------
outdir : str
directory to save toe traces. Defaults... | [
"def",
"export_traces",
"(",
"self",
",",
"outdir",
"=",
"None",
",",
"focus_stage",
"=",
"None",
",",
"analytes",
"=",
"None",
",",
"samples",
"=",
"None",
",",
"subset",
"=",
"'All_Analyses'",
",",
"filt",
"=",
"False",
",",
"zip_archive",
"=",
"False"... | Function to export raw data.
Parameters
----------
outdir : str
directory to save toe traces. Defaults to 'main-dir-name_export'.
focus_stage : str
The name of the analysis stage to export.
* 'rawdata': raw data, loaded from csv file.
* '... | [
"Function",
"to",
"export",
"raw",
"data",
"."
] | python | test |
python-diamond/Diamond | src/collectors/openstackswiftrecon/openstackswiftrecon.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/openstackswiftrecon/openstackswiftrecon.py#L37-L49 | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(OpenstackSwiftReconCollector, self).get_default_config()
config.update({
'path': 'swiftrecon',
'recon_account_cache': '/var/cache/swift/account.recon',
... | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"OpenstackSwiftReconCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'path'",
":",
"'swiftrecon'",
",",
"'recon_account_cache'"... | Returns the default collector settings | [
"Returns",
"the",
"default",
"collector",
"settings"
] | python | train |
calvinku96/labreporthelper | labreporthelper/bestfit/bestfit.py | https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L42-L55 | def set_args(self, **kwargs):
"""
Set more arguments to self.args
args:
**kwargs:
key and value represents dictionary key and value
"""
try:
kwargs_items = kwargs.iteritems()
except AttributeError:
kwargs_items = kwargs... | [
"def",
"set_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"kwargs_items",
"=",
"kwargs",
".",
"iteritems",
"(",
")",
"except",
"AttributeError",
":",
"kwargs_items",
"=",
"kwargs",
".",
"items",
"(",
")",
"for",
"key",
",",
"val",
... | Set more arguments to self.args
args:
**kwargs:
key and value represents dictionary key and value | [
"Set",
"more",
"arguments",
"to",
"self",
".",
"args"
] | python | train |
dddomodossola/remi | editor/editor_widgets.py | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor_widgets.py#L263-L266 | def show(self, baseAppInstance):
"""Allows to show the widget as root window"""
self.from_dict_to_fields(self.configDict)
super(ProjectConfigurationDialog, self).show(baseAppInstance) | [
"def",
"show",
"(",
"self",
",",
"baseAppInstance",
")",
":",
"self",
".",
"from_dict_to_fields",
"(",
"self",
".",
"configDict",
")",
"super",
"(",
"ProjectConfigurationDialog",
",",
"self",
")",
".",
"show",
"(",
"baseAppInstance",
")"
] | Allows to show the widget as root window | [
"Allows",
"to",
"show",
"the",
"widget",
"as",
"root",
"window"
] | python | train |
numenta/nupic | src/nupic/frameworks/opf/helpers.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/helpers.py#L37-L48 | def loadExperiment(path):
"""Loads the experiment description file from the path.
:param path: (string) The path to a directory containing a description.py file
or the file itself.
:returns: (config, control)
"""
if not os.path.isdir(path):
path = os.path.dirname(path)
descriptionPyModule = lo... | [
"def",
"loadExperiment",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"descriptionPyModule",
"=",
"loadExperimentDescriptionScriptFromDir",
"("... | Loads the experiment description file from the path.
:param path: (string) The path to a directory containing a description.py file
or the file itself.
:returns: (config, control) | [
"Loads",
"the",
"experiment",
"description",
"file",
"from",
"the",
"path",
"."
] | python | valid |
chrisrink10/basilisp | src/basilisp/lang/runtime.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L788-L793 | def concat(*seqs) -> ISeq:
"""Concatenate the sequences given by seqs into a single ISeq."""
allseqs = lseq.sequence(itertools.chain(*filter(None, map(to_seq, seqs))))
if allseqs is None:
return lseq.EMPTY
return allseqs | [
"def",
"concat",
"(",
"*",
"seqs",
")",
"->",
"ISeq",
":",
"allseqs",
"=",
"lseq",
".",
"sequence",
"(",
"itertools",
".",
"chain",
"(",
"*",
"filter",
"(",
"None",
",",
"map",
"(",
"to_seq",
",",
"seqs",
")",
")",
")",
")",
"if",
"allseqs",
"is"... | Concatenate the sequences given by seqs into a single ISeq. | [
"Concatenate",
"the",
"sequences",
"given",
"by",
"seqs",
"into",
"a",
"single",
"ISeq",
"."
] | python | test |
bdcht/grandalf | grandalf/layouts.py | https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L660-L682 | def _coord_vertical_alignment(self):
"""performs vertical alignment according to current dirvh internal state.
"""
dirh,dirv = self.dirh,self.dirv
g = self.grx
for l in self.layers[::-dirv]:
if not l.prevlayer(): continue
r=None
for vk in l[::d... | [
"def",
"_coord_vertical_alignment",
"(",
"self",
")",
":",
"dirh",
",",
"dirv",
"=",
"self",
".",
"dirh",
",",
"self",
".",
"dirv",
"g",
"=",
"self",
".",
"grx",
"for",
"l",
"in",
"self",
".",
"layers",
"[",
":",
":",
"-",
"dirv",
"]",
":",
"if",... | performs vertical alignment according to current dirvh internal state. | [
"performs",
"vertical",
"alignment",
"according",
"to",
"current",
"dirvh",
"internal",
"state",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/math/linalg.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/linalg.py#L837-L871 | def _sparse_tensor_dense_matmul(sp_a, b, **kwargs):
"""Returns (batched) matmul of a SparseTensor with a Tensor.
Args:
sp_a: `SparseTensor` representing a (batch of) matrices.
b: `Tensor` representing a (batch of) matrices, with the same batch shape of
`sp_a`. The shape must be compatible with the sh... | [
"def",
"_sparse_tensor_dense_matmul",
"(",
"sp_a",
",",
"b",
",",
"*",
"*",
"kwargs",
")",
":",
"batch_shape",
"=",
"_get_shape",
"(",
"sp_a",
")",
"[",
":",
"-",
"2",
"]",
"# Reshape the SparseTensor into a rank 3 SparseTensors, with the",
"# batch shape flattened to... | Returns (batched) matmul of a SparseTensor with a Tensor.
Args:
sp_a: `SparseTensor` representing a (batch of) matrices.
b: `Tensor` representing a (batch of) matrices, with the same batch shape of
`sp_a`. The shape must be compatible with the shape of `sp_a` and kwargs.
**kwargs: Keyword arguments... | [
"Returns",
"(",
"batched",
")",
"matmul",
"of",
"a",
"SparseTensor",
"with",
"a",
"Tensor",
"."
] | python | test |
neuropsychology/NeuroKit.py | neurokit/signal/events.py | https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/neurokit/signal/events.py#L235-L295 | def plot_events_in_signal(signal, events_onsets, color="red", marker=None):
"""
Plot events in signal.
Parameters
----------
signal : array or DataFrame
Signal array (can be a dataframe with many signals).
events_onsets : list or ndarray
Events location.
color : int or list
... | [
"def",
"plot_events_in_signal",
"(",
"signal",
",",
"events_onsets",
",",
"color",
"=",
"\"red\"",
",",
"marker",
"=",
"None",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"signal",
")",
"ax",
"=",
"df",
".",
"plot",
"(",
")",
"def",
"plotOnSignal... | Plot events in signal.
Parameters
----------
signal : array or DataFrame
Signal array (can be a dataframe with many signals).
events_onsets : list or ndarray
Events location.
color : int or list
Marker color.
marker : marker or list of markers (for possible marker values... | [
"Plot",
"events",
"in",
"signal",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.