repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
sv0/django-markdown-app | django_markdown/views.py | https://github.com/sv0/django-markdown-app/blob/973968c68d79cbe35304e9d6da876ad33f427d2d/django_markdown/views.py#L7-L23 | def preview(request):
""" Render preview page.
:returns: A rendered preview
"""
if settings.MARKDOWN_PROTECT_PREVIEW:
user = getattr(request, 'user', None)
if not user or not user.is_staff:
from django.contrib.auth.views import redirect_to_login
return redirect_... | [
"def",
"preview",
"(",
"request",
")",
":",
"if",
"settings",
".",
"MARKDOWN_PROTECT_PREVIEW",
":",
"user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"if",
"not",
"user",
"or",
"not",
"user",
".",
"is_staff",
":",
"from",
"django",... | Render preview page.
:returns: A rendered preview | [
"Render",
"preview",
"page",
"."
] | python | train | 31.411765 |
AlexandreDecan/python-intervals | intervals.py | https://github.com/AlexandreDecan/python-intervals/blob/eda4da7dd39afabab2c1689e0b5158abae08c831/intervals.py#L825-L848 | def overlaps(self, other, permissive=False):
"""
Test if intervals have any overlapping value.
If 'permissive' is set to True (default is False), then intervals that are contiguous
are considered as overlapping intervals as well (e.g. [1, 2) and [2, 3],
but not [1, 2) and (2, ... | [
"def",
"overlaps",
"(",
"self",
",",
"other",
",",
"permissive",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"AtomicInterval",
")",
":",
"for",
"interval",
"in",
"self",
".",
"_intervals",
":",
"if",
"interval",
".",
"overlaps",
"(",
... | Test if intervals have any overlapping value.
If 'permissive' is set to True (default is False), then intervals that are contiguous
are considered as overlapping intervals as well (e.g. [1, 2) and [2, 3],
but not [1, 2) and (2, 3] because 2 is not part of their union).
:param other:... | [
"Test",
"if",
"intervals",
"have",
"any",
"overlapping",
"value",
"."
] | python | train | 44.916667 |
zhelev/python-afsapi | afsapi/__init__.py | https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L262-L270 | def set_mode(self, value):
"""Set the currently active mode on the device (DAB, FM, Spotify)."""
mode = -1
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['label'] == value:
mode = temp_mode['band']
return (yield from self.han... | [
"def",
"set_mode",
"(",
"self",
",",
"value",
")",
":",
"mode",
"=",
"-",
"1",
"modes",
"=",
"yield",
"from",
"self",
".",
"get_modes",
"(",
")",
"for",
"temp_mode",
"in",
"modes",
":",
"if",
"temp_mode",
"[",
"'label'",
"]",
"==",
"value",
":",
"m... | Set the currently active mode on the device (DAB, FM, Spotify). | [
"Set",
"the",
"currently",
"active",
"mode",
"on",
"the",
"device",
"(",
"DAB",
"FM",
"Spotify",
")",
"."
] | python | valid | 38.666667 |
python-openxml/python-docx | docx/image/jpeg.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/image/jpeg.py#L118-L125 | def app0(self):
"""
First APP0 marker in image markers.
"""
for m in self._markers:
if m.marker_code == JPEG_MARKER_CODE.APP0:
return m
raise KeyError('no APP0 marker in image') | [
"def",
"app0",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"_markers",
":",
"if",
"m",
".",
"marker_code",
"==",
"JPEG_MARKER_CODE",
".",
"APP0",
":",
"return",
"m",
"raise",
"KeyError",
"(",
"'no APP0 marker in image'",
")"
] | First APP0 marker in image markers. | [
"First",
"APP0",
"marker",
"in",
"image",
"markers",
"."
] | python | train | 29.75 |
johnwmillr/LyricsGenius | lyricsgenius/api.py | https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L104-L107 | def get_annotation(self, id_):
"""Data for a specific annotation."""
endpoint = "annotations/{id}".format(id=id_)
return self._make_request(endpoint) | [
"def",
"get_annotation",
"(",
"self",
",",
"id_",
")",
":",
"endpoint",
"=",
"\"annotations/{id}\"",
".",
"format",
"(",
"id",
"=",
"id_",
")",
"return",
"self",
".",
"_make_request",
"(",
"endpoint",
")"
] | Data for a specific annotation. | [
"Data",
"for",
"a",
"specific",
"annotation",
"."
] | python | train | 42.5 |
lltk/lltk | lltk/textsamples/tatoeba.py | https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/textsamples/tatoeba.py#L8-L18 | def tatoeba(language, word, minlength = 10, maxlength = 100):
''' Returns a list of suitable textsamples for a given word using Tatoeba.org. '''
word, sentences = unicode(word), []
page = requests.get('http://tatoeba.org/deu/sentences/search?query=%s&from=%s&to=und' % (word, lltk.locale.iso639_1to3(language)))
tre... | [
"def",
"tatoeba",
"(",
"language",
",",
"word",
",",
"minlength",
"=",
"10",
",",
"maxlength",
"=",
"100",
")",
":",
"word",
",",
"sentences",
"=",
"unicode",
"(",
"word",
")",
",",
"[",
"]",
"page",
"=",
"requests",
".",
"get",
"(",
"'http://tatoeba... | Returns a list of suitable textsamples for a given word using Tatoeba.org. | [
"Returns",
"a",
"list",
"of",
"suitable",
"textsamples",
"for",
"a",
"given",
"word",
"using",
"Tatoeba",
".",
"org",
"."
] | python | train | 61.545455 |
genialis/resolwe | resolwe/flow/expression_engines/jinja/__init__.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/expression_engines/jinja/__init__.py#L115-L129 | def _wrap_jinja_filter(self, function):
"""Propagate exceptions as undefined values filter."""
def wrapper(*args, **kwargs):
"""Filter wrapper."""
try:
return function(*args, **kwargs)
except Exception: # pylint: disable=broad-except
r... | [
"def",
"_wrap_jinja_filter",
"(",
"self",
",",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Filter wrapper.\"\"\"",
"try",
":",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
... | Propagate exceptions as undefined values filter. | [
"Propagate",
"exceptions",
"as",
"undefined",
"values",
"filter",
"."
] | python | train | 37.933333 |
awslabs/sockeye | sockeye_contrib/autopilot/autopilot.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye_contrib/autopilot/autopilot.py#L319-L325 | def renew_step_dir(step_dir: str):
"""Delete step directory if exists and create, reporting actions."""
if os.path.exists(step_dir):
logging.info("Remove unfinished step %s", step_dir)
shutil.rmtree(step_dir)
logging.info("Create: %s", step_dir)
os.makedirs(step_dir) | [
"def",
"renew_step_dir",
"(",
"step_dir",
":",
"str",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"step_dir",
")",
":",
"logging",
".",
"info",
"(",
"\"Remove unfinished step %s\"",
",",
"step_dir",
")",
"shutil",
".",
"rmtree",
"(",
"step_dir",... | Delete step directory if exists and create, reporting actions. | [
"Delete",
"step",
"directory",
"if",
"exists",
"and",
"create",
"reporting",
"actions",
"."
] | python | train | 41.857143 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_profile.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L295-L311 | def root_directory(self):
"""Map the root directory to user profile/inasafe so the minimum needs
profile will be placed there (user profile/inasafe/minimum_needs).
:returns: root directory
:rtype: QString
"""
if not QgsApplication.qgisSettingsDirPath() or (
... | [
"def",
"root_directory",
"(",
"self",
")",
":",
"if",
"not",
"QgsApplication",
".",
"qgisSettingsDirPath",
"(",
")",
"or",
"(",
"QgsApplication",
".",
"qgisSettingsDirPath",
"(",
")",
"==",
"''",
")",
":",
"self",
".",
"_root_directory",
"=",
"None",
"else",... | Map the root directory to user profile/inasafe so the minimum needs
profile will be placed there (user profile/inasafe/minimum_needs).
:returns: root directory
:rtype: QString | [
"Map",
"the",
"root",
"directory",
"to",
"user",
"profile",
"/",
"inasafe",
"so",
"the",
"minimum",
"needs",
"profile",
"will",
"be",
"placed",
"there",
"(",
"user",
"profile",
"/",
"inasafe",
"/",
"minimum_needs",
")",
"."
] | python | train | 36.294118 |
hydraplatform/hydra-base | hydra_base/lib/template.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1988-L2091 | def get_network_as_xml_template(network_id,**kwargs):
"""
Turn an existing network into an xml template
using its attributes.
If an optional scenario ID is passed in, default
values will be populated from that scenario.
"""
template_xml = etree.Element("template_definition")
... | [
"def",
"get_network_as_xml_template",
"(",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"template_xml",
"=",
"etree",
".",
"Element",
"(",
"\"template_definition\"",
")",
"net_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Network",
")",
".",
"filt... | Turn an existing network into an xml template
using its attributes.
If an optional scenario ID is passed in, default
values will be populated from that scenario. | [
"Turn",
"an",
"existing",
"network",
"into",
"an",
"xml",
"template",
"using",
"its",
"attributes",
".",
"If",
"an",
"optional",
"scenario",
"ID",
"is",
"passed",
"in",
"default",
"values",
"will",
"be",
"populated",
"from",
"that",
"scenario",
"."
] | python | train | 36.471154 |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L591-L609 | def board_name(default):
"""Returns the boards name (if available)."""
try:
import board
try:
name = board.name
except AttributeError:
# There was a board.py file, but it didn't have an name attribute
# We also ignore this as an error
name ... | [
"def",
"board_name",
"(",
"default",
")",
":",
"try",
":",
"import",
"board",
"try",
":",
"name",
"=",
"board",
".",
"name",
"except",
"AttributeError",
":",
"# There was a board.py file, but it didn't have an name attribute",
"# We also ignore this as an error",
"name",
... | Returns the boards name (if available). | [
"Returns",
"the",
"boards",
"name",
"(",
"if",
"available",
")",
"."
] | python | train | 31.526316 |
mar10/wsgidav | wsgidav/server/ext_wsgiutils_server.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/ext_wsgiutils_server.py#L369-L381 | def serve_forever_stoppable(self):
"""Handle one request at a time until stop_serve_forever().
http://code.activestate.com/recipes/336012/
"""
self.stop_request = False
self.stopped = False
while not self.stop_request:
self.handle_request()
# ... | [
"def",
"serve_forever_stoppable",
"(",
"self",
")",
":",
"self",
".",
"stop_request",
"=",
"False",
"self",
".",
"stopped",
"=",
"False",
"while",
"not",
"self",
".",
"stop_request",
":",
"self",
".",
"handle_request",
"(",
")",
"# _logger.info \"serve_fo... | Handle one request at a time until stop_serve_forever().
http://code.activestate.com/recipes/336012/ | [
"Handle",
"one",
"request",
"at",
"a",
"time",
"until",
"stop_serve_forever",
"()",
"."
] | python | valid | 29.692308 |
marrow/cinje | cinje/inline/text.py | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L112-L162 | def process(self, context, lines):
"""Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting li... | [
"def",
"process",
"(",
"self",
",",
"context",
",",
"lines",
")",
":",
"handler",
"=",
"None",
"for",
"line",
"in",
"lines",
":",
"for",
"chunk",
"in",
"chunk_",
"(",
"line",
")",
":",
"if",
"'strip'",
"in",
"context",
".",
"flag",
":",
"chunk",
".... | Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting lines while accepting
sent chunks. Defer... | [
"Chop",
"up",
"individual",
"lines",
"into",
"static",
"and",
"dynamic",
"parts",
".",
"Applies",
"light",
"optimizations",
"such",
"as",
"empty",
"chunk",
"removal",
"and",
"calls",
"out",
"to",
"other",
"methods",
"to",
"process",
"different",
"chunk",
"type... | python | train | 30.921569 |
zeth/inputs | inputs.py | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2953-L2964 | def __get_vibration_code(self, left_motor, right_motor, duration):
"""This is some crazy voodoo, if you can simplify it, please do."""
inner_event = struct.pack(
'2h6x2h2x2H28x',
0x50,
-1,
duration,
0,
int(left_motor * 65535),
... | [
"def",
"__get_vibration_code",
"(",
"self",
",",
"left_motor",
",",
"right_motor",
",",
"duration",
")",
":",
"inner_event",
"=",
"struct",
".",
"pack",
"(",
"'2h6x2h2x2H28x'",
",",
"0x50",
",",
"-",
"1",
",",
"duration",
",",
"0",
",",
"int",
"(",
"left... | This is some crazy voodoo, if you can simplify it, please do. | [
"This",
"is",
"some",
"crazy",
"voodoo",
"if",
"you",
"can",
"simplify",
"it",
"please",
"do",
"."
] | python | train | 39.416667 |
ajenhl/tacl | tacl/results.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L1005-L1036 | def zero_fill(self, corpus):
"""Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appearing in the results
... | [
"def",
"zero_fill",
"(",
"self",
",",
"corpus",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Zero-filling results'",
")",
"zero_rows",
"=",
"[",
"]",
"work_sigla",
"=",
"{",
"}",
"grouping_cols",
"=",
"[",
"constants",
".",
"LABEL_FIELDNAME",
",",... | Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appearing in the results
:type corpus: `Corpus` | [
"Adds",
"rows",
"to",
"the",
"results",
"to",
"ensure",
"that",
"for",
"every",
"n",
"-",
"gram",
"that",
"is",
"attested",
"in",
"at",
"least",
"one",
"witness",
"every",
"witness",
"for",
"that",
"text",
"has",
"a",
"row",
"with",
"added",
"rows",
"h... | python | train | 47.40625 |
pyroscope/pyrocore | src/pyrocore/scripts/rtcontrol.py | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L421-L436 | def get_output_fields(self):
""" Get field names from output template.
"""
# Re-engineer list from output format
# XXX TODO: Would be better to use a FieldRecorder class to catch the full field names
emit_fields = list(i.lower() for i in re.sub(r"[^_A-Z]+", ' ', self.format_item(... | [
"def",
"get_output_fields",
"(",
"self",
")",
":",
"# Re-engineer list from output format",
"# XXX TODO: Would be better to use a FieldRecorder class to catch the full field names",
"emit_fields",
"=",
"list",
"(",
"i",
".",
"lower",
"(",
")",
"for",
"i",
"in",
"re",
".",
... | Get field names from output template. | [
"Get",
"field",
"names",
"from",
"output",
"template",
"."
] | python | train | 40.375 |
lepture/flask-oauthlib | flask_oauthlib/provider/oauth2.py | https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L966-L982 | def validate_refresh_token(self, refresh_token, client, request,
*args, **kwargs):
"""Ensure the token is valid and belongs to the client
This method is used by the authorization code grant indirectly by
issuing refresh tokens, resource owner password credentials ... | [
"def",
"validate_refresh_token",
"(",
"self",
",",
"refresh_token",
",",
"client",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"token",
"=",
"self",
".",
"_tokengetter",
"(",
"refresh_token",
"=",
"refresh_token",
")",
"if",
"token... | Ensure the token is valid and belongs to the client
This method is used by the authorization code grant indirectly by
issuing refresh tokens, resource owner password credentials grant
(also indirectly) and the refresh token grant. | [
"Ensure",
"the",
"token",
"is",
"valid",
"and",
"belongs",
"to",
"the",
"client"
] | python | test | 41.235294 |
hozn/coilmq | coilmq/topic.py | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/topic.py#L81-L96 | def unsubscribe(self, connection, destination):
"""
Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/top... | [
"def",
"unsubscribe",
"(",
"self",
",",
"connection",
",",
"destination",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Unsubscribing %s from %s\"",
"%",
"(",
"connection",
",",
"destination",
")",
")",
"if",
"connection",
"in",
"self",
".",
"_topics",... | Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | [
"Unsubscribes",
"a",
"connection",
"from",
"the",
"specified",
"topic",
"destination",
"."
] | python | train | 39.5625 |
intel-analytics/BigDL | pyspark/bigdl/dlframes/dl_image_reader.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/dlframes/dl_image_reader.py#L31-L42 | def readImages(path, sc=None, minParitions = 1, bigdl_type="float"):
"""
Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are sup... | [
"def",
"readImages",
"(",
"path",
",",
"sc",
"=",
"None",
",",
"minParitions",
"=",
"1",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"df",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"dlReadImage\"",
",",
"path",
",",
"sc",
",",
"minParitions",
")... | Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are supported similarly to sc.binaryFiles(path).
:param min_partitions A suggestion valu... | [
"Read",
"the",
"directory",
"of",
"images",
"into",
"DataFrame",
"from",
"the",
"local",
"or",
"remote",
"source",
".",
":",
"param",
"path",
"Directory",
"to",
"the",
"input",
"data",
"files",
"the",
"path",
"can",
"be",
"comma",
"separated",
"paths",
"as... | python | test | 63.5 |
openstack/networking-arista | networking_arista/ml2/security_groups/security_group_sync.py | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/security_groups/security_group_sync.py#L90-L107 | def synchronize(self):
"""Perform sync of the security groups between ML2 and EOS."""
# Get expected ACLs and rules
expected_acls = self.get_expected_acls()
# Get expected interface to ACL mappings
all_expected_bindings = self.get_expected_bindings()
# Check that confi... | [
"def",
"synchronize",
"(",
"self",
")",
":",
"# Get expected ACLs and rules",
"expected_acls",
"=",
"self",
".",
"get_expected_acls",
"(",
")",
"# Get expected interface to ACL mappings",
"all_expected_bindings",
"=",
"self",
".",
"get_expected_bindings",
"(",
")",
"# Che... | Perform sync of the security groups between ML2 and EOS. | [
"Perform",
"sync",
"of",
"the",
"security",
"groups",
"between",
"ML2",
"and",
"EOS",
"."
] | python | train | 41.944444 |
BlueBrain/NeuroM | neurom/fst/_neuritefunc.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L74-L76 | def n_forking_points(neurites, neurite_type=NeuriteType.all):
'''number of forking points in a collection of neurites'''
return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.iforking_point) | [
"def",
"n_forking_points",
"(",
"neurites",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"return",
"n_sections",
"(",
"neurites",
",",
"neurite_type",
"=",
"neurite_type",
",",
"iterator_type",
"=",
"Tree",
".",
"iforking_point",
")"
] | number of forking points in a collection of neurites | [
"number",
"of",
"forking",
"points",
"in",
"a",
"collection",
"of",
"neurites"
] | python | train | 72 |
eandersson/amqpstorm | amqpstorm/channel0.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/channel0.py#L168-L188 | def _send_tune_ok(self, frame_in):
"""Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune frame.
:return:
"""
self.max_allowed_channels = self._negotiate(frame_in.channel_max,
MAX_CHANNELS)
self.max... | [
"def",
"_send_tune_ok",
"(",
"self",
",",
"frame_in",
")",
":",
"self",
".",
"max_allowed_channels",
"=",
"self",
".",
"_negotiate",
"(",
"frame_in",
".",
"channel_max",
",",
"MAX_CHANNELS",
")",
"self",
".",
"max_frame_size",
"=",
"self",
".",
"_negotiate",
... | Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune frame.
:return: | [
"Send",
"Tune",
"OK",
"frame",
"."
] | python | train | 37.857143 |
rlabbe/filterpy | filterpy/stats/stats.py | https://github.com/rlabbe/filterpy/blob/8123214de798ffb63db968bb0b9492ee74e77950/filterpy/stats/stats.py#L399-L454 | def multivariate_multiply(m1, c1, m2, c2):
"""
Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
... | [
"def",
"multivariate_multiply",
"(",
"m1",
",",
"c1",
",",
"m2",
",",
"c2",
")",
":",
"C1",
"=",
"np",
".",
"asarray",
"(",
"c1",
")",
"C2",
"=",
"np",
".",
"asarray",
"(",
"c2",
")",
"M1",
"=",
"np",
".",
"asarray",
"(",
"m1",
")",
"M2",
"="... | Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
[3.2, 0], [[8.0, 1.1], [1.1,8.0]])
Pa... | [
"Multiplies",
"the",
"two",
"multivariate",
"Gaussians",
"together",
"and",
"returns",
"the",
"results",
"as",
"the",
"tuple",
"(",
"mean",
"covariance",
")",
"."
] | python | train | 24.5 |
cebel/pyuniprot | src/pyuniprot/manager/query.py | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/query.py#L135-L171 | def keyword(self, name=None, identifier=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.Keyword` objects in database
:param name: keyword name(s)
:type name: str or tuple(str) or None
:param identifier: keyword identifier(s)
:type identifier:... | [
"def",
"keyword",
"(",
"self",
",",
"name",
"=",
"None",
",",
"identifier",
"=",
"None",
",",
"entry_name",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"as_df",
"=",
"False",
")",
":",
"q",
"=",
"self",
".",
"session",
".",
"query",
"(",
"models",... | Method to query :class:`.models.Keyword` objects in database
:param name: keyword name(s)
:type name: str or tuple(str) or None
:param identifier: keyword identifier(s)
:type identifier: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:ty... | [
"Method",
"to",
"query",
":",
"class",
":",
".",
"models",
".",
"Keyword",
"objects",
"in",
"database"
] | python | train | 38.432432 |
googlefonts/fontbakery | Lib/fontbakery/reporters/__init__.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/__init__.py#L45-L50 | def run(self, order=None):
"""
self.runner must be present
"""
for event in self.runner.run(order=order):
self.receive(event) | [
"def",
"run",
"(",
"self",
",",
"order",
"=",
"None",
")",
":",
"for",
"event",
"in",
"self",
".",
"runner",
".",
"run",
"(",
"order",
"=",
"order",
")",
":",
"self",
".",
"receive",
"(",
"event",
")"
] | self.runner must be present | [
"self",
".",
"runner",
"must",
"be",
"present"
] | python | train | 23.666667 |
minhhoit/yacms | yacms/core/views.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L113-L136 | def search(request, template="search_results.html", extra_context=None):
"""
Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model.
"""
query = request.GET.get("q", "")
page = request.GET.get("page", 1)
... | [
"def",
"search",
"(",
"request",
",",
"template",
"=",
"\"search_results.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"query",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"q\"",
",",
"\"\"",
")",
"page",
"=",
"request",
".",
"GET",
".",
"ge... | Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model. | [
"Display",
"search",
"results",
".",
"Takes",
"an",
"optional",
"contenttype",
"GET",
"parameter",
"in",
"the",
"form",
"app",
"-",
"name",
".",
"ModelName",
"to",
"limit",
"search",
"results",
"to",
"a",
"single",
"model",
"."
] | python | train | 46.041667 |
tensorflow/tensor2tensor | tensor2tensor/models/image_transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L768-L775 | def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 256
return hparams | [
"def",
"imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_sep_channels_12l_16h_imagenet_large",
"(",
")",
"hparams",
".",
"num_hidden_layers",
"=",
"16",
"hparams",
".",
"local_attention",
"=",
"True",
"hparams",
".",
... | separate rgb embeddings. | [
"separate",
"rgb",
"embeddings",
"."
] | python | train | 36.125 |
fiesta/fiesta-python | fiesta/fiesta.py | https://github.com/fiesta/fiesta-python/blob/cfcc11e4ae4c76b1007794604c33dde877f62cfb/fiesta/fiesta.py#L111-L115 | def hello(self):
"""http://docs.fiesta.cc/index.html#getting-started"""
path = 'hello'
response = self.request(path, do_authentication=False)
return response | [
"def",
"hello",
"(",
"self",
")",
":",
"path",
"=",
"'hello'",
"response",
"=",
"self",
".",
"request",
"(",
"path",
",",
"do_authentication",
"=",
"False",
")",
"return",
"response"
] | http://docs.fiesta.cc/index.html#getting-started | [
"http",
":",
"//",
"docs",
".",
"fiesta",
".",
"cc",
"/",
"index",
".",
"html#getting",
"-",
"started"
] | python | train | 37 |
PGower/PyCanvas | pycanvas/apis/pages.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L562-L581 | def list_revisions_groups(self, url, group_id):
"""
List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
... | [
"def",
"list_revisions_groups",
"(",
"self",
",",
"url",
",",
"group_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"=",
"group_id",
... | List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history. | [
"List",
"revisions",
".",
"List",
"the",
"revisions",
"of",
"a",
"page",
".",
"Callers",
"must",
"have",
"update",
"rights",
"on",
"the",
"page",
"in",
"order",
"to",
"see",
"page",
"history",
"."
] | python | train | 37.75 |
expfactory/expfactory | expfactory/utils.py | https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/utils.py#L66-L74 | def find_subdirectories(basepath):
'''
Return directories (and sub) starting from a base
'''
directories = []
for root, dirnames, filenames in os.walk(basepath):
new_directories = [d for d in dirnames if d not in directories]
directories = directories + new_directories
return dir... | [
"def",
"find_subdirectories",
"(",
"basepath",
")",
":",
"directories",
"=",
"[",
"]",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"basepath",
")",
":",
"new_directories",
"=",
"[",
"d",
"for",
"d",
"in",
"dirnames",
... | Return directories (and sub) starting from a base | [
"Return",
"directories",
"(",
"and",
"sub",
")",
"starting",
"from",
"a",
"base"
] | python | train | 35.555556 |
RedFantom/ttkwidgets | ttkwidgets/color/colorsquare.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/color/colorsquare.py#L139-L158 | def get(self):
"""
Get selected color.
:return: color under cursor as a (RGB, HSV, HEX) tuple
"""
x = self.coords('cross_v')[0]
y = self.coords('cross_h')[1]
xp = min(x, self.bg.width() - 1)
yp = min(y, self.bg.height() - 1)
try:
r, g,... | [
"def",
"get",
"(",
"self",
")",
":",
"x",
"=",
"self",
".",
"coords",
"(",
"'cross_v'",
")",
"[",
"0",
"]",
"y",
"=",
"self",
".",
"coords",
"(",
"'cross_h'",
")",
"[",
"1",
"]",
"xp",
"=",
"min",
"(",
"x",
",",
"self",
".",
"bg",
".",
"wid... | Get selected color.
:return: color under cursor as a (RGB, HSV, HEX) tuple | [
"Get",
"selected",
"color",
"."
] | python | train | 35.15 |
pypa/pipenv | pipenv/patched/notpip/_vendor/ipaddress.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L810-L815 | def overlaps(self, other):
"""Tell if self is partly contained in other."""
return self.network_address in other or (
self.broadcast_address in other or (
other.network_address in self or (
other.broadcast_address in self))) | [
"def",
"overlaps",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"network_address",
"in",
"other",
"or",
"(",
"self",
".",
"broadcast_address",
"in",
"other",
"or",
"(",
"other",
".",
"network_address",
"in",
"self",
"or",
"(",
"other",
"."... | Tell if self is partly contained in other. | [
"Tell",
"if",
"self",
"is",
"partly",
"contained",
"in",
"other",
"."
] | python | train | 47.166667 |
stephenmcd/gnotty | gnotty/client.py | https://github.com/stephenmcd/gnotty/blob/bea3762dc9cbc3cb21a5ae7224091cf027273c40/gnotty/client.py#L137-L145 | def on_namreply(self, connection, event):
"""
Initial list of nicknames received - remove op/voice prefixes,
and send the list to the WebSocket.
"""
for nickname in event.arguments()[-1].split():
nickname = nickname.lstrip("@+")
self.nicknames[nickname] = ... | [
"def",
"on_namreply",
"(",
"self",
",",
"connection",
",",
"event",
")",
":",
"for",
"nickname",
"in",
"event",
".",
"arguments",
"(",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
")",
":",
"nickname",
"=",
"nickname",
".",
"lstrip",
"(",
"\"@+\"",
... | Initial list of nicknames received - remove op/voice prefixes,
and send the list to the WebSocket. | [
"Initial",
"list",
"of",
"nicknames",
"received",
"-",
"remove",
"op",
"/",
"voice",
"prefixes",
"and",
"send",
"the",
"list",
"to",
"the",
"WebSocket",
"."
] | python | train | 39.666667 |
pyros-dev/pyzmp | pyzmp/coprocess.py | https://github.com/pyros-dev/pyzmp/blob/fac0b719b25996ce94a80ca2118f3eba5779d53d/pyzmp/coprocess.py#L303-L342 | def start(self, timeout=None):
"""
Start child process
:param timeout: the maximum time to wait for child process to report it has actually started.
None waits until the context manager has been entered, but update might not have been called yet.
"""
# we lazily create o... | [
"def",
"start",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# we lazily create our process delegate (with same arguments)",
"if",
"self",
".",
"daemon",
":",
"daemonic",
"=",
"True",
"else",
":",
"daemonic",
"=",
"False",
"pargs",
"=",
"self",
".",
"_... | Start child process
:param timeout: the maximum time to wait for child process to report it has actually started.
None waits until the context manager has been entered, but update might not have been called yet. | [
"Start",
"child",
"process",
":",
"param",
"timeout",
":",
"the",
"maximum",
"time",
"to",
"wait",
"for",
"child",
"process",
"to",
"report",
"it",
"has",
"actually",
"started",
".",
"None",
"waits",
"until",
"the",
"context",
"manager",
"has",
"been",
"en... | python | train | 41.05 |
LEMS/pylems | lems/model/structure.py | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/structure.py#L41-L50 | def toxml(self):
"""
Exports this object into a LEMS XML object
"""
return '<With ' + \
(' instance="{0}"'.format(self.instance) if self.instance else '') +\
(' list="{0}"'.format(self.list) if self.list else '') + \
(' index="{0}"'.format(self.index) if se... | [
"def",
"toxml",
"(",
"self",
")",
":",
"return",
"'<With '",
"+",
"(",
"' instance=\"{0}\"'",
".",
"format",
"(",
"self",
".",
"instance",
")",
"if",
"self",
".",
"instance",
"else",
"''",
")",
"+",
"(",
"' list=\"{0}\"'",
".",
"format",
"(",
"self",
"... | Exports this object into a LEMS XML object | [
"Exports",
"this",
"object",
"into",
"a",
"LEMS",
"XML",
"object"
] | python | train | 38.8 |
ArabellaTech/django-basic-cms | basic_cms/admin/__init__.py | https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/admin/__init__.py#L193-L233 | def get_fieldsets(self, request, obj=None):
"""
Add fieldsets of placeholders to the list of already
existing fieldsets.
"""
# some ugly business to remove freeze_date
# from the field list
general_module = {
'fields': list(self.general_fields),
... | [
"def",
"get_fieldsets",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"# some ugly business to remove freeze_date",
"# from the field list",
"general_module",
"=",
"{",
"'fields'",
":",
"list",
"(",
"self",
".",
"general_fields",
")",
",",
"'clas... | Add fieldsets of placeholders to the list of already
existing fieldsets. | [
"Add",
"fieldsets",
"of",
"placeholders",
"to",
"the",
"list",
"of",
"already",
"existing",
"fieldsets",
"."
] | python | train | 35.536585 |
src-d/modelforge | modelforge/model.py | https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L403-L449 | def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None:
"""
Write the model to disk.
:param tree: The data dict - will be the ASDF tree.
:param output: The output file path or a file object.
:param file_mode: The output file's permissions.
... | [
"def",
"_write_tree",
"(",
"self",
",",
"tree",
":",
"dict",
",",
"output",
":",
"Union",
"[",
"str",
",",
"BinaryIO",
"]",
",",
"file_mode",
":",
"int",
"=",
"0o666",
")",
"->",
"None",
":",
"self",
".",
"meta",
"[",
"\"created_at\"",
"]",
"=",
"g... | Write the model to disk.
:param tree: The data dict - will be the ASDF tree.
:param output: The output file path or a file object.
:param file_mode: The output file's permissions.
:return: None | [
"Write",
"the",
"model",
"to",
"disk",
"."
] | python | train | 41.744681 |
saltstack/salt | salt/modules/dockermod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockermod.py#L1839-L1870 | def inspect_image(name):
'''
Retrieves image information. Equivalent to running the ``docker inspect``
Docker CLI command, but will only look for image information.
.. note::
To inspect an image, it must have been pulled from a registry or built
locally. Images on a Docker registry whic... | [
"def",
"inspect_image",
"(",
"name",
")",
":",
"ret",
"=",
"_client_wrapper",
"(",
"'inspect_image'",
",",
"name",
")",
"for",
"param",
"in",
"(",
"'Size'",
",",
"'VirtualSize'",
")",
":",
"if",
"param",
"in",
"ret",
":",
"ret",
"[",
"'{0}_Human'",
".",
... | Retrieves image information. Equivalent to running the ``docker inspect``
Docker CLI command, but will only look for image information.
.. note::
To inspect an image, it must have been pulled from a registry or built
locally. Images on a Docker registry which have not been pulled cannot
... | [
"Retrieves",
"image",
"information",
".",
"Equivalent",
"to",
"running",
"the",
"docker",
"inspect",
"Docker",
"CLI",
"command",
"but",
"will",
"only",
"look",
"for",
"image",
"information",
"."
] | python | train | 26.5 |
theonion/djes | djes/models.py | https://github.com/theonion/djes/blob/8f7347382c74172e82e959e3dfbc12b18fbb523f/djes/models.py#L124-L127 | def refresh(self):
"""Force a refresh of the Elasticsearch index
"""
self.client.indices.refresh(index=self.model.search_objects.mapping.index) | [
"def",
"refresh",
"(",
"self",
")",
":",
"self",
".",
"client",
".",
"indices",
".",
"refresh",
"(",
"index",
"=",
"self",
".",
"model",
".",
"search_objects",
".",
"mapping",
".",
"index",
")"
] | Force a refresh of the Elasticsearch index | [
"Force",
"a",
"refresh",
"of",
"the",
"Elasticsearch",
"index"
] | python | train | 41 |
gem/oq-engine | openquake/risklib/scientific.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L295-L309 | def mean_imls(self):
"""
Compute the mean IMLs (Intensity Measure Level)
for the given vulnerability function.
:param vulnerability_function: the vulnerability function where
the IMLs (Intensity Measure Level) are taken from.
:type vuln_function:
:py:class... | [
"def",
"mean_imls",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"max",
"(",
"0",
",",
"self",
".",
"imls",
"[",
"0",
"]",
"-",
"(",
"self",
".",
"imls",
"[",
"1",
"]",
"-",
"self",
".",
"imls",
"[",
"0",
"]",
")",
"/",... | Compute the mean IMLs (Intensity Measure Level)
for the given vulnerability function.
:param vulnerability_function: the vulnerability function where
the IMLs (Intensity Measure Level) are taken from.
:type vuln_function:
:py:class:`openquake.risklib.vulnerability_functio... | [
"Compute",
"the",
"mean",
"IMLs",
"(",
"Intensity",
"Measure",
"Level",
")",
"for",
"the",
"given",
"vulnerability",
"function",
"."
] | python | train | 42.066667 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_fc_auth.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fc_auth.py#L26-L38 | def fcsp_sa_fcsp_auth_proto_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth")
fcsp = ET.SubElement(fcsp_sa, "fcsp")
auth = ET.SubElement(fcsp, "auth")
... | [
"def",
"fcsp_sa_fcsp_auth_proto_group",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcsp_sa",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"fcsp-sa\"",
",",
"xmlns",
"=",
"\"urn:broca... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 40.615385 |
ib-lundgren/flask-oauthprovider | examples/mongo_demoprovider/utils.py | https://github.com/ib-lundgren/flask-oauthprovider/blob/6c91e8c11fc3cee410cb755d52d9d2c5331ee324/examples/mongo_demoprovider/utils.py#L5-L14 | def require_openid(f):
"""Require user to be logged in."""
@wraps(f)
def decorator(*args, **kwargs):
if g.user is None:
next_url = url_for("login") + "?next=" + request.url
return redirect(next_url)
else:
return f(*args, **kwargs)
return decorator | [
"def",
"require_openid",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"g",
".",
"user",
"is",
"None",
":",
"next_url",
"=",
"url_for",
"(",
"\"login\"",
")",
"+",
... | Require user to be logged in. | [
"Require",
"user",
"to",
"be",
"logged",
"in",
"."
] | python | train | 30.6 |
Miserlou/Zappa | zappa/cli.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1260-L1300 | def invoke(self, function_name, raw_python=False, command=None, no_color=False):
"""
Invoke a remote function.
"""
# There are three likely scenarios for 'command' here:
# command, which is a modular function path
# raw_command, which is a string of python to execute... | [
"def",
"invoke",
"(",
"self",
",",
"function_name",
",",
"raw_python",
"=",
"False",
",",
"command",
"=",
"None",
",",
"no_color",
"=",
"False",
")",
":",
"# There are three likely scenarios for 'command' here:",
"# command, which is a modular function path",
"# raw_c... | Invoke a remote function. | [
"Invoke",
"a",
"remote",
"function",
"."
] | python | train | 36.804878 |
pypyr/pypyr-cli | pypyr/steps/dsl/cmd.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/dsl/cmd.py#L95-L139 | def run_step(self, is_shell):
"""Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default shell.
"""
a... | [
"def",
"run_step",
"(",
"self",
",",
"is_shell",
")",
":",
"assert",
"is_shell",
"is",
"not",
"None",
",",
"(",
"\"is_shell param must exist for CmdStep.\"",
")",
"# why? If shell is True, it is recommended to pass args as a string",
"# rather than as a sequence.",
"if",
"is_... | Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default shell. | [
"Run",
"a",
"command",
"."
] | python | train | 43.422222 |
IEMLdev/ieml | ieml/dictionary/relations.py | https://github.com/IEMLdev/ieml/blob/4c842ba7e6165e2f1b4a4e2e98759f9f33af5f25/ieml/dictionary/relations.py#L96-L101 | def connexity(self):
"""
A boolean matrix, m[i, j] == True if there is a relation term(i) -> term(j)
:return: a np.matrix (len(dictionary), len(dictionary)) of boolean
"""
return np.matrix(sum(self.relations.values()).todense(), dtype=bool) | [
"def",
"connexity",
"(",
"self",
")",
":",
"return",
"np",
".",
"matrix",
"(",
"sum",
"(",
"self",
".",
"relations",
".",
"values",
"(",
")",
")",
".",
"todense",
"(",
")",
",",
"dtype",
"=",
"bool",
")"
] | A boolean matrix, m[i, j] == True if there is a relation term(i) -> term(j)
:return: a np.matrix (len(dictionary), len(dictionary)) of boolean | [
"A",
"boolean",
"matrix",
"m",
"[",
"i",
"j",
"]",
"==",
"True",
"if",
"there",
"is",
"a",
"relation",
"term",
"(",
"i",
")",
"-",
">",
"term",
"(",
"j",
")",
":",
"return",
":",
"a",
"np",
".",
"matrix",
"(",
"len",
"(",
"dictionary",
")",
"... | python | test | 45.833333 |
hyperledger/sawtooth-core | validator/sawtooth_validator/networking/interconnect.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/networking/interconnect.py#L773-L782 | def public_key_to_connection_id(self, public_key):
"""
Get stored connection id for a public key.
"""
with self._connections_lock:
for connection_id, connection_info in self._connections.items():
if connection_info.public_key == public_key:
... | [
"def",
"public_key_to_connection_id",
"(",
"self",
",",
"public_key",
")",
":",
"with",
"self",
".",
"_connections_lock",
":",
"for",
"connection_id",
",",
"connection_info",
"in",
"self",
".",
"_connections",
".",
"items",
"(",
")",
":",
"if",
"connection_info"... | Get stored connection id for a public key. | [
"Get",
"stored",
"connection",
"id",
"for",
"a",
"public",
"key",
"."
] | python | train | 35.7 |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/anchor/base.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/base.py#L847-L864 | async def get_txn(self, seq_no: int) -> str:
"""
Find a transaction on the distributed ledger by its sequence number.
:param seq_no: transaction number
:return: json sequence number of transaction, null for no match
"""
LOGGER.debug('BaseAnchor.get_txn >>> seq_no: %s', ... | [
"async",
"def",
"get_txn",
"(",
"self",
",",
"seq_no",
":",
"int",
")",
"->",
"str",
":",
"LOGGER",
".",
"debug",
"(",
"'BaseAnchor.get_txn >>> seq_no: %s'",
",",
"seq_no",
")",
"rv_json",
"=",
"json",
".",
"dumps",
"(",
"{",
"}",
")",
"req_json",
"=",
... | Find a transaction on the distributed ledger by its sequence number.
:param seq_no: transaction number
:return: json sequence number of transaction, null for no match | [
"Find",
"a",
"transaction",
"on",
"the",
"distributed",
"ledger",
"by",
"its",
"sequence",
"number",
"."
] | python | train | 34.111111 |
EconForge/dolo | dolo/compiler/model_numeric.py | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/compiler/model_numeric.py#L403-L421 | def decode_complementarity(comp, control):
'''
# comp can be either:
- None
- "a<=expr" where a is a controls
- "expr<=a" where a is a control
- "expr1<=a<=expr2"
'''
try:
res = regex.match(comp).groups()
except:
raise Exception("Unable to parse complementarity cond... | [
"def",
"decode_complementarity",
"(",
"comp",
",",
"control",
")",
":",
"try",
":",
"res",
"=",
"regex",
".",
"match",
"(",
"comp",
")",
".",
"groups",
"(",
")",
"except",
":",
"raise",
"Exception",
"(",
"\"Unable to parse complementarity condition '{}'\"",
".... | # comp can be either:
- None
- "a<=expr" where a is a controls
- "expr<=a" where a is a control
- "expr1<=a<=expr2" | [
"#",
"comp",
"can",
"be",
"either",
":",
"-",
"None",
"-",
"a<",
"=",
"expr",
"where",
"a",
"is",
"a",
"controls",
"-",
"expr<",
"=",
"a",
"where",
"a",
"is",
"a",
"control",
"-",
"expr1<",
"=",
"a<",
"=",
"expr2"
] | python | train | 29.473684 |
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 | 29.916667 |
sibirrer/lenstronomy | lenstronomy/ImSim/image_model.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/ImSim/image_model.py#L187-L196 | def error_response(self, kwargs_lens, kwargs_ps):
"""
returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties)
"""
model_error = self.error_map(kwargs_lens, k... | [
"def",
"error_response",
"(",
"self",
",",
"kwargs_lens",
",",
"kwargs_ps",
")",
":",
"model_error",
"=",
"self",
".",
"error_map",
"(",
"kwargs_lens",
",",
"kwargs_ps",
")",
"error_map_1d",
"=",
"self",
".",
"ImageNumerics",
".",
"image2array",
"(",
"model_er... | returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties) | [
"returns",
"the",
"1d",
"array",
"of",
"the",
"error",
"estimate",
"corresponding",
"to",
"the",
"data",
"response"
] | python | train | 49.8 |
cggh/scikit-allel | allel/chunked/core.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/chunked/core.py#L545-L586 | def eval_table(tbl, expression, vm='python', blen=None, storage=None,
create='array', vm_kwargs=None, **kwargs):
"""Evaluate `expression` against columns of a table."""
# setup
storage = _util.get_storage(storage)
names, columns = _util.check_table_like(tbl)
length = len(columns[0])
... | [
"def",
"eval_table",
"(",
"tbl",
",",
"expression",
",",
"vm",
"=",
"'python'",
",",
"blen",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"create",
"=",
"'array'",
",",
"vm_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# setup",
"storag... | Evaluate `expression` against columns of a table. | [
"Evaluate",
"expression",
"against",
"columns",
"of",
"a",
"table",
"."
] | python | train | 33.238095 |
cisco-sas/kitty | kitty/fuzzers/base.py | https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L246-L257 | def set_model(self, model):
'''
Set the model to fuzz
:type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass
:param model: Model object to fuzz
'''
self.model = model
if self.model:
self.model.set_notification_handler(self)
... | [
"def",
"set_model",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"model",
"=",
"model",
"if",
"self",
".",
"model",
":",
"self",
".",
"model",
".",
"set_notification_handler",
"(",
"self",
")",
"self",
".",
"handle_stage_changed",
"(",
"model",
")",... | Set the model to fuzz
:type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass
:param model: Model object to fuzz | [
"Set",
"the",
"model",
"to",
"fuzz"
] | python | train | 30.5 |
rigetti/pyquil | pyquil/noise.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/noise.py#L739-L757 | def bitstring_probs_to_z_moments(p):
"""
Convert between bitstring probabilities and joint Z moment expectations.
:param np.array p: An array that enumerates bitstring probabilities. When
flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must
therefore b... | [
"def",
"bitstring_probs_to_z_moments",
"(",
"p",
")",
":",
"zmat",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"1",
"]",
",",
"[",
"1",
",",
"-",
"1",
"]",
"]",
")",
"return",
"_apply_local_transforms",
"(",
"p",
",",
"(",
"zmat",
"for",
"_... | Convert between bitstring probabilities and joint Z moment expectations.
:param np.array p: An array that enumerates bitstring probabilities. When
flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must
therefore be a power of 2. The canonical shape has a separat... | [
"Convert",
"between",
"bitstring",
"probabilities",
"and",
"joint",
"Z",
"moment",
"expectations",
"."
] | python | train | 48.736842 |
explosion/spaCy | spacy/displacy/__init__.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L113-L165 | def parse_deps(orig_doc, options={}):
"""Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs.
"""
doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes())
if not doc.is_parsed:
u... | [
"def",
"parse_deps",
"(",
"orig_doc",
",",
"options",
"=",
"{",
"}",
")",
":",
"doc",
"=",
"Doc",
"(",
"orig_doc",
".",
"vocab",
")",
".",
"from_bytes",
"(",
"orig_doc",
".",
"to_bytes",
"(",
")",
")",
"if",
"not",
"doc",
".",
"is_parsed",
":",
"us... | Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs. | [
"Generate",
"dependency",
"parse",
"in",
"{",
"words",
":",
"[]",
"arcs",
":",
"[]",
"}",
"format",
"."
] | python | train | 38.207547 |
Rapptz/discord.py | discord/client.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L915-L955 | async def create_guild(self, name, region=None, icon=None):
"""|coro|
Creates a :class:`.Guild`.
Bot accounts in more than 10 guilds are not allowed to create guilds.
Parameters
----------
name: :class:`str`
The name of the guild.
region: :class:`Vo... | [
"async",
"def",
"create_guild",
"(",
"self",
",",
"name",
",",
"region",
"=",
"None",
",",
"icon",
"=",
"None",
")",
":",
"if",
"icon",
"is",
"not",
"None",
":",
"icon",
"=",
"utils",
".",
"_bytes_to_base64_data",
"(",
"icon",
")",
"if",
"region",
"i... | |coro|
Creates a :class:`.Guild`.
Bot accounts in more than 10 guilds are not allowed to create guilds.
Parameters
----------
name: :class:`str`
The name of the guild.
region: :class:`VoiceRegion`
The region for the voice communication server.
... | [
"|coro|"
] | python | train | 30.365854 |
gitpython-developers/GitPython | git/objects/util.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/util.py#L44-L65 | def get_object_type_by_name(object_type_name):
"""
:return: type suitable to handle the given object type name.
Use the type to create new instances.
:param object_type_name: Member of TYPES
:raise ValueError: In case object_type_name is unknown"""
if object_type_name == b"commit":
... | [
"def",
"get_object_type_by_name",
"(",
"object_type_name",
")",
":",
"if",
"object_type_name",
"==",
"b\"commit\"",
":",
"from",
".",
"import",
"commit",
"return",
"commit",
".",
"Commit",
"elif",
"object_type_name",
"==",
"b\"tag\"",
":",
"from",
".",
"import",
... | :return: type suitable to handle the given object type name.
Use the type to create new instances.
:param object_type_name: Member of TYPES
:raise ValueError: In case object_type_name is unknown | [
":",
"return",
":",
"type",
"suitable",
"to",
"handle",
"the",
"given",
"object",
"type",
"name",
".",
"Use",
"the",
"type",
"to",
"create",
"new",
"instances",
"."
] | python | train | 32.545455 |
quantopian/zipline | zipline/finance/order.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L124-L181 | def check_order_triggers(self, current_price):
"""
Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will al... | [
"def",
"check_order_triggers",
"(",
"self",
",",
"current_price",
")",
":",
"if",
"self",
".",
"triggered",
":",
"return",
"(",
"self",
".",
"stop_reached",
",",
"self",
".",
"limit_reached",
",",
"False",
")",
"stop_reached",
"=",
"False",
"limit_reached",
... | Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will always be False.
For stop limit orders a Boolean is returned ... | [
"Given",
"an",
"order",
"and",
"a",
"trade",
"event",
"return",
"a",
"tuple",
"of",
"(",
"stop_reached",
"limit_reached",
")",
".",
"For",
"market",
"orders",
"will",
"return",
"(",
"False",
"False",
")",
".",
"For",
"stop",
"orders",
"limit_reached",
"wil... | python | train | 34.12069 |
TorkamaniLab/metapipe | metapipe/models/command_template_factory.py | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L109-L124 | def _get_prelim_dependencies(command_template, all_templates):
""" Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met.
"""
deps = []
for ... | [
"def",
"_get_prelim_dependencies",
"(",
"command_template",
",",
"all_templates",
")",
":",
"deps",
"=",
"[",
"]",
"for",
"input",
"in",
"command_template",
".",
"input_parts",
":",
"if",
"'.'",
"not",
"in",
"input",
".",
"alias",
":",
"continue",
"for",
"te... | Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met. | [
"Given",
"a",
"command_template",
"determine",
"which",
"other",
"templates",
"it",
"depends",
"on",
".",
"This",
"should",
"not",
"be",
"used",
"as",
"the",
"be",
"-",
"all",
"end",
"-",
"all",
"of",
"dependencies",
"and",
"before",
"calling",
"each",
"co... | python | train | 39.25 |
pywbem/pywbem | pywbem/mof_compiler.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L425-L451 | def get_err_msg(self):
"""
Return a multi-line error message for being printed, in the following
format. The text in angle brackets refers to the same-named properties
of the exception instance:
::
Syntax error:<file>:<lineno>: <msg>
<context - MOF line>... | [
"def",
"get_err_msg",
"(",
"self",
")",
":",
"ret_str",
"=",
"'Syntax error:'",
"disp_file",
"=",
"'NoFile'",
"if",
"self",
".",
"file",
"is",
"None",
"else",
"self",
".",
"file",
"if",
"self",
".",
"lineno",
"is",
"not",
"None",
":",
"ret_str",
"+=",
... | Return a multi-line error message for being printed, in the following
format. The text in angle brackets refers to the same-named properties
of the exception instance:
::
Syntax error:<file>:<lineno>: <msg>
<context - MOF line>
<context - position indicator ... | [
"Return",
"a",
"multi",
"-",
"line",
"error",
"message",
"for",
"being",
"printed",
"in",
"the",
"following",
"format",
".",
"The",
"text",
"in",
"angle",
"brackets",
"refers",
"to",
"the",
"same",
"-",
"named",
"properties",
"of",
"the",
"exception",
"ins... | python | train | 32.555556 |
micheles/decorator | src/decorator.py | https://github.com/micheles/decorator/blob/7495513ee24deffbf5060860eb69b224fe1d0fe4/src/decorator.py#L259-L293 | def decorator(caller, _func=None):
"""decorator(caller) converts a caller function into a decorator"""
if _func is not None: # return a decorated function
# this is obsolete behavior; you should use decorate instead
return decorate(_func, caller)
# else return a decorator function
defau... | [
"def",
"decorator",
"(",
"caller",
",",
"_func",
"=",
"None",
")",
":",
"if",
"_func",
"is",
"not",
"None",
":",
"# return a decorated function",
"# this is obsolete behavior; you should use decorate instead",
"return",
"decorate",
"(",
"_func",
",",
"caller",
")",
... | decorator(caller) converts a caller function into a decorator | [
"decorator",
"(",
"caller",
")",
"converts",
"a",
"caller",
"function",
"into",
"a",
"decorator"
] | python | train | 44.8 |
agabrown/PyGaia | pygaia/errors/astrometric.py | https://github.com/agabrown/PyGaia/blob/ae972b0622a15f713ffae471f925eac25ccdae47/pygaia/errors/astrometric.py#L230-L256 | def positionMinError(G, vmini, extension=0.0):
"""
Calculate the minimum position errors from G and (V-I). These correspond to the sky regions with the
smallest astrometric errors.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ... | [
"def",
"positionMinError",
"(",
"G",
",",
"vmini",
",",
"extension",
"=",
"0.0",
")",
":",
"parallaxError",
"=",
"parallaxErrorSkyAvg",
"(",
"G",
",",
"vmini",
",",
"extension",
"=",
"extension",
")",
"return",
"_astrometricErrorFactors",
"[",
"'alphaStar'",
"... | Calculate the minimum position errors from G and (V-I). These correspond to the sky regions with the
smallest astrometric errors.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
Parameters
----------
G -... | [
"Calculate",
"the",
"minimum",
"position",
"errors",
"from",
"G",
"and",
"(",
"V",
"-",
"I",
")",
".",
"These",
"correspond",
"to",
"the",
"sky",
"regions",
"with",
"the",
"smallest",
"astrometric",
"errors",
"."
] | python | test | 31.666667 |
novopl/peltak | src/peltak/extra/docker/logic.py | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L58-L84 | def docker_list(registry_pass):
# type: (str) -> None
""" List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password.
"""
registry = conf.get('docker.registry', None)
if registry is None:
log.err("You must define doc... | [
"def",
"docker_list",
"(",
"registry_pass",
")",
":",
"# type: (str) -> None",
"registry",
"=",
"conf",
".",
"get",
"(",
"'docker.registry'",
",",
"None",
")",
"if",
"registry",
"is",
"None",
":",
"log",
".",
"err",
"(",
"\"You must define docker.registry conf var... | List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password. | [
"List",
"docker",
"images",
"stored",
"in",
"the",
"remote",
"registry",
"."
] | python | train | 31.851852 |
apache/airflow | airflow/hooks/dbapi_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/dbapi_hook.py#L114-L130 | def get_first(self, sql, parameters=None):
"""
Executes the sql and returns the first resulting row.
:param sql: the sql statement to be executed (str) or a list of
sql statements to execute
:type sql: str or list
:param parameters: The parameters to render the SQL q... | [
"def",
"get_first",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
")",
":",
"with",
"closing",
"(",
"self",
".",
"get_conn",
"(",
")",
")",
"as",
"conn",
":",
"with",
"closing",
"(",
"conn",
".",
"cursor",
"(",
")",
")",
"as",
"cur",
"... | Executes the sql and returns the first resulting row.
:param sql: the sql statement to be executed (str) or a list of
sql statements to execute
:type sql: str or list
:param parameters: The parameters to render the SQL query with.
:type parameters: mapping or iterable | [
"Executes",
"the",
"sql",
"and",
"returns",
"the",
"first",
"resulting",
"row",
"."
] | python | test | 38.588235 |
heigeo/climata | climata/base.py | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L163-L185 | def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def... | [
"def",
"getlist",
"(",
"self",
",",
"name",
")",
":",
"value",
"=",
"self",
".",
"getvalue",
"(",
"name",
")",
"complex",
"=",
"{",
"}",
"def",
"str_value",
"(",
"val",
")",
":",
"# TODO: nonlocal complex",
"if",
"isinstance",
"(",
"val",
",",
"dict",
... | Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list) | [
"Retrieve",
"given",
"property",
"from",
"class",
"/",
"instance",
"ensuring",
"it",
"is",
"a",
"list",
".",
"Also",
"determine",
"whether",
"the",
"list",
"contains",
"simple",
"text",
"/",
"numeric",
"values",
"or",
"nested",
"dictionaries",
"(",
"a",
"com... | python | train | 28.956522 |
jrabbit/hitman | hitman.py | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L384-L393 | def set_settings(key, value):
"""Set Hitman internal settings."""
with Database("settings") as settings:
if value in ['0', 'false', 'no', 'off', 'False']:
del settings[key]
print("Disabled setting")
else:
print(value)
settings[key] = value
... | [
"def",
"set_settings",
"(",
"key",
",",
"value",
")",
":",
"with",
"Database",
"(",
"\"settings\"",
")",
"as",
"settings",
":",
"if",
"value",
"in",
"[",
"'0'",
",",
"'false'",
",",
"'no'",
",",
"'off'",
",",
"'False'",
"]",
":",
"del",
"settings",
"... | Set Hitman internal settings. | [
"Set",
"Hitman",
"internal",
"settings",
"."
] | python | train | 33.7 |
open-mmlab/mmcv | mmcv/video/processing.py | https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/video/processing.py#L10-L47 | def convert_video(in_file, out_file, print_cmd=False, pre_options='',
**kwargs):
"""Convert a video with ffmpeg.
This provides a general api to ffmpeg, the executed command is::
`ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`
Options(kwargs) are mapped to ffmpeg comm... | [
"def",
"convert_video",
"(",
"in_file",
",",
"out_file",
",",
"print_cmd",
"=",
"False",
",",
"pre_options",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
... | Convert a video with ffmpeg.
This provides a general api to ffmpeg, the executed command is::
`ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`
Options(kwargs) are mapped to ffmpeg commands with the following rules:
- key=val: "-key val"
- key=True: "-key"
- key=False: ""
... | [
"Convert",
"a",
"video",
"with",
"ffmpeg",
"."
] | python | test | 34 |
SmokinCaterpillar/pypet | pypet/shareddata.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/shareddata.py#L107-L139 | def make_shared_result(result, key, trajectory, new_class=None):
"""Turns an ordinary data item into a shared one.
Removes the old result from the trajectory and replaces it.
Empties the given result.
:param result: The result containing ordinary data
:param key: Name of ordinary data item
:pa... | [
"def",
"make_shared_result",
"(",
"result",
",",
"key",
",",
"trajectory",
",",
"new_class",
"=",
"None",
")",
":",
"data",
"=",
"result",
".",
"f_get",
"(",
"key",
")",
"if",
"new_class",
"is",
"None",
":",
"if",
"isinstance",
"(",
"data",
",",
"Objec... | Turns an ordinary data item into a shared one.
Removes the old result from the trajectory and replaces it.
Empties the given result.
:param result: The result containing ordinary data
:param key: Name of ordinary data item
:param trajectory: Trajectory container
:param new_class:
Clas... | [
"Turns",
"an",
"ordinary",
"data",
"item",
"into",
"a",
"shared",
"one",
"."
] | python | test | 34.30303 |
openid/python-openid | openid/consumer/html_parse.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L228-L232 | def linkHasRel(link_attrs, target_rel):
"""Does this link have target_rel as a relationship?"""
# XXX: TESTME
rel_attr = link_attrs.get('rel')
return rel_attr and relMatches(rel_attr, target_rel) | [
"def",
"linkHasRel",
"(",
"link_attrs",
",",
"target_rel",
")",
":",
"# XXX: TESTME",
"rel_attr",
"=",
"link_attrs",
".",
"get",
"(",
"'rel'",
")",
"return",
"rel_attr",
"and",
"relMatches",
"(",
"rel_attr",
",",
"target_rel",
")"
] | Does this link have target_rel as a relationship? | [
"Does",
"this",
"link",
"have",
"target_rel",
"as",
"a",
"relationship?"
] | python | train | 41.4 |
tchellomello/raincloudy | raincloudy/faucet.py | https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L224-L239 | def watering_time(self):
"""Return watering_time from zone."""
# zone starts with index 0
index = self.id - 1
auto_watering_time =\
self._attributes['rain_delay_mode'][index]['auto_watering_time']
manual_watering_time =\
self._attributes['rain_delay_mode'... | [
"def",
"watering_time",
"(",
"self",
")",
":",
"# zone starts with index 0",
"index",
"=",
"self",
".",
"id",
"-",
"1",
"auto_watering_time",
"=",
"self",
".",
"_attributes",
"[",
"'rain_delay_mode'",
"]",
"[",
"index",
"]",
"[",
"'auto_watering_time'",
"]",
"... | Return watering_time from zone. | [
"Return",
"watering_time",
"from",
"zone",
"."
] | python | train | 33.25 |
jborean93/smbprotocol | smbprotocol/structure.py | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L258-L272 | def _get_calculated_value(self, value):
"""
Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value
"""
if isinstance(value, types.LambdaType... | [
"def",
"_get_calculated_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"types",
".",
"LambdaType",
")",
":",
"expanded_value",
"=",
"value",
"(",
"self",
".",
"structure",
")",
"return",
"self",
".",
"_get_calculated_valu... | Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value | [
"Get",
"s",
"the",
"final",
"value",
"of",
"the",
"field",
"and",
"runs",
"the",
"lambda",
"functions",
"recursively",
"until",
"a",
"final",
"value",
"is",
"derived",
"."
] | python | train | 39.533333 |
coldfix/udiskie | udiskie/common.py | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L151-L161 | def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return b... | [
"def",
"decode_ay",
"(",
"ay",
")",
":",
"if",
"ay",
"is",
"None",
":",
"return",
"''",
"elif",
"isinstance",
"(",
"ay",
",",
"str",
")",
":",
"return",
"ay",
"elif",
"isinstance",
"(",
"ay",
",",
"bytes",
")",
":",
"return",
"ay",
".",
"decode",
... | Convert binary blob from DBus queries to strings. | [
"Convert",
"binary",
"blob",
"from",
"DBus",
"queries",
"to",
"strings",
"."
] | python | train | 32.909091 |
StackStorm/pybind | pybind/slxos/v17s_1_02/mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/__init__.py#L539-L560 | def _set_interface_dynamic_bypass_name_prefix(self, v, load=False):
"""
Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dynamic_bypass_name_prefix ... | [
"def",
"_set_interface_dynamic_bypass_name_prefix",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
... | Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dynamic_bypass_name_prefix (string)
If this variable is read-only (config: false) in the
source YAN... | [
"Setter",
"method",
"for",
"interface_dynamic_bypass_name_prefix",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_config",
"/",
"router",
"/",
"mpls",
"/",
"mpls_cmds_holder",
"/",
"mpls_interface",
"/",
"interface_dynamic_bypass",
"/",
"mpls_interface_dynamic_bypass_sub_... | python | train | 100.772727 |
shaldengeki/python-mal | myanimelist/user.py | https://github.com/shaldengeki/python-mal/blob/2c3356411a74d88ba13f6b970388040d696f8392/myanimelist/user.py#L88-L203 | def parse_sidebar(self, user_page):
"""Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.MalformedUserPageError`
"... | [
"def",
"parse_sidebar",
"(",
"self",
",",
"user_page",
")",
":",
"user_info",
"=",
"{",
"}",
"# if MAL says the series doesn't exist, raise an InvalidUserError.",
"error_tag",
"=",
"user_page",
".",
"find",
"(",
"u'div'",
",",
"{",
"u'class'",
":",
"u'badresult'",
"... | Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.MalformedUserPageError` | [
"Parses",
"the",
"DOM",
"and",
"returns",
"user",
"attributes",
"in",
"the",
"sidebar",
"."
] | python | train | 43.991379 |
pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L650-L661 | def as_tuple(ireq):
"""
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
"""
if not is_pinned_requirement(ireq):
raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq))
name = key_from_req(ireq.req)
version = first(ireq... | [
"def",
"as_tuple",
"(",
"ireq",
")",
":",
"if",
"not",
"is_pinned_requirement",
"(",
"ireq",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a pinned InstallRequirement, got {}\"",
".",
"format",
"(",
"ireq",
")",
")",
"name",
"=",
"key_from_req",
"(",
"ireq",
... | Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement. | [
"Pulls",
"out",
"the",
"(",
"name",
":",
"str",
"version",
":",
"str",
"extras",
":",
"(",
"str",
"))",
"tuple",
"from",
"the",
"pinned",
"InstallRequirement",
"."
] | python | train | 34.083333 |
davenquinn/Attitude | attitude/display/hyperbola.py | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/hyperbola.py#L33-L103 | def hyperbolic_errors(hyp_axes, xvals,
transformation=None, axes=None,
means=None, correct_apparent_dip=True,
reverse=False):
"""
Returns a function that can be used to create a view of the
hyperbolic error ellipse from a specific direction.
... | [
"def",
"hyperbolic_errors",
"(",
"hyp_axes",
",",
"xvals",
",",
"transformation",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"means",
"=",
"None",
",",
"correct_apparent_dip",
"=",
"True",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"means",
"is",
"No... | Returns a function that can be used to create a view of the
hyperbolic error ellipse from a specific direction.
This creates a hyperbolic quadric and slices it to form a conic
on a 2d cartesian plane aligned with the requested direction.
A function is returned that takes x values (distance along nomin... | [
"Returns",
"a",
"function",
"that",
"can",
"be",
"used",
"to",
"create",
"a",
"view",
"of",
"the",
"hyperbolic",
"error",
"ellipse",
"from",
"a",
"specific",
"direction",
"."
] | python | train | 30.605634 |
instaloader/instaloader | instaloader/structures.py | https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/structures.py#L443-L467 | def from_id(cls, context: InstaloaderContext, profile_id: int):
"""Create a Profile instance from a given userid. If possible, use :meth:`Profile.from_username`
or constructor directly rather than this method, since it requires more requests.
:param context: :attr:`Instaloader.context`
... | [
"def",
"from_id",
"(",
"cls",
",",
"context",
":",
"InstaloaderContext",
",",
"profile_id",
":",
"int",
")",
":",
"if",
"profile_id",
"in",
"context",
".",
"profile_id_cache",
":",
"return",
"context",
".",
"profile_id_cache",
"[",
"profile_id",
"]",
"data",
... | Create a Profile instance from a given userid. If possible, use :meth:`Profile.from_username`
or constructor directly rather than this method, since it requires more requests.
:param context: :attr:`Instaloader.context`
:param profile_id: userid
:raises: :class:`ProfileNotExistsExceptio... | [
"Create",
"a",
"Profile",
"instance",
"from",
"a",
"given",
"userid",
".",
"If",
"possible",
"use",
":",
"meth",
":",
"Profile",
".",
"from_username",
"or",
"constructor",
"directly",
"rather",
"than",
"this",
"method",
"since",
"it",
"requires",
"more",
"re... | python | train | 55.8 |
MKLab-ITI/reveal-user-annotation | reveal_user_annotation/twitter/user_annotate.py | https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/twitter/user_annotate.py#L583-L599 | def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id):
"""
A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this.
"""
##################################################################################################################... | [
"def",
"on_demand_annotation",
"(",
"twitter_app_key",
",",
"twitter_app_secret",
",",
"user_twitter_id",
")",
":",
"####################################################################################################################",
"# Log into my application",
"##########################... | A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this. | [
"A",
"service",
"that",
"leverages",
"twitter",
"lists",
"for",
"on",
"-",
"demand",
"annotation",
"of",
"popular",
"users",
"."
] | python | train | 41.764706 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/rich_text.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/rich_text.py#L219-L230 | def ensure_utf8(image_tag):
"""wrapper for ensuring image_tag returns utf8-encoded str on Python 2"""
if py3compat.PY3:
# nothing to do on Python 3
return image_tag
def utf8_image_tag(*args, **kwargs):
s = image_tag(*args, **kwargs)
if isinstance(s, unicode):
... | [
"def",
"ensure_utf8",
"(",
"image_tag",
")",
":",
"if",
"py3compat",
".",
"PY3",
":",
"# nothing to do on Python 3",
"return",
"image_tag",
"def",
"utf8_image_tag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"image_tag",
"(",
"*",
"args... | wrapper for ensuring image_tag returns utf8-encoded str on Python 2 | [
"wrapper",
"for",
"ensuring",
"image_tag",
"returns",
"utf8",
"-",
"encoded",
"str",
"on",
"Python",
"2"
] | python | test | 31.083333 |
jupyterhub/kubespawner | kubespawner/clients.py | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/clients.py#L25-L46 | def shared_client(ClientType, *args, **kwargs):
"""Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared.
"""
kwarg_key = tuple(... | [
"def",
"shared_client",
"(",
"ClientType",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwarg_key",
"=",
"tuple",
"(",
"(",
"key",
",",
"kwargs",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"sorted",
"(",
"kwargs",
")",
")",
"cache_key",
"="... | Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared. | [
"Return",
"a",
"single",
"shared",
"kubernetes",
"client",
"instance"
] | python | train | 37.545455 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L902-L926 | def pawn_from_dummy(self, dummy):
"""Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy.
"""
dummy.pos = s... | [
"def",
"pawn_from_dummy",
"(",
"self",
",",
"dummy",
")",
":",
"dummy",
".",
"pos",
"=",
"self",
".",
"to_local",
"(",
"*",
"dummy",
".",
"pos",
")",
"for",
"spot",
"in",
"self",
".",
"board",
".",
"spotlayout",
".",
"children",
":",
"if",
"spot",
... | Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy. | [
"Make",
"a",
"real",
"thing",
"and",
"its",
"pawn",
"from",
"a",
"dummy",
"pawn",
"."
] | python | train | 31.96 |
lycantropos/paradigm | paradigm/cached.py | https://github.com/lycantropos/paradigm/blob/70415f77964dbb1b6d444f890a5d988174194ff0/paradigm/cached.py#L15-L33 | def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]:
"""
Returns decorator that calls wrapped function
if nothing was found in cache for its argument.
Wrapped function arguments should be hashable.
"""
def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]:
... | [
"def",
"map_",
"(",
"cache",
":",
"Mapping",
"[",
"Domain",
",",
"Range",
"]",
")",
"->",
"Operator",
"[",
"Map",
"[",
"Domain",
",",
"Range",
"]",
"]",
":",
"def",
"wrapper",
"(",
"function",
":",
"Map",
"[",
"Domain",
",",
"Range",
"]",
")",
"-... | Returns decorator that calls wrapped function
if nothing was found in cache for its argument.
Wrapped function arguments should be hashable. | [
"Returns",
"decorator",
"that",
"calls",
"wrapped",
"function",
"if",
"nothing",
"was",
"found",
"in",
"cache",
"for",
"its",
"argument",
"."
] | python | train | 28.315789 |
awslabs/sockeye | sockeye/data_io.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/data_io.py#L1119-L1126 | def ids2strids(ids: Iterable[int]) -> str:
"""
Returns a string representation of a sequence of integers.
:param ids: Sequence of integers.
:return: String sequence
"""
return C.TOKEN_SEPARATOR.join(map(str, ids)) | [
"def",
"ids2strids",
"(",
"ids",
":",
"Iterable",
"[",
"int",
"]",
")",
"->",
"str",
":",
"return",
"C",
".",
"TOKEN_SEPARATOR",
".",
"join",
"(",
"map",
"(",
"str",
",",
"ids",
")",
")"
] | Returns a string representation of a sequence of integers.
:param ids: Sequence of integers.
:return: String sequence | [
"Returns",
"a",
"string",
"representation",
"of",
"a",
"sequence",
"of",
"integers",
"."
] | python | train | 28.875 |
eqcorrscan/EQcorrscan | eqcorrscan/utils/mag_calc.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/mag_calc.py#L231-L287 | def _sim_WA(trace, PAZ, seedresp, water_level, velocity=False):
"""
Remove the instrument response from a trace and simulate a Wood-Anderson.
Returns a de-meaned, de-trended, Wood Anderson simulated trace in
its place.
Works in-place on data and will destroy your original data, copy the
trace ... | [
"def",
"_sim_WA",
"(",
"trace",
",",
"PAZ",
",",
"seedresp",
",",
"water_level",
",",
"velocity",
"=",
"False",
")",
":",
"# Note Wood anderson sensitivity is 2080 as per Uhrhammer & Collins 1990",
"PAZ_WA",
"=",
"{",
"'poles'",
":",
"[",
"-",
"6.283",
"+",
"4.712... | Remove the instrument response from a trace and simulate a Wood-Anderson.
Returns a de-meaned, de-trended, Wood Anderson simulated trace in
its place.
Works in-place on data and will destroy your original data, copy the
trace before giving it to this function!
:type trace: obspy.core.trace.Trace
... | [
"Remove",
"the",
"instrument",
"response",
"from",
"a",
"trace",
"and",
"simulate",
"a",
"Wood",
"-",
"Anderson",
"."
] | python | train | 42.982456 |
SiLab-Bonn/online_monitor | online_monitor/utils/utils.py | https://github.com/SiLab-Bonn/online_monitor/blob/113c7d33e9ea4bc18520cefa329462faa406cc08/online_monitor/utils/utils.py#L38-L55 | def parse_args(args):
''' Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module
'''
parser = argparse.ArgumentParser()
parser.add_argument('config_file', nargs='?',
help='Configura... | [
"def",
"parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'config_file'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'Configuration yaml file'",
",",
"default",
"=",
"None",... | Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module | [
"Parse",
"an",
"argument",
"string"
] | python | train | 38.833333 |
bwohlberg/sporco | sporco/admm/spline.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/spline.py#L176-L185 | def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
# If initial Y is non-zero, initial U is chosen so that
# the relevant dual optimality criterion (see (3.10) i... | [
"def",
"uinit",
"(",
"self",
",",
"ushape",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'Y0'",
"]",
"is",
"None",
":",
"return",
"np",
".",
"zeros",
"(",
"ushape",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"else",
":",
"# If initial Y is non-zero, ... | Return initialiser for working variable U. | [
"Return",
"initialiser",
"for",
"working",
"variable",
"U",
"."
] | python | train | 41.8 |
ozgurgunes/django-manifest | manifest/accounts/models.py | https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L173-L188 | def upload_to_picture(instance, filename):
"""
Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and
saving it under unique hash for the image. This is for privacy
reasons so others can't just browse through the picture directory.
"""
extension = filename.split('.')[-1].lower()
... | [
"def",
"upload_to_picture",
"(",
"instance",
",",
"filename",
")",
":",
"extension",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"salt",
",",
"hash",
"=",
"generate_sha1",
"(",
"instance",
".",
"id",
")... | Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and
saving it under unique hash for the image. This is for privacy
reasons so others can't just browse through the picture directory. | [
"Uploads",
"a",
"picture",
"for",
"a",
"user",
"to",
"the",
"ACCOUNTS_PICTURE_PATH",
"and",
"saving",
"it",
"under",
"unique",
"hash",
"for",
"the",
"image",
".",
"This",
"is",
"for",
"privacy",
"reasons",
"so",
"others",
"can",
"t",
"just",
"browse",
"thr... | python | train | 44.1875 |
inveniosoftware/invenio-files-rest | invenio_files_rest/models.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1557-L1567 | def get(cls, bucket, key, upload_id, with_completed=False):
"""Fetch a specific multipart object."""
q = cls.query.filter_by(
upload_id=upload_id,
bucket_id=as_bucket_id(bucket),
key=key,
)
if not with_completed:
q = q.filter(cls.completed.... | [
"def",
"get",
"(",
"cls",
",",
"bucket",
",",
"key",
",",
"upload_id",
",",
"with_completed",
"=",
"False",
")",
":",
"q",
"=",
"cls",
".",
"query",
".",
"filter_by",
"(",
"upload_id",
"=",
"upload_id",
",",
"bucket_id",
"=",
"as_bucket_id",
"(",
"buck... | Fetch a specific multipart object. | [
"Fetch",
"a",
"specific",
"multipart",
"object",
"."
] | python | train | 32.090909 |
photo/openphoto-python | trovebox/objects/tag.py | https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/objects/tag.py#L10-L20 | def delete(self, **kwds):
"""
Endpoint: /tag/<id>/delete.json
Deletes this tag.
Returns True if successful.
Raises a TroveboxError if not.
"""
result = self._client.tag.delete(self, **kwds)
self._delete_fields()
return result | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"tag",
".",
"delete",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
"self",
".",
"_delete_fields",
"(",
")",
"return",
"result"
] | Endpoint: /tag/<id>/delete.json
Deletes this tag.
Returns True if successful.
Raises a TroveboxError if not. | [
"Endpoint",
":",
"/",
"tag",
"/",
"<id",
">",
"/",
"delete",
".",
"json"
] | python | train | 26.181818 |
wmayner/pyphi | pyphi/models/cmp.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/cmp.py#L108-L133 | def general_eq(a, b, attributes):
"""Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared ... | [
"def",
"general_eq",
"(",
"a",
",",
"b",
",",
"attributes",
")",
":",
"try",
":",
"for",
"attr",
"in",
"attributes",
":",
"_a",
",",
"_b",
"=",
"getattr",
"(",
"a",
",",
"attr",
")",
",",
"getattr",
"(",
"b",
",",
"attr",
")",
"if",
"attr",
"in... | Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared with
:func:`numpy_aware_eq`. | [
"Return",
"whether",
"two",
"objects",
"are",
"equal",
"up",
"to",
"the",
"given",
"attributes",
"."
] | python | train | 36.807692 |
google/grumpy | third_party/stdlib/re.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/re.py#L176-L193 | def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
re... | [
"def",
"findall",
"(",
"pattern",
",",
"string",
",",
"flags",
"=",
"0",
")",
":",
"return",
"_compile",
"(",
"pattern",
",",
"flags",
")",
".",
"findall",
"(",
"string",
")",
"# if sys.hexversion >= 0x02020000:",
"# __all__.append(\"finditer\")",
"def",
"fi... | Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result. | [
"Return",
"a",
"list",
"of",
"all",
"non",
"-",
"overlapping",
"matches",
"in",
"the",
"string",
"."
] | python | valid | 40 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L100-L102 | def Lookup(self, x):
"""Looks up x and returns the corresponding value of y."""
return self._Bisect(x, self.xs, self.ys) | [
"def",
"Lookup",
"(",
"self",
",",
"x",
")",
":",
"return",
"self",
".",
"_Bisect",
"(",
"x",
",",
"self",
".",
"xs",
",",
"self",
".",
"ys",
")"
] | Looks up x and returns the corresponding value of y. | [
"Looks",
"up",
"x",
"and",
"returns",
"the",
"corresponding",
"value",
"of",
"y",
"."
] | python | train | 44.666667 |
pgmpy/pgmpy | pgmpy/extern/tabulate.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/extern/tabulate.py#L429-L450 | def _column_type(strings, has_invisible=True):
"""The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["f... | [
"def",
"_column_type",
"(",
"strings",
",",
"has_invisible",
"=",
"True",
")",
":",
"types",
"=",
"[",
"_type",
"(",
"s",
",",
"has_invisible",
")",
"for",
"s",
"in",
"strings",
"]",
"return",
"reduce",
"(",
"_more_generic",
",",
"types",
",",
"int",
"... | The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type
T... | [
"The",
"least",
"generic",
"type",
"all",
"column",
"values",
"are",
"convertible",
"to",
"."
] | python | train | 31.772727 |
elliterate/capybara.py | capybara/helpers.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L70-L107 | def failure_message(description, options):
"""
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
"""... | [
"def",
"failure_message",
"(",
"description",
",",
"options",
")",
":",
"message",
"=",
"\"expected to find {}\"",
".",
"format",
"(",
"description",
")",
"if",
"options",
"[",
"\"count\"",
"]",
"is",
"not",
"None",
":",
"message",
"+=",
"\" {count} {times}\"",
... | Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure. | [
"Returns",
"a",
"expectation",
"failure",
"message",
"for",
"the",
"given",
"query",
"description",
"."
] | python | test | 33.289474 |
DataBiosphere/toil | src/toil/batchSystems/singleMachine.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/singleMachine.py#L245-L259 | def killBatchJobs(self, jobIDs):
"""Kills jobs by ID."""
log.debug('Killing jobs: {}'.format(jobIDs))
for jobID in jobIDs:
if jobID in self.runningJobs:
info = self.runningJobs[jobID]
info.killIntended = True
if info.popen != None:
... | [
"def",
"killBatchJobs",
"(",
"self",
",",
"jobIDs",
")",
":",
"log",
".",
"debug",
"(",
"'Killing jobs: {}'",
".",
"format",
"(",
"jobIDs",
")",
")",
"for",
"jobID",
"in",
"jobIDs",
":",
"if",
"jobID",
"in",
"self",
".",
"runningJobs",
":",
"info",
"="... | Kills jobs by ID. | [
"Kills",
"jobs",
"by",
"ID",
"."
] | python | train | 42.333333 |
trailofbits/manticore | manticore/ethereum/abitypes.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abitypes.py#L51-L55 | def t_UINTN(t):
r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)"
size = int(t.lexer.lexmatch.group('size'))
t.value = ('uint', size)
return t | [
"def",
"t_UINTN",
"(",
"t",
")",
":",
"size",
"=",
"int",
"(",
"t",
".",
"lexer",
".",
"lexmatch",
".",
"group",
"(",
"'size'",
")",
")",
"t",
".",
"value",
"=",
"(",
"'uint'",
",",
"size",
")",
"return",
"t"
] | r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8) | [
"r",
"uint",
"(",
"?P<size",
">",
"256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8",
")"
] | python | valid | 47.2 |
hannes-brt/hebel | hebel/pycuda_ops/cublas.py | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2637-L2647 | def cublasDspr(handle, uplo, n, alpha, x, incx, AP):
"""
Rank-1 operation on real symmetric-packed matrix.
"""
status = _libcublas.cublasDspr_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctype... | [
"def",
"cublasDspr",
"(",
"handle",
",",
"uplo",
",",
"n",
",",
"alpha",
",",
"x",
",",
"incx",
",",
"AP",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasDspr_v2",
"(",
"handle",
",",
"_CUBLAS_FILL_MODE",
"[",
"uplo",
"]",
",",
"n",
",",
"ctypes"... | Rank-1 operation on real symmetric-packed matrix. | [
"Rank",
"-",
"1",
"operation",
"on",
"real",
"symmetric",
"-",
"packed",
"matrix",
"."
] | python | train | 43.363636 |
obulpathi/cdn-fastly-python | fastly/__init__.py | https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L946-L950 | def update_version(self, service_id, version_number, **kwargs):
"""Update a particular version for a particular service."""
body = self._formdata(kwargs, FastlyVersion.FIELDS)
content = self._fetch("/service/%s/version/%d/" % (service_id, version_number), method="PUT", body=body)
return FastlyVersion(self, cont... | [
"def",
"update_version",
"(",
"self",
",",
"service_id",
",",
"version_number",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"self",
".",
"_formdata",
"(",
"kwargs",
",",
"FastlyVersion",
".",
"FIELDS",
")",
"content",
"=",
"self",
".",
"_fetch",
"(",... | Update a particular version for a particular service. | [
"Update",
"a",
"particular",
"version",
"for",
"a",
"particular",
"service",
"."
] | python | train | 64 |
acutesoftware/AIKIF | aikif/dataTools/cls_sql_code_generator.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_sql_code_generator.py#L181-L197 | def populate_from_staging(self, staging_table, from_column_list, output_table):
"""
generate SQL to insert staging table records into
the core table based on column_list (If no column list
then insert sequentially)
"""
self.sql_text += 'INSERT INTO ' + output_table + ' (... | [
"def",
"populate_from_staging",
"(",
"self",
",",
"staging_table",
",",
"from_column_list",
",",
"output_table",
")",
":",
"self",
".",
"sql_text",
"+=",
"'INSERT INTO '",
"+",
"output_table",
"+",
"' (\\n'",
"for",
"c",
"in",
"self",
".",
"col_list",
":",
"if... | generate SQL to insert staging table records into
the core table based on column_list (If no column list
then insert sequentially) | [
"generate",
"SQL",
"to",
"insert",
"staging",
"table",
"records",
"into",
"the",
"core",
"table",
"based",
"on",
"column_list",
"(",
"If",
"no",
"column",
"list",
"then",
"insert",
"sequentially",
")"
] | python | train | 43.647059 |
seleniumbase/SeleniumBase | seleniumbase/plugins/db_reporting_plugin.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/plugins/db_reporting_plugin.py#L49-L57 | def begin(self):
""" At the start of the run, we want to record the test
execution information in the database. """
exec_payload = ExecutionQueryPayload()
exec_payload.execution_start_time = int(time.time() * 1000)
self.execution_start_time = exec_payload.execution_start_time... | [
"def",
"begin",
"(",
"self",
")",
":",
"exec_payload",
"=",
"ExecutionQueryPayload",
"(",
")",
"exec_payload",
".",
"execution_start_time",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
"self",
".",
"execution_start_time",
"=",
"exec_payl... | At the start of the run, we want to record the test
execution information in the database. | [
"At",
"the",
"start",
"of",
"the",
"run",
"we",
"want",
"to",
"record",
"the",
"test",
"execution",
"information",
"in",
"the",
"database",
"."
] | python | train | 52.888889 |
scanny/python-pptx | pptx/parts/chart.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/parts/chart.py#L63-L73 | def update_from_xlsx_blob(self, xlsx_blob):
"""
Replace the Excel spreadsheet in the related |EmbeddedXlsxPart| with
the Excel binary in *xlsx_blob*, adding a new |EmbeddedXlsxPart| if
there isn't one.
"""
xlsx_part = self.xlsx_part
if xlsx_part is None:
... | [
"def",
"update_from_xlsx_blob",
"(",
"self",
",",
"xlsx_blob",
")",
":",
"xlsx_part",
"=",
"self",
".",
"xlsx_part",
"if",
"xlsx_part",
"is",
"None",
":",
"self",
".",
"xlsx_part",
"=",
"EmbeddedXlsxPart",
".",
"new",
"(",
"xlsx_blob",
",",
"self",
".",
"_... | Replace the Excel spreadsheet in the related |EmbeddedXlsxPart| with
the Excel binary in *xlsx_blob*, adding a new |EmbeddedXlsxPart| if
there isn't one. | [
"Replace",
"the",
"Excel",
"spreadsheet",
"in",
"the",
"related",
"|EmbeddedXlsxPart|",
"with",
"the",
"Excel",
"binary",
"in",
"*",
"xlsx_blob",
"*",
"adding",
"a",
"new",
"|EmbeddedXlsxPart|",
"if",
"there",
"isn",
"t",
"one",
"."
] | python | train | 39.090909 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.