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 |
|---|---|---|---|---|---|---|---|---|---|
sdispater/orator | orator/orm/collection.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/collection.py#L7-L16 | def load(self, *relations):
"""
Load a set of relationships onto the collection.
"""
if len(self.items) > 0:
query = self.first().new_query().with_(*relations)
self._set_items(query.eager_load_relations(self.items))
return self | [
"def",
"load",
"(",
"self",
",",
"*",
"relations",
")",
":",
"if",
"len",
"(",
"self",
".",
"items",
")",
">",
"0",
":",
"query",
"=",
"self",
".",
"first",
"(",
")",
".",
"new_query",
"(",
")",
".",
"with_",
"(",
"*",
"relations",
")",
"self",... | Load a set of relationships onto the collection. | [
"Load",
"a",
"set",
"of",
"relationships",
"onto",
"the",
"collection",
"."
] | python | train | 28.4 |
arne-cl/discoursegraphs | src/discoursegraphs/discoursegraph.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/discoursegraph.py#L686-L723 | def merge_graphs(self, other_docgraph, verbose=False):
"""
Merges another document graph into the current one, thereby adding all
the necessary nodes and edges (with attributes, layers etc.).
NOTE: This will only work if both graphs have exactly the same
tokenization.
""... | [
"def",
"merge_graphs",
"(",
"self",
",",
"other_docgraph",
",",
"verbose",
"=",
"False",
")",
":",
"# keep track of all merged/old root nodes in case we need to",
"# delete them or their attributes (e.g. 'metadata')",
"if",
"hasattr",
"(",
"self",
",",
"'merged_rootnodes'",
"... | Merges another document graph into the current one, thereby adding all
the necessary nodes and edges (with attributes, layers etc.).
NOTE: This will only work if both graphs have exactly the same
tokenization. | [
"Merges",
"another",
"document",
"graph",
"into",
"the",
"current",
"one",
"thereby",
"adding",
"all",
"the",
"necessary",
"nodes",
"and",
"edges",
"(",
"with",
"attributes",
"layers",
"etc",
".",
")",
"."
] | python | train | 47.236842 |
jilljenn/tryalgo | tryalgo/pq_tree.py | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/pq_tree.py#L247-L271 | def consecutive_ones_property(sets, universe=None):
""" Check the consecutive ones property.
:param list sets: is a list of subsets of the ground set.
:param groundset: is the set of all elements,
by default it is the union of the given sets
:returns: returns a list of the ordered groun... | [
"def",
"consecutive_ones_property",
"(",
"sets",
",",
"universe",
"=",
"None",
")",
":",
"if",
"universe",
"is",
"None",
":",
"universe",
"=",
"set",
"(",
")",
"for",
"S",
"in",
"sets",
":",
"universe",
"|=",
"set",
"(",
"S",
")",
"tree",
"=",
"PQ_tr... | Check the consecutive ones property.
:param list sets: is a list of subsets of the ground set.
:param groundset: is the set of all elements,
by default it is the union of the given sets
:returns: returns a list of the ordered ground set where
every given set is consecutive,
... | [
"Check",
"the",
"consecutive",
"ones",
"property",
"."
] | python | train | 37.2 |
bretth/woven | woven/virtualenv.py | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L184-L207 | def mkvirtualenv():
"""
Create the virtualenv project environment
"""
root = '/'.join([deployment_root(),'env'])
path = '/'.join([root,env.project_fullname])
dirs_created = []
if env.verbosity:
print env.host,'CREATING VIRTUALENV', path
if not exists(root): dirs_created += mkdirs... | [
"def",
"mkvirtualenv",
"(",
")",
":",
"root",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
"]",
")",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"root",
",",
"env",
".",
"project_fullname",
"]",
")",
"dirs_created",
... | Create the virtualenv project environment | [
"Create",
"the",
"virtualenv",
"project",
"environment"
] | python | train | 37.125 |
suds-community/suds | suds/sudsobject.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sudsobject.py#L326-L350 | def print_dictionary(self, d, h, n, nl=False):
"""Print complex using the specified indent (n) and newline (nl)."""
if d in h:
return "{}..."
h.append(d)
s = []
if nl:
s.append("\n")
s.append(self.indent(n))
s.append("{")
for it... | [
"def",
"print_dictionary",
"(",
"self",
",",
"d",
",",
"h",
",",
"n",
",",
"nl",
"=",
"False",
")",
":",
"if",
"d",
"in",
"h",
":",
"return",
"\"{}...\"",
"h",
".",
"append",
"(",
"d",
")",
"s",
"=",
"[",
"]",
"if",
"nl",
":",
"s",
".",
"ap... | Print complex using the specified indent (n) and newline (nl). | [
"Print",
"complex",
"using",
"the",
"specified",
"indent",
"(",
"n",
")",
"and",
"newline",
"(",
"nl",
")",
"."
] | python | train | 30.52 |
googleapis/google-cloud-python | storage/google/cloud/storage/acl.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L506-L524 | def save_predefined(self, predefined, client=None):
"""Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
... | [
"def",
"save_predefined",
"(",
"self",
",",
"predefined",
",",
"client",
"=",
"None",
")",
":",
"predefined",
"=",
"self",
".",
"validate_predefined",
"(",
"predefined",
")",
"self",
".",
"_save",
"(",
"None",
",",
"predefined",
",",
"client",
")"
] | Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
of the keys in :attr:`PREDEFINED_JSON_ACLS`
... | [
"Save",
"this",
"ACL",
"for",
"the",
"current",
"bucket",
"using",
"a",
"predefined",
"ACL",
"."
] | python | train | 49 |
JohnVinyard/zounds | zounds/spectral/frequencyscale.py | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/frequencyscale.py#L387-L398 | def from_sample_rate(sample_rate, n_bands, always_even=False):
"""
Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist fre... | [
"def",
"from_sample_rate",
"(",
"sample_rate",
",",
"n_bands",
",",
"always_even",
"=",
"False",
")",
":",
"fb",
"=",
"FrequencyBand",
"(",
"0",
",",
"sample_rate",
".",
"nyquist",
")",
"return",
"LinearScale",
"(",
"fb",
",",
"n_bands",
",",
"always_even",
... | Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist frequency
will serve as the upper frequency bound of this scale
... | [
"Return",
"a",
":",
"class",
":",
"~zounds",
".",
"spectral",
".",
"LinearScale",
"instance",
"whose",
"upper",
"frequency",
"bound",
"is",
"informed",
"by",
"the",
"nyquist",
"frequency",
"of",
"the",
"sample",
"rate",
"."
] | python | train | 48.666667 |
grantmcconnaughey/django-field-history | field_history/json_nested_serializer.py | https://github.com/grantmcconnaughey/django-field-history/blob/b61885d8bddf7d1f53addf3bea098f67fcf9a618/field_history/json_nested_serializer.py#L26-L65 | def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.pop("stream", six.StringIO())
self.selected_fields = options.pop("fields", None)
self.use_natural_keys = options.pop("use_natural_keys", False)
... | [
"def",
"serialize",
"(",
"self",
",",
"queryset",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"options",
"=",
"options",
"self",
".",
"stream",
"=",
"options",
".",
"pop",
"(",
"\"stream\"",
",",
"six",
".",
"StringIO",
"(",
")",
")",
"self",
... | Serialize a queryset. | [
"Serialize",
"a",
"queryset",
"."
] | python | train | 50.8 |
benoitguigal/python-epson-printer | epson_printer/epsonprinter.py | https://github.com/benoitguigal/python-epson-printer/blob/7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5/epson_printer/epsonprinter.py#L103-L153 | def from_image(cls, image):
"""
Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return:
"""
(w, h) = image.size
# Thermal paper is 512 pixels wide
if w > 512:
ratio = 512. / w
h = int(h * ratio)
imag... | [
"def",
"from_image",
"(",
"cls",
",",
"image",
")",
":",
"(",
"w",
",",
"h",
")",
"=",
"image",
".",
"size",
"# Thermal paper is 512 pixels wide",
"if",
"w",
">",
"512",
":",
"ratio",
"=",
"512.",
"/",
"w",
"h",
"=",
"int",
"(",
"h",
"*",
"ratio",
... | Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return: | [
"Create",
"a",
"PrintableImage",
"from",
"a",
"PIL",
"Image",
":",
"param",
"image",
":",
"a",
"PIL",
"Image",
":",
"return",
":"
] | python | train | 27.156863 |
pandas-dev/pandas | pandas/core/arrays/datetimes.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimes.py#L2114-L2140 | def _maybe_localize_point(ts, is_none, is_not_none, freq, tz):
"""
Localize a start or end Timestamp to the timezone of the corresponding
start or end Timestamp
Parameters
----------
ts : start or end Timestamp to potentially localize
is_none : argument that should be None
is_not_none :... | [
"def",
"_maybe_localize_point",
"(",
"ts",
",",
"is_none",
",",
"is_not_none",
",",
"freq",
",",
"tz",
")",
":",
"# Make sure start and end are timezone localized if:",
"# 1) freq = a Timedelta-like frequency (Tick)",
"# 2) freq = None i.e. generating a linspaced range",
"if",
"i... | Localize a start or end Timestamp to the timezone of the corresponding
start or end Timestamp
Parameters
----------
ts : start or end Timestamp to potentially localize
is_none : argument that should be None
is_not_none : argument that should not be None
freq : Tick, DateOffset, or None
... | [
"Localize",
"a",
"start",
"or",
"end",
"Timestamp",
"to",
"the",
"timezone",
"of",
"the",
"corresponding",
"start",
"or",
"end",
"Timestamp"
] | python | train | 32.444444 |
rstoneback/pysat | pysat/instruments/sw_kp.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/instruments/sw_kp.py#L183-L234 | def download(date_array, tag, sat_id, data_path, user=None, password=None):
"""Routine to download Kp index data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or NoneType)
... | [
"def",
"download",
"(",
"date_array",
",",
"tag",
",",
"sat_id",
",",
"data_path",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"import",
"ftplib",
"from",
"ftplib",
"import",
"FTP",
"import",
"sys",
"ftp",
"=",
"FTP",
"(",
"'ftp.g... | Routine to download Kp index data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or NoneType)
Specifies the satellite ID for a constellation. Not used.
(default=None)... | [
"Routine",
"to",
"download",
"Kp",
"index",
"data"
] | python | train | 33.057692 |
tensorflow/tensor2tensor | tensor2tensor/utils/registry.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L174-L177 | def on_set(self, key, value):
"""Callback called on successful set. Uses function from __init__."""
if self._on_set is not None:
self._on_set(key, value) | [
"def",
"on_set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"_on_set",
"is",
"not",
"None",
":",
"self",
".",
"_on_set",
"(",
"key",
",",
"value",
")"
] | Callback called on successful set. Uses function from __init__. | [
"Callback",
"called",
"on",
"successful",
"set",
".",
"Uses",
"function",
"from",
"__init__",
"."
] | python | train | 41 |
EUDAT-B2SAFE/B2HANDLE | b2handle/handleclient.py | https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1068-L1082 | def __send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Opt... | [
"def",
"__send_handle_get_request",
"(",
"self",
",",
"handle",
",",
"indices",
"=",
"None",
")",
":",
"resp",
"=",
"self",
".",
"__handlesystemconnector",
".",
"send_handle_get_request",
"(",
"handle",
",",
"indices",
")",
"return",
"resp"
] | Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the enti... | [
"Send",
"a",
"HTTP",
"GET",
"request",
"to",
"the",
"handle",
"server",
"to",
"read",
"either",
"an",
"entire",
"handle",
"or",
"to",
"some",
"specified",
"values",
"from",
"a",
"handle",
"record",
"using",
"the",
"requests",
"module",
"."
] | python | train | 41.333333 |
dswah/pyGAM | pygam/utils.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/utils.py#L568-L707 | def b_spline_basis(x, edge_knots, n_splines=20, spline_order=3, sparse=True,
periodic=True, verbose=True):
"""
tool to generate b-spline basis using vectorized De Boor recursion
the basis functions extrapolate linearly past the end-knots.
Parameters
----------
x : array-like,... | [
"def",
"b_spline_basis",
"(",
"x",
",",
"edge_knots",
",",
"n_splines",
"=",
"20",
",",
"spline_order",
"=",
"3",
",",
"sparse",
"=",
"True",
",",
"periodic",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"np",
".",
"ravel",
"(",
"x",
"... | tool to generate b-spline basis using vectorized De Boor recursion
the basis functions extrapolate linearly past the end-knots.
Parameters
----------
x : array-like, with ndims == 1.
edge_knots : array-like contaning locations of the 2 edge knots.
n_splines : int. number of splines to generate.... | [
"tool",
"to",
"generate",
"b",
"-",
"spline",
"basis",
"using",
"vectorized",
"De",
"Boor",
"recursion",
"the",
"basis",
"functions",
"extrapolate",
"linearly",
"past",
"the",
"end",
"-",
"knots",
"."
] | python | train | 34.085714 |
jeffh/pyconstraints | pyconstraints/solvers.py | https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L277-L293 | def _next(self, possible_solution):
"""Where the magic happens. Produces a generator that returns all solutions given
a base solution to start searching.
"""
# bail out if we have seen it already. See __iter__ to where seen is initially set.
# A complete solution has all its vari... | [
"def",
"_next",
"(",
"self",
",",
"possible_solution",
")",
":",
"# bail out if we have seen it already. See __iter__ to where seen is initially set.",
"# A complete solution has all its variables set to a particular value.",
"is_complete",
"=",
"(",
"len",
"(",
"possible_solution",
... | Where the magic happens. Produces a generator that returns all solutions given
a base solution to start searching. | [
"Where",
"the",
"magic",
"happens",
".",
"Produces",
"a",
"generator",
"that",
"returns",
"all",
"solutions",
"given",
"a",
"base",
"solution",
"to",
"start",
"searching",
"."
] | python | train | 46.882353 |
pallets/werkzeug | src/werkzeug/wrappers/common_descriptors.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/common_descriptors.py#L147-L159 | def mimetype_params(self):
"""The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5
"""
def on_update(d):
self.headers["Content-Type"] = dump_optio... | [
"def",
"mimetype_params",
"(",
"self",
")",
":",
"def",
"on_update",
"(",
"d",
")",
":",
"self",
".",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"dump_options_header",
"(",
"self",
".",
"mimetype",
",",
"d",
")",
"d",
"=",
"parse_options_header",
"(",
... | The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5 | [
"The",
"mimetype",
"parameters",
"as",
"dict",
".",
"For",
"example",
"if",
"the",
"content",
"type",
"is",
"text",
"/",
"html",
";",
"charset",
"=",
"utf",
"-",
"8",
"the",
"params",
"would",
"be",
"{",
"charset",
":",
"utf",
"-",
"8",
"}",
"."
] | python | train | 34.769231 |
saltstack/salt | salt/modules/solr.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L902-L945 | def set_is_polling(polling, host=None, core_name=None):
'''
SLAVE CALL
Prevent the slaves from polling the master for updates.
polling : boolean
True will enable polling. False will disable it.
host : str (None)
The solr host to query. __opts__['host'] is default.
core_name : st... | [
"def",
"set_is_polling",
"(",
"polling",
",",
"host",
"=",
"None",
",",
"core_name",
"=",
"None",
")",
":",
"ret",
"=",
"_get_return_dict",
"(",
")",
"# since only slaves can call this let's check the config:",
"if",
"_is_master",
"(",
")",
"and",
"_get_none_or_valu... | SLAVE CALL
Prevent the slaves from polling the master for updates.
polling : boolean
True will enable polling. False will disable it.
host : str (None)
The solr host to query. __opts__['host'] is default.
core_name : str (None)
The name of the solr core if using cores. Leave thi... | [
"SLAVE",
"CALL",
"Prevent",
"the",
"slaves",
"from",
"polling",
"the",
"master",
"for",
"updates",
"."
] | python | train | 34.954545 |
proycon/clam | clam/common/data.py | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1881-L1887 | def getparent(self, profile):
"""Resolve a parent ID"""
assert self.parent
for inputtemplate in profile.input:
if inputtemplate == self.parent:
return inputtemplate
raise Exception("Parent InputTemplate '"+self.parent+"' not found!") | [
"def",
"getparent",
"(",
"self",
",",
"profile",
")",
":",
"assert",
"self",
".",
"parent",
"for",
"inputtemplate",
"in",
"profile",
".",
"input",
":",
"if",
"inputtemplate",
"==",
"self",
".",
"parent",
":",
"return",
"inputtemplate",
"raise",
"Exception",
... | Resolve a parent ID | [
"Resolve",
"a",
"parent",
"ID"
] | python | train | 41 |
ml4ai/delphi | delphi/GrFN/networks.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L641-L651 | def to_call_agraph(self):
""" Build a PyGraphviz AGraph object corresponding to a call graph of
functions. """
A = nx.nx_agraph.to_agraph(self.call_graph)
A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"})
A.node_attr.update(
{"shape": "rectangle"... | [
"def",
"to_call_agraph",
"(",
"self",
")",
":",
"A",
"=",
"nx",
".",
"nx_agraph",
".",
"to_agraph",
"(",
"self",
".",
"call_graph",
")",
"A",
".",
"graph_attr",
".",
"update",
"(",
"{",
"\"dpi\"",
":",
"227",
",",
"\"fontsize\"",
":",
"20",
",",
"\"f... | Build a PyGraphviz AGraph object corresponding to a call graph of
functions. | [
"Build",
"a",
"PyGraphviz",
"AGraph",
"object",
"corresponding",
"to",
"a",
"call",
"graph",
"of",
"functions",
"."
] | python | train | 40.454545 |
Yubico/python-pyhsm | pyhsm/soft_hsm.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L95-L129 | def aesCCM(key, key_handle, nonce, data, decrypt=False):
"""
Function implementing YubiHSM AEAD encrypt/decrypt in software.
"""
if decrypt:
(data, saved_mac) = _split_data(data, len(data) - pyhsm.defines.YSM_AEAD_MAC_SIZE)
nonce = pyhsm.util.input_validate_nonce(nonce, pad = True)
mac ... | [
"def",
"aesCCM",
"(",
"key",
",",
"key_handle",
",",
"nonce",
",",
"data",
",",
"decrypt",
"=",
"False",
")",
":",
"if",
"decrypt",
":",
"(",
"data",
",",
"saved_mac",
")",
"=",
"_split_data",
"(",
"data",
",",
"len",
"(",
"data",
")",
"-",
"pyhsm"... | Function implementing YubiHSM AEAD encrypt/decrypt in software. | [
"Function",
"implementing",
"YubiHSM",
"AEAD",
"encrypt",
"/",
"decrypt",
"in",
"software",
"."
] | python | train | 31.171429 |
UCL-INGI/INGInious | inginious/frontend/pages/course_admin/danger_zone.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/danger_zone.py#L67-L91 | def restore_course(self, courseid, backup):
""" Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HHMMSS) """
self.wipe_course(courseid)
filepath = os.path.join(self.backup_dir, courseid, backup + ".zip")
with zipfile.ZipFile(filepath, "r") as zipf:
... | [
"def",
"restore_course",
"(",
"self",
",",
"courseid",
",",
"backup",
")",
":",
"self",
".",
"wipe_course",
"(",
"courseid",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"backup_dir",
",",
"courseid",
",",
"backup",
"+",
"\".... | Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HHMMSS) | [
"Restores",
"a",
"course",
"of",
"given",
"courseid",
"to",
"a",
"date",
"specified",
"in",
"backup",
"(",
"format",
":",
"YYYYMMDD",
".",
"HHMMSS",
")"
] | python | train | 51.28 |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/percolator.py | https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/percolator.py#L78-L91 | def _new_percolator(spec, search_pattern):
"""Create new percolator associated with the new set."""
if spec and search_pattern:
query = query_string_parser(search_pattern=search_pattern).to_dict()
for index in current_search.mappings.keys():
# Create the percolator doc_type in the ex... | [
"def",
"_new_percolator",
"(",
"spec",
",",
"search_pattern",
")",
":",
"if",
"spec",
"and",
"search_pattern",
":",
"query",
"=",
"query_string_parser",
"(",
"search_pattern",
"=",
"search_pattern",
")",
".",
"to_dict",
"(",
")",
"for",
"index",
"in",
"current... | Create new percolator associated with the new set. | [
"Create",
"new",
"percolator",
"associated",
"with",
"the",
"new",
"set",
"."
] | python | train | 52.285714 |
google/grr | api_client/python/grr_api_client/hunt.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/api_client/python/grr_api_client/hunt.py#L342-L347 | def ListHunts(context=None):
"""List all GRR hunts."""
items = context.SendIteratorRequest("ListHunts", hunt_pb2.ApiListHuntsArgs())
return utils.MapItemsIterator(lambda data: Hunt(data=data, context=context),
items) | [
"def",
"ListHunts",
"(",
"context",
"=",
"None",
")",
":",
"items",
"=",
"context",
".",
"SendIteratorRequest",
"(",
"\"ListHunts\"",
",",
"hunt_pb2",
".",
"ApiListHuntsArgs",
"(",
")",
")",
"return",
"utils",
".",
"MapItemsIterator",
"(",
"lambda",
"data",
... | List all GRR hunts. | [
"List",
"all",
"GRR",
"hunts",
"."
] | python | train | 41.666667 |
moderngl/moderngl | moderngl/context.py | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L955-L979 | def depth_renderbuffer(self, size, *, samples=0) -> 'Renderbuffer':
'''
:py:class:`Renderbuffer` objects are OpenGL objects that contain images.
They are created and used specifically with :py:class:`Framebuffer` objects.
Args:
size (tuple): The width and hei... | [
"def",
"depth_renderbuffer",
"(",
"self",
",",
"size",
",",
"*",
",",
"samples",
"=",
"0",
")",
"->",
"'Renderbuffer'",
":",
"res",
"=",
"Renderbuffer",
".",
"__new__",
"(",
"Renderbuffer",
")",
"res",
".",
"mglo",
",",
"res",
".",
"_glo",
"=",
"self",... | :py:class:`Renderbuffer` objects are OpenGL objects that contain images.
They are created and used specifically with :py:class:`Framebuffer` objects.
Args:
size (tuple): The width and height of the renderbuffer.
Keyword Args:
samples (int): The numbe... | [
":",
"py",
":",
"class",
":",
"Renderbuffer",
"objects",
"are",
"OpenGL",
"objects",
"that",
"contain",
"images",
".",
"They",
"are",
"created",
"and",
"used",
"specifically",
"with",
":",
"py",
":",
"class",
":",
"Framebuffer",
"objects",
"."
] | python | train | 33.84 |
Esri/ArcREST | src/arcrest/ags/_uploads.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_uploads.py#L109-L129 | def download(self, itemID, savePath):
"""
downloads an item to local disk
Inputs:
itemID - unique id of item to download
savePath - folder to save the file in
"""
if os.path.isdir(savePath) == False:
os.makedirs(savePath)
url = self._url... | [
"def",
"download",
"(",
"self",
",",
"itemID",
",",
"savePath",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"savePath",
")",
"==",
"False",
":",
"os",
".",
"makedirs",
"(",
"savePath",
")",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/%s/dow... | downloads an item to local disk
Inputs:
itemID - unique id of item to download
savePath - folder to save the file in | [
"downloads",
"an",
"item",
"to",
"local",
"disk"
] | python | train | 34.809524 |
GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L313-L320 | def _get_vnet(self, adapter_number):
"""
Return the vnet will use in ubridge
"""
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet not in self._vmx_pairs:
raise VMwareError("vnet {} not in VMX file".format(vnet))
return vnet | [
"def",
"_get_vnet",
"(",
"self",
",",
"adapter_number",
")",
":",
"vnet",
"=",
"\"ethernet{}.vnet\"",
".",
"format",
"(",
"adapter_number",
")",
"if",
"vnet",
"not",
"in",
"self",
".",
"_vmx_pairs",
":",
"raise",
"VMwareError",
"(",
"\"vnet {} not in VMX file\""... | Return the vnet will use in ubridge | [
"Return",
"the",
"vnet",
"will",
"use",
"in",
"ubridge"
] | python | train | 35.375 |
srittau/python-asserts | asserts/__init__.py | https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L99-L115 | def assert_boolean_false(expr, msg_fmt="{msg}"):
"""Fail the test unless the expression is the constant False.
>>> assert_boolean_false(False)
>>> assert_boolean_false(0)
Traceback (most recent call last):
...
AssertionError: 0 is not False
The following msg_fmt arguments are supported... | [
"def",
"assert_boolean_false",
"(",
"expr",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"if",
"expr",
"is",
"not",
"False",
":",
"msg",
"=",
"\"{!r} is not False\"",
".",
"format",
"(",
"expr",
")",
"fail",
"(",
"msg_fmt",
".",
"format",
"(",
"msg",
"=",... | Fail the test unless the expression is the constant False.
>>> assert_boolean_false(False)
>>> assert_boolean_false(0)
Traceback (most recent call last):
...
AssertionError: 0 is not False
The following msg_fmt arguments are supported:
* msg - the default error message
* expr - tes... | [
"Fail",
"the",
"test",
"unless",
"the",
"expression",
"is",
"the",
"constant",
"False",
"."
] | python | train | 29.705882 |
mardix/Juice | juice/decorators.py | https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/decorators.py#L127-L190 | def template(page=None, layout=None, **kwargs):
"""
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:fi... | [
"def",
"template",
"(",
"page",
"=",
"None",
",",
"layout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pkey",
"=",
"\"_template_extends__\"",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"f",
")",
":",
"layout_"... | Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:first arg or $layout: The layout to use for that view
... | [
"Decorator",
"to",
"change",
"the",
"view",
"template",
"and",
"layout",
"."
] | python | train | 33.09375 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L637-L668 | def make_urls_hyperlinks(text: str) -> str:
"""
Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://stackp.online.f... | [
"def",
"make_urls_hyperlinks",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"find_url",
"=",
"r'''\n (?x)( # verbose identify URLs within text\n (http|ftp|gopher) # make sure we find a resource type\n :// # ...needs to be followed by colon... | Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://stackp.online.fr/?p=19 | [
"Adds",
"hyperlinks",
"to",
"text",
"that",
"appears",
"to",
"contain",
"URLs",
"."
] | python | train | 42.21875 |
creare-com/pydem | pydem/processing_manager.py | https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L487-L492 | def update_edge_todo(self, elev_fn, dem_proc):
"""
Can figure out how to update the todo based on the elev filename
"""
for key in self.edges[elev_fn].keys():
self.edges[elev_fn][key].set_data('todo', data=dem_proc.edge_todo) | [
"def",
"update_edge_todo",
"(",
"self",
",",
"elev_fn",
",",
"dem_proc",
")",
":",
"for",
"key",
"in",
"self",
".",
"edges",
"[",
"elev_fn",
"]",
".",
"keys",
"(",
")",
":",
"self",
".",
"edges",
"[",
"elev_fn",
"]",
"[",
"key",
"]",
".",
"set_data... | Can figure out how to update the todo based on the elev filename | [
"Can",
"figure",
"out",
"how",
"to",
"update",
"the",
"todo",
"based",
"on",
"the",
"elev",
"filename"
] | python | train | 44 |
pytroll/satpy | satpy/readers/goes_imager_nc.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/goes_imager_nc.py#L620-L634 | def _get_sector(self, channel, nlines, ncols):
"""Determine which sector was scanned"""
if self._is_vis(channel):
margin = 100
sectors_ref = self.vis_sectors
else:
margin = 50
sectors_ref = self.ir_sectors
for (nlines_ref, ncols_ref), sect... | [
"def",
"_get_sector",
"(",
"self",
",",
"channel",
",",
"nlines",
",",
"ncols",
")",
":",
"if",
"self",
".",
"_is_vis",
"(",
"channel",
")",
":",
"margin",
"=",
"100",
"sectors_ref",
"=",
"self",
".",
"vis_sectors",
"else",
":",
"margin",
"=",
"50",
... | Determine which sector was scanned | [
"Determine",
"which",
"sector",
"was",
"scanned"
] | python | train | 33.933333 |
ployground/bsdploy | bsdploy/bootstrap_utils.py | https://github.com/ployground/bsdploy/blob/096d63b316264931627bed1f8ca8abf7eb517352/bsdploy/bootstrap_utils.py#L158-L266 | def bootstrap_files(self):
""" we need some files to bootstrap the FreeBSD installation.
Some...
- need to be provided by the user (i.e. authorized_keys)
- others have some (sensible) defaults (i.e. rc.conf)
- some can be downloaded via URL (i.e.) http://pkg.freebsd.o... | [
"def",
"bootstrap_files",
"(",
"self",
")",
":",
"bootstrap_file_yamls",
"=",
"[",
"abspath",
"(",
"join",
"(",
"self",
".",
"default_template_path",
",",
"self",
".",
"bootstrap_files_yaml",
")",
")",
",",
"abspath",
"(",
"join",
"(",
"self",
".",
"custom_t... | we need some files to bootstrap the FreeBSD installation.
Some...
- need to be provided by the user (i.e. authorized_keys)
- others have some (sensible) defaults (i.e. rc.conf)
- some can be downloaded via URL (i.e.) http://pkg.freebsd.org/freebsd:10:x86:64/latest/Latest/pkg.... | [
"we",
"need",
"some",
"files",
"to",
"bootstrap",
"the",
"FreeBSD",
"installation",
".",
"Some",
"...",
"-",
"need",
"to",
"be",
"provided",
"by",
"the",
"user",
"(",
"i",
".",
"e",
".",
"authorized_keys",
")",
"-",
"others",
"have",
"some",
"(",
"sens... | python | train | 51.770642 |
awslabs/sockeye | sockeye/encoder.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/encoder.py#L937-L941 | def get_rnn_cells(self) -> List[mx.rnn.BaseRNNCell]:
"""
Returns a list of RNNCells used by this encoder.
"""
return self.forward_rnn.get_rnn_cells() + self.reverse_rnn.get_rnn_cells() | [
"def",
"get_rnn_cells",
"(",
"self",
")",
"->",
"List",
"[",
"mx",
".",
"rnn",
".",
"BaseRNNCell",
"]",
":",
"return",
"self",
".",
"forward_rnn",
".",
"get_rnn_cells",
"(",
")",
"+",
"self",
".",
"reverse_rnn",
".",
"get_rnn_cells",
"(",
")"
] | Returns a list of RNNCells used by this encoder. | [
"Returns",
"a",
"list",
"of",
"RNNCells",
"used",
"by",
"this",
"encoder",
"."
] | python | train | 42.4 |
python-cmd2/cmd2 | cmd2/history.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L76-L81 | def _zero_based_index(self, onebased: Union[int, str]) -> int:
"""Convert a one-based index to a zero-based index."""
result = int(onebased)
if result > 0:
result -= 1
return result | [
"def",
"_zero_based_index",
"(",
"self",
",",
"onebased",
":",
"Union",
"[",
"int",
",",
"str",
"]",
")",
"->",
"int",
":",
"result",
"=",
"int",
"(",
"onebased",
")",
"if",
"result",
">",
"0",
":",
"result",
"-=",
"1",
"return",
"result"
] | Convert a one-based index to a zero-based index. | [
"Convert",
"a",
"one",
"-",
"based",
"index",
"to",
"a",
"zero",
"-",
"based",
"index",
"."
] | python | train | 36.666667 |
guaix-ucm/numina | numina/store/gtc/load.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/store/gtc/load.py#L62-L76 | def build_result(data):
"""Create a dictionary with the contents of result.json"""
more = {}
for key, value in data.items():
if key != 'elements':
newnode = value
else:
newnode = {}
for el in value:
nkey, nvalue = process_node(el)
... | [
"def",
"build_result",
"(",
"data",
")",
":",
"more",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"key",
"!=",
"'elements'",
":",
"newnode",
"=",
"value",
"else",
":",
"newnode",
"=",
"{",
"}",
"for... | Create a dictionary with the contents of result.json | [
"Create",
"a",
"dictionary",
"with",
"the",
"contents",
"of",
"result",
".",
"json"
] | python | train | 25.466667 |
yuce/pyswip | pyswip/core.py | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L393-L432 | def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: T... | [
"def",
"_findSwipl",
"(",
")",
":",
"# Now begins the guesswork",
"platform",
"=",
"sys",
".",
"platform",
"[",
":",
"3",
"]",
"if",
"platform",
"==",
"\"win\"",
":",
"# In Windows, we have the default installer",
"# path and the registry to look",
"(",
"path",
",",
... | This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name... | [
"This",
"function",
"makes",
"a",
"big",
"effort",
"to",
"find",
"the",
"path",
"to",
"the",
"SWI",
"-",
"Prolog",
"shared",
"library",
".",
"Since",
"this",
"is",
"both",
"OS",
"dependent",
"and",
"installation",
"dependent",
"we",
"may",
"not",
"aways",
... | python | train | 37.35 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiVipRequest.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiVipRequest.py#L243-L252 | def deploy(self, ids):
"""
Method to deploy vip's
:param vips: List containing vip's desired to be deployed on equipment
:return: None
"""
url = build_uri_with_ids('api/v3/vip-request/deploy/%s/', ids)
return super(ApiVipRequest, self).post(url) | [
"def",
"deploy",
"(",
"self",
",",
"ids",
")",
":",
"url",
"=",
"build_uri_with_ids",
"(",
"'api/v3/vip-request/deploy/%s/'",
",",
"ids",
")",
"return",
"super",
"(",
"ApiVipRequest",
",",
"self",
")",
".",
"post",
"(",
"url",
")"
] | Method to deploy vip's
:param vips: List containing vip's desired to be deployed on equipment
:return: None | [
"Method",
"to",
"deploy",
"vip",
"s"
] | python | train | 29.4 |
arne-cl/discoursegraphs | src/discoursegraphs/discoursegraph.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/discoursegraph.py#L614-L640 | def add_layer(self, element, layer):
"""
add a layer to an existing node or edge
Parameters
----------
element : str, int, (str/int, str/int)
the ID of a node or edge (source node ID, target node ID)
layer : str
the layer that the element shall be... | [
"def",
"add_layer",
"(",
"self",
",",
"element",
",",
"layer",
")",
":",
"assert",
"isinstance",
"(",
"layer",
",",
"str",
")",
",",
"\"Layers must be strings!\"",
"if",
"isinstance",
"(",
"element",
",",
"tuple",
")",
":",
"# edge repr. by (source, target)",
... | add a layer to an existing node or edge
Parameters
----------
element : str, int, (str/int, str/int)
the ID of a node or edge (source node ID, target node ID)
layer : str
the layer that the element shall be added to | [
"add",
"a",
"layer",
"to",
"an",
"existing",
"node",
"or",
"edge"
] | python | train | 44.740741 |
asyrjasalo/RESTinstance | src/REST/keywords.py | https://github.com/asyrjasalo/RESTinstance/blob/9b003ffc6a89ec4b8b6f05eeb6cc8e56aad4be4e/src/REST/keywords.py#L81-L94 | def set_headers(self, headers):
"""*Sets new request headers or updates the existing.*
``headers``: The headers to add or update as a JSON object or a
dictionary.
*Examples*
| `Set Headers` | { "authorization": "Basic QWxhZGRpbjpPcGVuU2VzYW1"} |
| `Set Headers` | { "Ac... | [
"def",
"set_headers",
"(",
"self",
",",
"headers",
")",
":",
"self",
".",
"request",
"[",
"\"headers\"",
"]",
".",
"update",
"(",
"self",
".",
"_input_object",
"(",
"headers",
")",
")",
"return",
"self",
".",
"request",
"[",
"\"headers\"",
"]"
] | *Sets new request headers or updates the existing.*
``headers``: The headers to add or update as a JSON object or a
dictionary.
*Examples*
| `Set Headers` | { "authorization": "Basic QWxhZGRpbjpPcGVuU2VzYW1"} |
| `Set Headers` | { "Accept-Encoding": "identity"} |
| `Se... | [
"*",
"Sets",
"new",
"request",
"headers",
"or",
"updates",
"the",
"existing",
".",
"*"
] | python | train | 35.428571 |
openego/eDisGo | edisgo/grid/network.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/network.py#L1444-L1471 | def _worst_case_generation(self, worst_case_scale_factors, modes):
"""
Define worst case generation time series for fluctuating and
dispatchable generators.
Parameters
----------
worst_case_scale_factors : dict
Scale factors defined in config file 'config_tim... | [
"def",
"_worst_case_generation",
"(",
"self",
",",
"worst_case_scale_factors",
",",
"modes",
")",
":",
"self",
".",
"timeseries",
".",
"generation_fluctuating",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"'solar'",
":",
"[",
"worst_case_scale_factors",
"[",
"'{}_feedi... | Define worst case generation time series for fluctuating and
dispatchable generators.
Parameters
----------
worst_case_scale_factors : dict
Scale factors defined in config file 'config_timeseries.cfg'.
Scale factors describe actual power to nominal power ratio of... | [
"Define",
"worst",
"case",
"generation",
"time",
"series",
"for",
"fluctuating",
"and",
"dispatchable",
"generators",
"."
] | python | train | 41.75 |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L1550-L1567 | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._attachment is not None:
ret... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_uuid",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_created",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_updated",
"is",
"not",
"None",
... | :rtype: bool | [
":",
"rtype",
":",
"bool"
] | python | train | 18.5 |
cloudant/python-cloudant | src/cloudant/client.py | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L421-L443 | def get(self, key, default=None, remote=False):
"""
Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally c... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"remote",
"=",
"False",
")",
":",
"if",
"not",
"remote",
":",
"return",
"super",
"(",
"CouchDB",
",",
"self",
")",
".",
"get",
"(",
"key",
",",
"default",
")",
"db",
"=",
... | Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally cached database object is returned.
:param str key: Database... | [
"Overrides",
"dictionary",
"get",
"behavior",
"to",
"retrieve",
"database",
"objects",
"with",
"support",
"for",
"returning",
"a",
"default",
".",
"If",
"remote",
"=",
"True",
"then",
"a",
"remote",
"request",
"is",
"made",
"to",
"retrieve",
"the",
"database",... | python | train | 42.391304 |
TaurusOlson/incisive | incisive/core.py | https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L55-L88 | def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}):
"""Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"... | [
"def",
"read_csv",
"(",
"filename",
",",
"delimiter",
"=",
"\",\"",
",",
"skip",
"=",
"0",
",",
"guess_type",
"=",
"True",
",",
"has_header",
"=",
"True",
",",
"use_types",
"=",
"{",
"}",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
... | Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"sepal.length": int, "petal.width": float}
>>> data = read_csv(filename, guess_type=guess_type, use... | [
"Read",
"a",
"CSV",
"file",
"Usage",
"-----",
">>>",
"data",
"=",
"read_csv",
"(",
"filename",
"delimiter",
"=",
"delimiter",
"skip",
"=",
"skip",
"guess_type",
"=",
"guess_type",
"has_header",
"=",
"True",
"use_types",
"=",
"{}",
")"
] | python | valid | 30.470588 |
robotools/extractor | Lib/extractor/formats/opentype.py | https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L453-L501 | def _gatherLookupIndexes(gpos):
"""
Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
}
"""
# gather the indexes of the kern features
kernFe... | [
"def",
"_gatherLookupIndexes",
"(",
"gpos",
")",
":",
"# gather the indexes of the kern features",
"kernFeatureIndexes",
"=",
"[",
"index",
"for",
"index",
",",
"featureRecord",
"in",
"enumerate",
"(",
"gpos",
".",
"FeatureList",
".",
"FeatureRecord",
")",
"if",
"fe... | Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
} | [
"Gather",
"a",
"mapping",
"of",
"script",
"to",
"lookup",
"indexes",
"referenced",
"by",
"the",
"kern",
"feature",
"for",
"each",
"script",
".",
"Returns",
"a",
"dictionary",
"of",
"this",
"structure",
":",
"{",
"latn",
":",
"[",
"0",
"]",
"DFLT",
":",
... | python | train | 45.612245 |
mdsol/rwslib | rwslib/builders/metadata.py | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/metadata.py#L1687-L1697 | def build(self, builder):
"""Build XML by appending to builder"""
params = dict(
Namespace=self.namespace,
Name=self.name,
Value=self.value,
TransactionType=self.transaction_type,
)
builder.start("mdsol:Attribute", params)
builder.... | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"params",
"=",
"dict",
"(",
"Namespace",
"=",
"self",
".",
"namespace",
",",
"Name",
"=",
"self",
".",
"name",
",",
"Value",
"=",
"self",
".",
"value",
",",
"TransactionType",
"=",
"self",
".",
... | Build XML by appending to builder | [
"Build",
"XML",
"by",
"appending",
"to",
"builder"
] | python | train | 30.181818 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py#L671-L682 | def get_vnetwork_vswitches_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
config = get_vnetwork_vswitches
input = ET.SubElement(get_vnetwork_vswitches, "input... | [
"def",
"get_vnetwork_vswitches_input_last_rcvd_instance",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_vswitches",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_vswitches\"",
")",
"con... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 45.083333 |
gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L182-L186 | def add_output_opt(self, opt, out):
""" Add an option that determines an output
"""
self.add_opt(opt, out._dax_repr())
self._add_output(out) | [
"def",
"add_output_opt",
"(",
"self",
",",
"opt",
",",
"out",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
",",
"out",
".",
"_dax_repr",
"(",
")",
")",
"self",
".",
"_add_output",
"(",
"out",
")"
] | Add an option that determines an output | [
"Add",
"an",
"option",
"that",
"determines",
"an",
"output"
] | python | train | 33.6 |
DigitalGlobe/gbdxtools | gbdxtools/images/mixins/geo.py | https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/mixins/geo.py#L61-L79 | def histogram_equalize(self, use_bands, **kwargs):
''' Equalize and the histogram and normalize value range
Equalization is on all three bands, not per-band'''
data = self._read(self[use_bands,...], **kwargs)
data = np.rollaxis(data.astype(np.float32), 0, 3)
flattened = data.... | [
"def",
"histogram_equalize",
"(",
"self",
",",
"use_bands",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"_read",
"(",
"self",
"[",
"use_bands",
",",
"...",
"]",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"np",
".",
"rollaxis",
"(",... | Equalize and the histogram and normalize value range
Equalization is on all three bands, not per-band | [
"Equalize",
"and",
"the",
"histogram",
"and",
"normalize",
"value",
"range",
"Equalization",
"is",
"on",
"all",
"three",
"bands",
"not",
"per",
"-",
"band"
] | python | valid | 48.736842 |
stefankoegl/kdtree | kdtree.py | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L187-L199 | def require_axis(f):
""" Check if the object of the function has axis and sel_axis members """
@wraps(f)
def _wrapper(self, *args, **kwargs):
if None in (self.axis, self.sel_axis):
raise ValueError('%(func_name) requires the node %(node)s '
'to have an axis and a sel... | [
"def",
"require_axis",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"None",
"in",
"(",
"self",
".",
"axis",
",",
"self",
".",
"sel_axis",
")",
":",
... | Check if the object of the function has axis and sel_axis members | [
"Check",
"if",
"the",
"object",
"of",
"the",
"function",
"has",
"axis",
"and",
"sel_axis",
"members"
] | python | train | 34.769231 |
fukuball/fuku-ml | FukuML/MLBase.py | https://github.com/fukuball/fuku-ml/blob/0da15ad7af76adf344b5a6b3f3dbabbbab3446b0/FukuML/MLBase.py#L34-L55 | def set_feature_transform(self, mode='polynomial', degree=1):
'''
Transform data feature to high level
'''
if self.status != 'load_train_data':
print("Please load train data first.")
return self.train_X
self.feature_transform_mode = mode
self.fe... | [
"def",
"set_feature_transform",
"(",
"self",
",",
"mode",
"=",
"'polynomial'",
",",
"degree",
"=",
"1",
")",
":",
"if",
"self",
".",
"status",
"!=",
"'load_train_data'",
":",
"print",
"(",
"\"Please load train data first.\"",
")",
"return",
"self",
".",
"train... | Transform data feature to high level | [
"Transform",
"data",
"feature",
"to",
"high",
"level"
] | python | test | 26.681818 |
msztolcman/versionner | versionner/config.py | https://github.com/msztolcman/versionner/blob/78fca02859e3e3eb71c9eb7ea230758944177c54/versionner/config.py#L106-L118 | def _parse_config_file(self, cfg_files):
"""Parse config file (ini) and set properties
:return:
"""
cfg_handler = configparser.ConfigParser(interpolation=None)
if not cfg_handler.read(map(str, cfg_files)):
return
self._parse_global_section(cfg_handler)
... | [
"def",
"_parse_config_file",
"(",
"self",
",",
"cfg_files",
")",
":",
"cfg_handler",
"=",
"configparser",
".",
"ConfigParser",
"(",
"interpolation",
"=",
"None",
")",
"if",
"not",
"cfg_handler",
".",
"read",
"(",
"map",
"(",
"str",
",",
"cfg_files",
")",
"... | Parse config file (ini) and set properties
:return: | [
"Parse",
"config",
"file",
"(",
"ini",
")",
"and",
"set",
"properties"
] | python | train | 30.307692 |
modin-project/modin | modin/backends/pandas/query_compiler.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pandas/query_compiler.py#L1637-L1663 | def query(self, expr, **kwargs):
"""Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied.
"""
columns = se... | [
"def",
"query",
"(",
"self",
",",
"expr",
",",
"*",
"*",
"kwargs",
")",
":",
"columns",
"=",
"self",
".",
"columns",
"def",
"query_builder",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"# This is required because of an Arrow limitation",
"# TODO revisit for ... | Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied. | [
"Query",
"columns",
"of",
"the",
"DataManager",
"with",
"a",
"boolean",
"expression",
"."
] | python | train | 37.592593 |
dhermes/bezier | docs/make_images.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1080-L1108 | def newton_refine_curve(curve, point, s, new_s):
"""Image for :func:`._curve_helpers.newton_refine` docstring."""
if NO_IMAGES:
return
ax = curve.plot(256)
ax.plot(point[0, :], point[1, :], marker="H")
wrong_points = curve.evaluate_multi(np.asfortranarray([s, new_s]))
ax.plot(
w... | [
"def",
"newton_refine_curve",
"(",
"curve",
",",
"point",
",",
"s",
",",
"new_s",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"ax",
"=",
"curve",
".",
"plot",
"(",
"256",
")",
"ax",
".",
"plot",
"(",
"point",
"[",
"0",
",",
":",
"]",
",",
"point"... | Image for :func:`._curve_helpers.newton_refine` docstring. | [
"Image",
"for",
":",
"func",
":",
".",
"_curve_helpers",
".",
"newton_refine",
"docstring",
"."
] | python | train | 27.517241 |
pudo/apikit | apikit/args.py | https://github.com/pudo/apikit/blob/638f83fc3f727d56541dd76ceb5fde04993a2bc6/apikit/args.py#L8-L13 | def arg_bool(name, default=False):
""" Fetch a query argument, as a boolean. """
v = request.args.get(name, '')
if not len(v):
return default
return v in BOOL_TRUISH | [
"def",
"arg_bool",
"(",
"name",
",",
"default",
"=",
"False",
")",
":",
"v",
"=",
"request",
".",
"args",
".",
"get",
"(",
"name",
",",
"''",
")",
"if",
"not",
"len",
"(",
"v",
")",
":",
"return",
"default",
"return",
"v",
"in",
"BOOL_TRUISH"
] | Fetch a query argument, as a boolean. | [
"Fetch",
"a",
"query",
"argument",
"as",
"a",
"boolean",
"."
] | python | train | 30.666667 |
ssalentin/plip | plip/modules/supplemental.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L410-L442 | def readmol(path, as_string=False):
"""Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type.
In contrast to the standard Pybel implementation, the file is closed properly."""
supported_formats = ['pdb']
# Fix for Windows-generated files: Remove carria... | [
"def",
"readmol",
"(",
"path",
",",
"as_string",
"=",
"False",
")",
":",
"supported_formats",
"=",
"[",
"'pdb'",
"]",
"# Fix for Windows-generated files: Remove carriage return characters",
"if",
"\"\\r\"",
"in",
"path",
"and",
"as_string",
":",
"path",
"=",
"path",... | Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type.
In contrast to the standard Pybel implementation, the file is closed properly. | [
"Reads",
"the",
"given",
"molecule",
"file",
"and",
"returns",
"the",
"corresponding",
"Pybel",
"molecule",
"as",
"well",
"as",
"the",
"input",
"file",
"type",
".",
"In",
"contrast",
"to",
"the",
"standard",
"Pybel",
"implementation",
"the",
"file",
"is",
"c... | python | train | 40.363636 |
edx/edx-enterprise | integrated_channels/degreed/client.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L127-L158 | def _sync_content_metadata(self, serialized_data, http_method):
"""
Synchronize content metadata using the Degreed course content API.
Args:
serialized_data: JSON-encoded object containing content metadata.
http_method: The HTTP method to use for the API request.
... | [
"def",
"_sync_content_metadata",
"(",
"self",
",",
"serialized_data",
",",
"http_method",
")",
":",
"try",
":",
"status_code",
",",
"response_body",
"=",
"getattr",
"(",
"self",
",",
"'_'",
"+",
"http_method",
")",
"(",
"urljoin",
"(",
"self",
".",
"enterpri... | Synchronize content metadata using the Degreed course content API.
Args:
serialized_data: JSON-encoded object containing content metadata.
http_method: The HTTP method to use for the API request.
Raises:
ClientError: If Degreed API request fails. | [
"Synchronize",
"content",
"metadata",
"using",
"the",
"Degreed",
"course",
"content",
"API",
"."
] | python | valid | 38.28125 |
evandempsey/porter2-stemmer | porter2stemmer/porter2stemmer.py | https://github.com/evandempsey/porter2-stemmer/blob/949824b7767c25efb014ef738e682442fa70c10b/porter2stemmer/porter2stemmer.py#L295-L313 | def delete_suffixes(self, word):
"""
Delete some very common suffixes.
"""
length = len(word)
suffixes = ['al', 'ance', 'ence', 'er', 'ic', 'able', 'ible',
'ant', 'ement', 'ment', 'ent', 'ism', 'ate',
'iti', 'ous', 'ive', 'ize']
fo... | [
"def",
"delete_suffixes",
"(",
"self",
",",
"word",
")",
":",
"length",
"=",
"len",
"(",
"word",
")",
"suffixes",
"=",
"[",
"'al'",
",",
"'ance'",
",",
"'ence'",
",",
"'er'",
",",
"'ic'",
",",
"'able'",
",",
"'ible'",
",",
"'ant'",
",",
"'ement'",
... | Delete some very common suffixes. | [
"Delete",
"some",
"very",
"common",
"suffixes",
"."
] | python | train | 33 |
bukun/TorCMS | ext_script/autocrud/func_gen_html.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L135-L149 | def gen_checkbox_list(sig_dic):
'''
For generating List view HTML file for CHECKBOX.
for each item.
'''
view_zuoxiang = '''<span class="iga_pd_val">'''
dic_tmp = sig_dic['dic']
for key in dic_tmp.keys():
tmp_str = '''{{% if "{0}" in postinfo.extinfo["{1}"] %}} {2} {{% end %}}
... | [
"def",
"gen_checkbox_list",
"(",
"sig_dic",
")",
":",
"view_zuoxiang",
"=",
"'''<span class=\"iga_pd_val\">'''",
"dic_tmp",
"=",
"sig_dic",
"[",
"'dic'",
"]",
"for",
"key",
"in",
"dic_tmp",
".",
"keys",
"(",
")",
":",
"tmp_str",
"=",
"'''{{% if \"{0}\" in postinfo... | For generating List view HTML file for CHECKBOX.
for each item. | [
"For",
"generating",
"List",
"view",
"HTML",
"file",
"for",
"CHECKBOX",
".",
"for",
"each",
"item",
"."
] | python | train | 29.8 |
danilobellini/audiolazy | audiolazy/lazy_synth.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L325-L345 | def zeros(dur=None):
"""
Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a given time duration (if any) or
endlessl... | [
"def",
"zeros",
"(",
"dur",
"=",
"None",
")",
":",
"if",
"dur",
"is",
"None",
"or",
"(",
"isinf",
"(",
"dur",
")",
"and",
"dur",
">",
"0",
")",
":",
"while",
"True",
":",
"yield",
"0.0",
"for",
"x",
"in",
"xrange",
"(",
"int",
"(",
".5",
"+",... | Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a given time duration (if any) or
endlessly. | [
"Zeros",
"/",
"zeroes",
"stream",
"generator",
".",
"You",
"may",
"sum",
"your",
"endless",
"stream",
"by",
"this",
"to",
"enforce",
"an",
"end",
"to",
"it",
"."
] | python | train | 20.714286 |
slundberg/shap | shap/datasets.py | https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L200-L225 | def independentlinear60(display=False):
""" A simulated dataset with tight correlations among distinct groups of features.
"""
# set a constant seed
old_seed = np.random.seed()
np.random.seed(0)
# generate dataset with known correlation
N = 1000
M = 60
# set one coefficent from ea... | [
"def",
"independentlinear60",
"(",
"display",
"=",
"False",
")",
":",
"# set a constant seed",
"old_seed",
"=",
"np",
".",
"random",
".",
"seed",
"(",
")",
"np",
".",
"random",
".",
"seed",
"(",
"0",
")",
"# generate dataset with known correlation",
"N",
"=",
... | A simulated dataset with tight correlations among distinct groups of features. | [
"A",
"simulated",
"dataset",
"with",
"tight",
"correlations",
"among",
"distinct",
"groups",
"of",
"features",
"."
] | python | train | 25.769231 |
AustralianSynchrotron/lightflow | lightflow/models/utils.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/utils.py#L2-L19 | def find_indices(lst, element):
""" Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values
"""
result = []
offset = -1
while True:
try:
... | [
"def",
"find_indices",
"(",
"lst",
",",
"element",
")",
":",
"result",
"=",
"[",
"]",
"offset",
"=",
"-",
"1",
"while",
"True",
":",
"try",
":",
"offset",
"=",
"lst",
".",
"index",
"(",
"element",
",",
"offset",
"+",
"1",
")",
"except",
"ValueError... | Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values | [
"Returns",
"the",
"indices",
"for",
"all",
"occurrences",
"of",
"element",
"in",
"lst",
"."
] | python | train | 23.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.