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 |
|---|---|---|---|---|---|---|---|---|
fabioz/PyDev.Debugger | pydev_ipython/matplotlibtools.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/matplotlibtools.py#L66-L76 | def patch_use(enable_gui_function):
""" Patch matplotlib function 'use' """
matplotlib = sys.modules['matplotlib']
def patched_use(*args, **kwargs):
matplotlib.real_use(*args, **kwargs)
gui, backend = find_gui_and_backend()
enable_gui_function(gui)
matplotlib.real_use = matplot... | [
"def",
"patch_use",
"(",
"enable_gui_function",
")",
":",
"matplotlib",
"=",
"sys",
".",
"modules",
"[",
"'matplotlib'",
"]",
"def",
"patched_use",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"matplotlib",
".",
"real_use",
"(",
"*",
"args",
",",... | Patch matplotlib function 'use' | [
"Patch",
"matplotlib",
"function",
"use"
] | python | train |
OpenKMIP/PyKMIP | kmip/core/objects.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/objects.py#L4604-L4659 | def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3):
"""
Read the data encoding the ProfileInformation structure and decode it
into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting ... | [
"def",
"read",
"(",
"self",
",",
"input_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_3",
")",
":",
"if",
"kmip_version",
"<",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_3",
":",
"raise",
"exceptions",
".",
"VersionNotSupported",
... | Read the data encoding the ProfileInformation structure and decode it
into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (... | [
"Read",
"the",
"data",
"encoding",
"the",
"ProfileInformation",
"structure",
"and",
"decode",
"it",
"into",
"its",
"constituent",
"parts",
"."
] | python | test |
user-cont/conu | conu/utils/__init__.py | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/__init__.py#L335-L386 | def export_docker_container_to_directory(client, container, path):
"""
take selected docker container, create an archive out of it and
unpack it to a selected location
:param client: instance of docker.APIClient
:param container: instance of DockerContainer
:param path: str, path to a directory... | [
"def",
"export_docker_container_to_directory",
"(",
"client",
",",
"container",
",",
"path",
")",
":",
"# we don't do this because of a bug in docker:",
"# https://bugzilla.redhat.com/show_bug.cgi?id=1570828",
"# stream, _ = client.get_archive(container.get_id(), \"/\")",
"check_docker_com... | take selected docker container, create an archive out of it and
unpack it to a selected location
:param client: instance of docker.APIClient
:param container: instance of DockerContainer
:param path: str, path to a directory, doesn't need to exist
:return: None | [
"take",
"selected",
"docker",
"container",
"create",
"an",
"archive",
"out",
"of",
"it",
"and",
"unpack",
"it",
"to",
"a",
"selected",
"location"
] | python | train |
Nixiware/viper | nx/viper/service/mysql.py | https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L228-L246 | def runInteraction(self, interaction, *args, **kwargs):
"""
Interact with the database and return the result.
:param interaction: <function> method with first argument is a <adbapi.Transaction> instance
:param args: additional positional arguments to be passed to interaction
:pa... | [
"def",
"runInteraction",
"(",
"self",
",",
"interaction",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"_connectionPool",
".",
"runInteraction",
"(",
"interaction",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | Interact with the database and return the result.
:param interaction: <function> method with first argument is a <adbapi.Transaction> instance
:param args: additional positional arguments to be passed to interaction
:param kwargs: keyword arguments to be passed to interaction
:return: <... | [
"Interact",
"with",
"the",
"database",
"and",
"return",
"the",
"result",
"."
] | python | train |
phaethon/kamene | kamene/packet.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L1282-L1301 | def fuzz(p, _inplace=0):
"""Transform a layer into a fuzzy layer by replacing some default values by random objects"""
if not _inplace:
p = p.copy()
q = p
while not isinstance(q, NoPayload):
for f in q.fields_desc:
if isinstance(f, PacketListField):
for r in g... | [
"def",
"fuzz",
"(",
"p",
",",
"_inplace",
"=",
"0",
")",
":",
"if",
"not",
"_inplace",
":",
"p",
"=",
"p",
".",
"copy",
"(",
")",
"q",
"=",
"p",
"while",
"not",
"isinstance",
"(",
"q",
",",
"NoPayload",
")",
":",
"for",
"f",
"in",
"q",
".",
... | Transform a layer into a fuzzy layer by replacing some default values by random objects | [
"Transform",
"a",
"layer",
"into",
"a",
"fuzzy",
"layer",
"by",
"replacing",
"some",
"default",
"values",
"by",
"random",
"objects"
] | python | train |
QuantEcon/QuantEcon.py | quantecon/game_theory/random.py | https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/game_theory/random.py#L13-L44 | def random_game(nums_actions, random_state=None):
"""
Return a random NormalFormGame instance where the payoffs are drawn
independently from the uniform distribution on [0, 1).
Parameters
----------
nums_actions : tuple(int)
Tuple of the numbers of actions, one for each player.
ran... | [
"def",
"random_game",
"(",
"nums_actions",
",",
"random_state",
"=",
"None",
")",
":",
"N",
"=",
"len",
"(",
"nums_actions",
")",
"if",
"N",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'nums_actions must be non-empty'",
")",
"random_state",
"=",
"check_random... | Return a random NormalFormGame instance where the payoffs are drawn
independently from the uniform distribution on [0, 1).
Parameters
----------
nums_actions : tuple(int)
Tuple of the numbers of actions, one for each player.
random_state : int or np.random.RandomState, optional
Ran... | [
"Return",
"a",
"random",
"NormalFormGame",
"instance",
"where",
"the",
"payoffs",
"are",
"drawn",
"independently",
"from",
"the",
"uniform",
"distribution",
"on",
"[",
"0",
"1",
")",
"."
] | python | train |
saltstack/salt | salt/modules/boto_elb.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L991-L1012 | def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None):
'''
Add the tags on an ELB
name
name of the ELB
tags
list of tags to remove
CLI Example:
.. code-block:: bash
salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2']... | [
"def",
"delete_tags",
"(",
"name",
",",
"tags",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"exists",
"(",
"name",
",",
"region",
",",
"key",
",",
"keyid",
",",
"pro... | Add the tags on an ELB
name
name of the ELB
tags
list of tags to remove
CLI Example:
.. code-block:: bash
salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] | [
"Add",
"the",
"tags",
"on",
"an",
"ELB"
] | python | train |
Erotemic/utool | utool/util_dict.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1077-L1099 | def get_dict_column(dict_, colx):
r"""
Args:
dict_ (dict_): a dictionary of lists
colx (int):
CommandLine:
python -m utool.util_dict --test-get_dict_column
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
... | [
"def",
"get_dict_column",
"(",
"dict_",
",",
"colx",
")",
":",
"retdict_",
"=",
"{",
"key",
":",
"util_list",
".",
"list_take",
"(",
"val",
",",
"colx",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"dict_",
")",
"}",
"return",
... | r"""
Args:
dict_ (dict_): a dictionary of lists
colx (int):
CommandLine:
python -m utool.util_dict --test-get_dict_column
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': [0, 1, 2], 'b':... | [
"r",
"Args",
":",
"dict_",
"(",
"dict_",
")",
":",
"a",
"dictionary",
"of",
"lists",
"colx",
"(",
"int",
")",
":"
] | python | train |
mikedh/trimesh | docs/build.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/docs/build.py#L17-L32 | def abspath(rel):
"""
Take paths relative to the current file and
convert them to absolute paths.
Parameters
------------
rel : str
Relative path, IE '../stuff'
Returns
-------------
abspath : str
Absolute path, IE '/home/user/stuff'
"""
retu... | [
"def",
"abspath",
"(",
"rel",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"rel",
")",
")"
] | Take paths relative to the current file and
convert them to absolute paths.
Parameters
------------
rel : str
Relative path, IE '../stuff'
Returns
-------------
abspath : str
Absolute path, IE '/home/user/stuff' | [
"Take",
"paths",
"relative",
"to",
"the",
"current",
"file",
"and",
"convert",
"them",
"to",
"absolute",
"paths",
"."
] | python | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L226-L231 | def has_enacted(self, billing_cycle):
"""Has this recurring cost already enacted transactions for given billing cycle?"""
return RecurredCost.objects.filter(
recurring_cost=self,
billing_cycle=billing_cycle,
).exists() | [
"def",
"has_enacted",
"(",
"self",
",",
"billing_cycle",
")",
":",
"return",
"RecurredCost",
".",
"objects",
".",
"filter",
"(",
"recurring_cost",
"=",
"self",
",",
"billing_cycle",
"=",
"billing_cycle",
",",
")",
".",
"exists",
"(",
")"
] | Has this recurring cost already enacted transactions for given billing cycle? | [
"Has",
"this",
"recurring",
"cost",
"already",
"enacted",
"transactions",
"for",
"given",
"billing",
"cycle?"
] | python | train |
csparpa/pyowm | pyowm/weatherapi25/owm25.py | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L641-L680 | def daily_forecast(self, name, limit=None):
"""
Queries the OWM Weather API for daily weather forecast for the specified
location (eg: "London,uk"). A *Forecaster* object is returned,
containing a *Forecast* instance covering a global streak of fourteen
days by default: this inst... | [
"def",
"daily_forecast",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"str",
")",
",",
"\"Value must be a string\"",
"encoded_name",
"=",
"name",
"if",
"limit",
"is",
"not",
"None",
":",
"assert",... | Queries the OWM Weather API for daily weather forecast for the specified
location (eg: "London,uk"). A *Forecaster* object is returned,
containing a *Forecast* instance covering a global streak of fourteen
days by default: this instance encapsulates *Weather* objects, with a
time interva... | [
"Queries",
"the",
"OWM",
"Weather",
"API",
"for",
"daily",
"weather",
"forecast",
"for",
"the",
"specified",
"location",
"(",
"eg",
":",
"London",
"uk",
")",
".",
"A",
"*",
"Forecaster",
"*",
"object",
"is",
"returned",
"containing",
"a",
"*",
"Forecast",
... | python | train |
pytroll/satpy | satpy/readers/hrit_base.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/hrit_base.py#L182-L232 | def _get_hd(self, hdr_info):
"""Open the file, read and get the basic file header info and set the mda
dictionary
"""
hdr_map, variable_length_headers, text_headers = hdr_info
with open(self.filename) as fp:
total_header_length = 16
while fp.tell() < ... | [
"def",
"_get_hd",
"(",
"self",
",",
"hdr_info",
")",
":",
"hdr_map",
",",
"variable_length_headers",
",",
"text_headers",
"=",
"hdr_info",
"with",
"open",
"(",
"self",
".",
"filename",
")",
"as",
"fp",
":",
"total_header_length",
"=",
"16",
"while",
"fp",
... | Open the file, read and get the basic file header info and set the mda
dictionary | [
"Open",
"the",
"file",
"read",
"and",
"get",
"the",
"basic",
"file",
"header",
"info",
"and",
"set",
"the",
"mda",
"dictionary"
] | python | train |
crs4/pydoop | pydoop/hdfs/fs.py | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hdfs/fs.py#L348-L358 | def exists(self, path):
"""
Check if a given path exists on the filesystem.
:type path: str
:param path: the path to look for
:rtype: bool
:return: :obj:`True` if ``path`` exists
"""
_complain_ifclosed(self.closed)
return self.fs.exists(path) | [
"def",
"exists",
"(",
"self",
",",
"path",
")",
":",
"_complain_ifclosed",
"(",
"self",
".",
"closed",
")",
"return",
"self",
".",
"fs",
".",
"exists",
"(",
"path",
")"
] | Check if a given path exists on the filesystem.
:type path: str
:param path: the path to look for
:rtype: bool
:return: :obj:`True` if ``path`` exists | [
"Check",
"if",
"a",
"given",
"path",
"exists",
"on",
"the",
"filesystem",
"."
] | python | train |
mouradmourafiq/pandas-summary | pandas_summary/__init__.py | https://github.com/mouradmourafiq/pandas-summary/blob/554ae9ed94cb53d93f38b6aaab6f483b7b42609a/pandas_summary/__init__.py#L126-L138 | def _get_deviation_of_mean(self, series, multiplier=3):
"""
Returns count of values deviating of the mean, i.e. larger than `multiplier` * `std`.
:type series:
:param multiplier:
:return:
"""
capped_series = np.minimum(
series, series.mean() + multipli... | [
"def",
"_get_deviation_of_mean",
"(",
"self",
",",
"series",
",",
"multiplier",
"=",
"3",
")",
":",
"capped_series",
"=",
"np",
".",
"minimum",
"(",
"series",
",",
"series",
".",
"mean",
"(",
")",
"+",
"multiplier",
"*",
"series",
".",
"std",
"(",
")",... | Returns count of values deviating of the mean, i.e. larger than `multiplier` * `std`.
:type series:
:param multiplier:
:return: | [
"Returns",
"count",
"of",
"values",
"deviating",
"of",
"the",
"mean",
"i",
".",
"e",
".",
"larger",
"than",
"multiplier",
"*",
"std",
".",
":",
"type",
"series",
":",
":",
"param",
"multiplier",
":",
":",
"return",
":"
] | python | train |
angr/angr | angr/analyses/cfg/cfg_base.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_base.py#L2145-L2175 | def _process_one_indirect_jump(self, jump):
"""
Resolve a given indirect jump.
:param IndirectJump jump: The IndirectJump instance.
:return: A set of resolved indirect jump targets (ints).
"""
resolved = False
resolved_by = None
targets = None
... | [
"def",
"_process_one_indirect_jump",
"(",
"self",
",",
"jump",
")",
":",
"resolved",
"=",
"False",
"resolved_by",
"=",
"None",
"targets",
"=",
"None",
"block",
"=",
"self",
".",
"_lift",
"(",
"jump",
".",
"addr",
",",
"opt_level",
"=",
"1",
")",
"for",
... | Resolve a given indirect jump.
:param IndirectJump jump: The IndirectJump instance.
:return: A set of resolved indirect jump targets (ints). | [
"Resolve",
"a",
"given",
"indirect",
"jump",
"."
] | python | train |
mozilla/amo-validator | validator/opensearch.py | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/opensearch.py#L9-L218 | def detect_opensearch(err, package, listed=False):
'Detect, parse, and validate an OpenSearch provider'
# Parse the file.
try:
# Check if it is a file object.
if hasattr(package, 'read'):
srch_prov = parse(package)
else:
# It's not a file object; open it (the... | [
"def",
"detect_opensearch",
"(",
"err",
",",
"package",
",",
"listed",
"=",
"False",
")",
":",
"# Parse the file.",
"try",
":",
"# Check if it is a file object.",
"if",
"hasattr",
"(",
"package",
",",
"'read'",
")",
":",
"srch_prov",
"=",
"parse",
"(",
"packag... | Detect, parse, and validate an OpenSearch provider | [
"Detect",
"parse",
"and",
"validate",
"an",
"OpenSearch",
"provider"
] | python | train |
google/grumpy | third_party/pypy/datetime.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1614-L1638 | def isoformat(self, sep='T'):
"""Return the time formatted according to ISO.
This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-... | [
"def",
"isoformat",
"(",
"self",
",",
"sep",
"=",
"'T'",
")",
":",
"s",
"=",
"(",
"\"%04d-%02d-%02d%c\"",
"%",
"(",
"self",
".",
"_year",
",",
"self",
".",
"_month",
",",
"self",
".",
"_day",
",",
"sep",
")",
"+",
"_format_time",
"(",
"self",
".",
... | Return the time formatted according to ISO.
This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
Optional ... | [
"Return",
"the",
"time",
"formatted",
"according",
"to",
"ISO",
"."
] | python | valid |
saltstack/salt | salt/utils/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vmware.py#L1184-L1209 | def set_dvs_network_resource_management_enabled(dvs_ref, enabled):
'''
Sets whether NIOC is enabled on a DVS.
dvs_ref
The DVS reference.
enabled
Flag specifying whether NIOC is enabled.
'''
dvs_name = get_managed_object_name(dvs_ref)
log.trace('Setting network resource mana... | [
"def",
"set_dvs_network_resource_management_enabled",
"(",
"dvs_ref",
",",
"enabled",
")",
":",
"dvs_name",
"=",
"get_managed_object_name",
"(",
"dvs_ref",
")",
"log",
".",
"trace",
"(",
"'Setting network resource management enable to %s on '",
"'dvs \\'%s\\''",
",",
"enabl... | Sets whether NIOC is enabled on a DVS.
dvs_ref
The DVS reference.
enabled
Flag specifying whether NIOC is enabled. | [
"Sets",
"whether",
"NIOC",
"is",
"enabled",
"on",
"a",
"DVS",
"."
] | python | train |
MacHu-GWU/angora-project | angora/math/interp.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/interp.py#L161-L193 | def linear_interpolate(x_axis, y_axis, x_new_axis, enable_warning=True):
"""Interpolate a y = f(x) function using linear interpolation.
A smart way to interpolate arbitrary-range x_new_axis. The trick is
to add one more point to the original x_axis at x_new_axis[0] and
x_new_axis[-1], if x_new_axis i... | [
"def",
"linear_interpolate",
"(",
"x_axis",
",",
"y_axis",
",",
"x_new_axis",
",",
"enable_warning",
"=",
"True",
")",
":",
"left_pad_x",
",",
"left_pad_y",
"=",
"list",
"(",
")",
",",
"list",
"(",
")",
"right_pad_x",
",",
"right_pad_y",
"=",
"list",
"(",
... | Interpolate a y = f(x) function using linear interpolation.
A smart way to interpolate arbitrary-range x_new_axis. The trick is
to add one more point to the original x_axis at x_new_axis[0] and
x_new_axis[-1], if x_new_axis is out of range. | [
"Interpolate",
"a",
"y",
"=",
"f",
"(",
"x",
")",
"function",
"using",
"linear",
"interpolation",
"."
] | python | train |
KelSolaar/Foundations | foundations/trace.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L673-L694 | def untrace_class(cls):
"""
Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool
"""
for name, method in inspect.getmembers(cls, inspect.ismethod):
untrace_method(cls, method)
for name, function in inspect.getmembe... | [
"def",
"untrace_class",
"(",
"cls",
")",
":",
"for",
"name",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"cls",
",",
"inspect",
".",
"ismethod",
")",
":",
"untrace_method",
"(",
"cls",
",",
"method",
")",
"for",
"name",
",",
"function",
"in... | Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool | [
"Untraces",
"given",
"class",
"."
] | python | train |
lsst-sqre/zenodio | zenodio/harvest.py | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L101-L121 | def from_collection_xml(cls, xml_content):
"""Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
... | [
"def",
"from_collection_xml",
"(",
"cls",
",",
"xml_content",
")",
":",
"xml_dataset",
"=",
"xmltodict",
".",
"parse",
"(",
"xml_content",
",",
"process_namespaces",
"=",
"False",
")",
"# Unwrap the record list when harvesting a collection's datacite 3",
"xml_records",
"=... | Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
----------
xml_content : str
... | [
"Build",
"a",
":",
"class",
":",
"~zenodio",
".",
"harvest",
".",
"Datacite3Collection",
"from",
"Datecite3",
"-",
"formatted",
"XML",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/multi.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L155-L169 | def group_batches_joint(samples):
"""Perform grouping by batches for joint calling/squaring off.
"""
def _caller_batches(data):
jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data)
batch = tz.get_in(("metadata", "batch"), data) if jointcaller else None
return jointca... | [
"def",
"group_batches_joint",
"(",
"samples",
")",
":",
"def",
"_caller_batches",
"(",
"data",
")",
":",
"jointcaller",
"=",
"tz",
".",
"get_in",
"(",
"(",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"jointcaller\"",
")",
",",
"data",
")",
"batch",
"=",
"tz... | Perform grouping by batches for joint calling/squaring off. | [
"Perform",
"grouping",
"by",
"batches",
"for",
"joint",
"calling",
"/",
"squaring",
"off",
"."
] | python | train |
collectiveacuity/labPack | labpack/compilers/filters.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/compilers/filters.py#L6-L148 | def positional_filter(positional_filters, title=''):
'''
a method to construct a conditional filter function to test positional arguments
:param positional_filters: dictionary or list of dictionaries with query criteria
:param title: string with name of function to use instead
:return: callab... | [
"def",
"positional_filter",
"(",
"positional_filters",
",",
"title",
"=",
"''",
")",
":",
"# define help text ",
"if",
"not",
"title",
":",
"title",
"=",
"'positional_filter'",
"filter_arg",
"=",
"'%s(positional_filters=[...])'",
"%",
"title",
"# construct path_filte... | a method to construct a conditional filter function to test positional arguments
:param positional_filters: dictionary or list of dictionaries with query criteria
:param title: string with name of function to use instead
:return: callable for filter_function
NOTE: query criteria architecture
... | [
"a",
"method",
"to",
"construct",
"a",
"conditional",
"filter",
"function",
"to",
"test",
"positional",
"arguments"
] | python | train |
pbrisk/timewave | timewave/stochasticconsumer.py | https://github.com/pbrisk/timewave/blob/cf641391d1607a424042724c8b990d43ee270ef6/timewave/stochasticconsumer.py#L63-L69 | def finalize(self):
"""finalize for StatisticsConsumer"""
super(StatisticsConsumer, self).finalize()
# run statistics on timewave slice w at grid point g
# self.result = [(g, self.statistics(w)) for g, w in zip(self.grid, self.result)]
# self.result = zip(self.grid, (self.statist... | [
"def",
"finalize",
"(",
"self",
")",
":",
"super",
"(",
"StatisticsConsumer",
",",
"self",
")",
".",
"finalize",
"(",
")",
"# run statistics on timewave slice w at grid point g",
"# self.result = [(g, self.statistics(w)) for g, w in zip(self.grid, self.result)]",
"# self.result =... | finalize for StatisticsConsumer | [
"finalize",
"for",
"StatisticsConsumer"
] | python | train |
couchbase/couchbase-python-client | couchbase/exceptions.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/exceptions.py#L698-L726 | def _mk_lcberr(rc, name=None, default=CouchbaseError, docstr="", extrabase=[]):
"""
Create a new error class derived from the appropriate exceptions.
:param int rc: libcouchbase error code to map
:param str name: The name of the new exception
:param class default: Default exception to return if no c... | [
"def",
"_mk_lcberr",
"(",
"rc",
",",
"name",
"=",
"None",
",",
"default",
"=",
"CouchbaseError",
",",
"docstr",
"=",
"\"\"",
",",
"extrabase",
"=",
"[",
"]",
")",
":",
"categories",
"=",
"C",
".",
"_get_errtype",
"(",
"rc",
")",
"if",
"not",
"categor... | Create a new error class derived from the appropriate exceptions.
:param int rc: libcouchbase error code to map
:param str name: The name of the new exception
:param class default: Default exception to return if no categories are found
:return: a new exception derived from the appropriate categories, or... | [
"Create",
"a",
"new",
"error",
"class",
"derived",
"from",
"the",
"appropriate",
"exceptions",
".",
":",
"param",
"int",
"rc",
":",
"libcouchbase",
"error",
"code",
"to",
"map",
":",
"param",
"str",
"name",
":",
"The",
"name",
"of",
"the",
"new",
"except... | python | train |
rackerlabs/simpl | simpl/config.py | https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/config.py#L248-L311 | def add_argument(self, parser, permissive=False, **override_kwargs):
"""Add an option to a an argparse parser.
:keyword permissive: when true, build a parser that does not validate
required arguments.
"""
kwargs = {}
required = None
if self.kwargs:
... | [
"def",
"add_argument",
"(",
"self",
",",
"parser",
",",
"permissive",
"=",
"False",
",",
"*",
"*",
"override_kwargs",
")",
":",
"kwargs",
"=",
"{",
"}",
"required",
"=",
"None",
"if",
"self",
".",
"kwargs",
":",
"kwargs",
"=",
"copy",
".",
"copy",
"(... | Add an option to a an argparse parser.
:keyword permissive: when true, build a parser that does not validate
required arguments. | [
"Add",
"an",
"option",
"to",
"a",
"an",
"argparse",
"parser",
"."
] | python | train |
awslabs/serverless-application-model | samtranslator/plugins/api/implicit_api_plugin.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L120-L162 | def _process_api_events(self, function, api_events, template, condition=None):
"""
Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api
resource from the template
:param SamResource function: SAM Function containing the API event... | [
"def",
"_process_api_events",
"(",
"self",
",",
"function",
",",
"api_events",
",",
"template",
",",
"condition",
"=",
"None",
")",
":",
"for",
"logicalId",
",",
"event",
"in",
"api_events",
".",
"items",
"(",
")",
":",
"event_properties",
"=",
"event",
".... | Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api
resource from the template
:param SamResource function: SAM Function containing the API events to be processed
:param dict api_events: API Events extracted from the function. These eve... | [
"Actually",
"process",
"given",
"API",
"events",
".",
"Iteratively",
"adds",
"the",
"APIs",
"to",
"Swagger",
"JSON",
"in",
"the",
"respective",
"Serverless",
"::",
"Api",
"resource",
"from",
"the",
"template"
] | python | train |
Azure/blobxfer | blobxfer/operations/azure/file.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/azure/file.py#L239-L257 | def delete_file(client, fileshare, name, timeout=None):
# type: (azure.storage.file.FileService, str, str, int) -> None
"""Delete file from share
:param azure.storage.file.FileService client: file client
:param str fileshare: file share
:param str name: file name
:param int timeout: timeout
... | [
"def",
"delete_file",
"(",
"client",
",",
"fileshare",
",",
"name",
",",
"timeout",
"=",
"None",
")",
":",
"# type: (azure.storage.file.FileService, str, str, int) -> None",
"dir",
",",
"fpath",
",",
"snapshot",
"=",
"parse_file_path",
"(",
"name",
")",
"if",
"blo... | Delete file from share
:param azure.storage.file.FileService client: file client
:param str fileshare: file share
:param str name: file name
:param int timeout: timeout | [
"Delete",
"file",
"from",
"share",
":",
"param",
"azure",
".",
"storage",
".",
"file",
".",
"FileService",
"client",
":",
"file",
"client",
":",
"param",
"str",
"fileshare",
":",
"file",
"share",
":",
"param",
"str",
"name",
":",
"file",
"name",
":",
"... | python | train |
apache/airflow | airflow/ti_deps/deps/trigger_rule_dep.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/ti_deps/deps/trigger_rule_dep.py#L91-L224 | def _evaluate_trigger_rule(
self,
ti,
successes,
skipped,
failed,
upstream_failed,
done,
flag_upstream_failed,
session):
"""
Yields a dependency status that indicate whether the given task instanc... | [
"def",
"_evaluate_trigger_rule",
"(",
"self",
",",
"ti",
",",
"successes",
",",
"skipped",
",",
"failed",
",",
"upstream_failed",
",",
"done",
",",
"flag_upstream_failed",
",",
"session",
")",
":",
"TR",
"=",
"airflow",
".",
"utils",
".",
"trigger_rule",
"."... | Yields a dependency status that indicate whether the given task instance's trigger
rule was met.
:param ti: the task instance to evaluate the trigger rule of
:type ti: airflow.models.TaskInstance
:param successes: Number of successful upstream tasks
:type successes: bool
... | [
"Yields",
"a",
"dependency",
"status",
"that",
"indicate",
"whether",
"the",
"given",
"task",
"instance",
"s",
"trigger",
"rule",
"was",
"met",
"."
] | python | test |
lemieuxl/pyplink | pyplink/pyplink.py | https://github.com/lemieuxl/pyplink/blob/31d47c86f589064bda98206314a2d0b20e7fd2f0/pyplink/pyplink.py#L231-L295 | def _read_bim(self):
"""Reads the BIM file."""
# Reading the BIM file and setting the values
bim = pd.read_csv(self.bim_filename, delim_whitespace=True,
names=["chrom", "snp", "cm", "pos", "a1", "a2"],
dtype=dict(snp=str, a1=str, a2=str))
... | [
"def",
"_read_bim",
"(",
"self",
")",
":",
"# Reading the BIM file and setting the values",
"bim",
"=",
"pd",
".",
"read_csv",
"(",
"self",
".",
"bim_filename",
",",
"delim_whitespace",
"=",
"True",
",",
"names",
"=",
"[",
"\"chrom\"",
",",
"\"snp\"",
",",
"\"... | Reads the BIM file. | [
"Reads",
"the",
"BIM",
"file",
"."
] | python | train |
CalebBell/ht | ht/boiling_flow.py | https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/boiling_flow.py#L201-L280 | def Sun_Mishima(m, D, rhol, rhog, mul, kl, Hvap, sigma, q=None, Te=None):
r'''Calculates heat transfer coefficient for film boiling of saturated
fluid in any orientation of flow. Correlation
is as shown in [1]_, and also reviewed in [2]_ and [3]_.
Either the heat flux or excess temperature is requi... | [
"def",
"Sun_Mishima",
"(",
"m",
",",
"D",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"kl",
",",
"Hvap",
",",
"sigma",
",",
"q",
"=",
"None",
",",
"Te",
"=",
"None",
")",
":",
"G",
"=",
"m",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
... | r'''Calculates heat transfer coefficient for film boiling of saturated
fluid in any orientation of flow. Correlation
is as shown in [1]_, and also reviewed in [2]_ and [3]_.
Either the heat flux or excess temperature is required for the calculation
of heat transfer coefficient. Uses liquid-only Rey... | [
"r",
"Calculates",
"heat",
"transfer",
"coefficient",
"for",
"film",
"boiling",
"of",
"saturated",
"fluid",
"in",
"any",
"orientation",
"of",
"flow",
".",
"Correlation",
"is",
"as",
"shown",
"in",
"[",
"1",
"]",
"_",
"and",
"also",
"reviewed",
"in",
"[",
... | python | train |
Erotemic/utool | utool/util_type.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L377-L403 | def get_type(var):
"""
Gets types accounting for numpy
Ignore:
import utool as ut
import pandas as pd
var = np.array(['a', 'b', 'c'])
ut.get_type(var)
var = pd.Index(['a', 'b', 'c'])
ut.get_type(var)
"""
if HAVE_NUMPY and isinstance(var, np.ndarray):
... | [
"def",
"get_type",
"(",
"var",
")",
":",
"if",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"var",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"_WIN32",
":",
"# This is a weird system specific error",
"# https://github.com/numpy/numpy/issues/3667",
"type_",
"=",
"var",
... | Gets types accounting for numpy
Ignore:
import utool as ut
import pandas as pd
var = np.array(['a', 'b', 'c'])
ut.get_type(var)
var = pd.Index(['a', 'b', 'c'])
ut.get_type(var) | [
"Gets",
"types",
"accounting",
"for",
"numpy"
] | python | train |
gbowerman/azurerm | azurerm/computerp.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/computerp.py#L780-L798 | def poweroff_vmss(access_token, subscription_id, resource_group, vmss_name):
'''Power off all the VMs in a virtual machine scale set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group na... | [
"def",
"poweroff_vmss",
"(",
"access_token",
",",
"subscription_id",
",",
"resource_group",
",",
"vmss_name",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourceG... | Power off all the VMs in a virtual machine scale set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name of the virtual machine scale set.
Returns:
... | [
"Power",
"off",
"all",
"the",
"VMs",
"in",
"a",
"virtual",
"machine",
"scale",
"set",
"."
] | python | train |
SylvanasSun/FishFishJump | fish_core/search_engine.py | https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/search_engine.py#L528-L542 | def append_condition(statement, condition, key, value):
"""
>>> list = []
>>> append_condition(list, 'match', 'name', 'Jack')
>>> list
[{'match': {'name': 'Jack'}}]
>>> dict = {}
>>> append_condition(dict, 'match', 'name', 'Marry')
>>> dict
{'match': {'name': 'Marry'}}
"""
if... | [
"def",
"append_condition",
"(",
"statement",
",",
"condition",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"statement",
",",
"list",
")",
":",
"statement",
".",
"append",
"(",
"{",
"condition",
":",
"{",
"key",
":",
"value",
"}",
"}",
... | >>> list = []
>>> append_condition(list, 'match', 'name', 'Jack')
>>> list
[{'match': {'name': 'Jack'}}]
>>> dict = {}
>>> append_condition(dict, 'match', 'name', 'Marry')
>>> dict
{'match': {'name': 'Marry'}} | [
">>>",
"list",
"=",
"[]",
">>>",
"append_condition",
"(",
"list",
"match",
"name",
"Jack",
")",
">>>",
"list",
"[",
"{",
"match",
":",
"{",
"name",
":",
"Jack",
"}}",
"]",
">>>",
"dict",
"=",
"{}",
">>>",
"append_condition",
"(",
"dict",
"match",
"na... | python | train |
grundic/yagocd | yagocd/client.py | https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L232-L241 | def notification_filters(self):
"""
Property for accessing :class:`NotificationFilterManager` instance, which is used to manage notification
filters.
:rtype: yagocd.resources.notification_filter.NotificationFilterManager
"""
if self._notification_filter_manager is None:
... | [
"def",
"notification_filters",
"(",
"self",
")",
":",
"if",
"self",
".",
"_notification_filter_manager",
"is",
"None",
":",
"self",
".",
"_notification_filter_manager",
"=",
"NotificationFilterManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
... | Property for accessing :class:`NotificationFilterManager` instance, which is used to manage notification
filters.
:rtype: yagocd.resources.notification_filter.NotificationFilterManager | [
"Property",
"for",
"accessing",
":",
"class",
":",
"NotificationFilterManager",
"instance",
"which",
"is",
"used",
"to",
"manage",
"notification",
"filters",
"."
] | python | train |
rabitt/pysox | sox/transform.py | https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1964-L1975 | def oops(self):
'''Out Of Phase Stereo effect. Mixes stereo to twin-mono where each
mono channel contains the difference between the left and right stereo
channels. This is sometimes known as the 'karaoke' effect as it often
has the effect of removing most or all of the vocals from a rec... | [
"def",
"oops",
"(",
"self",
")",
":",
"effect_args",
"=",
"[",
"'oops'",
"]",
"self",
".",
"effects",
".",
"extend",
"(",
"effect_args",
")",
"self",
".",
"effects_log",
".",
"append",
"(",
"'oops'",
")",
"return",
"self"
] | Out Of Phase Stereo effect. Mixes stereo to twin-mono where each
mono channel contains the difference between the left and right stereo
channels. This is sometimes known as the 'karaoke' effect as it often
has the effect of removing most or all of the vocals from a recording. | [
"Out",
"Of",
"Phase",
"Stereo",
"effect",
".",
"Mixes",
"stereo",
"to",
"twin",
"-",
"mono",
"where",
"each",
"mono",
"channel",
"contains",
"the",
"difference",
"between",
"the",
"left",
"and",
"right",
"stereo",
"channels",
".",
"This",
"is",
"sometimes",
... | python | valid |
jason-weirather/py-seq-tools | seqtools/range/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/range/__init__.py#L296-L309 | def intersect(self,range2):
"""Return the chunk they overlap as a range.
options is passed to result from this object
:param range2:
:type range2: GenomicRange
:return: Range with the intersecting segement, or None if not overlapping
:rtype: GenomicRange
"""
if not self.overlaps(rang... | [
"def",
"intersect",
"(",
"self",
",",
"range2",
")",
":",
"if",
"not",
"self",
".",
"overlaps",
"(",
"range2",
")",
":",
"return",
"None",
"return",
"type",
"(",
"self",
")",
"(",
"self",
".",
"chr",
",",
"max",
"(",
"self",
".",
"start",
",",
"r... | Return the chunk they overlap as a range.
options is passed to result from this object
:param range2:
:type range2: GenomicRange
:return: Range with the intersecting segement, or None if not overlapping
:rtype: GenomicRange | [
"Return",
"the",
"chunk",
"they",
"overlap",
"as",
"a",
"range",
"."
] | python | train |
askovpen/discord_simple | discord_simple/transport.py | https://github.com/askovpen/discord_simple/blob/6dff3a94b63bb3657fae8b16e3d03f944afee71b/discord_simple/transport.py#L118-L131 | def on_connect(self, ws):
""" Todo """
self.logger.info("onconnect")
msg = {'op': self.IDENTIFY,
'd': {'token': self.token,
'properties': {'$os': 'lnx',
'$browser': 'discord_simple',
'$device': 'discord_simple',
... | [
"def",
"on_connect",
"(",
"self",
",",
"ws",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"onconnect\"",
")",
"msg",
"=",
"{",
"'op'",
":",
"self",
".",
"IDENTIFY",
",",
"'d'",
":",
"{",
"'token'",
":",
"self",
".",
"token",
",",
"'properti... | Todo | [
"Todo"
] | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L2214-L2217 | def macro_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#create-macro"
api_path = "/api/v2/macros.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"macro_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/macros.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kw... | https://developer.zendesk.com/rest_api/docs/core/macros#create-macro | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"macros#create",
"-",
"macro"
] | python | train |
mdgoldberg/sportsref | sportsref/nfl/boxscores.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nfl/boxscores.py#L212-L221 | def surface(self):
"""The playing surface on which the game was played.
:returns: string representing the type of surface. Returns np.nan if
not avaiable.
"""
doc = self.get_doc()
table = doc('table#game_info')
giTable = sportsref.utils.parse_info_table(table)
... | [
"def",
"surface",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"get_doc",
"(",
")",
"table",
"=",
"doc",
"(",
"'table#game_info'",
")",
"giTable",
"=",
"sportsref",
".",
"utils",
".",
"parse_info_table",
"(",
"table",
")",
"return",
"giTable",
".",
... | The playing surface on which the game was played.
:returns: string representing the type of surface. Returns np.nan if
not avaiable. | [
"The",
"playing",
"surface",
"on",
"which",
"the",
"game",
"was",
"played",
"."
] | python | test |
tchellomello/python-amcrest | src/amcrest/special.py | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/special.py#L95-L118 | def mjpeg_url(self, channelno=None, typeno=None):
"""
Return MJPEG streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
... | [
"def",
"mjpeg_url",
"(",
"self",
",",
"channelno",
"=",
"None",
",",
"typeno",
"=",
"None",
")",
":",
"if",
"channelno",
"is",
"None",
":",
"channelno",
"=",
"0",
"if",
"typeno",
"is",
"None",
":",
"typeno",
"=",
"1",
"cmd",
"=",
"\"mjpg/video.cgi?chan... | Return MJPEG streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
the following value:
0-Main Str... | [
"Return",
"MJPEG",
"streaming",
"url"
] | python | train |
gebn/wood | wood/entities.py | https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/entities.py#L61-L70 | def from_path(cls, path: pathlib.Path) -> 'Entity':
"""
Create an entity from a local path.
:param path: The path to the entity, either a file or directory.
:return: An entity instance representing the path.
"""
if path.is_file():
return File.from_path(path)
... | [
"def",
"from_path",
"(",
"cls",
",",
"path",
":",
"pathlib",
".",
"Path",
")",
"->",
"'Entity'",
":",
"if",
"path",
".",
"is_file",
"(",
")",
":",
"return",
"File",
".",
"from_path",
"(",
"path",
")",
"return",
"Directory",
".",
"from_path",
"(",
"pa... | Create an entity from a local path.
:param path: The path to the entity, either a file or directory.
:return: An entity instance representing the path. | [
"Create",
"an",
"entity",
"from",
"a",
"local",
"path",
"."
] | python | train |
BerkeleyAutomation/autolab_core | autolab_core/utils.py | https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/utils.py#L104-L124 | def skew(xi):
"""Return the skew-symmetric matrix that can be used to calculate
cross-products with vector xi.
Multiplying this matrix by a vector `v` gives the same result
as `xi x v`.
Parameters
----------
xi : :obj:`numpy.ndarray` of float
A 3-entry vector.
Returns
----... | [
"def",
"skew",
"(",
"xi",
")",
":",
"S",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"-",
"xi",
"[",
"2",
"]",
",",
"xi",
"[",
"1",
"]",
"]",
",",
"[",
"xi",
"[",
"2",
"]",
",",
"0",
",",
"-",
"xi",
"[",
"0",
"]",
"]",
",",
... | Return the skew-symmetric matrix that can be used to calculate
cross-products with vector xi.
Multiplying this matrix by a vector `v` gives the same result
as `xi x v`.
Parameters
----------
xi : :obj:`numpy.ndarray` of float
A 3-entry vector.
Returns
-------
:obj:`numpy.n... | [
"Return",
"the",
"skew",
"-",
"symmetric",
"matrix",
"that",
"can",
"be",
"used",
"to",
"calculate",
"cross",
"-",
"products",
"with",
"vector",
"xi",
"."
] | python | train |
tensorflow/cleverhans | cleverhans/attacks/bapp.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L417-L468 | def binary_search_batch(original_image, perturbed_images, decision_function,
shape, constraint, theta):
""" Binary search to approach the boundary. """
# Compute distance between each of perturbed image and original image.
dists_post_update = np.array([
compute_distance(
o... | [
"def",
"binary_search_batch",
"(",
"original_image",
",",
"perturbed_images",
",",
"decision_function",
",",
"shape",
",",
"constraint",
",",
"theta",
")",
":",
"# Compute distance between each of perturbed image and original image.",
"dists_post_update",
"=",
"np",
".",
"a... | Binary search to approach the boundary. | [
"Binary",
"search",
"to",
"approach",
"the",
"boundary",
"."
] | python | train |
hannes-brt/cudnn-python-wrappers | libcudnn.py | https://github.com/hannes-brt/cudnn-python-wrappers/blob/55aab1242924c2fd43db150cf2ccc2a3df958dd5/libcudnn.py#L1049-L1088 | def cudnnGetConvolutionForwardAlgorithm(handle, srcDesc, wDesc,
convDesc, destDesc, preference, memoryLimitInbytes):
""""
This function returns the best algorithm to choose for the forward convolution
depending on the critera expressed in the cudnnConvolutionFwdPrefer... | [
"def",
"cudnnGetConvolutionForwardAlgorithm",
"(",
"handle",
",",
"srcDesc",
",",
"wDesc",
",",
"convDesc",
",",
"destDesc",
",",
"preference",
",",
"memoryLimitInbytes",
")",
":",
"algo",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcudnn",
".",... | This function returns the best algorithm to choose for the forward convolution
depending on the critera expressed in the cudnnConvolutionFwdPreference_t enumerant.
Parameters
----------
handle : cudnnHandle
Handle to a previously created cuDNN context.
srcDesc : cudnnTensorDescriptor
... | [
"This",
"function",
"returns",
"the",
"best",
"algorithm",
"to",
"choose",
"for",
"the",
"forward",
"convolution",
"depending",
"on",
"the",
"critera",
"expressed",
"in",
"the",
"cudnnConvolutionFwdPreference_t",
"enumerant",
"."
] | python | train |
fozzle/python-brotherprint | brotherprint/brotherprint.py | https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L974-L987 | def received_char_count(self, count):
'''Set recieved char count limit
Args:
count: the amount of received characters you want to stop at.
Returns:
None
Raises:
None
'''
n1 = count/100
n2 = (count-(n1*100))/10
n... | [
"def",
"received_char_count",
"(",
"self",
",",
"count",
")",
":",
"n1",
"=",
"count",
"/",
"100",
"n2",
"=",
"(",
"count",
"-",
"(",
"n1",
"*",
"100",
")",
")",
"/",
"10",
"n3",
"=",
"(",
"count",
"-",
"(",
"(",
"n1",
"*",
"100",
")",
"+",
... | Set recieved char count limit
Args:
count: the amount of received characters you want to stop at.
Returns:
None
Raises:
None | [
"Set",
"recieved",
"char",
"count",
"limit",
"Args",
":",
"count",
":",
"the",
"amount",
"of",
"received",
"characters",
"you",
"want",
"to",
"stop",
"at",
".",
"Returns",
":",
"None",
"Raises",
":",
"None"
] | python | train |
xray7224/PyPump | pypump/client.py | https://github.com/xray7224/PyPump/blob/f921f691c39fe021f4fd124b6bc91718c9e49b4a/pypump/client.py#L125-L155 | def request(self, server=None):
""" Sends the request """
request = {
"headers": {"Content-Type": "application/json"},
"timeout": self._pump.timeout,
"data": self.context,
}
url = "{proto}://{server}/{endpoint}".format(
proto=self._pump.pr... | [
"def",
"request",
"(",
"self",
",",
"server",
"=",
"None",
")",
":",
"request",
"=",
"{",
"\"headers\"",
":",
"{",
"\"Content-Type\"",
":",
"\"application/json\"",
"}",
",",
"\"timeout\"",
":",
"self",
".",
"_pump",
".",
"timeout",
",",
"\"data\"",
":",
... | Sends the request | [
"Sends",
"the",
"request"
] | python | train |
berkeley-cocosci/Wallace | wallace/db.py | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/db.py#L65-L71 | def init_db(drop_all=False):
"""Initialize the database, optionally dropping existing tables."""
if drop_all:
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
return session | [
"def",
"init_db",
"(",
"drop_all",
"=",
"False",
")",
":",
"if",
"drop_all",
":",
"Base",
".",
"metadata",
".",
"drop_all",
"(",
"bind",
"=",
"engine",
")",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"bind",
"=",
"engine",
")",
"return",
"session... | Initialize the database, optionally dropping existing tables. | [
"Initialize",
"the",
"database",
"optionally",
"dropping",
"existing",
"tables",
"."
] | python | train |
autokey/autokey | lib/autokey/gtkapp.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/gtkapp.py#L276-L285 | def show_error_dialog(self, message, details=None):
"""
Convenience method for showing an error dialog.
"""
dlg = Gtk.MessageDialog(type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
message_format=message)
if details is not None:
... | [
"def",
"show_error_dialog",
"(",
"self",
",",
"message",
",",
"details",
"=",
"None",
")",
":",
"dlg",
"=",
"Gtk",
".",
"MessageDialog",
"(",
"type",
"=",
"Gtk",
".",
"MessageType",
".",
"ERROR",
",",
"buttons",
"=",
"Gtk",
".",
"ButtonsType",
".",
"OK... | Convenience method for showing an error dialog. | [
"Convenience",
"method",
"for",
"showing",
"an",
"error",
"dialog",
"."
] | python | train |
deepmind/sonnet | sonnet/python/modules/gated_rnn.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1028-L1074 | def initial_state(self, batch_size, dtype=tf.float32, trainable=False,
trainable_initializers=None, trainable_regularizers=None,
name=None):
"""Builds the default start state tensor of zeros.
Args:
batch_size: An int, float or scalar Tensor representing the batch s... | [
"def",
"initial_state",
"(",
"self",
",",
"batch_size",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"trainable",
"=",
"False",
",",
"trainable_initializers",
"=",
"None",
",",
"trainable_regularizers",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if... | Builds the default start state tensor of zeros.
Args:
batch_size: An int, float or scalar Tensor representing the batch size.
dtype: The data type to use for the state.
trainable: Boolean that indicates whether to learn the initial state.
trainable_initializers: An optional pair of initiali... | [
"Builds",
"the",
"default",
"start",
"state",
"tensor",
"of",
"zeros",
"."
] | python | train |
ansible/tower-cli | tower_cli/resources/host.py | https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/host.py#L42-L66 | def list(self, group=None, host_filter=None, **kwargs):
"""Return a list of hosts.
=====API DOCS=====
Retrieve a list of hosts.
:param group: Primary key or name of the group whose hosts will be listed.
:type group: str
:param all_pages: Flag that if set, collect all pa... | [
"def",
"list",
"(",
"self",
",",
"group",
"=",
"None",
",",
"host_filter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"group",
":",
"kwargs",
"[",
"'query'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'query'",
",",
"(",
")",
")",
"+",
"(... | Return a list of hosts.
=====API DOCS=====
Retrieve a list of hosts.
:param group: Primary key or name of the group whose hosts will be listed.
:type group: str
:param all_pages: Flag that if set, collect all pages of content from the API when returning results.
:type a... | [
"Return",
"a",
"list",
"of",
"hosts",
"."
] | python | valid |
mozilla/PyPOM | src/pypom/page.py | https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/page.py#L86-L117 | def seed_url(self):
"""A URL that can be used to open the page.
The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then
appended to :py:attr:`base_url` unless the template results in an
absolute URL.
:return: URL that can be used to open the page.
:rtype: str
... | [
"def",
"seed_url",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"if",
"self",
".",
"URL_TEMPLATE",
"is",
"not",
"None",
":",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"URL_TEMPLATE",
".",
"... | A URL that can be used to open the page.
The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then
appended to :py:attr:`base_url` unless the template results in an
absolute URL.
:return: URL that can be used to open the page.
:rtype: str | [
"A",
"URL",
"that",
"can",
"be",
"used",
"to",
"open",
"the",
"page",
"."
] | python | valid |
dswah/pyGAM | pygam/pygam.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L395-L417 | def predict_mu(self, X):
"""
preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
... | [
"def",
"predict_mu",
"(",
"self",
",",
"X",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"X",
"=",
"check_X",
"(",
"X",
",",
"n_feats",
"=",
"self",
".",
"statistics... | preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
containing expected values under the mo... | [
"preduct",
"expected",
"value",
"of",
"target",
"given",
"model",
"and",
"input",
"X"
] | python | train |
rwl/pylon | pyreto/discrete/experiment.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/discrete/experiment.py#L72-L83 | def doInteractions(self, number=1):
""" Directly maps the agents and the tasks.
"""
t0 = time.time()
for _ in range(number):
self._oneInteraction()
elapsed = time.time() - t0
logger.info("%d interactions executed in %.3fs." % (number, elapsed))
retu... | [
"def",
"doInteractions",
"(",
"self",
",",
"number",
"=",
"1",
")",
":",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"number",
")",
":",
"self",
".",
"_oneInteraction",
"(",
")",
"elapsed",
"=",
"time",
".",
"time",
... | Directly maps the agents and the tasks. | [
"Directly",
"maps",
"the",
"agents",
"and",
"the",
"tasks",
"."
] | python | train |
its-rigs/Trolly | trolly/card.py | https://github.com/its-rigs/Trolly/blob/483dc94c352df40dc05ead31820b059b2545cf82/trolly/card.py#L158-L166 | def _add_label_from_class(self, label=None):
'''
Add an existing label to this card.
'''
return self.fetch_json(
uri_path=self.base_uri + '/idLabels',
http_method='POST',
query_params={'value': label.id}
) | [
"def",
"_add_label_from_class",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"return",
"self",
".",
"fetch_json",
"(",
"uri_path",
"=",
"self",
".",
"base_uri",
"+",
"'/idLabels'",
",",
"http_method",
"=",
"'POST'",
",",
"query_params",
"=",
"{",
"'va... | Add an existing label to this card. | [
"Add",
"an",
"existing",
"label",
"to",
"this",
"card",
"."
] | python | test |
blockstack/blockstack-core | blockstack/lib/rpc.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1108-L1130 | def GET_blockchain_name_record( self, path_info, blockchain_name, name ):
"""
Get the name's blockchain record in full
Reply the raw blockchain record on success
Reply 404 if the name is not found
Reply 502 if we have an error talking to the server
"""
if not chec... | [
"def",
"GET_blockchain_name_record",
"(",
"self",
",",
"path_info",
",",
"blockchain_name",
",",
"name",
")",
":",
"if",
"not",
"check_name",
"(",
"name",
")",
"and",
"not",
"check_subdomain",
"(",
"name",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",... | Get the name's blockchain record in full
Reply the raw blockchain record on success
Reply 404 if the name is not found
Reply 502 if we have an error talking to the server | [
"Get",
"the",
"name",
"s",
"blockchain",
"record",
"in",
"full",
"Reply",
"the",
"raw",
"blockchain",
"record",
"on",
"success",
"Reply",
"404",
"if",
"the",
"name",
"is",
"not",
"found",
"Reply",
"502",
"if",
"we",
"have",
"an",
"error",
"talking",
"to"... | python | train |
log2timeline/plaso | plaso/parsers/plist_plugins/dtfabric_plugin.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/plist_plugins/dtfabric_plugin.py#L82-L99 | def _GetDataTypeMap(self, name):
"""Retrieves a data type map defined by the definition file.
The data type maps are cached for reuse.
Args:
name (str): name of the data type as defined by the definition file.
Returns:
dtfabric.DataTypeMap: data type map which contains a data type definit... | [
"def",
"_GetDataTypeMap",
"(",
"self",
",",
"name",
")",
":",
"data_type_map",
"=",
"self",
".",
"_data_type_maps",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"not",
"data_type_map",
":",
"data_type_map",
"=",
"self",
".",
"_fabric",
".",
"CreateData... | Retrieves a data type map defined by the definition file.
The data type maps are cached for reuse.
Args:
name (str): name of the data type as defined by the definition file.
Returns:
dtfabric.DataTypeMap: data type map which contains a data type definition,
such as a structure, that... | [
"Retrieves",
"a",
"data",
"type",
"map",
"defined",
"by",
"the",
"definition",
"file",
"."
] | python | train |
contentful/contentful-management.py | contentful_management/personal_access_tokens_proxy.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/personal_access_tokens_proxy.py#L39-L51 | def delete(self, token_id, *args, **kwargs):
"""
Revokes a personal access token.
"""
return self.client._put(
"{0}/revoked".format(
self._url(token_id)
),
None,
*args,
**kwargs
) | [
"def",
"delete",
"(",
"self",
",",
"token_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"_put",
"(",
"\"{0}/revoked\"",
".",
"format",
"(",
"self",
".",
"_url",
"(",
"token_id",
")",
")",
",",
"None... | Revokes a personal access token. | [
"Revokes",
"a",
"personal",
"access",
"token",
"."
] | python | train |
nion-software/nionswift-io | nionswift_plugin/DM_IO/dm3_image_utils.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/DM_IO/dm3_image_utils.py#L69-L89 | def imagedatadict_to_ndarray(imdict):
"""
Converts the ImageData dictionary, imdict, to an nd image.
"""
arr = imdict['Data']
im = None
if isinstance(arr, parse_dm3.array.array):
im = numpy.asarray(arr, dtype=arr.typecode)
elif isinstance(arr, parse_dm3.structarray):
t = tupl... | [
"def",
"imagedatadict_to_ndarray",
"(",
"imdict",
")",
":",
"arr",
"=",
"imdict",
"[",
"'Data'",
"]",
"im",
"=",
"None",
"if",
"isinstance",
"(",
"arr",
",",
"parse_dm3",
".",
"array",
".",
"array",
")",
":",
"im",
"=",
"numpy",
".",
"asarray",
"(",
... | Converts the ImageData dictionary, imdict, to an nd image. | [
"Converts",
"the",
"ImageData",
"dictionary",
"imdict",
"to",
"an",
"nd",
"image",
"."
] | python | train |
spacetelescope/synphot_refactor | synphot/spectrum.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/spectrum.py#L330-L343 | def _validate_wavelengths(self, wave):
"""Validate wavelengths for sampling."""
if wave is None:
if self.waveset is None:
raise exceptions.SynphotError(
'self.waveset is undefined; '
'Provide wavelengths for sampling.')
wave... | [
"def",
"_validate_wavelengths",
"(",
"self",
",",
"wave",
")",
":",
"if",
"wave",
"is",
"None",
":",
"if",
"self",
".",
"waveset",
"is",
"None",
":",
"raise",
"exceptions",
".",
"SynphotError",
"(",
"'self.waveset is undefined; '",
"'Provide wavelengths for sampli... | Validate wavelengths for sampling. | [
"Validate",
"wavelengths",
"for",
"sampling",
"."
] | python | train |
automl/HpBandSter | hpbandster/optimizers/bohb.py | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/bohb.py#L119-L141 | def get_next_iteration(self, iteration, iteration_kwargs={}):
"""
BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters
----------
iteration: int
the index of the iteration to be instantiated
Returns
-------
SuccessiveHalving: t... | [
"def",
"get_next_iteration",
"(",
"self",
",",
"iteration",
",",
"iteration_kwargs",
"=",
"{",
"}",
")",
":",
"# number of 'SH rungs'",
"s",
"=",
"self",
".",
"max_SH_iter",
"-",
"1",
"-",
"(",
"iteration",
"%",
"self",
".",
"max_SH_iter",
")",
"# number of ... | BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters
----------
iteration: int
the index of the iteration to be instantiated
Returns
-------
SuccessiveHalving: the SuccessiveHalving iteration with the
corresponding number of co... | [
"BO",
"-",
"HB",
"uses",
"(",
"just",
"like",
"Hyperband",
")",
"SuccessiveHalving",
"for",
"each",
"iteration",
".",
"See",
"Li",
"et",
"al",
".",
"(",
"2016",
")",
"for",
"reference",
".",
"Parameters",
"----------",
"iteration",
":",
"int",
"the",
"in... | python | train |
rbw/pysnow | pysnow/legacy_request.py | https://github.com/rbw/pysnow/blob/87c8ce0d3a089c2f59247f30efbd545fcdb8e985/pysnow/legacy_request.py#L142-L150 | def insert(self, payload):
"""Inserts a new record with the payload passed as an argument
:param payload: The record to create (dict)
:return:
- Created record
"""
response = self.session.post(self._get_table_url(), data=json.dumps(payload))
return self._get_... | [
"def",
"insert",
"(",
"self",
",",
"payload",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"_get_table_url",
"(",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"return",
"self",
".",
"_g... | Inserts a new record with the payload passed as an argument
:param payload: The record to create (dict)
:return:
- Created record | [
"Inserts",
"a",
"new",
"record",
"with",
"the",
"payload",
"passed",
"as",
"an",
"argument"
] | python | train |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiV4VirtualInterface.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiV4VirtualInterface.py#L36-L49 | def search(self, **kwargs):
"""
Method to search Virtual Interfaces based on extends search.
:param search: Dict containing QuerySets to find Virtual Interfaces.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on... | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ApiV4VirtualInterface",
",",
"self",
")",
".",
"get",
"(",
"self",
".",
"prepare_url",
"(",
"'api/v4/virtual-interface/'",
",",
"kwargs",
")",
")"
] | Method to search Virtual Interfaces based on extends search.
:param search: Dict containing QuerySets to find Virtual Interfaces.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array contain... | [
"Method",
"to",
"search",
"Virtual",
"Interfaces",
"based",
"on",
"extends",
"search",
"."
] | python | train |
Hackerfleet/hfos | modules/robot/hfos/robot/machineroom.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/robot/hfos/robot/machineroom.py#L241-L248 | def on_pumprequest(self, event):
"""
Activates or deactivates a connected pump.
:param event:
"""
self.log("Updating pump status: ", event.controlvalue)
self._set_digital_pin(self._pump_channel, event.controlvalue) | [
"def",
"on_pumprequest",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"\"Updating pump status: \"",
",",
"event",
".",
"controlvalue",
")",
"self",
".",
"_set_digital_pin",
"(",
"self",
".",
"_pump_channel",
",",
"event",
".",
"controlvalue",
... | Activates or deactivates a connected pump.
:param event: | [
"Activates",
"or",
"deactivates",
"a",
"connected",
"pump",
"."
] | python | train |
striglia/pyramid_swagger | pyramid_swagger/tween.py | https://github.com/striglia/pyramid_swagger/blob/1dbc0b4f23e2e5f4ed575c116f3f7d0e83e30d45/pyramid_swagger/tween.py#L144-L201 | def validation_tween_factory(handler, registry):
"""Pyramid tween for performing validation.
Note this is very simple -- it validates requests, responses, and paths
while delegating to the relevant matching view.
"""
settings = load_settings(registry)
route_mapper = registry.queryUtility(IRoute... | [
"def",
"validation_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"settings",
"=",
"load_settings",
"(",
"registry",
")",
"route_mapper",
"=",
"registry",
".",
"queryUtility",
"(",
"IRoutesMapper",
")",
"validation_context",
"=",
"_get_validation_context",... | Pyramid tween for performing validation.
Note this is very simple -- it validates requests, responses, and paths
while delegating to the relevant matching view. | [
"Pyramid",
"tween",
"for",
"performing",
"validation",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | scripts/tpip.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L197-L211 | def write_csv_file(output_filename, tpip_pkgs):
"""Write the TPIP report out to a CSV file.
:param str output_filename: filename for CSV.
:param List tpip_pkgs: a list of dictionaries compatible with DictWriter.
"""
dirname = os.path.dirname(os.path.abspath(os.path.expanduser(output_filename)))
... | [
"def",
"write_csv_file",
"(",
"output_filename",
",",
"tpip_pkgs",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"output_filename",
")",
")",
")",
"i... | Write the TPIP report out to a CSV file.
:param str output_filename: filename for CSV.
:param List tpip_pkgs: a list of dictionaries compatible with DictWriter. | [
"Write",
"the",
"TPIP",
"report",
"out",
"to",
"a",
"CSV",
"file",
"."
] | python | train |
Xython/Linq.py | linq/standard/dict.py | https://github.com/Xython/Linq.py/blob/ffb65f92f1df0d8161d5f835f5947554f6f33d72/linq/standard/dict.py#L74-L88 | def ChunkBy(self: dict, f=None):
"""
[
{
'self': [1, 1, 3, 3, 1, 1],
'f': lambda x: x%2,
'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]]
}
]
"""
if f is None:
return _chunk(self.items())
if is_to_destruct(f):
f = destruct... | [
"def",
"ChunkBy",
"(",
"self",
":",
"dict",
",",
"f",
"=",
"None",
")",
":",
"if",
"f",
"is",
"None",
":",
"return",
"_chunk",
"(",
"self",
".",
"items",
"(",
")",
")",
"if",
"is_to_destruct",
"(",
"f",
")",
":",
"f",
"=",
"destruct_func",
"(",
... | [
{
'self': [1, 1, 3, 3, 1, 1],
'f': lambda x: x%2,
'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]]
}
] | [
"[",
"{",
"self",
":",
"[",
"1",
"1",
"3",
"3",
"1",
"1",
"]",
"f",
":",
"lambda",
"x",
":",
"x%2",
"assert",
":",
"lambda",
"ret",
":",
"ret",
"==",
"[[",
"1",
"1",
"]",
"[",
"3",
"3",
"]",
"[",
"1",
"1",
"]]",
"}",
"]"
] | python | train |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1458-L1531 | def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Return... | [
"def",
"CleanseRawStrings",
"(",
"raw_lines",
")",
":",
"delimiter",
"=",
"None",
"lines_without_raw_strings",
"=",
"[",
"]",
"for",
"line",
"in",
"raw_lines",
":",
"if",
"delimiter",
":",
"# Inside a raw string, look for the end",
"end",
"=",
"line",
".",
"find",... | Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw str... | [
"Removes",
"C",
"++",
"11",
"raw",
"strings",
"from",
"lines",
"."
] | python | valid |
Spinmob/spinmob | _settings.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_settings.py#L67-L74 | def List(self):
"""
Lists the keys and values.
"""
print()
for key in list(self.keys()):
print(key,'=',self[key])
print() | [
"def",
"List",
"(",
"self",
")",
":",
"print",
"(",
")",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
":",
"print",
"(",
"key",
",",
"'='",
",",
"self",
"[",
"key",
"]",
")",
"print",
"(",
")"
] | Lists the keys and values. | [
"Lists",
"the",
"keys",
"and",
"values",
"."
] | python | train |
xapple/plumbing | plumbing/databases/access_database.py | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L250-L299 | def create(cls, destination):
"""Create a new empty MDB at destination."""
mdb_gz_b64 = """\
H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a
jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+
qKgIIHL8Znb39u72znWJiWP3+9l473fzm... | [
"def",
"create",
"(",
"cls",
",",
"destination",
")",
":",
"mdb_gz_b64",
"=",
"\"\"\"\\\n H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a\n jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+\n qKgIIHL8Znb39u72znWJiWP3+9l... | Create a new empty MDB at destination. | [
"Create",
"a",
"new",
"empty",
"MDB",
"at",
"destination",
"."
] | python | train |
jantman/pypi-download-stats | pypi_download_stats/outputgenerator.py | https://github.com/jantman/pypi-download-stats/blob/44a7a6bbcd61a9e7f02bd02c52584a98183f80c5/pypi_download_stats/outputgenerator.py#L125-L154 | def _data_dict_to_bokeh_chart_data(self, data):
"""
Take a dictionary of data, as returned by the :py:class:`~.ProjectStats`
per_*_data properties, return a 2-tuple of data dict and x labels list
usable by bokeh.charts.
:param data: data dict from :py:class:`~.ProjectStats` prop... | [
"def",
"_data_dict_to_bokeh_chart_data",
"(",
"self",
",",
"data",
")",
":",
"labels",
"=",
"[",
"]",
"# find all the data keys",
"keys",
"=",
"set",
"(",
")",
"for",
"date",
"in",
"data",
":",
"for",
"k",
"in",
"data",
"[",
"date",
"]",
":",
"keys",
"... | Take a dictionary of data, as returned by the :py:class:`~.ProjectStats`
per_*_data properties, return a 2-tuple of data dict and x labels list
usable by bokeh.charts.
:param data: data dict from :py:class:`~.ProjectStats` property
:type data: dict
:return: 2-tuple of data dict,... | [
"Take",
"a",
"dictionary",
"of",
"data",
"as",
"returned",
"by",
"the",
":",
"py",
":",
"class",
":",
"~",
".",
"ProjectStats",
"per_",
"*",
"_data",
"properties",
"return",
"a",
"2",
"-",
"tuple",
"of",
"data",
"dict",
"and",
"x",
"labels",
"list",
... | python | train |
materialsproject/pymatgen | pymatgen/core/tensors.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/tensors.py#L315-L326 | def voigt_symmetrized(self):
"""
Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation
tensor such that it is invariant wrt permutation of indices
"""
if not (self.rank % 2 == 0 and self.rank >= 2):
raise ValueError("V-symmetrization requires rank even and >= 2... | [
"def",
"voigt_symmetrized",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"rank",
"%",
"2",
"==",
"0",
"and",
"self",
".",
"rank",
">=",
"2",
")",
":",
"raise",
"ValueError",
"(",
"\"V-symmetrization requires rank even and >= 2\"",
")",
"v",
"=",
... | Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation
tensor such that it is invariant wrt permutation of indices | [
"Returns",
"a",
"voigt",
"-",
"symmetrized",
"tensor",
"i",
".",
"e",
".",
"a",
"voigt",
"-",
"notation",
"tensor",
"such",
"that",
"it",
"is",
"invariant",
"wrt",
"permutation",
"of",
"indices"
] | python | train |
fukuball/fuku-ml | FukuML/MLBase.py | https://github.com/fukuball/fuku-ml/blob/0da15ad7af76adf344b5a6b3f3dbabbbab3446b0/FukuML/MLBase.py#L102-L142 | def prediction(self, input_data='', mode='test_data'):
'''
Make prediction
input test data
output the prediction
'''
prediction = {}
if (self.status != 'train'):
print("Please load train data and init W then train the W first.")
return p... | [
"def",
"prediction",
"(",
"self",
",",
"input_data",
"=",
"''",
",",
"mode",
"=",
"'test_data'",
")",
":",
"prediction",
"=",
"{",
"}",
"if",
"(",
"self",
".",
"status",
"!=",
"'train'",
")",
":",
"print",
"(",
"\"Please load train data and init W then train... | Make prediction
input test data
output the prediction | [
"Make",
"prediction",
"input",
"test",
"data",
"output",
"the",
"prediction"
] | python | test |
sdispater/eloquent | eloquent/orm/relations/has_many_through.py | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/has_many_through.py#L29-L40 | def add_constraints(self):
"""
Set the base constraints on the relation query.
:rtype: None
"""
parent_table = self._parent.get_table()
self._set_join()
if self._constraints:
self._query.where('%s.%s' % (parent_table, self._first_key), '=', self._fa... | [
"def",
"add_constraints",
"(",
"self",
")",
":",
"parent_table",
"=",
"self",
".",
"_parent",
".",
"get_table",
"(",
")",
"self",
".",
"_set_join",
"(",
")",
"if",
"self",
".",
"_constraints",
":",
"self",
".",
"_query",
".",
"where",
"(",
"'%s.%s'",
"... | Set the base constraints on the relation query.
:rtype: None | [
"Set",
"the",
"base",
"constraints",
"on",
"the",
"relation",
"query",
"."
] | python | train |
FNNDSC/pftree | pftree/pftree.py | https://github.com/FNNDSC/pftree/blob/b841e337c976bce151735f9d5dd95eded62aa094/pftree/pftree.py#L42-L105 | def declare_selfvars(self):
"""
A block to declare self variables
"""
self._dictErr = {
'inputDirFail' : {
'action' : 'trying to check on the input directory, ',
'error' : 'directory not found. This is a *required* input',
... | [
"def",
"declare_selfvars",
"(",
"self",
")",
":",
"self",
".",
"_dictErr",
"=",
"{",
"'inputDirFail'",
":",
"{",
"'action'",
":",
"'trying to check on the input directory, '",
",",
"'error'",
":",
"'directory not found. This is a *required* input'",
",",
"'exitCode'",
"... | A block to declare self variables | [
"A",
"block",
"to",
"declare",
"self",
"variables"
] | python | train |
gitpython-developers/GitPython | git/objects/fun.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/fun.py#L91-L110 | def _find_by_name(tree_data, name, is_dir, start_at):
"""return data entry matching the given name and tree mode
or None.
Before the item is returned, the respective data item is set
None in the tree_data list to mark it done"""
try:
item = tree_data[start_at]
if item and item[2] == ... | [
"def",
"_find_by_name",
"(",
"tree_data",
",",
"name",
",",
"is_dir",
",",
"start_at",
")",
":",
"try",
":",
"item",
"=",
"tree_data",
"[",
"start_at",
"]",
"if",
"item",
"and",
"item",
"[",
"2",
"]",
"==",
"name",
"and",
"S_ISDIR",
"(",
"item",
"[",... | return data entry matching the given name and tree mode
or None.
Before the item is returned, the respective data item is set
None in the tree_data list to mark it done | [
"return",
"data",
"entry",
"matching",
"the",
"given",
"name",
"and",
"tree",
"mode",
"or",
"None",
".",
"Before",
"the",
"item",
"is",
"returned",
"the",
"respective",
"data",
"item",
"is",
"set",
"None",
"in",
"the",
"tree_data",
"list",
"to",
"mark",
... | python | train |
akfullfo/taskforce | taskforce/task.py | https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/task.py#L1374-L1409 | def _reap(self):
"""
Reap all processes that have exited. We try to reap bursts of
processes so that groups that cluster will tend to restart in the
configured order.
"""
log = self._params.get('log', self._discard)
try:
cnt = len(os.read(self._watch_chil... | [
"def",
"_reap",
"(",
"self",
")",
":",
"log",
"=",
"self",
".",
"_params",
".",
"get",
"(",
"'log'",
",",
"self",
".",
"_discard",
")",
"try",
":",
"cnt",
"=",
"len",
"(",
"os",
".",
"read",
"(",
"self",
".",
"_watch_child",
",",
"102400",
")",
... | Reap all processes that have exited. We try to reap bursts of
processes so that groups that cluster will tend to restart in the
configured order. | [
"Reap",
"all",
"processes",
"that",
"have",
"exited",
".",
"We",
"try",
"to",
"reap",
"bursts",
"of",
"processes",
"so",
"that",
"groups",
"that",
"cluster",
"will",
"tend",
"to",
"restart",
"in",
"the",
"configured",
"order",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/read.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L82-L91 | def map_to_precursors_on_fly(seqs, names, loci, args):
"""map sequences to precursors with franpr algorithm to avoid writting on disk"""
precursor = precursor_sequence(loci, args.ref).upper()
dat = dict()
for s, n in itertools.izip(seqs, names):
res = pyMatch.Match(precursor, str(s), 1, 3)
... | [
"def",
"map_to_precursors_on_fly",
"(",
"seqs",
",",
"names",
",",
"loci",
",",
"args",
")",
":",
"precursor",
"=",
"precursor_sequence",
"(",
"loci",
",",
"args",
".",
"ref",
")",
".",
"upper",
"(",
")",
"dat",
"=",
"dict",
"(",
")",
"for",
"s",
","... | map sequences to precursors with franpr algorithm to avoid writting on disk | [
"map",
"sequences",
"to",
"precursors",
"with",
"franpr",
"algorithm",
"to",
"avoid",
"writting",
"on",
"disk"
] | python | train |
ryan-roemer/django-cloud-browser | cloud_browser/cloud/fs.py | https://github.com/ryan-roemer/django-cloud-browser/blob/b06cdd24885a6309e843ed924dbf1705b67e7f48/cloud_browser/cloud/fs.py#L142-L148 | def _get_containers(self):
"""Return available containers."""
def full_fn(path):
return os.path.join(self.abs_root, path)
return [self.cont_cls.from_path(self, d)
for d in os.listdir(self.abs_root) if is_dir(full_fn(d))] | [
"def",
"_get_containers",
"(",
"self",
")",
":",
"def",
"full_fn",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"abs_root",
",",
"path",
")",
"return",
"[",
"self",
".",
"cont_cls",
".",
"from_path",
"(",
"self",... | Return available containers. | [
"Return",
"available",
"containers",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L4363-L4368 | def newDocProp(self, name, value):
"""Create a new property carried by a document. """
ret = libxml2mod.xmlNewDocProp(self._o, name, value)
if ret is None:raise treeError('xmlNewDocProp() failed')
__tmp = xmlAttr(_obj=ret)
return __tmp | [
"def",
"newDocProp",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocProp",
"(",
"self",
".",
"_o",
",",
"name",
",",
"value",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewDocProp() ... | Create a new property carried by a document. | [
"Create",
"a",
"new",
"property",
"carried",
"by",
"a",
"document",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L258-L266 | def get_bool_raw(s: str) -> Optional[bool]:
"""
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
"""
if s == "Y" or s == "y":
return True
elif s == "N" or s == "n":
return False
return None | [
"def",
"get_bool_raw",
"(",
"s",
":",
"str",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"if",
"s",
"==",
"\"Y\"",
"or",
"s",
"==",
"\"y\"",
":",
"return",
"True",
"elif",
"s",
"==",
"\"N\"",
"or",
"s",
"==",
"\"n\"",
":",
"return",
"False",
"r... | Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``. | [
"Maps",
"Y",
"y",
"to",
"True",
"and",
"N",
"n",
"to",
"False",
"."
] | python | train |
barryp/py-amqplib | amqplib/client_0_8/method_framing.py | https://github.com/barryp/py-amqplib/blob/2b3a47de34b4712c111d0a55d7ff109dffc2a7b2/amqplib/client_0_8/method_framing.py#L213-L222 | def read_method(self):
"""
Read a method from the peer.
"""
self._next_method()
m = self.queue.get()
if isinstance(m, Exception):
raise m
return m | [
"def",
"read_method",
"(",
"self",
")",
":",
"self",
".",
"_next_method",
"(",
")",
"m",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"m",
",",
"Exception",
")",
":",
"raise",
"m",
"return",
"m"
] | Read a method from the peer. | [
"Read",
"a",
"method",
"from",
"the",
"peer",
"."
] | python | train |
datasift/datasift-python | datasift/historics.py | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/historics.py#L41-L52 | def start(self, historics_id):
""" Start the historics job with the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart
:param historics_id: hash of the job to start
:type historics_id: str
:return: dict of REST AP... | [
"def",
"start",
"(",
"self",
",",
"historics_id",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'start'",
",",
"data",
"=",
"dict",
"(",
"id",
"=",
"historics_id",
")",
")"
] | Start the historics job with the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart
:param historics_id: hash of the job to start
:type historics_id: str
:return: dict of REST API output with headers attached
... | [
"Start",
"the",
"historics",
"job",
"with",
"the",
"given",
"ID",
"."
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/interactive.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/interactive.py#L1379-L1402 | def do_threadlist(self, arg):
"""
tl - show the threads being debugged
threadlist - show the threads being debugged
"""
if arg:
raise CmdError("too many arguments")
if self.cmdprefix:
process = self.get_process_from_prefix()
for thread ... | [
"def",
"do_threadlist",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
":",
"raise",
"CmdError",
"(",
"\"too many arguments\"",
")",
"if",
"self",
".",
"cmdprefix",
":",
"process",
"=",
"self",
".",
"get_process_from_prefix",
"(",
")",
"for",
"thread",
"i... | tl - show the threads being debugged
threadlist - show the threads being debugged | [
"tl",
"-",
"show",
"the",
"threads",
"being",
"debugged",
"threadlist",
"-",
"show",
"the",
"threads",
"being",
"debugged"
] | python | train |
chrippa/ds4drv | ds4drv/backends/bluetooth.py | https://github.com/chrippa/ds4drv/blob/be7327fc3f5abb8717815f2a1a2ad3d335535d8a/ds4drv/backends/bluetooth.py#L99-L114 | def scan(self):
"""Scan for bluetooth devices."""
try:
res = subprocess.check_output(["hcitool", "scan", "--flush"],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
raise BackendError("'hcitool scan' returned erro... | [
"def",
"scan",
"(",
"self",
")",
":",
"try",
":",
"res",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"hcitool\"",
",",
"\"scan\"",
",",
"\"--flush\"",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"except",
"subprocess",
".",
"Called... | Scan for bluetooth devices. | [
"Scan",
"for",
"bluetooth",
"devices",
"."
] | python | train |
schneiderfelipe/pyrrole | pyrrole/drawing.py | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L24-L78 | def _longest_common_subsequence(x, y):
"""
Return the longest common subsequence between two sequences.
Parameters
----------
x, y : sequence
Returns
-------
sequence
Longest common subsequence of x and y.
Examples
--------
>>> _longest_common_subsequence("AGGTAB",... | [
"def",
"_longest_common_subsequence",
"(",
"x",
",",
"y",
")",
":",
"m",
"=",
"len",
"(",
"x",
")",
"n",
"=",
"len",
"(",
"y",
")",
"# L[i, j] will contain the length of the longest common subsequence of",
"# x[0..i - 1] and y[0..j - 1].",
"L",
"=",
"_np",
".",
"z... | Return the longest common subsequence between two sequences.
Parameters
----------
x, y : sequence
Returns
-------
sequence
Longest common subsequence of x and y.
Examples
--------
>>> _longest_common_subsequence("AGGTAB", "GXTXAYB")
['G', 'T', 'A', 'B']
>>> _longe... | [
"Return",
"the",
"longest",
"common",
"subsequence",
"between",
"two",
"sequences",
"."
] | python | train |
pantsbuild/pants | src/python/pants/base/payload.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/payload.py#L136-L145 | def mark_dirty(self):
"""Invalidates memoized fingerprints for this payload.
Exposed for testing.
:API: public
"""
self._fingerprint_memo_map = {}
for field in self._fields.values():
field.mark_dirty() | [
"def",
"mark_dirty",
"(",
"self",
")",
":",
"self",
".",
"_fingerprint_memo_map",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"_fields",
".",
"values",
"(",
")",
":",
"field",
".",
"mark_dirty",
"(",
")"
] | Invalidates memoized fingerprints for this payload.
Exposed for testing.
:API: public | [
"Invalidates",
"memoized",
"fingerprints",
"for",
"this",
"payload",
"."
] | python | train |
quantopian/zipline | zipline/pipeline/loaders/blaze/core.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L881-L913 | def register_column(self,
column,
expr,
deltas=None,
checkpoints=None,
odo_kwargs=None):
"""Explicitly map a single bound column to a collection of blaze
expressions. The expressions n... | [
"def",
"register_column",
"(",
"self",
",",
"column",
",",
"expr",
",",
"deltas",
"=",
"None",
",",
"checkpoints",
"=",
"None",
",",
"odo_kwargs",
"=",
"None",
")",
":",
"self",
".",
"_table_expressions",
"[",
"column",
"]",
"=",
"ExprData",
"(",
"expr",... | Explicitly map a single bound column to a collection of blaze
expressions. The expressions need to have ``timestamp`` and ``as_of``
columns.
Parameters
----------
column : BoundColumn
The pipeline dataset to map to the given expressions.
expr : Expr
... | [
"Explicitly",
"map",
"a",
"single",
"bound",
"column",
"to",
"a",
"collection",
"of",
"blaze",
"expressions",
".",
"The",
"expressions",
"need",
"to",
"have",
"timestamp",
"and",
"as_of",
"columns",
"."
] | python | train |
odlgroup/odl | odl/contrib/tomo/elekta.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/tomo/elekta.py#L334-L369 | def elekta_xvi_fbp(ray_transform,
padding=False, filter_type='Hann', frequency_scaling=0.6):
"""Approximation of the FDK reconstruction used in the Elekta XVI.
Parameters
----------
ray_transform : `RayTransform`
The ray transform to be used, should have an Elekta XVI geometr... | [
"def",
"elekta_xvi_fbp",
"(",
"ray_transform",
",",
"padding",
"=",
"False",
",",
"filter_type",
"=",
"'Hann'",
",",
"frequency_scaling",
"=",
"0.6",
")",
":",
"fbp_op",
"=",
"odl",
".",
"tomo",
".",
"fbp_op",
"(",
"ray_transform",
",",
"padding",
"=",
"pa... | Approximation of the FDK reconstruction used in the Elekta XVI.
Parameters
----------
ray_transform : `RayTransform`
The ray transform to be used, should have an Elekta XVI geometry.
padding : bool, optional
Whether the FBP filter should use padding, increases memory use
signifi... | [
"Approximation",
"of",
"the",
"FDK",
"reconstruction",
"used",
"in",
"the",
"Elekta",
"XVI",
"."
] | python | train |
fitnr/convertdate | convertdate/mayan.py | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/mayan.py#L197-L206 | def next_tzolkin(tzolkin, jd):
'''For a given tzolk'in day, and a julian day count, find the next occurrance of that tzolk'in after the date'''
if jd < EPOCH:
raise IndexError("Input day is before Mayan epoch.")
count1 = _tzolkin_count(*to_tzolkin(jd))
count2 = _tzolkin_count(*tzolkin)
add... | [
"def",
"next_tzolkin",
"(",
"tzolkin",
",",
"jd",
")",
":",
"if",
"jd",
"<",
"EPOCH",
":",
"raise",
"IndexError",
"(",
"\"Input day is before Mayan epoch.\"",
")",
"count1",
"=",
"_tzolkin_count",
"(",
"*",
"to_tzolkin",
"(",
"jd",
")",
")",
"count2",
"=",
... | For a given tzolk'in day, and a julian day count, find the next occurrance of that tzolk'in after the date | [
"For",
"a",
"given",
"tzolk",
"in",
"day",
"and",
"a",
"julian",
"day",
"count",
"find",
"the",
"next",
"occurrance",
"of",
"that",
"tzolk",
"in",
"after",
"the",
"date"
] | python | train |
pgmpy/pgmpy | pgmpy/readwrite/ProbModelXML.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/ProbModelXML.py#L370-L376 | def _add_additional_properties(position, properties_dict):
"""
Sets AdditionalProperties of the ProbModelXML.
"""
add_prop = etree.SubElement(position, 'AdditionalProperties')
for key, value in properties_dict.items():
etree.SubElement(add_prop, 'Property', attrib={'n... | [
"def",
"_add_additional_properties",
"(",
"position",
",",
"properties_dict",
")",
":",
"add_prop",
"=",
"etree",
".",
"SubElement",
"(",
"position",
",",
"'AdditionalProperties'",
")",
"for",
"key",
",",
"value",
"in",
"properties_dict",
".",
"items",
"(",
")",... | Sets AdditionalProperties of the ProbModelXML. | [
"Sets",
"AdditionalProperties",
"of",
"the",
"ProbModelXML",
"."
] | python | train |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L579-L589 | def _escapeText(text):
""" Adds backslash-escapes to property value characters that need them."""
output = ""
index = 0
match = reCharsToEscape.search(text, index)
while match:
output = output + text[index:match.start()] + '\\' + text[match.start()]
index = match.end()
match = reCharsToEscape.search(text, in... | [
"def",
"_escapeText",
"(",
"text",
")",
":",
"output",
"=",
"\"\"",
"index",
"=",
"0",
"match",
"=",
"reCharsToEscape",
".",
"search",
"(",
"text",
",",
"index",
")",
"while",
"match",
":",
"output",
"=",
"output",
"+",
"text",
"[",
"index",
":",
"ma... | Adds backslash-escapes to property value characters that need them. | [
"Adds",
"backslash",
"-",
"escapes",
"to",
"property",
"value",
"characters",
"that",
"need",
"them",
"."
] | python | train |
angr/angr | angr/knowledge_plugins/functions/function_manager.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/knowledge_plugins/functions/function_manager.py#L91-L100 | def _genenare_callmap_sif(self, filepath):
"""
Generate a sif file from the call map.
:param filepath: Path of the sif file
:return: None
"""
with open(filepath, "wb") as f:
for src, dst in self.callgraph.edges():
f.write("%#x\tD... | [
"def",
"_genenare_callmap_sif",
"(",
"self",
",",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"\"wb\"",
")",
"as",
"f",
":",
"for",
"src",
",",
"dst",
"in",
"self",
".",
"callgraph",
".",
"edges",
"(",
")",
":",
"f",
".",
"write",
"... | Generate a sif file from the call map.
:param filepath: Path of the sif file
:return: None | [
"Generate",
"a",
"sif",
"file",
"from",
"the",
"call",
"map",
"."
] | python | train |
project-rig/rig | rig/scripts/rig_counters.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/scripts/rig_counters.py#L78-L101 | def press_enter(multiple=False, silent=False):
"""Return a generator function which yields every time the user presses
return."""
def f():
try:
while True:
if silent:
yield input()
else:
sys.stderr.write("<press ent... | [
"def",
"press_enter",
"(",
"multiple",
"=",
"False",
",",
"silent",
"=",
"False",
")",
":",
"def",
"f",
"(",
")",
":",
"try",
":",
"while",
"True",
":",
"if",
"silent",
":",
"yield",
"input",
"(",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"wri... | Return a generator function which yields every time the user presses
return. | [
"Return",
"a",
"generator",
"function",
"which",
"yields",
"every",
"time",
"the",
"user",
"presses",
"return",
"."
] | python | train |
CalebBell/thermo | thermo/vapor_pressure.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/vapor_pressure.py#L669-L717 | def boiling_critical_relation(T, Tb, Tc, Pc):
r'''Calculates vapor pressure of a fluid at arbitrary temperatures using a
CSP relationship as in [1]_; requires a chemical's critical temperature
and pressure as well as boiling point.
The vapor pressure is given by:
.. math::
\ln P^{sat}_r = ... | [
"def",
"boiling_critical_relation",
"(",
"T",
",",
"Tb",
",",
"Tc",
",",
"Pc",
")",
":",
"Tbr",
"=",
"Tb",
"/",
"Tc",
"Tr",
"=",
"T",
"/",
"Tc",
"h",
"=",
"Tbr",
"*",
"log",
"(",
"Pc",
"/",
"101325.",
")",
"/",
"(",
"1",
"-",
"Tbr",
")",
"r... | r'''Calculates vapor pressure of a fluid at arbitrary temperatures using a
CSP relationship as in [1]_; requires a chemical's critical temperature
and pressure as well as boiling point.
The vapor pressure is given by:
.. math::
\ln P^{sat}_r = h\left( 1 - \frac{1}{T_r}\right)
h = T_{b... | [
"r",
"Calculates",
"vapor",
"pressure",
"of",
"a",
"fluid",
"at",
"arbitrary",
"temperatures",
"using",
"a",
"CSP",
"relationship",
"as",
"in",
"[",
"1",
"]",
"_",
";",
"requires",
"a",
"chemical",
"s",
"critical",
"temperature",
"and",
"pressure",
"as",
"... | python | valid |
waqasbhatti/astrobase | astrobase/hatsurveys/hatlc.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L456-L479 | def _pyuncompress_sqlitecurve(sqlitecurve, force=False):
'''This just uncompresses the sqlitecurve. Should be independent of OS.
'''
outfile = sqlitecurve.replace('.gz','')
try:
if os.path.exists(outfile) and not force:
return outfile
else:
with gzip.open(sq... | [
"def",
"_pyuncompress_sqlitecurve",
"(",
"sqlitecurve",
",",
"force",
"=",
"False",
")",
":",
"outfile",
"=",
"sqlitecurve",
".",
"replace",
"(",
"'.gz'",
",",
"''",
")",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"outfile",
")",
"and",
"... | This just uncompresses the sqlitecurve. Should be independent of OS. | [
"This",
"just",
"uncompresses",
"the",
"sqlitecurve",
".",
"Should",
"be",
"independent",
"of",
"OS",
"."
] | python | valid |
nocarryr/python-dispatch | pydispatch/utils.py | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/utils.py#L61-L73 | def del_method(self, m):
"""Remove an instance method or function if it exists
Args:
m: The instance method or function to remove
"""
if isinstance(m, types.FunctionType) and not iscoroutinefunction(m):
wrkey = ('function', id(m))
else:
f, obj... | [
"def",
"del_method",
"(",
"self",
",",
"m",
")",
":",
"if",
"isinstance",
"(",
"m",
",",
"types",
".",
"FunctionType",
")",
"and",
"not",
"iscoroutinefunction",
"(",
"m",
")",
":",
"wrkey",
"=",
"(",
"'function'",
",",
"id",
"(",
"m",
")",
")",
"el... | Remove an instance method or function if it exists
Args:
m: The instance method or function to remove | [
"Remove",
"an",
"instance",
"method",
"or",
"function",
"if",
"it",
"exists"
] | python | train |
svenevs/exhale | exhale/graph.py | https://github.com/svenevs/exhale/blob/fe7644829057af622e467bb529db6c03a830da99/exhale/graph.py#L2419-L2657 | def generateSingleNodeRST(self, node):
'''
Creates the reStructuredText document for the leaf like node object.
It is **assumed** that the specified ``node.kind`` is in
:data:`~exhale.utils.LEAF_LIKE_KINDS`. File, directory, and namespace nodes are
treated separately.
... | [
"def",
"generateSingleNodeRST",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"with",
"codecs",
".",
"open",
"(",
"node",
".",
"file_name",
",",
"\"w\"",
",",
"\"utf-8\"",
")",
"as",
"gen_file",
":",
"#############################################################... | Creates the reStructuredText document for the leaf like node object.
It is **assumed** that the specified ``node.kind`` is in
:data:`~exhale.utils.LEAF_LIKE_KINDS`. File, directory, and namespace nodes are
treated separately.
:Parameters:
``node`` (ExhaleNode)
... | [
"Creates",
"the",
"reStructuredText",
"document",
"for",
"the",
"leaf",
"like",
"node",
"object",
"."
] | python | train |
UCL-INGI/INGInious | base-containers/base/inginious/feedback.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L79-L86 | def set_problem_feedback(feedback, problem_id, append=False):
""" Set problem specific feedback """
rdict = load_feedback()
if not 'problems' in rdict:
rdict['problems'] = {}
cur_val = rdict['problems'].get(problem_id, '')
rdict['problems'][problem_id] = (cur_val + feedback if append else fe... | [
"def",
"set_problem_feedback",
"(",
"feedback",
",",
"problem_id",
",",
"append",
"=",
"False",
")",
":",
"rdict",
"=",
"load_feedback",
"(",
")",
"if",
"not",
"'problems'",
"in",
"rdict",
":",
"rdict",
"[",
"'problems'",
"]",
"=",
"{",
"}",
"cur_val",
"... | Set problem specific feedback | [
"Set",
"problem",
"specific",
"feedback"
] | python | train |
LuminosoInsight/luminoso-api-client-python | luminoso_api/v4_client.py | https://github.com/LuminosoInsight/luminoso-api-client-python/blob/3bedf2a454aee39214c11fbf556ead3eecc27881/luminoso_api/v4_client.py#L389-L403 | def _get_default_account(self):
"""
Get the ID of an account you can use to access projects.
"""
newclient = self.__class__(self.session, self.root_url)
account_info = newclient.get('/accounts/')
if account_info['default_account'] is not None:
return account_i... | [
"def",
"_get_default_account",
"(",
"self",
")",
":",
"newclient",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"session",
",",
"self",
".",
"root_url",
")",
"account_info",
"=",
"newclient",
".",
"get",
"(",
"'/accounts/'",
")",
"if",
"account_info",
... | Get the ID of an account you can use to access projects. | [
"Get",
"the",
"ID",
"of",
"an",
"account",
"you",
"can",
"use",
"to",
"access",
"projects",
"."
] | python | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.