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 |
|---|---|---|---|---|---|---|---|---|---|
MartinThoma/mpu | mpu/__init__.py | https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L128-L133 | def longitude(self, longitude):
"""Setter for longitude."""
if not (-180 <= longitude <= 180):
raise ValueError('longitude was {}, but has to be in [-180, 180]'
.format(longitude))
self._longitude = longitude | [
"def",
"longitude",
"(",
"self",
",",
"longitude",
")",
":",
"if",
"not",
"(",
"-",
"180",
"<=",
"longitude",
"<=",
"180",
")",
":",
"raise",
"ValueError",
"(",
"'longitude was {}, but has to be in [-180, 180]'",
".",
"format",
"(",
"longitude",
")",
")",
"s... | Setter for longitude. | [
"Setter",
"for",
"longitude",
"."
] | python | train | 44.666667 |
brocade/pynos | pynos/versions/base/yang/ietf_netconf.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/ietf_netconf.py#L112-L123 | def edit_config_input_default_operation(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
edit_config = ET.Element("edit_config")
config = edit_config
input = ET.SubElement(edit_config, "input")
default_operation = ET.SubElement(input, "def... | [
"def",
"edit_config_input_default_operation",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"edit_config",
"=",
"ET",
".",
"Element",
"(",
"\"edit_config\"",
")",
"config",
"=",
"edit_config",
"i... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 40.083333 |
tensorflow/probability | tensorflow_probability/python/mcmc/transformed_kernel.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/transformed_kernel.py#L275-L347 | def bootstrap_results(self, init_state=None, transformed_init_state=None):
"""Returns an object with the same type as returned by `one_step`.
Unlike other `TransitionKernel`s,
`TransformedTransitionKernel.bootstrap_results` has the option of
initializing the `TransformedTransitionKernelResults` from ei... | [
"def",
"bootstrap_results",
"(",
"self",
",",
"init_state",
"=",
"None",
",",
"transformed_init_state",
"=",
"None",
")",
":",
"if",
"(",
"init_state",
"is",
"None",
")",
"==",
"(",
"transformed_init_state",
"is",
"None",
")",
":",
"raise",
"ValueError",
"("... | Returns an object with the same type as returned by `one_step`.
Unlike other `TransitionKernel`s,
`TransformedTransitionKernel.bootstrap_results` has the option of
initializing the `TransformedTransitionKernelResults` from either an initial
state, eg, requiring computing `bijector.inverse(init_state)`,... | [
"Returns",
"an",
"object",
"with",
"the",
"same",
"type",
"as",
"returned",
"by",
"one_step",
"."
] | python | test | 44.342466 |
mvn23/pyotgw | pyotgw/protocol.py | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/protocol.py#L73-L94 | def data_received(self, data):
"""
Gets called when new data is received on the serial interface.
Perform line buffering and call line_received() with complete
lines.
"""
# DIY line buffering...
newline = b'\r\n'
eot = b'\x04'
self._readbuf += data... | [
"def",
"data_received",
"(",
"self",
",",
"data",
")",
":",
"# DIY line buffering...",
"newline",
"=",
"b'\\r\\n'",
"eot",
"=",
"b'\\x04'",
"self",
".",
"_readbuf",
"+=",
"data",
"while",
"newline",
"in",
"self",
".",
"_readbuf",
":",
"line",
",",
"_",
","... | Gets called when new data is received on the serial interface.
Perform line buffering and call line_received() with complete
lines. | [
"Gets",
"called",
"when",
"new",
"data",
"is",
"received",
"on",
"the",
"serial",
"interface",
".",
"Perform",
"line",
"buffering",
"and",
"call",
"line_received",
"()",
"with",
"complete",
"lines",
"."
] | python | train | 37.5 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L4612-L4617 | def setOverlayName(self, ulOverlayHandle, pchName):
"""set the name to use for this overlay"""
fn = self.function_table.setOverlayName
result = fn(ulOverlayHandle, pchName)
return result | [
"def",
"setOverlayName",
"(",
"self",
",",
"ulOverlayHandle",
",",
"pchName",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayName",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"pchName",
")",
"return",
"result"
] | set the name to use for this overlay | [
"set",
"the",
"name",
"to",
"use",
"for",
"this",
"overlay"
] | python | train | 35.666667 |
alexmojaki/outdated | outdated/__init__.py | https://github.com/alexmojaki/outdated/blob/565bb3fe1adc30da5e50249912cd2ac494662659/outdated/__init__.py#L12-L65 | def check_outdated(package, version):
"""
Given the name of a package on PyPI and a version (both strings), checks
if the given version is the latest version of the package available.
Returns a 2-tuple (is_outdated, latest_version) where
is_outdated is a boolean which is True if the given version i... | [
"def",
"check_outdated",
"(",
"package",
",",
"version",
")",
":",
"from",
"pkg_resources",
"import",
"parse_version",
"parsed_version",
"=",
"parse_version",
"(",
"version",
")",
"latest",
"=",
"None",
"with",
"utils",
".",
"cache_file",
"(",
"package",
",",
... | Given the name of a package on PyPI and a version (both strings), checks
if the given version is the latest version of the package available.
Returns a 2-tuple (is_outdated, latest_version) where
is_outdated is a boolean which is True if the given version is earlier
than the latest version, which is th... | [
"Given",
"the",
"name",
"of",
"a",
"package",
"on",
"PyPI",
"and",
"a",
"version",
"(",
"both",
"strings",
")",
"checks",
"if",
"the",
"given",
"version",
"is",
"the",
"latest",
"version",
"of",
"the",
"package",
"available",
"."
] | python | train | 33.833333 |
mattloper/chumpy | chumpy/utils.py | https://github.com/mattloper/chumpy/blob/a3cfdb1be3c8265c369c507b22f6f3f89414c772/chumpy/utils.py#L81-L93 | def convert_inputs_to_sparse_if_necessary(lhs, rhs):
'''
This function checks to see if a sparse output is desireable given the inputs and if so, casts the inputs to sparse in order to make it so.
'''
if not sp.issparse(lhs) or not sp.issparse(rhs):
if sparse_is_desireable(lhs, rhs):
... | [
"def",
"convert_inputs_to_sparse_if_necessary",
"(",
"lhs",
",",
"rhs",
")",
":",
"if",
"not",
"sp",
".",
"issparse",
"(",
"lhs",
")",
"or",
"not",
"sp",
".",
"issparse",
"(",
"rhs",
")",
":",
"if",
"sparse_is_desireable",
"(",
"lhs",
",",
"rhs",
")",
... | This function checks to see if a sparse output is desireable given the inputs and if so, casts the inputs to sparse in order to make it so. | [
"This",
"function",
"checks",
"to",
"see",
"if",
"a",
"sparse",
"output",
"is",
"desireable",
"given",
"the",
"inputs",
"and",
"if",
"so",
"casts",
"the",
"inputs",
"to",
"sparse",
"in",
"order",
"to",
"make",
"it",
"so",
"."
] | python | train | 45.384615 |
genialis/resolwe | resolwe/process/parser.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/process/parser.py#L225-L234 | def parse(self):
"""Parse process.
:return: A list of discovered process descriptors
"""
root = ast.parse(self._source)
visitor = ProcessVisitor(source=self._source)
visitor.visit(root)
return visitor.processes | [
"def",
"parse",
"(",
"self",
")",
":",
"root",
"=",
"ast",
".",
"parse",
"(",
"self",
".",
"_source",
")",
"visitor",
"=",
"ProcessVisitor",
"(",
"source",
"=",
"self",
".",
"_source",
")",
"visitor",
".",
"visit",
"(",
"root",
")",
"return",
"visito... | Parse process.
:return: A list of discovered process descriptors | [
"Parse",
"process",
"."
] | python | train | 25.9 |
oscarbranson/latools | latools/filtering/filters.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/filtering/filters.py#L58-L94 | def defrag(filt, threshold=3, mode='include'):
"""
'Defragment' a filter.
Parameters
----------
filt : boolean array
A filter
threshold : int
Consecutive values equal to or below this threshold
length are considered fragments, and will be removed.
mode : str
... | [
"def",
"defrag",
"(",
"filt",
",",
"threshold",
"=",
"3",
",",
"mode",
"=",
"'include'",
")",
":",
"if",
"bool_2_indices",
"(",
"filt",
")",
"is",
"None",
":",
"return",
"filt",
"if",
"mode",
"==",
"'include'",
":",
"inds",
"=",
"bool_2_indices",
"(",
... | 'Defragment' a filter.
Parameters
----------
filt : boolean array
A filter
threshold : int
Consecutive values equal to or below this threshold
length are considered fragments, and will be removed.
mode : str
Wheter to change False fragments to True ('include')
... | [
"Defragment",
"a",
"filter",
"."
] | python | test | 23.135135 |
delph-in/pydelphin | delphin/mrs/components.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/components.py#L595-L618 | def split_pred_string(predstr):
"""
Split *predstr* and return the (lemma, pos, sense, suffix) components.
Examples:
>>> Pred.split_pred_string('_dog_n_1_rel')
('dog', 'n', '1', 'rel')
>>> Pred.split_pred_string('quant_rel')
('quant', None, None, 'rel')
"""
predstr =... | [
"def",
"split_pred_string",
"(",
"predstr",
")",
":",
"predstr",
"=",
"predstr",
".",
"strip",
"(",
"'\"\\''",
")",
"# surrounding quotes don't matter",
"rel_added",
"=",
"False",
"if",
"not",
"predstr",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'_rel'",
... | Split *predstr* and return the (lemma, pos, sense, suffix) components.
Examples:
>>> Pred.split_pred_string('_dog_n_1_rel')
('dog', 'n', '1', 'rel')
>>> Pred.split_pred_string('quant_rel')
('quant', None, None, 'rel') | [
"Split",
"*",
"predstr",
"*",
"and",
"return",
"the",
"(",
"lemma",
"pos",
"sense",
"suffix",
")",
"components",
"."
] | python | train | 38 |
nitmir/django-cas-server | cas_server/views.py | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L543-L581 | def process_post(self):
"""
Analyse the POST request:
* check that the LoginTicket is valid
* check that the user sumited credentials are valid
:return:
* :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid
... | [
"def",
"process_post",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"check_lt",
"(",
")",
":",
"self",
".",
"init_form",
"(",
"self",
".",
"request",
".",
"POST",
")",
"logger",
".",
"warning",
"(",
"\"Received an invalid login ticket\"",
")",
"return"... | Analyse the POST request:
* check that the LoginTicket is valid
* check that the user sumited credentials are valid
:return:
* :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid
* :attr:`USER_ALREADY_LOGGED` if the user is al... | [
"Analyse",
"the",
"POST",
"request",
":"
] | python | train | 49.333333 |
synw/dataswim | dataswim/data/export.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/export.py#L73-L86 | def to_rst_(self) -> str:
"""Convert the main dataframe to restructured text
:return: rst data
:rtype: str
:example: ``ds.to_rst_()``
"""
try:
renderer = pytablewriter.RstGridTableWriter
data = self._build_export(renderer)
return data... | [
"def",
"to_rst_",
"(",
"self",
")",
"->",
"str",
":",
"try",
":",
"renderer",
"=",
"pytablewriter",
".",
"RstGridTableWriter",
"data",
"=",
"self",
".",
"_build_export",
"(",
"renderer",
")",
"return",
"data",
"except",
"Exception",
"as",
"e",
":",
"self",... | Convert the main dataframe to restructured text
:return: rst data
:rtype: str
:example: ``ds.to_rst_()`` | [
"Convert",
"the",
"main",
"dataframe",
"to",
"restructured",
"text"
] | python | train | 29.071429 |
tanghaibao/jcvi | jcvi/utils/cbook.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/cbook.py#L230-L244 | def percentage(a, b, precision=1, mode=0):
"""
>>> percentage(100, 200)
'100 of 200 (50.0%)'
"""
_a, _b = a, b
pct = "{0:.{1}f}%".format(a * 100. / b, precision)
a, b = thousands(a), thousands(b)
if mode == 0:
return "{0} of {1} ({2})".format(a, b, pct)
elif mode == 1:
... | [
"def",
"percentage",
"(",
"a",
",",
"b",
",",
"precision",
"=",
"1",
",",
"mode",
"=",
"0",
")",
":",
"_a",
",",
"_b",
"=",
"a",
",",
"b",
"pct",
"=",
"\"{0:.{1}f}%\"",
".",
"format",
"(",
"a",
"*",
"100.",
"/",
"b",
",",
"precision",
")",
"a... | >>> percentage(100, 200)
'100 of 200 (50.0%)' | [
">>>",
"percentage",
"(",
"100",
"200",
")",
"100",
"of",
"200",
"(",
"50",
".",
"0%",
")"
] | python | train | 27.066667 |
sfalkner/pynisher | pynisher/limit_function_call.py | https://github.com/sfalkner/pynisher/blob/8e9518e874673bfc0a62a54fa1580cd1df931617/pynisher/limit_function_call.py#L19-L130 | def subprocess_func(func, pipe, logger, mem_in_mb, cpu_time_limit_in_s, wall_time_limit_in_s, num_procs, grace_period_in_s, tmp_dir, *args, **kwargs):
# simple signal handler to catch the signals for time limits
def handler(signum, frame):
# logs message with level debug on this logger
logger.debug("signal hand... | [
"def",
"subprocess_func",
"(",
"func",
",",
"pipe",
",",
"logger",
",",
"mem_in_mb",
",",
"cpu_time_limit_in_s",
",",
"wall_time_limit_in_s",
",",
"num_procs",
",",
"grace_period_in_s",
",",
"tmp_dir",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# ... | for i in [x for x in dir(signal) if x.startswith("SIG")]:
try:
signum = getattr(signal,i)
print("register {}, {}".format(signum, i))
signal.signal(signum, handler)
except:
print("Skipping %s"%i) | [
"for",
"i",
"in",
"[",
"x",
"for",
"x",
"in",
"dir",
"(",
"signal",
")",
"if",
"x",
".",
"startswith",
"(",
"SIG",
")",
"]",
":",
"try",
":",
"signum",
"=",
"getattr",
"(",
"signal",
"i",
")",
"print",
"(",
"register",
"{}",
"{}",
".",
"format"... | python | train | 34.964286 |
PredixDev/predixpy | predix/data/timeseries.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/timeseries.py#L422-L498 | def queue(self, name, value, quality=None, timestamp=None,
attributes=None):
"""
To reduce network traffic, you can buffer datapoints and
then flush() anything in the queue.
:param name: the name / label / tag for sensor data
:param value: the sensor reading or valu... | [
"def",
"queue",
"(",
"self",
",",
"name",
",",
"value",
",",
"quality",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"# Get timestamp first in case delay opening websocket connection",
"# and it must have millisecond accuracy",
... | To reduce network traffic, you can buffer datapoints and
then flush() anything in the queue.
:param name: the name / label / tag for sensor data
:param value: the sensor reading or value to record
:param quality: the quality value, use the constants BAD, GOOD, etc.
(option... | [
"To",
"reduce",
"network",
"traffic",
"you",
"can",
"buffer",
"datapoints",
"and",
"then",
"flush",
"()",
"anything",
"in",
"the",
"queue",
"."
] | python | train | 39 |
saltstack/salt | salt/utils/roster_matcher.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L84-L90 | def ret_pcre_minions(self):
'''
Return minions that match via pcre
'''
tgt = re.compile(self.tgt)
refilter = functools.partial(filter, tgt.match)
return self._ret_minions(refilter) | [
"def",
"ret_pcre_minions",
"(",
"self",
")",
":",
"tgt",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"tgt",
")",
"refilter",
"=",
"functools",
".",
"partial",
"(",
"filter",
",",
"tgt",
".",
"match",
")",
"return",
"self",
".",
"_ret_minions",
"(",
... | Return minions that match via pcre | [
"Return",
"minions",
"that",
"match",
"via",
"pcre"
] | python | train | 31.714286 |
rosenbrockc/fortpy | fortpy/parsers/docstring.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/parsers/docstring.py#L325-L354 | def process_embedded(self, xlist, anexec, add=True):
"""Processes the specified xml list and executable to link *embedded*
types and executables to their docstrings.
:arg xlist: a list of XML elements returned by parse_docs().
:arg add: when true, docstrings are only appended, never ove... | [
"def",
"process_embedded",
"(",
"self",
",",
"xlist",
",",
"anexec",
",",
"add",
"=",
"True",
")",
":",
"#Keep track of the changes that took place in the lengths of the ",
"#docstrings that got added/updated on the elements children.",
"delta",
"=",
"0",
"for",
"t",
"in",
... | Processes the specified xml list and executable to link *embedded*
types and executables to their docstrings.
:arg xlist: a list of XML elements returned by parse_docs().
:arg add: when true, docstrings are only appended, never overwritten. | [
"Processes",
"the",
"specified",
"xml",
"list",
"and",
"executable",
"to",
"link",
"*",
"embedded",
"*",
"types",
"and",
"executables",
"to",
"their",
"docstrings",
"."
] | python | train | 46.2 |
sods/ods | pods/datasets.py | https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1321-L1343 | def movie_body_count_r_classify(data_set='movie_body_count'):
"""Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R."""
data = movie_body_count()['Y']
import pandas as pd
import numpy a... | [
"def",
"movie_body_count_r_classify",
"(",
"data_set",
"=",
"'movie_body_count'",
")",
":",
"data",
"=",
"movie_body_count",
"(",
")",
"[",
"'Y'",
"]",
"import",
"pandas",
"as",
"pd",
"import",
"numpy",
"as",
"np",
"X",
"=",
"data",
"[",
"[",
"'Year'",
","... | Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R. | [
"Data",
"set",
"of",
"movies",
"and",
"body",
"count",
"for",
"movies",
"scraped",
"from",
"www",
".",
"MovieBodyCounts",
".",
"com",
"created",
"by",
"Simon",
"Garnier",
"and",
"Randy",
"Olson",
"for",
"exploring",
"differences",
"between",
"Python",
"and",
... | python | train | 59.086957 |
honzamach/pydgets | pydgets/widgets.py | https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L579-L584 | def render(self, content = None, **settings):
"""
Perform widget rendering, but do not print anything.
"""
(content, settings) = self.get_setup(content, **settings)
return self._render(content, **settings) | [
"def",
"render",
"(",
"self",
",",
"content",
"=",
"None",
",",
"*",
"*",
"settings",
")",
":",
"(",
"content",
",",
"settings",
")",
"=",
"self",
".",
"get_setup",
"(",
"content",
",",
"*",
"*",
"settings",
")",
"return",
"self",
".",
"_render",
"... | Perform widget rendering, but do not print anything. | [
"Perform",
"widget",
"rendering",
"but",
"do",
"not",
"print",
"anything",
"."
] | python | train | 40 |
matousc89/padasip | padasip/filters/gngd.py | https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/filters/gngd.py#L158-L175 | def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
y = np.dot(self.w, x)
e = d - y
self.eps = self.eps - self.ro * self.mu * e... | [
"def",
"adapt",
"(",
"self",
",",
"d",
",",
"x",
")",
":",
"y",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"w",
",",
"x",
")",
"e",
"=",
"d",
"-",
"y",
"self",
".",
"eps",
"=",
"self",
".",
"eps",
"-",
"self",
".",
"ro",
"*",
"self",
".",... | Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array) | [
"Adapt",
"weights",
"according",
"one",
"desired",
"value",
"and",
"its",
"input",
"."
] | python | train | 29.5 |
postlund/pyatv | pyatv/dmap/__init__.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L185-L188 | def set_position(self, pos):
"""Seek in the current playing media."""
time_in_ms = int(pos)*1000
return self.apple_tv.set_property('dacp.playingtime', time_in_ms) | [
"def",
"set_position",
"(",
"self",
",",
"pos",
")",
":",
"time_in_ms",
"=",
"int",
"(",
"pos",
")",
"*",
"1000",
"return",
"self",
".",
"apple_tv",
".",
"set_property",
"(",
"'dacp.playingtime'",
",",
"time_in_ms",
")"
] | Seek in the current playing media. | [
"Seek",
"in",
"the",
"current",
"playing",
"media",
"."
] | python | train | 45.75 |
googleapis/google-cloud-python | bigtable/google/cloud/bigtable/instance.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L170-L192 | def name(self):
"""Instance name used in requests.
.. note::
This property will not change if ``instance_id`` does not,
but the return value is not cached.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_instance_name]
... | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"instance_admin_client",
".",
"instance_path",
"(",
"project",
"=",
"self",
".",
"_client",
".",
"project",
",",
"instance",
"=",
"self",
".",
"instance_id",
")"
] | Instance name used in requests.
.. note::
This property will not change if ``instance_id`` does not,
but the return value is not cached.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_instance_name]
:end-before: [END bigt... | [
"Instance",
"name",
"used",
"in",
"requests",
"."
] | python | train | 29.73913 |
radjkarl/imgProcessor | imgProcessor/equations/poisson.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/equations/poisson.py#L4-L15 | def poisson(x, a, b, c, d=0):
'''
Poisson function
a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation
d -> offset
'''
from scipy.misc import factorial #save startup time
lamb = 1
X = (x/(2*c)).astype(int)
return a * ((... | [
"def",
"poisson",
"(",
"x",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
"=",
"0",
")",
":",
"from",
"scipy",
".",
"misc",
"import",
"factorial",
"#save startup time\r",
"lamb",
"=",
"1",
"X",
"=",
"(",
"x",
"/",
"(",
"2",
"*",
"c",
")",
")",
".",... | Poisson function
a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation
d -> offset | [
"Poisson",
"function",
"a",
"-",
">",
"height",
"of",
"the",
"curve",
"s",
"peak",
"b",
"-",
">",
"position",
"of",
"the",
"center",
"of",
"the",
"peak",
"c",
"-",
">",
"standard",
"deviation",
"d",
"-",
">",
"offset"
] | python | train | 29.333333 |
profitbricks/profitbricks-sdk-python | profitbricks/client.py | https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1634-L1649 | def update_snapshot(self, snapshot_id, **kwargs):
"""
Removes a snapshot from your account.
:param snapshot_id: The unique ID of the snapshot.
:type snapshot_id: ``str``
"""
data = {}
for attr, value in kwargs.items():
data[self._underscor... | [
"def",
"update_snapshot",
"(",
"self",
",",
"snapshot_id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"}",
"for",
"attr",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"data",
"[",
"self",
".",
"_underscore_to_camelcase",
"(",
... | Removes a snapshot from your account.
:param snapshot_id: The unique ID of the snapshot.
:type snapshot_id: ``str`` | [
"Removes",
"a",
"snapshot",
"from",
"your",
"account",
"."
] | python | valid | 30.375 |
bcbio/bcbio-nextgen | bcbio/distributed/runfn.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L273-L284 | def _check_for_single_nested(target, items_by_key, input_order):
"""Check for single nested inputs that match our target count and unnest.
Handles complex var inputs where some have an extra layer of nesting.
"""
out = utils.deepish_copy(items_by_key)
for (k, t) in input_order.items():
if t... | [
"def",
"_check_for_single_nested",
"(",
"target",
",",
"items_by_key",
",",
"input_order",
")",
":",
"out",
"=",
"utils",
".",
"deepish_copy",
"(",
"items_by_key",
")",
"for",
"(",
"k",
",",
"t",
")",
"in",
"input_order",
".",
"items",
"(",
")",
":",
"if... | Check for single nested inputs that match our target count and unnest.
Handles complex var inputs where some have an extra layer of nesting. | [
"Check",
"for",
"single",
"nested",
"inputs",
"that",
"match",
"our",
"target",
"count",
"and",
"unnest",
"."
] | python | train | 39.916667 |
OpenKMIP/PyKMIP | kmip/core/objects.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/objects.py#L2555-L2635 | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the KeyWrappingData struct and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"KeyWrappingData",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_version",
... | Read the data encoding the KeyWrappingData struct and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVe... | [
"Read",
"the",
"data",
"encoding",
"the",
"KeyWrappingData",
"struct",
"and",
"decode",
"it",
"into",
"its",
"constituent",
"parts",
"."
] | python | test | 35.691358 |
SuperCowPowers/workbench | workbench/workers/pcap_http_graph.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pcap_http_graph.py#L45-L66 | def execute(self, input_data):
''' Okay this worker is going build graphs from PCAP Bro output logs '''
# Grab the Bro log handles from the input
bro_logs = input_data['pcap_bro']
# Weird log
if 'weird_log' in bro_logs:
stream = self.workbench.stream_sample(bro_logs... | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Grab the Bro log handles from the input",
"bro_logs",
"=",
"input_data",
"[",
"'pcap_bro'",
"]",
"# Weird log",
"if",
"'weird_log'",
"in",
"bro_logs",
":",
"stream",
"=",
"self",
".",
"workbench",
".",... | Okay this worker is going build graphs from PCAP Bro output logs | [
"Okay",
"this",
"worker",
"is",
"going",
"build",
"graphs",
"from",
"PCAP",
"Bro",
"output",
"logs"
] | python | train | 36.136364 |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L836-L846 | def _desc_has_data(desc):
"""Returns true if there is any data set for a particular PhoneNumberDesc."""
if desc is None:
return False
# Checking most properties since we don't know what's present, since a custom build may have
# stripped just one of them (e.g. liteBuild strips exampleNumber). We... | [
"def",
"_desc_has_data",
"(",
"desc",
")",
":",
"if",
"desc",
"is",
"None",
":",
"return",
"False",
"# Checking most properties since we don't know what's present, since a custom build may have",
"# stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking... | Returns true if there is any data set for a particular PhoneNumberDesc. | [
"Returns",
"true",
"if",
"there",
"is",
"any",
"data",
"set",
"for",
"a",
"particular",
"PhoneNumberDesc",
"."
] | python | train | 61.363636 |
theolind/pymysensors | mqtt.py | https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mqtt.py#L22-L33 | def subscribe(self, topic, callback, qos):
"""Subscribe to an MQTT topic."""
if topic in self.topics:
return
def _message_callback(mqttc, userdata, msg):
"""Callback added to callback list for received message."""
callback(msg.topic, msg.payload.decode('utf-8... | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"callback",
",",
"qos",
")",
":",
"if",
"topic",
"in",
"self",
".",
"topics",
":",
"return",
"def",
"_message_callback",
"(",
"mqttc",
",",
"userdata",
",",
"msg",
")",
":",
"\"\"\"Callback added to callb... | Subscribe to an MQTT topic. | [
"Subscribe",
"to",
"an",
"MQTT",
"topic",
"."
] | python | train | 39.083333 |
juju/charm-helpers | charmhelpers/contrib/storage/linux/ceph.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L825-L841 | def set_app_name_for_pool(client, pool, name):
"""
Calls `osd pool application enable` for the specified pool name
:param client: Name of the ceph client to use
:type client: str
:param pool: Pool to set app name for
:type pool: str
:param name: app name for the specified pool
:type nam... | [
"def",
"set_app_name_for_pool",
"(",
"client",
",",
"pool",
",",
"name",
")",
":",
"if",
"cmp_pkgrevno",
"(",
"'ceph-common'",
",",
"'12.0.0'",
")",
">=",
"0",
":",
"cmd",
"=",
"[",
"'ceph'",
",",
"'--id'",
",",
"client",
",",
"'osd'",
",",
"'pool'",
"... | Calls `osd pool application enable` for the specified pool name
:param client: Name of the ceph client to use
:type client: str
:param pool: Pool to set app name for
:type pool: str
:param name: app name for the specified pool
:type name: str
:raises: CalledProcessError if ceph call fails | [
"Calls",
"osd",
"pool",
"application",
"enable",
"for",
"the",
"specified",
"pool",
"name"
] | python | train | 32.411765 |
mommermi/callhorizons | callhorizons/callhorizons.py | https://github.com/mommermi/callhorizons/blob/fdd7ad9e87cac107c1b7f88e594d118210da3b1a/callhorizons/callhorizons.py#L1260-L1314 | def export2pyephem(self, center='500@10', equinox=2000.):
"""Call JPL HORIZONS website to obtain orbital elements based on the
provided targetname, epochs, and center code and create a
PyEphem (http://rhodesmill.org/pyephem/) object. This function
requires PyEphem to be installed.
... | [
"def",
"export2pyephem",
"(",
"self",
",",
"center",
"=",
"'500@10'",
",",
"equinox",
"=",
"2000.",
")",
":",
"try",
":",
"import",
"ephem",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'export2pyephem requires PyEphem to be installed'",
")",
"# obt... | Call JPL HORIZONS website to obtain orbital elements based on the
provided targetname, epochs, and center code and create a
PyEphem (http://rhodesmill.org/pyephem/) object. This function
requires PyEphem to be installed.
:param center: str;
center body (default: 500@10 = Sun)... | [
"Call",
"JPL",
"HORIZONS",
"website",
"to",
"obtain",
"orbital",
"elements",
"based",
"on",
"the",
"provided",
"targetname",
"epochs",
"and",
"center",
"code",
"and",
"create",
"a",
"PyEphem",
"(",
"http",
":",
"//",
"rhodesmill",
".",
"org",
"/",
"pyephem",... | python | train | 44.381818 |
apache/incubator-superset | superset/common/query_context.py | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L112-L117 | def df_metrics_to_num(self, df, query_object):
"""Converting metrics to numeric when pandas.read_sql cannot"""
metrics = [metric for metric in query_object.metrics]
for col, dtype in df.dtypes.items():
if dtype.type == np.object_ and col in metrics:
df[col] = pd.to_nu... | [
"def",
"df_metrics_to_num",
"(",
"self",
",",
"df",
",",
"query_object",
")",
":",
"metrics",
"=",
"[",
"metric",
"for",
"metric",
"in",
"query_object",
".",
"metrics",
"]",
"for",
"col",
",",
"dtype",
"in",
"df",
".",
"dtypes",
".",
"items",
"(",
")",... | Converting metrics to numeric when pandas.read_sql cannot | [
"Converting",
"metrics",
"to",
"numeric",
"when",
"pandas",
".",
"read_sql",
"cannot"
] | python | train | 57.666667 |
saltstack/salt | salt/states/win_license.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_license.py#L33-L71 | def activate(name):
'''
Install and activate the given product key
name
The 5x5 product key given to you by Microsoft
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
product_key = name
license_info = __salt__['license.info']... | [
"def",
"activate",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"product_key",
"=",
"name",
"license_info",
"=",
"__salt__",
"[",
"'lic... | Install and activate the given product key
name
The 5x5 product key given to you by Microsoft | [
"Install",
"and",
"activate",
"the",
"given",
"product",
"key"
] | python | train | 28.769231 |
totalgood/nlpia | src/nlpia/skeleton.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/skeleton.py#L101-L111 | def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Starting crazy calculations...")
print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n)))
... | [
"def",
"main",
"(",
"args",
")",
":",
"args",
"=",
"parse_args",
"(",
"args",
")",
"setup_logging",
"(",
"args",
".",
"loglevel",
")",
"_logger",
".",
"debug",
"(",
"\"Starting crazy calculations...\"",
")",
"print",
"(",
"\"The {}-th Fibonacci number is {}\"",
... | Main entry point allowing external calls
Args:
args ([str]): command line parameter list | [
"Main",
"entry",
"point",
"allowing",
"external",
"calls"
] | python | train | 31.272727 |
pybel/pybel | src/pybel/utils.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L79-L92 | def tokenize_version(version_string: str) -> Tuple[int, int, int]:
"""Tokenize a version string to a tuple.
Truncates qualifiers like ``-dev``.
:param version_string: A version string
:return: A tuple representing the version string
>>> tokenize_version('0.1.2-dev')
(0, 1, 2)
"""
befo... | [
"def",
"tokenize_version",
"(",
"version_string",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"before_dash",
"=",
"version_string",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
"major",
",",
"minor",
",",
"patch",
"... | Tokenize a version string to a tuple.
Truncates qualifiers like ``-dev``.
:param version_string: A version string
:return: A tuple representing the version string
>>> tokenize_version('0.1.2-dev')
(0, 1, 2) | [
"Tokenize",
"a",
"version",
"string",
"to",
"a",
"tuple",
"."
] | python | train | 36.428571 |
Salamek/cron-descriptor | cron_descriptor/ExpressionDescriptor.py | https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L511-L539 | def format_time(
self,
hour_expression,
minute_expression,
second_expression=''
):
"""Given time parts, will contruct a formatted time description
Args:
hour_expression: Hours part
minute_expression: Minutes part
second_expression: ... | [
"def",
"format_time",
"(",
"self",
",",
"hour_expression",
",",
"minute_expression",
",",
"second_expression",
"=",
"''",
")",
":",
"hour",
"=",
"int",
"(",
"hour_expression",
")",
"period",
"=",
"''",
"if",
"self",
".",
"_options",
".",
"use_24hour_time_forma... | Given time parts, will contruct a formatted time description
Args:
hour_expression: Hours part
minute_expression: Minutes part
second_expression: Seconds part
Returns:
Formatted time description | [
"Given",
"time",
"parts",
"will",
"contruct",
"a",
"formatted",
"time",
"description",
"Args",
":",
"hour_expression",
":",
"Hours",
"part",
"minute_expression",
":",
"Minutes",
"part",
"second_expression",
":",
"Seconds",
"part",
"Returns",
":",
"Formatted",
"tim... | python | train | 31.482759 |
srossross/rpmfile | rpmfile/__init__.py | https://github.com/srossross/rpmfile/blob/3ab96f211da7b56f5e99d8cc248f714a6e542d31/rpmfile/__init__.py#L135-L147 | def getmember(self, name):
'''
Return an RPMInfo object for member `name'. If `name' can not be
found in the archive, KeyError is raised. If a member occurs more
than once in the archive, its last occurrence is assumed to be the
most up-to-date version.
'''
member... | [
"def",
"getmember",
"(",
"self",
",",
"name",
")",
":",
"members",
"=",
"self",
".",
"getmembers",
"(",
")",
"for",
"m",
"in",
"members",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"m",
".",
"name",
"==",
"name",
":",
"return",
"m",
"raise",
"Key... | Return an RPMInfo object for member `name'. If `name' can not be
found in the archive, KeyError is raised. If a member occurs more
than once in the archive, its last occurrence is assumed to be the
most up-to-date version. | [
"Return",
"an",
"RPMInfo",
"object",
"for",
"member",
"name",
".",
"If",
"name",
"can",
"not",
"be",
"found",
"in",
"the",
"archive",
"KeyError",
"is",
"raised",
".",
"If",
"a",
"member",
"occurs",
"more",
"than",
"once",
"in",
"the",
"archive",
"its",
... | python | train | 36.923077 |
cvxopt/chompack | src/python/symbolic.py | https://github.com/cvxopt/chompack/blob/e07106b58b8055c34f6201e8c954482f86987833/src/python/symbolic.py#L866-L873 | def separators(self, reordered = True):
"""
Returns a list of separator sets
"""
if reordered:
return [list(self.snrowidx[self.sncolptr[k]+self.snptr[k+1]-self.snptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)]
else:
return [list(self.__p[self.snrow... | [
"def",
"separators",
"(",
"self",
",",
"reordered",
"=",
"True",
")",
":",
"if",
"reordered",
":",
"return",
"[",
"list",
"(",
"self",
".",
"snrowidx",
"[",
"self",
".",
"sncolptr",
"[",
"k",
"]",
"+",
"self",
".",
"snptr",
"[",
"k",
"+",
"1",
"]... | Returns a list of separator sets | [
"Returns",
"a",
"list",
"of",
"separator",
"sets"
] | python | train | 51.375 |
kislyuk/ensure | ensure/main.py | https://github.com/kislyuk/ensure/blob/0a562a4b469ffbaf71c75dc4d394e94334c831f0/ensure/main.py#L251-L260 | def contains_only(self, elements):
"""
Ensures :attr:`subject` contains all of *elements*, which must be an iterable, and no other items.
"""
for element in self._subject:
if element not in elements:
raise self._error_factory(_format("Expected {} to have only ... | [
"def",
"contains_only",
"(",
"self",
",",
"elements",
")",
":",
"for",
"element",
"in",
"self",
".",
"_subject",
":",
"if",
"element",
"not",
"in",
"elements",
":",
"raise",
"self",
".",
"_error_factory",
"(",
"_format",
"(",
"\"Expected {} to have only {}, bu... | Ensures :attr:`subject` contains all of *elements*, which must be an iterable, and no other items. | [
"Ensures",
":",
"attr",
":",
"subject",
"contains",
"all",
"of",
"*",
"elements",
"*",
"which",
"must",
"be",
"an",
"iterable",
"and",
"no",
"other",
"items",
"."
] | python | train | 50.4 |
contentful/contentful-management.py | contentful_management/asset.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/asset.py#L22-L40 | def url(self, **kwargs):
"""
Returns a formatted URL for the asset's File
with serialized parameters.
Usage:
>>> my_asset.url()
"//images.contentful.com/spaces/foobar/..."
>>> my_asset.url(w=120, h=160)
"//images.contentful.com/spaces/foob... | [
"def",
"url",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"fields",
"(",
"self",
".",
"_locale",
"(",
")",
")",
".",
"get",
"(",
"'file'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'url'",
",",
"''",
")",
"args",
"=... | Returns a formatted URL for the asset's File
with serialized parameters.
Usage:
>>> my_asset.url()
"//images.contentful.com/spaces/foobar/..."
>>> my_asset.url(w=120, h=160)
"//images.contentful.com/spaces/foobar/...?w=120&h=160" | [
"Returns",
"a",
"formatted",
"URL",
"for",
"the",
"asset",
"s",
"File",
"with",
"serialized",
"parameters",
"."
] | python | train | 29.526316 |
googlefonts/ufo2ft | Lib/ufo2ft/fontInfoData.py | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/fontInfoData.py#L449-L464 | def getAttrWithFallback(info, attr):
"""
Get the value for *attr* from the *info* object.
If the object does not have the attribute or the value
for the atribute is None, this will either get a
value from a predefined set of attributes or it
will synthesize a value from the available data.
"... | [
"def",
"getAttrWithFallback",
"(",
"info",
",",
"attr",
")",
":",
"if",
"hasattr",
"(",
"info",
",",
"attr",
")",
"and",
"getattr",
"(",
"info",
",",
"attr",
")",
"is",
"not",
"None",
":",
"value",
"=",
"getattr",
"(",
"info",
",",
"attr",
")",
"el... | Get the value for *attr* from the *info* object.
If the object does not have the attribute or the value
for the atribute is None, this will either get a
value from a predefined set of attributes or it
will synthesize a value from the available data. | [
"Get",
"the",
"value",
"for",
"*",
"attr",
"*",
"from",
"the",
"*",
"info",
"*",
"object",
".",
"If",
"the",
"object",
"does",
"not",
"have",
"the",
"attribute",
"or",
"the",
"value",
"for",
"the",
"atribute",
"is",
"None",
"this",
"will",
"either",
... | python | train | 36.1875 |
maas/python-libmaas | maas/client/viscera/maas.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L167-L176 | async def get_upstream_dns(cls) -> list:
"""Upstream DNS server addresses.
Upstream DNS servers used to resolve domains not managed by this MAAS
(space-separated IP addresses). Only used when MAAS is running its own
DNS server. This value is used as the value of 'forwarders' in the DNS
... | [
"async",
"def",
"get_upstream_dns",
"(",
"cls",
")",
"->",
"list",
":",
"data",
"=",
"await",
"cls",
".",
"get_config",
"(",
"\"upstream_dns\"",
")",
"return",
"[",
"]",
"if",
"data",
"is",
"None",
"else",
"re",
".",
"split",
"(",
"r'[,\\s]+'",
",",
"d... | Upstream DNS server addresses.
Upstream DNS servers used to resolve domains not managed by this MAAS
(space-separated IP addresses). Only used when MAAS is running its own
DNS server. This value is used as the value of 'forwarders' in the DNS
server config. | [
"Upstream",
"DNS",
"server",
"addresses",
"."
] | python | train | 46.2 |
un33k/django-ipware | ipware/utils.py | https://github.com/un33k/django-ipware/blob/dc6b754137d1bb7d056ac206a6e0443aa3ed68dc/ipware/utils.py#L23-L31 | def is_valid_ipv6(ip_str):
"""
Check the validity of an IPv6 address
"""
try:
socket.inet_pton(socket.AF_INET6, ip_str)
except socket.error:
return False
return True | [
"def",
"is_valid_ipv6",
"(",
"ip_str",
")",
":",
"try",
":",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"ip_str",
")",
"except",
"socket",
".",
"error",
":",
"return",
"False",
"return",
"True"
] | Check the validity of an IPv6 address | [
"Check",
"the",
"validity",
"of",
"an",
"IPv6",
"address"
] | python | train | 21.888889 |
mozilla/taar | taar/recommenders/similarity_recommender.py | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/similarity_recommender.py#L220-L247 | def get_similar_donors(self, client_data):
"""Computes a set of :float: similarity scores between a client and a set of candidate
donors for which comparable variables have been measured.
A custom similarity metric is defined in this function that combines the Hamming distance
for categ... | [
"def",
"get_similar_donors",
"(",
"self",
",",
"client_data",
")",
":",
"# Compute the distance between self and any comparable client.",
"distances",
"=",
"self",
".",
"compute_clients_dist",
"(",
"client_data",
")",
"# Compute the LR based on precomputed distributions that relate... | Computes a set of :float: similarity scores between a client and a set of candidate
donors for which comparable variables have been measured.
A custom similarity metric is defined in this function that combines the Hamming distance
for categorical variables with the Canberra distance for contin... | [
"Computes",
"a",
"set",
"of",
":",
"float",
":",
"similarity",
"scores",
"between",
"a",
"client",
"and",
"a",
"set",
"of",
"candidate",
"donors",
"for",
"which",
"comparable",
"variables",
"have",
"been",
"measured",
"."
] | python | train | 51.964286 |
CivicSpleen/ambry | ambry/orm/partition.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L756-L778 | def select(self, predicate=None, headers=None):
"""
Select rows from the reader using a predicate to select rows and and itemgetter to return a
subset of elements
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in ... | [
"def",
"select",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"# FIXME; in Python 3, use yield from",
"with",
"self",
".",
"reader",
"as",
"r",
":",
"for",
"row",
"in",
"r",
".",
"select",
"(",
"predicate",
",",
"hea... | Select rows from the reader using a predicate to select rows and and itemgetter to return a
subset of elements
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param headers: If defined, a list or tuple of h... | [
"Select",
"rows",
"from",
"the",
"reader",
"using",
"a",
"predicate",
"to",
"select",
"rows",
"and",
"and",
"itemgetter",
"to",
"return",
"a",
"subset",
"of",
"elements",
":",
"param",
"predicate",
":",
"If",
"defined",
"a",
"callable",
"that",
"is",
"call... | python | train | 50.26087 |
mdickinson/bigfloat | bigfloat/core.py | https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L1961-L1971 | def eint(x, context=None):
"""
Return the exponential integral of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_eint,
(BigFloat._implicit_convert(x),),
context,
) | [
"def",
"eint",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_eint",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
... | Return the exponential integral of x. | [
"Return",
"the",
"exponential",
"integral",
"of",
"x",
"."
] | python | train | 20.818182 |
PyCQA/pydocstyle | src/pydocstyle/checker.py | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/checker.py#L204-L208 | def _get_docstring_indent(definition, docstring):
"""Return the indentation of the docstring's opening quotes."""
before_docstring, _, _ = definition.source.partition(docstring)
_, _, indent = before_docstring.rpartition('\n')
return indent | [
"def",
"_get_docstring_indent",
"(",
"definition",
",",
"docstring",
")",
":",
"before_docstring",
",",
"_",
",",
"_",
"=",
"definition",
".",
"source",
".",
"partition",
"(",
"docstring",
")",
"_",
",",
"_",
",",
"indent",
"=",
"before_docstring",
".",
"r... | Return the indentation of the docstring's opening quotes. | [
"Return",
"the",
"indentation",
"of",
"the",
"docstring",
"s",
"opening",
"quotes",
"."
] | python | train | 53.6 |
tornadoweb/tornado | tornado/httputil.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L162-L172 | def add(self, name: str, value: str) -> None:
"""Adds a new value for the given key."""
norm_name = _normalized_headers[name]
self._last_key = norm_name
if norm_name in self:
self._dict[norm_name] = (
native_str(self[norm_name]) + "," + native_str(value)
... | [
"def",
"add",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"norm_name",
"=",
"_normalized_headers",
"[",
"name",
"]",
"self",
".",
"_last_key",
"=",
"norm_name",
"if",
"norm_name",
"in",
"self",
":",
"self",
... | Adds a new value for the given key. | [
"Adds",
"a",
"new",
"value",
"for",
"the",
"given",
"key",
"."
] | python | train | 38.090909 |
gboeing/osmnx | osmnx/utils.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L792-L826 | def get_bearing(origin_point, destination_point):
"""
Calculate the bearing between two lat-long points. Each tuple should
represent (lat, lng) as decimal degrees.
Parameters
----------
origin_point : tuple
destination_point : tuple
Returns
-------
bearing : float
the c... | [
"def",
"get_bearing",
"(",
"origin_point",
",",
"destination_point",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"origin_point",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"destination_point",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"'or... | Calculate the bearing between two lat-long points. Each tuple should
represent (lat, lng) as decimal degrees.
Parameters
----------
origin_point : tuple
destination_point : tuple
Returns
-------
bearing : float
the compass bearing in decimal degrees from the origin point
... | [
"Calculate",
"the",
"bearing",
"between",
"two",
"lat",
"-",
"long",
"points",
".",
"Each",
"tuple",
"should",
"represent",
"(",
"lat",
"lng",
")",
"as",
"decimal",
"degrees",
"."
] | python | train | 35 |
idlesign/envbox | envbox/utils.py | https://github.com/idlesign/envbox/blob/4d10cc007e1bc6acf924413c4c16c3b5960d460a/envbox/utils.py#L56-L119 | def read_envfile(fpath):
"""Reads environment variables from .env key-value file.
Rules:
* Lines starting with # (hash) considered comments. Inline comments not supported;
* Multiline values not supported.
* Invalid lines are ignored;
* Matching opening-closing quotes are stripp... | [
"def",
"read_envfile",
"(",
"fpath",
")",
":",
"environ",
"=",
"os",
".",
"environ",
"env_vars",
"=",
"OrderedDict",
"(",
")",
"try",
":",
"with",
"io",
".",
"open",
"(",
"fpath",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
... | Reads environment variables from .env key-value file.
Rules:
* Lines starting with # (hash) considered comments. Inline comments not supported;
* Multiline values not supported.
* Invalid lines are ignored;
* Matching opening-closing quotes are stripped;
* ${VAL} will be rep... | [
"Reads",
"environment",
"variables",
"from",
".",
"env",
"key",
"-",
"value",
"file",
"."
] | python | train | 24.015625 |
proteanhq/protean | src/protean/core/repository/factory.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L66-L83 | def _find_entity_in_records_by_class_name(self, entity_name):
"""Fetch by Entity Name in values"""
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
# If more than one record was found, we are dealing with... | [
"def",
"_find_entity_in_records_by_class_name",
"(",
"self",
",",
"entity_name",
")",
":",
"records",
"=",
"{",
"key",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"_registry",
".",
"items",
"(",
")",
"if",
"value",
".",
"name",... | Fetch by Entity Name in values | [
"Fetch",
"by",
"Entity",
"Name",
"in",
"values"
] | python | train | 49.222222 |
the01/python-paps | paps/si/app/sensorClient.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L218-L242 | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start
"""
self.debug("()")
... | [
"def",
"start",
"(",
"self",
",",
"blocking",
"=",
"False",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"super",
"(",
"SensorClient",
",",
"self",
")",
".",
"start",
"(",
"blocking",
"=",
"False",
")",
"try",
":",
"a_thread",
"=",
"threading"... | Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start | [
"Start",
"the",
"interface"
] | python | train | 32.64 |
pysal/spglm | spglm/links.py | https://github.com/pysal/spglm/blob/1339898adcb7e1638f1da83d57aa37392525f018/spglm/links.py#L749-L768 | def deriv(self, p):
"""
Derivative of C-Log-Log transform link function
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g'(p) : array
The derivative of the CLogLog transform link function
Notes
... | [
"def",
"deriv",
"(",
"self",
",",
"p",
")",
":",
"p",
"=",
"self",
".",
"_clean",
"(",
"p",
")",
"return",
"1.",
"/",
"(",
"(",
"p",
"-",
"1",
")",
"*",
"(",
"np",
".",
"log",
"(",
"1",
"-",
"p",
")",
")",
")"
] | Derivative of C-Log-Log transform link function
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g'(p) : array
The derivative of the CLogLog transform link function
Notes
-----
g'(p) = - 1 / ((p-1)*log... | [
"Derivative",
"of",
"C",
"-",
"Log",
"-",
"Log",
"transform",
"link",
"function"
] | python | train | 21.7 |
paylogic/pip-accel | pip_accel/config.py | https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/config.py#L117-L121 | def available_configuration_files(self):
"""A list of strings with the absolute pathnames of the available configuration files."""
known_files = [GLOBAL_CONFIG, LOCAL_CONFIG, self.environment.get('PIP_ACCEL_CONFIG')]
absolute_paths = [parse_path(pathname) for pathname in known_files if pathname]... | [
"def",
"available_configuration_files",
"(",
"self",
")",
":",
"known_files",
"=",
"[",
"GLOBAL_CONFIG",
",",
"LOCAL_CONFIG",
",",
"self",
".",
"environment",
".",
"get",
"(",
"'PIP_ACCEL_CONFIG'",
")",
"]",
"absolute_paths",
"=",
"[",
"parse_path",
"(",
"pathna... | A list of strings with the absolute pathnames of the available configuration files. | [
"A",
"list",
"of",
"strings",
"with",
"the",
"absolute",
"pathnames",
"of",
"the",
"available",
"configuration",
"files",
"."
] | python | train | 80.2 |
googleapis/google-cloud-python | logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py#L268-L414 | def write_log_entries(
self,
entries,
log_name=None,
resource=None,
labels=None,
partial_success=None,
dry_run=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... | [
"def",
"write_log_entries",
"(",
"self",
",",
"entries",
",",
"log_name",
"=",
"None",
",",
"resource",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"partial_success",
"=",
"None",
",",
"dry_run",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core... | Writes log entries to Logging. This API method is the
only way to send log entries to Logging. This method
is used, directly or indirectly, by the Logging agent
(fluentd) and all logging libraries configured to use Logging.
A single request may contain log entries for a maximum of 1000
... | [
"Writes",
"log",
"entries",
"to",
"Logging",
".",
"This",
"API",
"method",
"is",
"the",
"only",
"way",
"to",
"send",
"log",
"entries",
"to",
"Logging",
".",
"This",
"method",
"is",
"used",
"directly",
"or",
"indirectly",
"by",
"the",
"Logging",
"agent",
... | python | train | 50.721088 |
DarkEnergySurvey/ugali | ugali/analysis/results.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L317-L332 | def surfaceBrightness(abs_mag, r_physical, distance):
"""
Compute the average surface brightness [mag arcsec^-2] within the half-light radius
abs_mag = absolute magnitude [mag]
r_physical = half-light radius [kpc]
distance = [kpc]
The factor 2 in the c_v equation below account for half the lu... | [
"def",
"surfaceBrightness",
"(",
"abs_mag",
",",
"r_physical",
",",
"distance",
")",
":",
"r_angle",
"=",
"np",
".",
"degrees",
"(",
"np",
".",
"arctan",
"(",
"r_physical",
"/",
"distance",
")",
")",
"c_v",
"=",
"19.78",
"# mag/arcsec^2",
"return",
"abs_ma... | Compute the average surface brightness [mag arcsec^-2] within the half-light radius
abs_mag = absolute magnitude [mag]
r_physical = half-light radius [kpc]
distance = [kpc]
The factor 2 in the c_v equation below account for half the luminosity
within the half-light radius. The 3600.**2 is conver... | [
"Compute",
"the",
"average",
"surface",
"brightness",
"[",
"mag",
"arcsec^",
"-",
"2",
"]",
"within",
"the",
"half",
"-",
"light",
"radius"
] | python | train | 40.25 |
UCL-INGI/INGInious | base-containers/base/inginious/lang.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/lang.py#L22-L29 | def init():
""" Install gettext with the default parameters """
if "_" not in builtins.__dict__: # avoid installing lang two times
os.environ["LANGUAGE"] = inginious.input.get_lang()
if inginious.DEBUG:
gettext.install("messages", get_lang_dir_path())
else:
gette... | [
"def",
"init",
"(",
")",
":",
"if",
"\"_\"",
"not",
"in",
"builtins",
".",
"__dict__",
":",
"# avoid installing lang two times",
"os",
".",
"environ",
"[",
"\"LANGUAGE\"",
"]",
"=",
"inginious",
".",
"input",
".",
"get_lang",
"(",
")",
"if",
"inginious",
"... | Install gettext with the default parameters | [
"Install",
"gettext",
"with",
"the",
"default",
"parameters"
] | python | train | 44.5 |
tensorflow/cleverhans | cleverhans/utils_pytorch.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L14-L38 | def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
"""
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when statef... | [
"def",
"_py_func_with_gradient",
"(",
"func",
",",
"inp",
",",
"Tout",
",",
"stateful",
"=",
"True",
",",
"name",
"=",
"None",
",",
"grad_func",
"=",
"None",
")",
":",
"# Generate random name in order to avoid conflicts with inbuilt names",
"rnd_name",
"=",
"'PyFunc... | PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when stateful is True
:param name: Name of the PyFunction
:param grad: Custom Gradient Function
:return: | [
"PyFunc",
"defined",
"as",
"given",
"by",
"Tensorflow",
":",
"param",
"func",
":",
"Custom",
"Function",
":",
"param",
"inp",
":",
"Function",
"Inputs",
":",
"param",
"Tout",
":",
"Ouput",
"Type",
"of",
"out",
"Custom",
"Function",
":",
"param",
"stateful"... | python | train | 34.96 |
diamondman/proteusisc | proteusisc/drivers/digilentdriver.py | https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/drivers/digilentdriver.py#L334-L367 | def write_tdi_bits(self, buff, return_tdo=False, TMS=True):
"""
Command controller to write TDI data (with constant TMS bit)
to the physical scan chain. Optionally return TDO bits sent
back from scan the chain.
Args:
data - bits to send over TDI line of scan chain (b... | [
"def",
"write_tdi_bits",
"(",
"self",
",",
"buff",
",",
"return_tdo",
"=",
"False",
",",
"TMS",
"=",
"True",
")",
":",
"self",
".",
"_check_jtag",
"(",
")",
"tms_bits",
"=",
"bitarray",
"(",
"[",
"TMS",
"]",
"*",
"len",
"(",
"buff",
")",
")",
"self... | Command controller to write TDI data (with constant TMS bit)
to the physical scan chain. Optionally return TDO bits sent
back from scan the chain.
Args:
data - bits to send over TDI line of scan chain (bitarray)
return_tdo (bool) - return the devices bitarray response
... | [
"Command",
"controller",
"to",
"write",
"TDI",
"data",
"(",
"with",
"constant",
"TMS",
"bit",
")",
"to",
"the",
"physical",
"scan",
"chain",
".",
"Optionally",
"return",
"TDO",
"bits",
"sent",
"back",
"from",
"scan",
"the",
"chain",
"."
] | python | train | 41.911765 |
opentracing-contrib/python-flask | flask_opentracing/tracing.py | https://github.com/opentracing-contrib/python-flask/blob/74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca/flask_opentracing/tracing.py#L66-L93 | def trace(self, *attributes):
"""
Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span
"""
def decorator(f):
... | [
"def",
"trace",
"(",
"self",
",",
"*",
"attributes",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_trace_all_requests",
":",
"return",
"f",
"(",
"*",
... | Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span | [
"Function",
"decorator",
"that",
"traces",
"functions"
] | python | train | 30.857143 |
twilio/twilio-python | twilio/rest/flex_api/v1/configuration.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/flex_api/v1/configuration.py#L240-L250 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ConfigurationContext for this ConfigurationInstance
:rtype: twilio.rest.flex_api.v1.configuration... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"ConfigurationContext",
"(",
"self",
".",
"_version",
",",
")",
"return",
"self",
".",
"_context"
] | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ConfigurationContext for this ConfigurationInstance
:rtype: twilio.rest.flex_api.v1.configuration.ConfigurationContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train | 42.909091 |
apache/incubator-mxnet | example/gluon/lipnet/utils/align.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/align.py#L62-L69 | def word(self, _id, padding=75):
"""
Get words
"""
word = self.words[_id][2]
vec = word_to_vector(word)
vec += [-1] * (padding - len(vec))
return np.array(vec, dtype=np.int32) | [
"def",
"word",
"(",
"self",
",",
"_id",
",",
"padding",
"=",
"75",
")",
":",
"word",
"=",
"self",
".",
"words",
"[",
"_id",
"]",
"[",
"2",
"]",
"vec",
"=",
"word_to_vector",
"(",
"word",
")",
"vec",
"+=",
"[",
"-",
"1",
"]",
"*",
"(",
"paddin... | Get words | [
"Get",
"words"
] | python | train | 28 |
hfaran/Tornado-JSON | tornado_json/utils.py | https://github.com/hfaran/Tornado-JSON/blob/8d8b35ff77f13cb3ab1a606bd2083b26cc69c54f/tornado_json/utils.py#L25-L40 | def container(dec):
"""Meta-decorator (for decorating decorators)
Keeps around original decorated function as a property ``orig_func``
:param dec: Decorator to decorate
:type dec: function
:returns: Decorated decorator
"""
# Credits: http://stackoverflow.com/a/1167248/1798683
@wraps(d... | [
"def",
"container",
"(",
"dec",
")",
":",
"# Credits: http://stackoverflow.com/a/1167248/1798683",
"@",
"wraps",
"(",
"dec",
")",
"def",
"meta_decorator",
"(",
"f",
")",
":",
"decorator",
"=",
"dec",
"(",
"f",
")",
"decorator",
".",
"orig_func",
"=",
"f",
"r... | Meta-decorator (for decorating decorators)
Keeps around original decorated function as a property ``orig_func``
:param dec: Decorator to decorate
:type dec: function
:returns: Decorated decorator | [
"Meta",
"-",
"decorator",
"(",
"for",
"decorating",
"decorators",
")"
] | python | train | 27.8125 |
xiongchiamiov/pyfixit | pyfixit/image.py | https://github.com/xiongchiamiov/pyfixit/blob/808a0c852a26e4211b2e3a72da972ab34a586dc4/pyfixit/image.py#L39-L58 | def refresh(self):
'''Refetch instance data from the API.
'''
response = requests.get('%s/media/images/%s' % (API_BASE_URL, self.id))
attributes = response.json()
#self.exif = attributes['exif']
self.height = attributes['height']
self.width = attributes['width']
#s... | [
"def",
"refresh",
"(",
"self",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"'%s/media/images/%s'",
"%",
"(",
"API_BASE_URL",
",",
"self",
".",
"id",
")",
")",
"attributes",
"=",
"response",
".",
"json",
"(",
")",
"#self.exif = attributes['exif']"... | Refetch instance data from the API. | [
"Refetch",
"instance",
"data",
"from",
"the",
"API",
"."
] | python | train | 37.15 |
jazzband/django-constance | constance/checks.py | https://github.com/jazzband/django-constance/blob/2948dff3cc7a5bcab3f996e7da89af18700de3cc/constance/checks.py#L30-L42 | def get_inconsistent_fieldnames():
"""
Returns a set of keys from settings.CONFIG that are not accounted for in
settings.CONFIG_FIELDSETS.
If there are no fieldnames in settings.CONFIG_FIELDSETS, returns an empty set.
"""
field_name_list = []
for fieldset_title, fields_list in settings.CONFI... | [
"def",
"get_inconsistent_fieldnames",
"(",
")",
":",
"field_name_list",
"=",
"[",
"]",
"for",
"fieldset_title",
",",
"fields_list",
"in",
"settings",
".",
"CONFIG_FIELDSETS",
".",
"items",
"(",
")",
":",
"for",
"field_name",
"in",
"fields_list",
":",
"field_name... | Returns a set of keys from settings.CONFIG that are not accounted for in
settings.CONFIG_FIELDSETS.
If there are no fieldnames in settings.CONFIG_FIELDSETS, returns an empty set. | [
"Returns",
"a",
"set",
"of",
"keys",
"from",
"settings",
".",
"CONFIG",
"that",
"are",
"not",
"accounted",
"for",
"in",
"settings",
".",
"CONFIG_FIELDSETS",
".",
"If",
"there",
"are",
"no",
"fieldnames",
"in",
"settings",
".",
"CONFIG_FIELDSETS",
"returns",
... | python | train | 40.538462 |
twilio/twilio-python | twilio/rest/serverless/v1/service/environment/deployment.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/serverless/v1/service/environment/deployment.py#L326-L341 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: DeploymentContext for this DeploymentInstance
:rtype: twilio.rest.serverless.v1.service.environme... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"DeploymentContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: DeploymentContext for this DeploymentInstance
:rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train | 42 |
ynop/audiomate | audiomate/feeding/partitioning.py | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/partitioning.py#L150-L158 | def _raise_error_if_container_is_missing_an_utterance(self):
""" Check if there is a dataset for every utterance in every container, otherwise raise an error. """
expected_keys = frozenset(self.utt_ids)
for cnt in self.containers:
keys = set(cnt.keys())
if not keys.issu... | [
"def",
"_raise_error_if_container_is_missing_an_utterance",
"(",
"self",
")",
":",
"expected_keys",
"=",
"frozenset",
"(",
"self",
".",
"utt_ids",
")",
"for",
"cnt",
"in",
"self",
".",
"containers",
":",
"keys",
"=",
"set",
"(",
"cnt",
".",
"keys",
"(",
")",... | Check if there is a dataset for every utterance in every container, otherwise raise an error. | [
"Check",
"if",
"there",
"is",
"a",
"dataset",
"for",
"every",
"utterance",
"in",
"every",
"container",
"otherwise",
"raise",
"an",
"error",
"."
] | python | train | 46.333333 |
saltstack/salt | salt/payload.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L193-L272 | def dumps(self, msg, use_bin_type=False):
'''
Run the correct dumps serialization format
:param use_bin_type: Useful for Python 3 support. Tells msgpack to
differentiate between 'str' and 'bytes' types
by encoding them differently.
... | [
"def",
"dumps",
"(",
"self",
",",
"msg",
",",
"use_bin_type",
"=",
"False",
")",
":",
"def",
"ext_type_encoder",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"integer_types",
")",
":",
"# msgpack can't handle the very long Python long... | Run the correct dumps serialization format
:param use_bin_type: Useful for Python 3 support. Tells msgpack to
differentiate between 'str' and 'bytes' types
by encoding them differently.
Since this changes the wire protocol, ... | [
"Run",
"the",
"correct",
"dumps",
"serialization",
"format"
] | python | train | 52.8125 |
RJT1990/pyflux | pyflux/garch/egarchm.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/garch/egarchm.py#L309-L359 | def _sim_prediction_bayes(self, h, simulations):
""" Simulates a h-step ahead mean prediction
Parameters
----------
h : int
How many steps ahead for the prediction
simulations : int
How many simulations to perform
Returns
----------
... | [
"def",
"_sim_prediction_bayes",
"(",
"self",
",",
"h",
",",
"simulations",
")",
":",
"sim_vector",
"=",
"np",
".",
"zeros",
"(",
"[",
"simulations",
",",
"h",
"]",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"simulations",
")",
":",
"t_z",
"=",
... | Simulates a h-step ahead mean prediction
Parameters
----------
h : int
How many steps ahead for the prediction
simulations : int
How many simulations to perform
Returns
----------
Matrix of simulations | [
"Simulates",
"a",
"h",
"-",
"step",
"ahead",
"mean",
"prediction"
] | python | train | 34.333333 |
saltstack/salt | salt/states/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L806-L949 | def _check_directory_win(name,
win_owner=None,
win_perms=None,
win_deny_perms=None,
win_inheritance=None,
win_perms_reset=None):
'''
Check what changes need to be made on a directory
... | [
"def",
"_check_directory_win",
"(",
"name",
",",
"win_owner",
"=",
"None",
",",
"win_perms",
"=",
"None",
",",
"win_deny_perms",
"=",
"None",
",",
"win_inheritance",
"=",
"None",
",",
"win_perms_reset",
"=",
"None",
")",
":",
"changes",
"=",
"{",
"}",
"if"... | Check what changes need to be made on a directory | [
"Check",
"what",
"changes",
"need",
"to",
"be",
"made",
"on",
"a",
"directory"
] | python | train | 45.645833 |
mbedmicro/pyOCD | pyocd/utility/server.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/utility/server.py#L148-L156 | def read(self, size=-1):
"""! @brief Return bytes read from the connection."""
if self.connected is None:
return None
# Extract requested amount of data from the read buffer.
data = self._get_input(size)
return data | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"connected",
"is",
"None",
":",
"return",
"None",
"# Extract requested amount of data from the read buffer.",
"data",
"=",
"self",
".",
"_get_input",
"(",
"size",
")",
"retu... | ! @brief Return bytes read from the connection. | [
"!"
] | python | train | 29 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2256-L2264 | def _delToC(self):
"""_delToC(self) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
val = _fitz.Document__delToC(self)
self.initData()
return val | [
"def",
"_delToC",
"(",
"self",
")",
":",
"if",
"self",
".",
"isClosed",
"or",
"self",
".",
"isEncrypted",
":",
"raise",
"ValueError",
"(",
"\"operation illegal for closed / encrypted doc\"",
")",
"val",
"=",
"_fitz",
".",
"Document__delToC",
"(",
"self",
")",
... | _delToC(self) -> PyObject * | [
"_delToC",
"(",
"self",
")",
"-",
">",
"PyObject",
"*"
] | python | train | 29.222222 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/program.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/program.py#L224-L238 | def bind(self, data):
""" Bind a VertexBuffer that has structured data
Parameters
----------
data : VertexBuffer
The vertex buffer to bind. The field names of the array
are mapped to attribute names in GLSL.
"""
# Check
if not isin... | [
"def",
"bind",
"(",
"self",
",",
"data",
")",
":",
"# Check",
"if",
"not",
"isinstance",
"(",
"data",
",",
"VertexBuffer",
")",
":",
"raise",
"ValueError",
"(",
"'Program.bind() requires a VertexBuffer.'",
")",
"# Apply",
"for",
"name",
"in",
"data",
".",
"d... | Bind a VertexBuffer that has structured data
Parameters
----------
data : VertexBuffer
The vertex buffer to bind. The field names of the array
are mapped to attribute names in GLSL. | [
"Bind",
"a",
"VertexBuffer",
"that",
"has",
"structured",
"data",
"Parameters",
"----------",
"data",
":",
"VertexBuffer",
"The",
"vertex",
"buffer",
"to",
"bind",
".",
"The",
"field",
"names",
"of",
"the",
"array",
"are",
"mapped",
"to",
"attribute",
"names",... | python | train | 33 |
althonos/pronto | pronto/term.py | https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/term.py#L150-L217 | def obo(self):
"""str: the `Term` serialized in an Obo ``[Term]`` stanza.
Note:
The following guide was used:
ftp://ftp.geneontology.org/pub/go/www/GO.format.obo-1_4.shtml
"""
def add_tags(stanza_list, tags):
for tag in tags:
if tag in... | [
"def",
"obo",
"(",
"self",
")",
":",
"def",
"add_tags",
"(",
"stanza_list",
",",
"tags",
")",
":",
"for",
"tag",
"in",
"tags",
":",
"if",
"tag",
"in",
"self",
".",
"other",
":",
"if",
"isinstance",
"(",
"self",
".",
"other",
"[",
"tag",
"]",
",",... | str: the `Term` serialized in an Obo ``[Term]`` stanza.
Note:
The following guide was used:
ftp://ftp.geneontology.org/pub/go/www/GO.format.obo-1_4.shtml | [
"str",
":",
"the",
"Term",
"serialized",
"in",
"an",
"Obo",
"[",
"Term",
"]",
"stanza",
"."
] | python | train | 36.367647 |
saltstack/salt | salt/modules/cron.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L180-L188 | def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path) | [
"def",
"_get_cron_cmdstr",
"(",
"path",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
":",
"cmd",
"=",
"'crontab -u {0}'",
".",
"format",
"(",
"user",
")",
"else",
":",
"cmd",
"=",
"'crontab'",
"return",
"'{0} {1}'",
".",
"format",
"(",
"cmd",
",",... | Returns a format string, to be used to build a crontab command. | [
"Returns",
"a",
"format",
"string",
"to",
"be",
"used",
"to",
"build",
"a",
"crontab",
"command",
"."
] | python | train | 27.111111 |
staugur/Flask-PluginKit | flask_pluginkit/flask_pluginkit.py | https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L697-L716 | def push_func(self, cuin, callback):
"""Push a function for dfp.
:param cuin: str,unicode: Callback Unique Identifier Name.
:param callback: callable: Corresponding to the cuin to perform a function.
:raises: DFPError,NotCallableError: raises an exception
.. versionadded:: 2.... | [
"def",
"push_func",
"(",
"self",
",",
"cuin",
",",
"callback",
")",
":",
"if",
"cuin",
"and",
"isinstance",
"(",
"cuin",
",",
"string_types",
")",
"and",
"callable",
"(",
"callback",
")",
":",
"if",
"cuin",
"in",
"self",
".",
"_dfp_funcs",
":",
"raise"... | Push a function for dfp.
:param cuin: str,unicode: Callback Unique Identifier Name.
:param callback: callable: Corresponding to the cuin to perform a function.
:raises: DFPError,NotCallableError: raises an exception
.. versionadded:: 2.3.0 | [
"Push",
"a",
"function",
"for",
"dfp",
"."
] | python | train | 37 |
biolink/ontobio | ontobio/golr/golr_query.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/golr/golr_query.py#L506-L533 | def _process_search_results(self,
results: pysolr.Results) -> SearchResults:
"""
Convert solr docs to biolink object
:param results: pysolr.Results
:return: model.GolrResults.SearchResults
"""
# map go-golr fields to standard
for ... | [
"def",
"_process_search_results",
"(",
"self",
",",
"results",
":",
"pysolr",
".",
"Results",
")",
"->",
"SearchResults",
":",
"# map go-golr fields to standard",
"for",
"doc",
"in",
"results",
".",
"docs",
":",
"if",
"'entity'",
"in",
"doc",
":",
"doc",
"[",
... | Convert solr docs to biolink object
:param results: pysolr.Results
:return: model.GolrResults.SearchResults | [
"Convert",
"solr",
"docs",
"to",
"biolink",
"object"
] | python | train | 32.142857 |
pymc-devs/pymc | pymc/distributions.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L722-L738 | def rarlognormal(a, sigma, rho, size=1):
R"""
Autoregressive normal random variates.
If a is a scalar, generates one series of length size.
If a is a sequence, generates size series of the same length
as a.
"""
f = utils.ar1
if np.isscalar(a):
r = f(rho, 0, sigma, size)
else... | [
"def",
"rarlognormal",
"(",
"a",
",",
"sigma",
",",
"rho",
",",
"size",
"=",
"1",
")",
":",
"f",
"=",
"utils",
".",
"ar1",
"if",
"np",
".",
"isscalar",
"(",
"a",
")",
":",
"r",
"=",
"f",
"(",
"rho",
",",
"0",
",",
"sigma",
",",
"size",
")",... | R"""
Autoregressive normal random variates.
If a is a scalar, generates one series of length size.
If a is a sequence, generates size series of the same length
as a. | [
"R",
"Autoregressive",
"normal",
"random",
"variates",
"."
] | python | train | 26.294118 |
dlecocq/nsq-py | nsq/util.py | https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/util.py#L12-L20 | def pack_iterable(messages):
'''Pack an iterable of messages in the TCP protocol format'''
# [ 4-byte body size ]
# [ 4-byte num messages ]
# [ 4-byte message #1 size ][ N-byte binary data ]
# ... (repeated <num_messages> times)
return pack_string(
struct.pack('>l', len(messages)) +... | [
"def",
"pack_iterable",
"(",
"messages",
")",
":",
"# [ 4-byte body size ]",
"# [ 4-byte num messages ]",
"# [ 4-byte message #1 size ][ N-byte binary data ]",
"# ... (repeated <num_messages> times)",
"return",
"pack_string",
"(",
"struct",
".",
"pack",
"(",
"'>l'",
",",
"... | Pack an iterable of messages in the TCP protocol format | [
"Pack",
"an",
"iterable",
"of",
"messages",
"in",
"the",
"TCP",
"protocol",
"format"
] | python | train | 39.666667 |
mar10/wsgidav | wsgidav/dav_provider.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L1507-L1514 | def is_collection(self, path, environ):
"""Return True, if path maps to an existing collection resource.
This method should only be used, if no other information is queried
for <path>. Otherwise a _DAVResource should be created first.
"""
res = self.get_resource_inst(path, envir... | [
"def",
"is_collection",
"(",
"self",
",",
"path",
",",
"environ",
")",
":",
"res",
"=",
"self",
".",
"get_resource_inst",
"(",
"path",
",",
"environ",
")",
"return",
"res",
"and",
"res",
".",
"is_collection"
] | Return True, if path maps to an existing collection resource.
This method should only be used, if no other information is queried
for <path>. Otherwise a _DAVResource should be created first. | [
"Return",
"True",
"if",
"path",
"maps",
"to",
"an",
"existing",
"collection",
"resource",
"."
] | python | valid | 44.625 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L663-L687 | def set_dwelling_current(self, settings):
'''
Sets the amperage of each motor for when it is dwelling.
Values are initialized from the `robot_config.log_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the dwe... | [
"def",
"set_dwelling_current",
"(",
"self",
",",
"settings",
")",
":",
"self",
".",
"_dwelling_current_settings",
"[",
"'now'",
"]",
".",
"update",
"(",
"settings",
")",
"# if an axis specified in the `settings` is currently dwelling,",
"# reset it's current to the new dwelli... | Sets the amperage of each motor for when it is dwelling.
Values are initialized from the `robot_config.log_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the dwelling-current of it's pipette,
depending on what model... | [
"Sets",
"the",
"amperage",
"of",
"each",
"motor",
"for",
"when",
"it",
"is",
"dwelling",
".",
"Values",
"are",
"initialized",
"from",
"the",
"robot_config",
".",
"log_current",
"values",
"and",
"can",
"then",
"be",
"changed",
"through",
"this",
"method",
"by... | python | train | 44.44 |
clld/clldutils | src/clldutils/jsonlib.py | https://github.com/clld/clldutils/blob/7b8587ef5b56a2fc6cafaff90bc5004355c2b13f/src/clldutils/jsonlib.py#L56-L66 | def load(path, **kw):
"""python 2 + 3 compatible version of json.load.
:param kw: Keyword parameters are passed to json.load
:return: The python object read from path.
"""
_kw = {}
if PY3: # pragma: no cover
_kw['encoding'] = 'utf-8'
with open(str(path), **_kw) as fp:
retur... | [
"def",
"load",
"(",
"path",
",",
"*",
"*",
"kw",
")",
":",
"_kw",
"=",
"{",
"}",
"if",
"PY3",
":",
"# pragma: no cover",
"_kw",
"[",
"'encoding'",
"]",
"=",
"'utf-8'",
"with",
"open",
"(",
"str",
"(",
"path",
")",
",",
"*",
"*",
"_kw",
")",
"as... | python 2 + 3 compatible version of json.load.
:param kw: Keyword parameters are passed to json.load
:return: The python object read from path. | [
"python",
"2",
"+",
"3",
"compatible",
"version",
"of",
"json",
".",
"load",
"."
] | python | train | 30.090909 |
ibis-project/ibis | ibis/client.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/client.py#L192-L201 | def compile(self, expr, params=None, limit=None):
"""
Translate expression to one or more queries according to backend target
Returns
-------
output : single query or list of queries
"""
query_ast = self._build_ast_ensure_limit(expr, limit, params=params)
... | [
"def",
"compile",
"(",
"self",
",",
"expr",
",",
"params",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"query_ast",
"=",
"self",
".",
"_build_ast_ensure_limit",
"(",
"expr",
",",
"limit",
",",
"params",
"=",
"params",
")",
"return",
"query_ast",
... | Translate expression to one or more queries according to backend target
Returns
-------
output : single query or list of queries | [
"Translate",
"expression",
"to",
"one",
"or",
"more",
"queries",
"according",
"to",
"backend",
"target"
] | python | train | 33.8 |
zyga/python-glibc | tempfile_ext.py | https://github.com/zyga/python-glibc/blob/d6fdb306b123a995471584a5201155c60a34448a/tempfile_ext.py#L254-L277 | def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which
_get_default_tempdir will try."""
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# F... | [
"def",
"_candidate_tempdir_list",
"(",
")",
":",
"dirlist",
"=",
"[",
"]",
"# First, try the environment.",
"for",
"envname",
"in",
"'TMPDIR'",
",",
"'TEMP'",
",",
"'TMP'",
":",
"dirname",
"=",
"_os",
".",
"getenv",
"(",
"envname",
")",
"if",
"dirname",
":",... | Generate a list of candidate temporary directories which
_get_default_tempdir will try. | [
"Generate",
"a",
"list",
"of",
"candidate",
"temporary",
"directories",
"which",
"_get_default_tempdir",
"will",
"try",
"."
] | python | train | 28.583333 |
soravux/scoop | scoop/futures.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/futures.py#L154-L196 | def _recursiveReduce(mapFunc, reductionFunc, scan, *iterables):
"""Generates the recursive reduction tree. Used by mapReduce."""
if iterables:
half = min(len(x) // 2 for x in iterables)
data_left = [list(x)[:half] for x in iterables]
data_right = [list(x)[half:] for x in iterables]
e... | [
"def",
"_recursiveReduce",
"(",
"mapFunc",
",",
"reductionFunc",
",",
"scan",
",",
"*",
"iterables",
")",
":",
"if",
"iterables",
":",
"half",
"=",
"min",
"(",
"len",
"(",
"x",
")",
"//",
"2",
"for",
"x",
"in",
"iterables",
")",
"data_left",
"=",
"["... | Generates the recursive reduction tree. Used by mapReduce. | [
"Generates",
"the",
"recursive",
"reduction",
"tree",
".",
"Used",
"by",
"mapReduce",
"."
] | python | train | 34.162791 |
Parquery/icontract | icontract/_recompute.py | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L413-L415 | def visit_Return(self, node: ast.Return) -> Any: # pylint: disable=no-self-use
"""Raise an exception that this node is unexpected."""
raise AssertionError("Unexpected return node during the re-computation: {}".format(ast.dump(node))) | [
"def",
"visit_Return",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Return",
")",
"->",
"Any",
":",
"# pylint: disable=no-self-use",
"raise",
"AssertionError",
"(",
"\"Unexpected return node during the re-computation: {}\"",
".",
"format",
"(",
"ast",
".",
"dump",
"(... | Raise an exception that this node is unexpected. | [
"Raise",
"an",
"exception",
"that",
"this",
"node",
"is",
"unexpected",
"."
] | python | train | 82.666667 |
joshuaduffy/dota2api | dota2api/__init__.py | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L251-L262 | def __build_url(self, api_call, **kwargs):
"""Builds the api query"""
kwargs['key'] = self.api_key
if 'language' not in kwargs:
kwargs['language'] = self.language
if 'format' not in kwargs:
kwargs['format'] = self.__format
api_query = urlencode(kwargs)
... | [
"def",
"__build_url",
"(",
"self",
",",
"api_call",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'key'",
"]",
"=",
"self",
".",
"api_key",
"if",
"'language'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'language'",
"]",
"=",
"self",
".",
"lang... | Builds the api query | [
"Builds",
"the",
"api",
"query"
] | python | train | 37.25 |
xtrinch/fcm-django | fcm_django/fcm.py | https://github.com/xtrinch/fcm-django/blob/8480d1cf935bfb28e2ad6d86a0abf923c2ecb266/fcm_django/fcm.py#L352-L420 | def fcm_send_bulk_data_messages(
api_key,
registration_ids=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
... | [
"def",
"fcm_send_bulk_data_messages",
"(",
"api_key",
",",
"registration_ids",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"collapse_key",
"=",
"None",
",",
"delay_while_idle",
"=",
"False",
",",
"time_to_live",
"=",
"None",
",",
"restricted_package_name",
"=... | Arguments correspond to those from pyfcm/fcm.py.
Sends push message to multiple devices,
can send to over 1000 devices
Args:
api_key
registration_ids (list): FCM device registration IDs.
data_message (dict): Data message payload to send alone or with the notification message
K... | [
"Arguments",
"correspond",
"to",
"those",
"from",
"pyfcm",
"/",
"fcm",
".",
"py",
"."
] | python | train | 43.130435 |
kumar303/mohawk | mohawk/util.py | https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/util.py#L91-L106 | def calculate_ts_mac(ts, credentials):
"""Calculates a message authorization code (MAC) for a timestamp."""
normalized = ('hawk.{hawk_ver}.ts\n{ts}\n'
.format(hawk_ver=HAWK_VER, ts=ts))
log.debug(u'normalized resource for ts mac calc: {norm}'
.format(norm=normalized))
dig... | [
"def",
"calculate_ts_mac",
"(",
"ts",
",",
"credentials",
")",
":",
"normalized",
"=",
"(",
"'hawk.{hawk_ver}.ts\\n{ts}\\n'",
".",
"format",
"(",
"hawk_ver",
"=",
"HAWK_VER",
",",
"ts",
"=",
"ts",
")",
")",
"log",
".",
"debug",
"(",
"u'normalized resource for ... | Calculates a message authorization code (MAC) for a timestamp. | [
"Calculates",
"a",
"message",
"authorization",
"code",
"(",
"MAC",
")",
"for",
"a",
"timestamp",
"."
] | python | train | 40.8125 |
pypa/pipenv | pipenv/vendor/click/decorators.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L31-L66 | def make_pass_decorator(object_type, ensure=False):
"""Given an object type this creates a decorator that will work
similar to :func:`pass_obj` but instead of passing the object of the
current context, it will find the innermost context of type
:func:`object_type`.
This generates a decorator that w... | [
"def",
"make_pass_decorator",
"(",
"object_type",
",",
"ensure",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"get_current_context",
"(",
")",
"if",
... | Given an object type this creates a decorator that will work
similar to :func:`pass_obj` but instead of passing the object of the
current context, it will find the innermost context of type
:func:`object_type`.
This generates a decorator that works roughly like this::
from functools import upd... | [
"Given",
"an",
"object",
"type",
"this",
"creates",
"a",
"decorator",
"that",
"will",
"work",
"similar",
"to",
":",
"func",
":",
"pass_obj",
"but",
"instead",
"of",
"passing",
"the",
"object",
"of",
"the",
"current",
"context",
"it",
"will",
"find",
"the",... | python | train | 40 |
googleapis/gax-python | google/gapic/longrunning/operations_client.py | https://github.com/googleapis/gax-python/blob/309aedfcfd48e4c8fa22dd60e9c84c3cc71bb20e/google/gapic/longrunning/operations_client.py#L298-L322 | def delete_operation(self, name, options=None):
"""
Deletes a long-running operation. This method indicates that the client is
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
``google.rpc.Code.U... | [
"def",
"delete_operation",
"(",
"self",
",",
"name",
",",
"options",
"=",
"None",
")",
":",
"# Create the request object.",
"request",
"=",
"operations_pb2",
".",
"DeleteOperationRequest",
"(",
"name",
"=",
"name",
")",
"self",
".",
"_delete_operation",
"(",
"re... | Deletes a long-running operation. This method indicates that the client is
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
``google.rpc.Code.UNIMPLEMENTED``.
Example:
>>> from google.gapic.lo... | [
"Deletes",
"a",
"long",
"-",
"running",
"operation",
".",
"This",
"method",
"indicates",
"that",
"the",
"client",
"is",
"no",
"longer",
"interested",
"in",
"the",
"operation",
"result",
".",
"It",
"does",
"not",
"cancel",
"the",
"operation",
".",
"If",
"th... | python | train | 42.24 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L121-L139 | def MetaField(self, name, t=None):
"""
Creates an instance of a metadata field of the dataset. It can be used in building expressions
or conditions for projection or selection.
Notice that this function is equivalent to call::
dataset["name"]
If the Meta... | [
"def",
"MetaField",
"(",
"self",
",",
"name",
",",
"t",
"=",
"None",
")",
":",
"return",
"MetaField",
"(",
"name",
"=",
"name",
",",
"index",
"=",
"self",
".",
"__index",
",",
"t",
"=",
"t",
")"
] | Creates an instance of a metadata field of the dataset. It can be used in building expressions
or conditions for projection or selection.
Notice that this function is equivalent to call::
dataset["name"]
If the MetaField is used in a region projection (:meth:`~.reg_proj... | [
"Creates",
"an",
"instance",
"of",
"a",
"metadata",
"field",
"of",
"the",
"dataset",
".",
"It",
"can",
"be",
"used",
"in",
"building",
"expressions",
"or",
"conditions",
"for",
"projection",
"or",
"selection",
".",
"Notice",
"that",
"this",
"function",
"is",... | python | train | 42.421053 |
artisanofcode/python-broadway | broadway/errors.py | https://github.com/artisanofcode/python-broadway/blob/a051ca5a922ecb38a541df59e8740e2a047d9a4a/broadway/errors.py#L40-L45 | def init_app(application):
"""
Associates the error handler
"""
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) | [
"def",
"init_app",
"(",
"application",
")",
":",
"for",
"code",
"in",
"werkzeug",
".",
"exceptions",
".",
"default_exceptions",
":",
"application",
".",
"register_error_handler",
"(",
"code",
",",
"handle_http_exception",
")"
] | Associates the error handler | [
"Associates",
"the",
"error",
"handler"
] | python | train | 33 |
pysam-developers/pysam | pysam/Pileup.py | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/Pileup.py#L256-L282 | def iterate_from_vcf(infile, sample):
'''iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This... | [
"def",
"iterate_from_vcf",
"(",
"infile",
",",
"sample",
")",
":",
"vcf",
"=",
"pysam",
".",
"VCF",
"(",
")",
"vcf",
".",
"connect",
"(",
"infile",
")",
"if",
"sample",
"not",
"in",
"vcf",
".",
"getsamples",
"(",
")",
":",
"raise",
"KeyError",
"(",
... | iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support sa... | [
"iterate",
"over",
"a",
"vcf",
"-",
"formatted",
"file",
"."
] | python | train | 25.666667 |
majerteam/sqla_inspect | sqla_inspect/ascii.py | https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/ascii.py#L35-L45 | def force_encoding(value, encoding='utf-8'):
"""
Return a string encoded in the provided encoding
"""
if not isinstance(value, (str, unicode)):
value = str(value)
if isinstance(value, unicode):
value = value.encode(encoding)
elif encoding != 'utf-8':
value = value.decode(... | [
"def",
"force_encoding",
"(",
"value",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
... | Return a string encoded in the provided encoding | [
"Return",
"a",
"string",
"encoded",
"in",
"the",
"provided",
"encoding"
] | python | train | 32 |
bwohlberg/sporco | sporco/dictlrn/cbpdndlmd.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndlmd.py#L63-L87 | def ConvBPDNMaskOptions(opt=None, method='admm'):
"""A wrapper function that dynamically defines a class derived from
the Options class associated with one of the implementations of
the Convolutional BPDN problem, and returns an object
instantiated with the provided parameters. The wrapper is designed
... | [
"def",
"ConvBPDNMaskOptions",
"(",
"opt",
"=",
"None",
",",
"method",
"=",
"'admm'",
")",
":",
"# Assign base class depending on method selection argument",
"base",
"=",
"cbpdnmsk_class_label_lookup",
"(",
"method",
")",
".",
"Options",
"# Nested class with dynamically dete... | A wrapper function that dynamically defines a class derived from
the Options class associated with one of the implementations of
the Convolutional BPDN problem, and returns an object
instantiated with the provided parameters. The wrapper is designed
to allow the appropriate object to be created by calli... | [
"A",
"wrapper",
"function",
"that",
"dynamically",
"defines",
"a",
"class",
"derived",
"from",
"the",
"Options",
"class",
"associated",
"with",
"one",
"of",
"the",
"implementations",
"of",
"the",
"Convolutional",
"BPDN",
"problem",
"and",
"returns",
"an",
"objec... | python | train | 44.88 |
ivelum/graphql-py | graphql/parser.py | https://github.com/ivelum/graphql-py/blob/72baf16d838e82349ee5e8d8f8971ce11cfcedf9/graphql/parser.py#L52-L56 | def p_document_shorthand_with_fragments(self, p):
"""
document : selection_set fragment_list
"""
p[0] = Document(definitions=[Query(selections=p[1])] + p[2]) | [
"def",
"p_document_shorthand_with_fragments",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Document",
"(",
"definitions",
"=",
"[",
"Query",
"(",
"selections",
"=",
"p",
"[",
"1",
"]",
")",
"]",
"+",
"p",
"[",
"2",
"]",
")"
] | document : selection_set fragment_list | [
"document",
":",
"selection_set",
"fragment_list"
] | python | train | 37 |
gtzampanakis/downloader | downloader.py | https://github.com/gtzampanakis/downloader/blob/7354f68adc72f2bfc472f41596af6ee8b3e6ea88/downloader.py#L192-L297 | def open_url(self, url, stale_after, parse_as_html = True, **kwargs):
"""
Download or retrieve from cache.
url -- The URL to be downloaded, as a string.
stale_after -- A network request for the url will be performed if the
cached copy does not exist or if it exists but its age (in days) is
larger ... | [
"def",
"open_url",
"(",
"self",
",",
"url",
",",
"stale_after",
",",
"parse_as_html",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'open_url() received url: %s'",
",",
"url",
")",
"today",
"=",
"datetime",
".",
"date",
".... | Download or retrieve from cache.
url -- The URL to be downloaded, as a string.
stale_after -- A network request for the url will be performed if the
cached copy does not exist or if it exists but its age (in days) is
larger or equal to the stale_after value. A non-positive value will
force re-downloa... | [
"Download",
"or",
"retrieve",
"from",
"cache",
".",
"url",
"--",
"The",
"URL",
"to",
"be",
"downloaded",
"as",
"a",
"string",
".",
"stale_after",
"--",
"A",
"network",
"request",
"for",
"the",
"url",
"will",
"be",
"performed",
"if",
"the",
"cached",
"cop... | python | train | 29.990566 |
njsmith/colorspacious | colorspacious/basics.py | https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/basics.py#L60-L64 | def sRGB1_to_sRGB1_linear(sRGB1):
"""Convert sRGB (as floats in the 0-to-1 range) to linear sRGB."""
sRGB1 = np.asarray(sRGB1, dtype=float)
sRGB1_linear = C_linear(sRGB1)
return sRGB1_linear | [
"def",
"sRGB1_to_sRGB1_linear",
"(",
"sRGB1",
")",
":",
"sRGB1",
"=",
"np",
".",
"asarray",
"(",
"sRGB1",
",",
"dtype",
"=",
"float",
")",
"sRGB1_linear",
"=",
"C_linear",
"(",
"sRGB1",
")",
"return",
"sRGB1_linear"
] | Convert sRGB (as floats in the 0-to-1 range) to linear sRGB. | [
"Convert",
"sRGB",
"(",
"as",
"floats",
"in",
"the",
"0",
"-",
"to",
"-",
"1",
"range",
")",
"to",
"linear",
"sRGB",
"."
] | python | train | 40.4 |
facebookresearch/fastText | python/fastText/FastText.py | https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L100-L143 | def predict(self, text, k=1, threshold=0.0, on_unicode_error='strict'):
"""
Given a string, get a list of labels and a list of
corresponding probabilities. k controls the number
of returned labels. A choice of 5, will return the 5
most probable labels. By default this returns onl... | [
"def",
"predict",
"(",
"self",
",",
"text",
",",
"k",
"=",
"1",
",",
"threshold",
"=",
"0.0",
",",
"on_unicode_error",
"=",
"'strict'",
")",
":",
"def",
"check",
"(",
"entry",
")",
":",
"if",
"entry",
".",
"find",
"(",
"'\\n'",
")",
"!=",
"-",
"1... | Given a string, get a list of labels and a list of
corresponding probabilities. k controls the number
of returned labels. A choice of 5, will return the 5
most probable labels. By default this returns only
the most likely label and probability. threshold filters
the returned labe... | [
"Given",
"a",
"string",
"get",
"a",
"list",
"of",
"labels",
"and",
"a",
"list",
"of",
"corresponding",
"probabilities",
".",
"k",
"controls",
"the",
"number",
"of",
"returned",
"labels",
".",
"A",
"choice",
"of",
"5",
"will",
"return",
"the",
"5",
"most"... | python | train | 42.75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.