text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
async def create_subprocess_with_handle(command,
display_handle,
*,
shell=False,
cwd,
**kwargs):
'''Writes subproces... | [
"async",
"def",
"create_subprocess_with_handle",
"(",
"command",
",",
"display_handle",
",",
"*",
",",
"shell",
"=",
"False",
",",
"cwd",
",",
"*",
"*",
"kwargs",
")",
":",
"# We're going to get chunks of bytes from the subprocess, and it's possible",
"# that one of those... | 41.014706 | 0.00035 |
def filesys_decode(path):
"""
Ensure that the given path is decoded,
NONE when no expected encoding works
"""
if isinstance(path, six.text_type):
return path
fs_enc = sys.getfilesystemencoding() or 'utf-8'
candidates = fs_enc, 'utf-8'
for enc in candidates:
try:
... | [
"def",
"filesys_decode",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"return",
"path",
"fs_enc",
"=",
"sys",
".",
"getfilesystemencoding",
"(",
")",
"or",
"'utf-8'",
"candidates",
"=",
"fs_enc",
",",
"'... | 22.882353 | 0.002469 |
def add_loom(self, other_file: str, key: str = None, fill_values: Dict[str, np.ndarray] = None, batch_size: int = 1000, convert_attrs: bool = False, include_graphs: bool = False) -> None:
"""
Add the content of another loom file
Args:
other_file: filename of the loom file to append
key: ... | [
"def",
"add_loom",
"(",
"self",
",",
"other_file",
":",
"str",
",",
"key",
":",
"str",
"=",
"None",
",",
"fill_values",
":",
"Dict",
"[",
"str",
",",
"np",
".",
"ndarray",
"]",
"=",
"None",
",",
"batch_size",
":",
"int",
"=",
"1000",
",",
"convert_... | 55.293333 | 0.021796 |
def _push_status(data, item):
'''
Process a status update from a docker push, updating the data structure
'''
status = item['status'].lower()
if 'id' in item:
if 'already pushed' in status or 'already exists' in status:
# Layer already exists
already_pushed = data.set... | [
"def",
"_push_status",
"(",
"data",
",",
"item",
")",
":",
"status",
"=",
"item",
"[",
"'status'",
"]",
".",
"lower",
"(",
")",
"if",
"'id'",
"in",
"item",
":",
"if",
"'already pushed'",
"in",
"status",
"or",
"'already exists'",
"in",
"status",
":",
"#... | 40.875 | 0.001495 |
def push(i):
"""
Input: {
(repo_uoa) - repo UOA, if needed
module_uoa - module UOA
data_uoa - data UOA
(filename) - local filename
or
(cid[0])
(extra_path) ... | [
"def",
"push",
"(",
"i",
")",
":",
"# Check if global writing is allowed",
"r",
"=",
"check_writing",
"(",
"{",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",
"r",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"ruoa"... | 25.794521 | 0.037075 |
def get_oldest_commit(self):
'''
Get oldest commit involving this file
:returns: Oldest commit
'''
return self.git.get_commits(self.content.source_path, self.follow)[-1] | [
"def",
"get_oldest_commit",
"(",
"self",
")",
":",
"return",
"self",
".",
"git",
".",
"get_commits",
"(",
"self",
".",
"content",
".",
"source_path",
",",
"self",
".",
"follow",
")",
"[",
"-",
"1",
"]"
] | 29.142857 | 0.009524 |
def _get_vsan_datastore(si, cluster_name):
'''Retrieves the vsan_datastore'''
log.trace('Retrieving vsan datastore')
vsan_datastores = [ds for ds in
__salt__['vsphere.list_datastores_via_proxy'](
service_instance=si)
if ds['type'] == ... | [
"def",
"_get_vsan_datastore",
"(",
"si",
",",
"cluster_name",
")",
":",
"log",
".",
"trace",
"(",
"'Retrieving vsan datastore'",
")",
"vsan_datastores",
"=",
"[",
"ds",
"for",
"ds",
"in",
"__salt__",
"[",
"'vsphere.list_datastores_via_proxy'",
"]",
"(",
"service_i... | 38.357143 | 0.001818 |
def normalized_per_object(image, labels):
"""Normalize the intensities of each object to the [0, 1] range."""
nobjects = labels.max()
objects = np.arange(nobjects + 1)
lmin, lmax = scind.extrema(image, labels, objects)[:2]
# Divisor is the object's max - min, or 1 if they are the same.
divisor =... | [
"def",
"normalized_per_object",
"(",
"image",
",",
"labels",
")",
":",
"nobjects",
"=",
"labels",
".",
"max",
"(",
")",
"objects",
"=",
"np",
".",
"arange",
"(",
"nobjects",
"+",
"1",
")",
"lmin",
",",
"lmax",
"=",
"scind",
".",
"extrema",
"(",
"imag... | 49.222222 | 0.002217 |
def listen_on(self, trigger: str, **kwargs) -> callable:
"""
This is a simple decorator for registering a callback for an event. You can also use 'register_listener'.
A list with all possible options is available via LISTEN_ON_OPTIONS.
:param trigger: Currently supported options: 'univer... | [
"def",
"listen_on",
"(",
"self",
",",
"trigger",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"callable",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"register_listener",
"(",
"trigger",
",",
"f",
",",
"*",
"*",
"kwargs",
")",
"ret... | 48.7 | 0.008065 |
def create_tag(self, tag_name=None, **properties):
"""Creates a tag and adds it to the tag table of the TextBuffer.
:param str tag_name:
Name of the new tag, or None
:param **properties:
Keyword list of properties and their values
:returns:
A new tag.... | [
"def",
"create_tag",
"(",
"self",
",",
"tag_name",
"=",
"None",
",",
"*",
"*",
"properties",
")",
":",
"tag",
"=",
"Gtk",
".",
"TextTag",
"(",
"name",
"=",
"tag_name",
",",
"*",
"*",
"properties",
")",
"self",
".",
"_get_or_create_tag_table",
"(",
")",... | 35.538462 | 0.002107 |
def right(self):
"""
Entry is right sibling of current directory entry
"""
return self.source.directory[self.right_sibling_id] \
if self.right_sibling_id != NOSTREAM else None | [
"def",
"right",
"(",
"self",
")",
":",
"return",
"self",
".",
"source",
".",
"directory",
"[",
"self",
".",
"right_sibling_id",
"]",
"if",
"self",
".",
"right_sibling_id",
"!=",
"NOSTREAM",
"else",
"None"
] | 35.666667 | 0.009132 |
def parse_mark_duplicate_metrics(fn):
"""
Parse the output from Picard's MarkDuplicates and return as pandas
Series.
Parameters
----------
filename : str of filename or file handle
Filename of the Picard output you want to parse.
Returns
-------
metrics : pandas.Series
... | [
"def",
"parse_mark_duplicate_metrics",
"(",
"fn",
")",
":",
"with",
"open",
"(",
"fn",
")",
"as",
"f",
":",
"lines",
"=",
"[",
"x",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"for",
"x",
"in",
"f",
".",
"readlines",
"(",
")",
"]",
... | 26.137931 | 0.001272 |
def notify(self, message, priority='normal', timeout=0, block=False):
"""
opens notification popup.
:param message: message to print
:type message: str
:param priority: priority string, used to format the popup: currently,
'normal' and 'error' are define... | [
"def",
"notify",
"(",
"self",
",",
"message",
",",
"priority",
"=",
"'normal'",
",",
"timeout",
"=",
"0",
",",
"block",
"=",
"False",
")",
":",
"def",
"build_line",
"(",
"msg",
",",
"prio",
")",
":",
"cols",
"=",
"urwid",
".",
"Columns",
"(",
"[",
... | 43.057692 | 0.000873 |
def extract_table(html):
soup = BeautifulSoup(html,'lxml')
table = soup.find("table", attrs={"class":"basic_table"})
if table is None:
return table
return table
'''# The first tr contains the field names.
datasets = []
for row in table.find_all("tr"):
dataset = list((td... | [
"def",
"extract_table",
"(",
"html",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'lxml'",
")",
"table",
"=",
"soup",
".",
"find",
"(",
"\"table\"",
",",
"attrs",
"=",
"{",
"\"class\"",
":",
"\"basic_table\"",
"}",
")",
"if",
"table",
"is... | 31.705882 | 0.010811 |
def solve(self, lam):
'''Solves the GFL for a fixed value of lambda.'''
s = weighted_graphtf_poisson(self.nnodes, self.obs, lam,
self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz,
self.Dk.row.astype('int32'), self.Dk.col.astype('int32'), se... | [
"def",
"solve",
"(",
"self",
",",
"lam",
")",
":",
"s",
"=",
"weighted_graphtf_poisson",
"(",
"self",
".",
"nnodes",
",",
"self",
".",
"obs",
",",
"lam",
",",
"self",
".",
"Dk",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"Dk",
".",
"shape",
... | 56.555556 | 0.015474 |
def did_you_mean(message: str, user_input: str, choices: Sequence[str]) -> str:
""" Given a list of choices and an invalid user input, display the closest
items in the list that match the input.
"""
if not choices:
return message
else:
result = {
difflib.SequenceMatcher(... | [
"def",
"did_you_mean",
"(",
"message",
":",
"str",
",",
"user_input",
":",
"str",
",",
"choices",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"str",
":",
"if",
"not",
"choices",
":",
"return",
"message",
"else",
":",
"result",
"=",
"{",
"difflib",
"... | 34 | 0.002045 |
def find_all( source, substring, start=None, end=None, overlap=False ):
"""Return every location a substring can be found in a source string.
source
The source string to search.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
... | [
"def",
"find_all",
"(",
"source",
",",
"substring",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"overlap",
"=",
"False",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"find_all_iter",
"(",
"source",
",",
"substring",
",",
"start",
",",... | 29.1875 | 0.010373 |
def main(self, args=None, prog_name=None, complete_var=None,
standalone_mode=True, **extra):
"""This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, ``Syste... | [
"def",
"main",
"(",
"self",
",",
"args",
"=",
"None",
",",
"prog_name",
"=",
"None",
",",
"complete_var",
"=",
"None",
",",
"standalone_mode",
"=",
"True",
",",
"*",
"*",
"extra",
")",
":",
"# If we are in Python 3, we will verify that the environment is",
"# sa... | 45.952381 | 0.000761 |
def _defaultReducePartitions(self):
"""
Returns the default number of partitions to use during reduce tasks (e.g., groupBy).
If spark.default.parallelism is set, then we'll use the value from SparkContext
defaultParallelism, otherwise we'll use the number of partitions in this RDD.
... | [
"def",
"_defaultReducePartitions",
"(",
"self",
")",
":",
"if",
"self",
".",
"ctx",
".",
"_conf",
".",
"contains",
"(",
"\"spark.default.parallelism\"",
")",
":",
"return",
"self",
".",
"ctx",
".",
"defaultParallelism",
"else",
":",
"return",
"self",
".",
"g... | 49.785714 | 0.009859 |
def hotp(key, counter, digits=6):
"""
These test vectors come from RFC-4226
(https://tools.ietf.org/html/rfc4226#page-32).
>>> key = b'12345678901234567890'
>>> for c in range(10):
... hotp(key, c)
'755224'
'287082'
'359152'
'969429'
'338314'
'254676'
'287922'
... | [
"def",
"hotp",
"(",
"key",
",",
"counter",
",",
"digits",
"=",
"6",
")",
":",
"msg",
"=",
"struct",
".",
"pack",
"(",
"'>Q'",
",",
"counter",
")",
"hs",
"=",
"hmac",
".",
"new",
"(",
"key",
",",
"msg",
",",
"hashlib",
".",
"sha1",
")",
".",
"... | 24.68 | 0.00156 |
def create_api_pool(self):
"""Get an instance of Api Pool services facade."""
return ApiPool(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_api_pool",
"(",
"self",
")",
":",
"return",
"ApiPool",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 30.571429 | 0.009091 |
def validateInterfaceName(n):
"""
Verifies that the supplied name is a valid DBus Interface name. Throws
an L{error.MarshallingError} if the format is invalid
@type n: C{string}
@param n: A DBus interface name
"""
try:
if '.' not in n:
raise Exception('At least two compo... | [
"def",
"validateInterfaceName",
"(",
"n",
")",
":",
"try",
":",
"if",
"'.'",
"not",
"in",
"n",
":",
"raise",
"Exception",
"(",
"'At least two components required'",
")",
"if",
"'..'",
"in",
"n",
":",
"raise",
"Exception",
"(",
"'\"..\" not allowed in interface n... | 38.814815 | 0.000931 |
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
... | [
"def",
"_build_latex_array",
"(",
"self",
",",
"aliases",
"=",
"None",
")",
":",
"columns",
"=",
"1",
"# Rename qregs if necessary",
"if",
"aliases",
":",
"qregdata",
"=",
"{",
"}",
"for",
"q",
"in",
"aliases",
".",
"values",
"(",
")",
":",
"if",
"q",
... | 55.248227 | 0.001513 |
def get_results_sig(self):
"""Get significant results."""
# Only print results when uncorrected p-value < this value.
print("{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\n".format(
N=sum(1 for r in self.results_all if r.p_uncorrected < self.args.pval),
... | [
"def",
"get_results_sig",
"(",
"self",
")",
":",
"# Only print results when uncorrected p-value < this value.",
"print",
"(",
"\"{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\\n\"",
".",
"format",
"(",
"N",
"=",
"sum",
"(",
"1",
"for",
"r",
"in",
"self",
... | 52.4 | 0.009381 |
def message_info(message):
"""Return a string describing a message, for debugging purposes."""
method = message.get('method')
msgid = message.get('id')
error = message.get('error')
if method and msgid is not None:
return 'method call "{}", id = "{}"'.format(method, msgid)
elif method:
... | [
"def",
"message_info",
"(",
"message",
")",
":",
"method",
"=",
"message",
".",
"get",
"(",
"'method'",
")",
"msgid",
"=",
"message",
".",
"get",
"(",
"'id'",
")",
"error",
"=",
"message",
".",
"get",
"(",
"'error'",
")",
"if",
"method",
"and",
"msgi... | 41.5625 | 0.001471 |
def read_tracers_h5(xdmf_file, infoname, snapshot, position):
"""Extract tracers data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
infoname (str): name of information to extract.
snapshot (int): snapshot number.
position (bool): whether to ext... | [
"def",
"read_tracers_h5",
"(",
"xdmf_file",
",",
"infoname",
",",
"snapshot",
",",
"position",
")",
":",
"xdmf_root",
"=",
"xmlET",
".",
"parse",
"(",
"str",
"(",
"xdmf_file",
")",
")",
".",
"getroot",
"(",
")",
"tra",
"=",
"{",
"}",
"tra",
"[",
"inf... | 44.594595 | 0.000593 |
def get_ilwdchar_class(tbl_name, col_name, namespace = globals()):
"""
Searches this module's namespace for a subclass of _ilwd.ilwdchar
whose table_name and column_name attributes match those provided.
If a matching subclass is found it is returned; otherwise a new
class is defined, added to this module's namespa... | [
"def",
"get_ilwdchar_class",
"(",
"tbl_name",
",",
"col_name",
",",
"namespace",
"=",
"globals",
"(",
")",
")",
":",
"#",
"# if the class already exists, retrieve and return it",
"#",
"key",
"=",
"(",
"str",
"(",
"tbl_name",
")",
",",
"str",
"(",
"col_name",
"... | 21.295775 | 0.037295 |
def saveSettings( self, settings ):
"""
Saves the plugin data to the inputed settings system.
:param settings | <QSettings>
:return <bool> success
"""
dataSet = self.dataSet()
if ( not dataSet ):
return False
... | [
"def",
"saveSettings",
"(",
"self",
",",
"settings",
")",
":",
"dataSet",
"=",
"self",
".",
"dataSet",
"(",
")",
"if",
"(",
"not",
"dataSet",
")",
":",
"return",
"False",
"projexui",
".",
"saveDataSet",
"(",
"settings",
",",
"self",
".",
"uniqueName",
... | 26.764706 | 0.027601 |
def decode_conjure_bean_type(cls, obj, conjure_type):
"""Decodes json into a conjure bean type (a plain bean, not enum
or union).
Args:
obj: the json object to decode
conjure_type: a class object which is the bean type
we're decoding into
Returns:... | [
"def",
"decode_conjure_bean_type",
"(",
"cls",
",",
"obj",
",",
"conjure_type",
")",
":",
"deserialized",
"=",
"{",
"}",
"# type: Dict[str, Any]",
"for",
"(",
"python_arg_name",
",",
"field_definition",
")",
"in",
"conjure_type",
".",
"_fields",
"(",
")",
".",
... | 41.24 | 0.001896 |
def from_file(cls, filename):
"""Read the configuration parameters from the Yaml file filename."""
try:
with open(filename, "r") as fh:
return cls.from_dict(yaml.safe_load(fh))
except Exception as exc:
print("Error while reading TaskManager parameters from... | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"fh",
":",
"return",
"cls",
".",
"from_dict",
"(",
"yaml",
".",
"safe_load",
"(",
"fh",
")",
")",
"except",
"Exception",
... | 43.625 | 0.008427 |
def get_aligned_adjacent_coords(x, y):
'''
returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned.
'''
return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)] | [
"def",
"get_aligned_adjacent_coords",
"(",
"x",
",",
"y",
")",
":",
"return",
"[",
"(",
"x",
"-",
"1",
",",
"y",
")",
",",
"(",
"x",
"-",
"1",
",",
"y",
"-",
"1",
")",
",",
"(",
"x",
",",
"y",
"-",
"1",
")",
",",
"(",
"x",
"+",
"1",
","... | 50.6 | 0.011673 |
def prime_gen() -> int:
# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra
"""
A generator for prime numbers starting from 2.
"""
D = {}
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q * q] = 2 * q
... | [
"def",
"prime_gen",
"(",
")",
"->",
"int",
":",
"# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra",
"D",
"=",
"{",
"}",
"yield",
"2",
"for",
"q",
"in",
"itertools",
".",
"islice",
"(",
"itertools",
".",
"count",
"(",
"3",
")",
",",
"0",
",",
"No... | 25.176471 | 0.002252 |
def clear(self):
"""Clear the console"""
if hasattr(self, '_bytes_012'):
self._bytes_012.fill(0)
self._bytes_345.fill(0)
self._text_lines = [] * self._n_rows
self._pending_writes = [] | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_bytes_012'",
")",
":",
"self",
".",
"_bytes_012",
".",
"fill",
"(",
"0",
")",
"self",
".",
"_bytes_345",
".",
"fill",
"(",
"0",
")",
"self",
".",
"_text_lines",
"=",
"[",
... | 33.285714 | 0.008368 |
def make_vertical_bar(percentage, width=1):
"""
Draws a vertical bar made of unicode characters.
:param value: A value between 0 and 100
:param width: How many characters wide the bar should be.
:returns: Bar as a String
"""
bar = ' _▁▂▃▄▅▆▇█'
percentage //= 10
percentage = int(perc... | [
"def",
"make_vertical_bar",
"(",
"percentage",
",",
"width",
"=",
"1",
")",
":",
"bar",
"=",
"' _▁▂▃▄▅▆▇█'",
"percentage",
"//=",
"10",
"percentage",
"=",
"int",
"(",
"percentage",
")",
"if",
"percentage",
"<",
"0",
":",
"output",
"=",
"bar",
"[",
"0",
... | 26.888889 | 0.001996 |
def _new_point(self, loglstar, logvol):
"""Propose points until a new point that satisfies the log-likelihood
constraint `loglstar` is found."""
ncall, nupdate = 0, 0
while True:
# Get the next point from the queue
u, v, logl, nc, blob = self._get_point_value(log... | [
"def",
"_new_point",
"(",
"self",
",",
"loglstar",
",",
"logvol",
")",
":",
"ncall",
",",
"nupdate",
"=",
"0",
",",
"0",
"while",
"True",
":",
"# Get the next point from the queue",
"u",
",",
"v",
",",
"logl",
",",
"nc",
",",
"blob",
"=",
"self",
".",
... | 39.694444 | 0.001366 |
def material_to_texture(material):
"""
Convert a trimesh.visual.texture.Material object into
a pyglet- compatible texture object.
Parameters
--------------
material : trimesh.visual.texture.Material
Material to be converted
Returns
---------------
texture : pyglet.image.Textu... | [
"def",
"material_to_texture",
"(",
"material",
")",
":",
"# try to extract a PIL image from material",
"if",
"hasattr",
"(",
"material",
",",
"'image'",
")",
":",
"img",
"=",
"material",
".",
"image",
"else",
":",
"img",
"=",
"material",
".",
"baseColorTexture",
... | 24.973684 | 0.001014 |
def scan(self, M):
"""
LML, fixed-effect sizes, and scale of the candidate set.
Parameters
----------
M : array_like
Fixed-effects set.
Returns
-------
lml : float
Log of the marginal likelihood.
effsizes0 : ndarray
... | [
"def",
"scan",
"(",
"self",
",",
"M",
")",
":",
"from",
"numpy_sugar",
".",
"linalg",
"import",
"ddot",
"from",
"numpy_sugar",
"import",
"is_all_finite",
"M",
"=",
"asarray",
"(",
"M",
",",
"float",
")",
"if",
"M",
".",
"shape",
"[",
"1",
"]",
"==",
... | 31.081633 | 0.001273 |
def reformat_record(record):
"""Repack a record into a cleaner structure for consumption."""
return {
"key": record["dynamodb"].get("Keys", None),
"new": record["dynamodb"].get("NewImage", None),
"old": record["dynamodb"].get("OldImage", None),
"meta": {
"created_at"... | [
"def",
"reformat_record",
"(",
"record",
")",
":",
"return",
"{",
"\"key\"",
":",
"record",
"[",
"\"dynamodb\"",
"]",
".",
"get",
"(",
"\"Keys\"",
",",
"None",
")",
",",
"\"new\"",
":",
"record",
"[",
"\"dynamodb\"",
"]",
".",
"get",
"(",
"\"NewImage\"",... | 36.647059 | 0.001565 |
def predict(self, X, exposure=None):
"""
preduct expected value of target given model and input X
often this is done via expected value of GAM given input X
Parameters
---------
X : array-like of shape (n_samples, m_features), default: None
containing the inp... | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"exposure",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"X",
"=",
"check_X",
"(",
"X",
",",
"n_feats",
... | 34.515152 | 0.001708 |
def unparse(self, indent_step = 4, max_linelen = 72) :
"returns an XML string description of this Introspection tree."
out = io.StringIO()
def to_string(obj, indent) :
tag_name = obj.tag_name
attrs = []
for attrname in obj.tag_attrs :
attr = ... | [
"def",
"unparse",
"(",
"self",
",",
"indent_step",
"=",
"4",
",",
"max_linelen",
"=",
"72",
")",
":",
"out",
"=",
"io",
".",
"StringIO",
"(",
")",
"def",
"to_string",
"(",
"obj",
",",
"indent",
")",
":",
"tag_name",
"=",
"obj",
".",
"tag_name",
"at... | 34.478723 | 0.017696 |
def max_likelihood(self, data, weights=None, stats=None, lmbda=0.1):
"""
As an alternative to MCMC with Polya-gamma augmentation,
we also implement maximum likelihood learning via gradient
descent with autograd. This follows the pybasicbayes
convention.
:param data: list... | [
"def",
"max_likelihood",
"(",
"self",
",",
"data",
",",
"weights",
"=",
"None",
",",
"stats",
"=",
"None",
",",
"lmbda",
"=",
"0.1",
")",
":",
"import",
"autograd",
".",
"numpy",
"as",
"anp",
"from",
"autograd",
"import",
"value_and_grad",
",",
"hessian_... | 36.929825 | 0.000925 |
def _build_cmd(self, args: Union[list, tuple]) -> str:
'''Build command.'''
cmd = [self.path]
cmd.extend(args)
return cmd | [
"def",
"_build_cmd",
"(",
"self",
",",
"args",
":",
"Union",
"[",
"list",
",",
"tuple",
"]",
")",
"->",
"str",
":",
"cmd",
"=",
"[",
"self",
".",
"path",
"]",
"cmd",
".",
"extend",
"(",
"args",
")",
"return",
"cmd"
] | 29.8 | 0.013072 |
def shape_weights_hidden(self) -> Tuple[int, int, int]:
"""Shape of the array containing the activation of the hidden neurons.
The first integer value is the number of connection between the
hidden layers, the second integer value is maximum number of
neurons of all hidden layers feedin... | [
"def",
"shape_weights_hidden",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"if",
"self",
".",
"nmb_layers",
">",
"1",
":",
"nmb_neurons",
"=",
"self",
".",
"nmb_neurons",
"return",
"(",
"self",
".",
"nmb_layers",
"-",... | 42.038462 | 0.001789 |
def frequency_bins(header):
'''
Returnes the frequency-axis lower bin edge values for the spectrogram.
'''
center_frequency = 1.0e6*header['rf_center_frequency']
if header["number_of_subbands"] > 1:
center_frequency += header["subband_spacing_hz"]*(header["number_of_subbands"]/2.0 - 0.5)
return np.ff... | [
"def",
"frequency_bins",
"(",
"header",
")",
":",
"center_frequency",
"=",
"1.0e6",
"*",
"header",
"[",
"'rf_center_frequency'",
"]",
"if",
"header",
"[",
"\"number_of_subbands\"",
"]",
">",
"1",
":",
"center_frequency",
"+=",
"header",
"[",
"\"subband_spacing_hz\... | 41.307692 | 0.023679 |
def _assemble_and_send_request(self):
"""
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(),
WHICH RESIDES ON FedexBaseService AND IS INHERITED.
"""
# Fire off the query.
return self.client.service.getPickupAvailabil... | [
"def",
"_assemble_and_send_request",
"(",
"self",
")",
":",
"# Fire off the query.",
"return",
"self",
".",
"client",
".",
"service",
".",
"getPickupAvailability",
"(",
"WebAuthenticationDetail",
"=",
"self",
".",
"WebAuthenticationDetail",
",",
"ClientDetail",
"=",
"... | 40.153846 | 0.001871 |
def filters_apply(self, objects, filters, context):
"""
Helper function: Applies a list of filters to a list of either statuses
or notifications and returns only those matched by none. This function will
apply all filters that match the context provided in `context`, i.e.
if you... | [
"def",
"filters_apply",
"(",
"self",
",",
"objects",
",",
"filters",
",",
"context",
")",
":",
"# Build filter regex",
"filter_strings",
"=",
"[",
"]",
"for",
"keyword_filter",
"in",
"filters",
":",
"if",
"not",
"context",
"in",
"keyword_filter",
"[",
"\"conte... | 45.515152 | 0.008475 |
def _MigrationFilenameToInt(fname):
"""Converts migration filename to a migration number."""
base, _ = os.path.splitext(fname)
return int(base) | [
"def",
"_MigrationFilenameToInt",
"(",
"fname",
")",
":",
"base",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"return",
"int",
"(",
"base",
")"
] | 36.5 | 0.026846 |
def _unique_id(self, prefix):
"""
Generate a unique (within the graph) identifer
internal to graph generation.
"""
_id = self._id_gen
self._id_gen += 1
return prefix + str(_id) | [
"def",
"_unique_id",
"(",
"self",
",",
"prefix",
")",
":",
"_id",
"=",
"self",
".",
"_id_gen",
"self",
".",
"_id_gen",
"+=",
"1",
"return",
"prefix",
"+",
"str",
"(",
"_id",
")"
] | 28.125 | 0.008621 |
def generate_stop_word_filter(stop_words, language=None):
"""Builds a stopWordFilter function from the provided list of stop words.
The built in `stop_word_filter` is built using this factory and can be used
to generate custom `stop_word_filter` for applications or non English
languages.
"""
d... | [
"def",
"generate_stop_word_filter",
"(",
"stop_words",
",",
"language",
"=",
"None",
")",
":",
"def",
"stop_word_filter",
"(",
"token",
",",
"i",
"=",
"None",
",",
"tokens",
"=",
"None",
")",
":",
"if",
"token",
"and",
"str",
"(",
"token",
")",
"not",
... | 34.45 | 0.001412 |
def simulate_dynamic(self, order = 0.998, solution = solve_type.FAST, collect_dynamic = False, step = 0.1, int_step = 0.01, threshold_changes = 0.0000001):
"""!
@brief Performs dynamic simulation of the network until stop condition is not reached. Stop condition is defined by input argument 'order'.
... | [
"def",
"simulate_dynamic",
"(",
"self",
",",
"order",
"=",
"0.998",
",",
"solution",
"=",
"solve_type",
".",
"FAST",
",",
"collect_dynamic",
"=",
"False",
",",
"step",
"=",
"0.1",
",",
"int_step",
"=",
"0.01",
",",
"threshold_changes",
"=",
"0.0000001",
")... | 49.830769 | 0.019074 |
def floodFill(points, startx, starty):
"""
Returns a set of the (x, y) points of a filled in area.
`points` is an iterable of (x, y) tuples of an arbitrary shape.
`startx` and `starty` mark the starting point (likely inside the
arbitrary shape) to begin filling from.
>>> drawPoints(polygon(5,... | [
"def",
"floodFill",
"(",
"points",
",",
"startx",
",",
"starty",
")",
":",
"# Note: We're not going to use recursion here because 1) recursion is",
"# overrated 2) on a large enough shape it would cause a stackoverflow",
"# 3) flood fill doesn't strictly need recursion because it doesn't req... | 34.205128 | 0.001093 |
def encryption_iv(self):
"""
Returns the byte string of the initialization vector for the encryption
scheme. Only the PBES2 stores the IV in the params. For PBES1, the IV
is derived from the KDF and this property will return None.
:return:
A byte string or None
... | [
"def",
"encryption_iv",
"(",
"self",
")",
":",
"encryption_algo",
"=",
"self",
"[",
"'algorithm'",
"]",
".",
"native",
"if",
"encryption_algo",
"in",
"set",
"(",
"[",
"'rc2'",
",",
"'rc5'",
"]",
")",
":",
"return",
"self",
"[",
"'parameters'",
"]",
".",
... | 34.173913 | 0.001855 |
def check_aki_richards_convention(cls, edges):
"""
Verify that surface (as defined by corner points) conforms with Aki and
Richard convention (i.e. surface dips right of surface strike)
This method doesn't have to be called by hands before creating the
surface object, because it... | [
"def",
"check_aki_richards_convention",
"(",
"cls",
",",
"edges",
")",
":",
"# 1) extract 4 corner points of surface mesh",
"# 2) compute cross products between left and right edges and top edge",
"# (these define vectors normal to the surface)",
"# 3) compute dot products between cross produc... | 41.078431 | 0.000932 |
def list_issues(
self, status=None, tags=None, assignee=None, author=None,
milestones=None, priority=None, no_stones=None, since=None,
order=None
):
"""
List all issues of a project.
:param status: filters the status of the issues
:param tags: file... | [
"def",
"list_issues",
"(",
"self",
",",
"status",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"assignee",
"=",
"None",
",",
"author",
"=",
"None",
",",
"milestones",
"=",
"None",
",",
"priority",
"=",
"None",
",",
"no_stones",
"=",
"None",
",",
"sinc... | 38.5625 | 0.001581 |
def eq(a, b):
""" The great missing equivalence function: Guaranteed evaluation
to a single bool value.
"""
if a is b:
return True
if a is None or b is None:
return True if a is None and b is None else False
try:
e = a == b
except ValueError:
return False
... | [
"def",
"eq",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"is",
"b",
":",
"return",
"True",
"if",
"a",
"is",
"None",
"or",
"b",
"is",
"None",
":",
"return",
"True",
"if",
"a",
"is",
"None",
"and",
"b",
"is",
"None",
"else",
"False",
"try",
":",
... | 27.162162 | 0.000961 |
def inv(self, q_data, max_iterations=100, tollerance=1e-5):
"""
Inverse Rosenblatt transformation.
If possible the transformation is done analytically. If not possible,
transformation is approximated using an algorithm that alternates
between Newton-Raphson and binary search.
... | [
"def",
"inv",
"(",
"self",
",",
"q_data",
",",
"max_iterations",
"=",
"100",
",",
"tollerance",
"=",
"1e-5",
")",
":",
"q_data",
"=",
"numpy",
".",
"asfarray",
"(",
"q_data",
")",
"assert",
"numpy",
".",
"all",
"(",
"(",
"q_data",
">=",
"0",
")",
"... | 43.352941 | 0.001991 |
def _setEndpoint(self, location):
'''
Set the endpoint after when Salesforce returns the URL after successful login()
'''
# suds 0.3.7+ supports multiple wsdl services, but breaks setlocation :(
# see https://fedorahosted.org/suds/ticket/261
try:
self._sforce.set_options(location = locatio... | [
"def",
"_setEndpoint",
"(",
"self",
",",
"location",
")",
":",
"# suds 0.3.7+ supports multiple wsdl services, but breaks setlocation :(",
"# see https://fedorahosted.org/suds/ticket/261",
"try",
":",
"self",
".",
"_sforce",
".",
"set_options",
"(",
"location",
"=",
"location... | 34 | 0.016706 |
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
... | [
"def",
"list_nodes",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called with -f or --function.'",
")",
"nodes",
"=",
"list_nodes_full",
"(",
")",
"ret",
"=",
"{",
"... | 28.409091 | 0.001548 |
def remove_locations(node):
"""
Removes locations from the given AST tree completely
"""
def fix(node):
if 'lineno' in node._attributes and hasattr(node, 'lineno'):
del node.lineno
if 'col_offset' in node._attributes and hasattr(node, 'col_offset'):
del node.col... | [
"def",
"remove_locations",
"(",
"node",
")",
":",
"def",
"fix",
"(",
"node",
")",
":",
"if",
"'lineno'",
"in",
"node",
".",
"_attributes",
"and",
"hasattr",
"(",
"node",
",",
"'lineno'",
")",
":",
"del",
"node",
".",
"lineno",
"if",
"'col_offset'",
"in... | 24.75 | 0.002433 |
def _mint_new_ott_ids(self, how_many=1):
""" ASSUMES the caller holds the _doc_counter_lock !
Checks the current int value of the next ottid, reserves a block of
{how_many} ids, advances the counter to the next available value,
stores the counter in a file in case the server is restarted... | [
"def",
"_mint_new_ott_ids",
"(",
"self",
",",
"how_many",
"=",
"1",
")",
":",
"first_minted_id",
"=",
"self",
".",
"_next_ott_id",
"self",
".",
"_next_ott_id",
"=",
"first_minted_id",
"+",
"how_many",
"content",
"=",
"u'{\"next_ott_id\": %d}\\n'",
"%",
"self",
"... | 57.352941 | 0.002018 |
def info(ctx):
"""
Display status of OpenPGP application.
"""
controller = ctx.obj['controller']
click.echo('OpenPGP version: %d.%d.%d' % controller.version)
retries = controller.get_remaining_pin_tries()
click.echo('PIN tries remaining: {}'.format(retries.pin))
click.echo('Reset code tr... | [
"def",
"info",
"(",
"ctx",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"click",
".",
"echo",
"(",
"'OpenPGP version: %d.%d.%d'",
"%",
"controller",
".",
"version",
")",
"retries",
"=",
"controller",
".",
"get_remaining_pin_tries",... | 39.52381 | 0.001176 |
def _generate_ids(self, document, content):
"""Generate unique ids for html elements in page content so that it's
possible to link to them.
"""
existing_ids = content.xpath('//*/@id')
elements = [
'p', 'dl', 'dt', 'dd', 'table', 'div', 'section', 'figure',
... | [
"def",
"_generate_ids",
"(",
"self",
",",
"document",
",",
"content",
")",
":",
"existing_ids",
"=",
"content",
".",
"xpath",
"(",
"'//*/@id'",
")",
"elements",
"=",
"[",
"'p'",
",",
"'dl'",
",",
"'dt'",
",",
"'dd'",
",",
"'table'",
",",
"'div'",
",",
... | 43.782609 | 0.000971 |
def get_default_ref(repo):
"""Return a `github.GitRef` object for the HEAD of the default branch.
Parameters
----------
repo: github.Repository.Repository
repo to get default branch head ref from
Returns
-------
head : :class:`github.GitRef` instance
Raises
------
gith... | [
"def",
"get_default_ref",
"(",
"repo",
")",
":",
"assert",
"isinstance",
"(",
"repo",
",",
"github",
".",
"Repository",
".",
"Repository",
")",
",",
"type",
"(",
"repo",
")",
"# XXX this probably should be resolved via repos.yaml",
"default_branch",
"=",
"repo",
"... | 30.030303 | 0.000978 |
def _get_main_language():
"""
returns the main language
:return:
"""
try:
main_language = TransLanguage.objects.filter(main_language=True).get()
return main_language.code
except TransLanguage.DoesNotExist:
return 'es' | [
"def",
"_get_main_language",
"(",
")",
":",
"try",
":",
"main_language",
"=",
"TransLanguage",
".",
"objects",
".",
"filter",
"(",
"main_language",
"=",
"True",
")",
".",
"get",
"(",
")",
"return",
"main_language",
".",
"code",
"except",
"TransLanguage",
"."... | 29.2 | 0.009967 |
def parse_mimetype(mimetype: str) -> MimeType:
"""Parses a MIME type into its components.
mimetype is a MIME type string.
Returns a MimeType object.
Example:
>>> parse_mimetype('text/html; charset=utf-8')
MimeType(type='text', subtype='html', suffix='',
parameters={'charset': 'u... | [
"def",
"parse_mimetype",
"(",
"mimetype",
":",
"str",
")",
"->",
"MimeType",
":",
"if",
"not",
"mimetype",
":",
"return",
"MimeType",
"(",
"type",
"=",
"''",
",",
"subtype",
"=",
"''",
",",
"suffix",
"=",
"''",
",",
"parameters",
"=",
"MultiDictProxy",
... | 32.210526 | 0.000793 |
def authorize_security_group(
self, group_name=None, group_id=None, source_group_name="", source_group_owner_id="",
ip_protocol="", from_port="", to_port="", cidr_ip=""):
"""
There are two ways to use C{authorize_security_group}:
1) associate an existing group (source group) ... | [
"def",
"authorize_security_group",
"(",
"self",
",",
"group_name",
"=",
"None",
",",
"group_id",
"=",
"None",
",",
"source_group_name",
"=",
"\"\"",
",",
"source_group_owner_id",
"=",
"\"\"",
",",
"ip_protocol",
"=",
"\"\"",
",",
"from_port",
"=",
"\"\"",
",",... | 45.984127 | 0.001352 |
def check_mailfy(self, query, kwargs={}):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return a dictionary as defined.
Args:
-----
query: The eleme... | [
"def",
"check_mailfy",
"(",
"self",
",",
"query",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"import",
"re",
"import",
"requests",
"s",
"=",
"requests",
".",
"Session",
"(",
")",
"# Getting the first response to grab the csrf_token",
"r1",
"=",
"s",
".",
"get",... | 30.416667 | 0.00177 |
def matchesEachOf(cntxt: Context, T: RDFGraph, expr: ShExJ.EachOf, _: DebugContext) -> bool:
""" expr is an EachOf and there is some partition of T into T1, T2,… such that for every expression
expr1, expr2,… in shapeExprs, matches(Tn, exprn, m).
"""
return EachOfEvaluator(cntxt, T, expr).evaluate(cnt... | [
"def",
"matchesEachOf",
"(",
"cntxt",
":",
"Context",
",",
"T",
":",
"RDFGraph",
",",
"expr",
":",
"ShExJ",
".",
"EachOf",
",",
"_",
":",
"DebugContext",
")",
"->",
"bool",
":",
"return",
"EachOfEvaluator",
"(",
"cntxt",
",",
"T",
",",
"expr",
")",
"... | 53 | 0.009288 |
def setHoverBackground( self, column, brush ):
"""
Returns the brush to use when coloring when the user hovers over
the item for the given column.
:param column | <int>
brush | <QtGui.QBrush)
"""
self._hoverBackground[column] = Q... | [
"def",
"setHoverBackground",
"(",
"self",
",",
"column",
",",
"brush",
")",
":",
"self",
".",
"_hoverBackground",
"[",
"column",
"]",
"=",
"QtGui",
".",
"QBrush",
"(",
"brush",
")"
] | 36.666667 | 0.014793 |
def polyline(document, coords):
"polyline with more then 2 vertices"
points = []
for i in range(0, len(coords), 2):
points.append("%s,%s" % (coords[i], coords[i+1]))
return setattribs(
document.createElement('polyline'),
points = ' '.join(points),
) | [
"def",
"polyline",
"(",
"document",
",",
"coords",
")",
":",
"points",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"coords",
")",
",",
"2",
")",
":",
"points",
".",
"append",
"(",
"\"%s,%s\"",
"%",
"(",
"coords",
"[",
"... | 25.3 | 0.049618 |
def auto_detect(self, args):
"""Check for already Slackware binary packages exist
"""
suffixes = [
".tgz",
".txz",
".tbz",
".tlz"
]
if (not args[0].startswith("-") and args[0] not in self.commands and
args[0].endswit... | [
"def",
"auto_detect",
"(",
"self",
",",
"args",
")",
":",
"suffixes",
"=",
"[",
"\".tgz\"",
",",
"\".txz\"",
",",
"\".tbz\"",
",",
"\".tlz\"",
"]",
"if",
"(",
"not",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"-\"",
")",
"and",
"args",
"[",
"... | 34.625 | 0.002342 |
def prepare_logfile(filename: str) -> str:
"""Prepare an empty log file eventually and return its absolute path.
When passing the "filename" `stdout`, |prepare_logfile| does not
prepare any file and just returns `stdout`:
>>> from hydpy.exe.commandtools import prepare_logfile
>>> prepare_logfile('... | [
"def",
"prepare_logfile",
"(",
"filename",
":",
"str",
")",
"->",
"str",
":",
"if",
"filename",
"==",
"'stdout'",
":",
"return",
"filename",
"if",
"filename",
"==",
"'default'",
":",
"filename",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"."... | 35.555556 | 0.000608 |
def add_device_with_name_location_timezone( self,
model,
serial,
name,
location,
... | [
"def",
"add_device_with_name_location_timezone",
"(",
"self",
",",
"model",
",",
"serial",
",",
"name",
",",
"location",
",",
"timezone",
")",
":",
"retval",
"=",
"None",
"retval",
"=",
"self",
".",
"add_location_timezone_to_device",
"(",
"self",
".",
"rename_de... | 35.458333 | 0.010297 |
def list_math_multiplication(a, b):
"""!
@brief Multiplication of two lists.
@details Each element from list 'a' is multiplied by element from list 'b' accordingly.
@param[in] a (list): List of elements that supports mathematic multiplication.
@param[in] b (list): List of elements that su... | [
"def",
"list_math_multiplication",
"(",
"a",
",",
"b",
")",
":",
"return",
"[",
"a",
"[",
"i",
"]",
"*",
"b",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
"]"
] | 41 | 0.017893 |
def fit_delta_ts(data, time_s):
"""Fits gaussians to delta t for each PMT pair.
Parameters
----------
data: 2d np.array: x = PMT combinations (465), y = time, entry = frequency
time_s: length of data taking in seconds
Returns
-------
numpy arrays with rates and means for all PMT combin... | [
"def",
"fit_delta_ts",
"(",
"data",
",",
"time_s",
")",
":",
"data",
"=",
"data",
"/",
"time_s",
"xs",
"=",
"np",
".",
"arange",
"(",
"-",
"20",
",",
"21",
")",
"def",
"gaussian",
"(",
"x",
",",
"mean",
",",
"sigma",
",",
"rate",
",",
"offset",
... | 26.424242 | 0.001106 |
def getFullname(self):
"""Person's Fullname
"""
fn = self.getFirstname()
mi = self.getMiddleinitial()
md = self.getMiddlename()
sn = self.getSurname()
fullname = ""
if fn or sn:
if mi and md:
fullname = "%s %s %s %s" % (
... | [
"def",
"getFullname",
"(",
"self",
")",
":",
"fn",
"=",
"self",
".",
"getFirstname",
"(",
")",
"mi",
"=",
"self",
".",
"getMiddleinitial",
"(",
")",
"md",
"=",
"self",
".",
"getMiddlename",
"(",
")",
"sn",
"=",
"self",
".",
"getSurname",
"(",
")",
... | 32.862069 | 0.002039 |
def rmd_options_to_metadata(options):
"""
Parse rmd options and return a metadata dictionary
:param options:
:return:
"""
options = re.split(r'\s|,', options, 1)
if len(options) == 1:
language = options[0]
chunk_options = []
else:
language, others = options
... | [
"def",
"rmd_options_to_metadata",
"(",
"options",
")",
":",
"options",
"=",
"re",
".",
"split",
"(",
"r'\\s|,'",
",",
"options",
",",
"1",
")",
"if",
"len",
"(",
"options",
")",
"==",
"1",
":",
"language",
"=",
"options",
"[",
"0",
"]",
"chunk_options"... | 30.641026 | 0.001622 |
def reflect_well(value, bounds):
"""Given some boundaries, reflects the value until it falls within both
boundaries. This is done iteratively, reflecting left off of the
`boundaries.max`, then right off of the `boundaries.min`, etc.
Parameters
----------
value : float
The value to apply... | [
"def",
"reflect_well",
"(",
"value",
",",
"bounds",
")",
":",
"while",
"value",
"not",
"in",
"bounds",
":",
"value",
"=",
"bounds",
".",
"_max",
".",
"reflect_left",
"(",
"value",
")",
"value",
"=",
"bounds",
".",
"_min",
".",
"reflect_right",
"(",
"va... | 33.73913 | 0.001253 |
def wait(self, wait_interval=None, wait_time=None):
"""
Poll the server periodically until the action has either completed or
errored out and return its final state.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing the
action's most recently fetched state) is raise... | [
"def",
"wait",
"(",
"self",
",",
"wait_interval",
"=",
"None",
",",
"wait_time",
"=",
"None",
")",
":",
"return",
"next",
"(",
"self",
".",
"doapi_manager",
".",
"wait_actions",
"(",
"[",
"self",
"]",
",",
"wait_interval",
",",
"wait_time",
")",
")"
] | 49.5 | 0.002123 |
def stringGetNodeList(self, value):
"""Parse the value string and build the node list associated.
Should produce a flat tree with only TEXTs and ENTITY_REFs. """
ret = libxml2mod.xmlStringGetNodeList(self._o, value)
if ret is None:raise treeError('xmlStringGetNodeList() failed')
... | [
"def",
"stringGetNodeList",
"(",
"self",
",",
"value",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlStringGetNodeList",
"(",
"self",
".",
"_o",
",",
"value",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlStringGetNodeList() failed'",
"... | 51.857143 | 0.01084 |
def find_string(regex, s):
"""Find a string using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
s - The string to search.
regex - A string containing the regular expressi... | [
"def",
"find_string",
"(",
"regex",
",",
"s",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"s",
")",
"if",
"m",
"is",
"None",
":",
"return",
"None",
"return",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]"
] | 30.066667 | 0.008602 |
def string_to_response(content_type):
"""
Wrap a view-like function that returns a string and marshalls it into an
HttpResponse with the given Content-Type
If the view raises an HttpBadRequestException, it will be converted into
an HttpResponseBadRequest.
"""
def outer_wrapper(req_function):... | [
"def",
"string_to_response",
"(",
"content_type",
")",
":",
"def",
"outer_wrapper",
"(",
"req_function",
")",
":",
"@",
"wraps",
"(",
"req_function",
")",
"def",
"newreq",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
... | 36.814815 | 0.00098 |
def _repr_png_(self):
"""This is used by ipython to plot inline.
"""
app.process_events()
QApplication.processEvents()
img = read_pixels()
return bytes(_make_png(img)) | [
"def",
"_repr_png_",
"(",
"self",
")",
":",
"app",
".",
"process_events",
"(",
")",
"QApplication",
".",
"processEvents",
"(",
")",
"img",
"=",
"read_pixels",
"(",
")",
"return",
"bytes",
"(",
"_make_png",
"(",
"img",
")",
")"
] | 26.125 | 0.009259 |
def get_captcha(self):
"""获取验证码数据。
:return: 验证码图片数据。
:rtype: bytes
"""
self._session.get(Zhihu_URL)
r = self._session.get(self._get_captcha_url())
return r.content | [
"def",
"get_captcha",
"(",
"self",
")",
":",
"self",
".",
"_session",
".",
"get",
"(",
"Zhihu_URL",
")",
"r",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"self",
".",
"_get_captcha_url",
"(",
")",
")",
"return",
"r",
".",
"content"
] | 23.555556 | 0.009091 |
def timeout(timeout_time, default):
'''
Decorate a method so it is required to execute in a given time period,
or return a default value.
'''
def timeout_function(f):
def f2(*args):
def timeout_handler(signum, frame):
raise MethodTi... | [
"def",
"timeout",
"(",
"timeout_time",
",",
"default",
")",
":",
"def",
"timeout_function",
"(",
"f",
")",
":",
"def",
"f2",
"(",
"*",
"args",
")",
":",
"def",
"timeout_handler",
"(",
"signum",
",",
"frame",
")",
":",
"raise",
"MethodTimer",
".",
"Deco... | 36.826087 | 0.002301 |
def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
for contract in self.contracts:
txt = "\nContract %s\n"%contract.name
table = PrettyTable(["Function", "State variables written", "Conditions on msg... | [
"def",
"output",
"(",
"self",
",",
"_filename",
")",
":",
"for",
"contract",
"in",
"self",
".",
"contracts",
":",
"txt",
"=",
"\"\\nContract %s\\n\"",
"%",
"contract",
".",
"name",
"table",
"=",
"PrettyTable",
"(",
"[",
"\"Function\"",
",",
"\"State variable... | 42.6875 | 0.008596 |
def get_safe_redirect_target(arg='next'):
"""Get URL to redirect to and ensure that it is local.
:param arg: URL argument.
:returns: The redirect target or ``None``.
"""
for target in request.args.get(arg), request.referrer:
if target:
redirect_uri = urisplit(target)
... | [
"def",
"get_safe_redirect_target",
"(",
"arg",
"=",
"'next'",
")",
":",
"for",
"target",
"in",
"request",
".",
"args",
".",
"get",
"(",
"arg",
")",
",",
"request",
".",
"referrer",
":",
"if",
"target",
":",
"redirect_uri",
"=",
"urisplit",
"(",
"target",... | 36.473684 | 0.001406 |
def set_codes(self, codes):
'''Set the country code map for the data.
Codes given in a list.
i.e. DE - Germany
AT - Austria
US - United States
'''
codemap = ''
for cc in codes:
cc = cc.upper()
if cc in self.__cc... | [
"def",
"set_codes",
"(",
"self",
",",
"codes",
")",
":",
"codemap",
"=",
"''",
"for",
"cc",
"in",
"codes",
":",
"cc",
"=",
"cc",
".",
"upper",
"(",
")",
"if",
"cc",
"in",
"self",
".",
"__ccodes",
":",
"codemap",
"+=",
"cc",
"else",
":",
"raise",
... | 23.736842 | 0.008529 |
def get_as_nullable_map(self, key):
"""
Converts map element into an AnyValueMap or returns None if conversion is not possible.
:param key: a key of element to get.
:return: AnyValueMap value of the element or None if conversion is not supported.
"""
value = self.get_as... | [
"def",
"get_as_nullable_map",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"self",
".",
"get_as_object",
"(",
"key",
")",
"return",
"AnyValueMap",
".",
"from_value",
"(",
"value",
")"
] | 36.8 | 0.01061 |
def list_app(self):
'''
List the apps.
'''
kwd = {
'pager': '',
'title': ''
}
self.render('user/info_list/list_app.html', kwd=kwd,
userinfo=self.userinfo) | [
"def",
"list_app",
"(",
"self",
")",
":",
"kwd",
"=",
"{",
"'pager'",
":",
"''",
",",
"'title'",
":",
"''",
"}",
"self",
".",
"render",
"(",
"'user/info_list/list_app.html'",
",",
"kwd",
"=",
"kwd",
",",
"userinfo",
"=",
"self",
".",
"userinfo",
")"
] | 23.7 | 0.00813 |
def line_search_step(state, value_and_gradients_function, search_direction,
grad_tolerance, f_relative_tolerance, x_tolerance,
stopping_condition):
"""Performs the line search step of the BFGS search procedure.
Uses hager_zhang line search procedure to compute a suitable s... | [
"def",
"line_search_step",
"(",
"state",
",",
"value_and_gradients_function",
",",
"search_direction",
",",
"grad_tolerance",
",",
"f_relative_tolerance",
",",
"x_tolerance",
",",
"stopping_condition",
")",
":",
"line_search_value_grad_func",
"=",
"_restrict_along_direction",... | 49.528736 | 0.002275 |
def unpack_img(s, iscolor=-1):
"""Unpack a MXImageRecord to image.
Parameters
----------
s : str
String buffer from ``MXRecordIO.read``.
iscolor : int
Image format option for ``cv2.imdecode``.
Returns
-------
header : IRHeader
Header of the image record.
img... | [
"def",
"unpack_img",
"(",
"s",
",",
"iscolor",
"=",
"-",
"1",
")",
":",
"header",
",",
"s",
"=",
"unpack",
"(",
"s",
")",
"img",
"=",
"np",
".",
"frombuffer",
"(",
"s",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"assert",
"cv2",
"is",
"not",
... | 24.357143 | 0.00094 |
def find_xy_peak(img, center=None, sigma=3.0):
""" Find the center of the peak of offsets """
# find level of noise in histogram
istats = imagestats.ImageStats(img.astype(np.float32), nclip=1,
fields='stddev,mode,mean,max,min')
if istats.stddev == 0.0:
istats =... | [
"def",
"find_xy_peak",
"(",
"img",
",",
"center",
"=",
"None",
",",
"sigma",
"=",
"3.0",
")",
":",
"# find level of noise in histogram",
"istats",
"=",
"imagestats",
".",
"ImageStats",
"(",
"img",
".",
"astype",
"(",
"np",
".",
"float32",
")",
",",
"nclip"... | 35.072727 | 0.000504 |
def groups_rename(self, room_id, name, **kwargs):
"""Changes the name of the private group."""
return self.__call_api_post('groups.rename', roomId=room_id, name=name, kwargs=kwargs) | [
"def",
"groups_rename",
"(",
"self",
",",
"room_id",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'groups.rename'",
",",
"roomId",
"=",
"room_id",
",",
"name",
"=",
"name",
",",
"kwargs",
"=",
"kwargs",
... | 65 | 0.015228 |
def writePatternLine(self, step_milliseconds, color, pos, led_number=0):
"""Write a color & step time color pattern line to RAM
:param step_milliseconds: how long for this pattern line to take
:param color: LED color
:param pos: color pattern line number (0-15)
:param led_number... | [
"def",
"writePatternLine",
"(",
"self",
",",
"step_milliseconds",
",",
"color",
",",
"pos",
",",
"led_number",
"=",
"0",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''",
"self",
".",
"setLedN",
"(",
"led_number",
")",
... | 47.0625 | 0.011719 |
def validate_data_columns(self, data_columns, min_itemsize):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
if not len(self.non_index_axes):
return []
axis, axis_labels = self.non_index_axes[0]
info = self.info.get(axis, di... | [
"def",
"validate_data_columns",
"(",
"self",
",",
"data_columns",
",",
"min_itemsize",
")",
":",
"if",
"not",
"len",
"(",
"self",
".",
"non_index_axes",
")",
":",
"return",
"[",
"]",
"axis",
",",
"axis_labels",
"=",
"self",
".",
"non_index_axes",
"[",
"0",... | 37.78125 | 0.001613 |
def select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs):
"""Show a list of options and return user selection.
This method blocks until the user makes their choice.
Parameters
----------
prompt: string
The prompt telling the user what the... | [
"def",
"select",
"(",
"self",
",",
"prompt",
",",
"options",
",",
"rofi_args",
"=",
"None",
",",
"message",
"=",
"\"\"",
",",
"select",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"rofi_args",
"=",
"rofi_args",
"or",
"[",
"]",
"# Replace newlines a... | 35.681034 | 0.001175 |
def p_DictionaryMember(p):
"""DictionaryMember : Type IDENTIFIER Default ";"
"""
p[0] = model.DictionaryMember(type=p[1], name=p[2], default=p[3]) | [
"def",
"p_DictionaryMember",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"DictionaryMember",
"(",
"type",
"=",
"p",
"[",
"1",
"]",
",",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"default",
"=",
"p",
"[",
"3",
"]",
")"
] | 37.25 | 0.019737 |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(Registration,self).get_email_context(**kwargs)
context.update({
'first_name': self.customer.first_name,
'last_name': self.customer.last_name,
'registrationComments': se... | [
"def",
"get_email_context",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"Registration",
",",
"self",
")",
".",
"get_email_context",
"(",
"*",
"*",
"kwargs",
")",
"context",
".",
"update",
"(",
"{",
"'first_name'",
":",
... | 40.235294 | 0.008571 |
def Enable(self, value):
"enable or disable all top menus"
for i in range(self.GetMenuCount()):
self.EnableTop(i, value) | [
"def",
"Enable",
"(",
"self",
",",
"value",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"GetMenuCount",
"(",
")",
")",
":",
"self",
".",
"EnableTop",
"(",
"i",
",",
"value",
")"
] | 37 | 0.013245 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.