text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def generate(self, *args, **kwargs):
"""
Implementation for the generate method defined in ReportBase.
Generates a html report and saves it.
:param args: 1 argument, which is the filename
:param kwargs: 3 keyword arguments with keys 'title', 'heads' and 'refresh'
:return... | [
"def",
"generate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"title",
"=",
"kwargs",
".",
"get",
"(",
"\"title\"",
")",
"heads",
"=",
"kwargs",
".",
"get",
"(",
"\"heads\"",
")",
"refresh",
"=",
"kwargs",
".",
"get",
"(",
... | 40 | 15.066667 |
def set_user_profile(self,
displayname=None,
avatar_url=None,
reason="Changing room profile information"):
"""Set user profile within a room.
This sets displayname and avatar_url for the logged in user only in a
specific... | [
"def",
"set_user_profile",
"(",
"self",
",",
"displayname",
"=",
"None",
",",
"avatar_url",
"=",
"None",
",",
"reason",
"=",
"\"Changing room profile information\"",
")",
":",
"member",
"=",
"self",
".",
"client",
".",
"api",
".",
"get_membership",
"(",
"self"... | 39.2 | 15.88 |
def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX ... | [
"def",
"_get_available_extensions",
"(",
")",
":",
"extensions",
"=",
"[",
"]",
"# from filenames",
"parsers_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"glob_filename",
"=",
"os",
".",
"p... | 35.478261 | 14.652174 |
def _parse_args():
"""
Parses the command line arguments.
:return: Namespace with arguments.
:rtype: Namespace
"""
parser = argparse.ArgumentParser(description='rain - a new sort of automated builder.')
parser.add_argument('action', help='what shall we do?', default='build', nargs='?',... | [
"def",
"_parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'rain - a new sort of automated builder.'",
")",
"parser",
".",
"add_argument",
"(",
"'action'",
",",
"help",
"=",
"'what shall we do?'",
",",
"default",... | 40.230769 | 28.384615 |
def screenshots_done(self, jobid):
"""
Return true if the screenshots job is done
"""
resp = self.session.get(os.path.join(self.api_url, '{0}.json'.format(jobid)))
resp = self._process_response(resp)
return True if resp.json()['state'] == 'done' else False | [
"def",
"screenshots_done",
"(",
"self",
",",
"jobid",
")",
":",
"resp",
"=",
"self",
".",
"session",
".",
"get",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"api_url",
",",
"'{0}.json'",
".",
"format",
"(",
"jobid",
")",
")",
")",
"resp"... | 42.571429 | 12.571429 |
def update_cov(self):
"""Recursively compute the covariance matrix for the multivariate normal
proposal distribution.
This method is called every self.interval once self.delay iterations
have been performed.
"""
scaling = (2.4) ** 2 / self.dim # Gelman et al. 1996.
... | [
"def",
"update_cov",
"(",
"self",
")",
":",
"scaling",
"=",
"(",
"2.4",
")",
"**",
"2",
"/",
"self",
".",
"dim",
"# Gelman et al. 1996.",
"epsilon",
"=",
"1.0e-5",
"chain",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"_trace",
")",
"# Recursively comput... | 41.454545 | 21.945455 |
def build_actions(self):
"""Create an ActionCollection that will perform sanity checks, copy the file,
create a database entry and perform cleanup actions and in case of a failure clean everything up.
:param work: the workfile
:type work: :class:`JB_File`
:param release: the rel... | [
"def",
"build_actions",
"(",
"self",
")",
":",
"checkau",
"=",
"ActionUnit",
"(",
"\"Sanity Checks\"",
",",
"\"Check the workfile. If the file is not conform, ask the user to continue.\"",
",",
"self",
".",
"sanity_check",
")",
"copyau",
"=",
"ActionUnit",
"(",
"\"Copy Fi... | 56.06 | 19.58 |
def get_reversed_statuses(context):
"""Return a mapping of exit codes to status strings.
Args:
context (scriptworker.context.Context): the scriptworker context
Returns:
dict: the mapping of exit codes to status strings.
"""
_rev = {v: k for k, v in STATUSES.items()}
_rev.updat... | [
"def",
"get_reversed_statuses",
"(",
"context",
")",
":",
"_rev",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"STATUSES",
".",
"items",
"(",
")",
"}",
"_rev",
".",
"update",
"(",
"dict",
"(",
"context",
".",
"config",
"[",
"'reversed_statuse... | 28.307692 | 21.769231 |
def case_insensitive_file_search(directory, pattern):
"""
Looks for file with pattern with case insensitive search
"""
try:
return os.path.join(
directory,
[filename for filename in os.listdir(directory)
if re.search(pattern, filename, re.IGNORECASE)][0])
... | [
"def",
"case_insensitive_file_search",
"(",
"directory",
",",
"pattern",
")",
":",
"try",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"[",
"filename",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
"if",
"... | 32.416667 | 15.75 |
def extract_uhs(dstore, what):
"""
Extracts uniform hazard spectra. Use it as /extract/uhs?kind=mean or
/extract/uhs?kind=rlz-0, etc
"""
info = get_info(dstore)
if what == '': # npz exports for QGIS
sitecol = dstore['sitecol']
mesh = get_mesh(sitecol, complete=False)
dic... | [
"def",
"extract_uhs",
"(",
"dstore",
",",
"what",
")",
":",
"info",
"=",
"get_info",
"(",
"dstore",
")",
"if",
"what",
"==",
"''",
":",
"# npz exports for QGIS",
"sitecol",
"=",
"dstore",
"[",
"'sitecol'",
"]",
"mesh",
"=",
"get_mesh",
"(",
"sitecol",
",... | 33.972222 | 13.305556 |
def add_method(self, pattern):
"""Decorator to add new dispatch functions."""
def wrap(f):
def frozen_function(class_instance, f):
def _(pattern, *args, **kwargs):
return f(class_instance, pattern, *args, **kwargs)
return _
se... | [
"def",
"add_method",
"(",
"self",
",",
"pattern",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"def",
"frozen_function",
"(",
"class_instance",
",",
"f",
")",
":",
"def",
"_",
"(",
"pattern",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | 31.230769 | 22 |
def values(obj, glob, separator="/", afilter=None, dirs=True):
"""
Given an object and a path glob, return an array of all values which match
the glob. The arguments to this function are identical to those of search(),
and it is primarily a shorthand for a list comprehension over a yielded
search ca... | [
"def",
"values",
"(",
"obj",
",",
"glob",
",",
"separator",
"=",
"\"/\"",
",",
"afilter",
"=",
"None",
",",
"dirs",
"=",
"True",
")",
":",
"return",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"dpath",
".",
"util",
".",
"search",
"(",
"obj",
","... | 55.375 | 29.625 |
def update(self, query_name, saved_query_attributes):
"""
Given a dict of attributes to be updated, update only those attributes
in the Saved Query at the resource given by 'query_name'. This will
perform two HTTP requests--one to fetch the query definition, and one
to set the ne... | [
"def",
"update",
"(",
"self",
",",
"query_name",
",",
"saved_query_attributes",
")",
":",
"query_name_attr_name",
"=",
"\"query_name\"",
"refresh_rate_attr_name",
"=",
"\"refresh_rate\"",
"query_attr_name",
"=",
"\"query\"",
"metadata_attr_name",
"=",
"\"metadata\"",
"old... | 43.617021 | 26.723404 |
def write_to_file(self, file_path='', date=(datetime.date.today()),
organization='llnl'):
"""
Writes stargazers data to file.
"""
with open(file_path, 'w+') as out:
out.write('date,organization,stargazers\n')
sorted_stargazers = sorted(self.stargazers)#sor... | [
"def",
"write_to_file",
"(",
"self",
",",
"file_path",
"=",
"''",
",",
"date",
"=",
"(",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
",",
"organization",
"=",
"'llnl'",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'w+'",
")",
"as",
"... | 42.454545 | 13.727273 |
def plot_subtract_from_data_all(self):
"""
subtract model components from data
:return:
"""
f, axes = plt.subplots(2, 3, figsize=(16, 8))
self.subtract_from_data_plot(ax=axes[0, 0], text='Data')
self.subtract_from_data_plot(ax=axes[0, 1], text='Data - Point Sour... | [
"def",
"plot_subtract_from_data_all",
"(",
"self",
")",
":",
"f",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"2",
",",
"3",
",",
"figsize",
"=",
"(",
"16",
",",
"8",
")",
")",
"self",
".",
"subtract_from_data_plot",
"(",
"ax",
"=",
"axes",
"[",
... | 53.842105 | 31.631579 |
def refresh_token(
self,
token_url,
refresh_token=None,
body="",
auth=None,
timeout=None,
headers=None,
verify=True,
proxies=None,
**kwargs
):
"""Fetch a new access token using a refresh token.
:param token_url: The tok... | [
"def",
"refresh_token",
"(",
"self",
",",
"token_url",
",",
"refresh_token",
"=",
"None",
",",
"body",
"=",
"\"\"",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"proxies",
"=",
"... | 37.216216 | 22.797297 |
def add_item(self, item, replace = False):
"""
Add an item to the roster.
This will not automatically update the roster on the server.
:Parameters:
- `item`: the item to add
- `replace`: if `True` then existing item will be replaced,
otherwise a `V... | [
"def",
"add_item",
"(",
"self",
",",
"item",
",",
"replace",
"=",
"False",
")",
":",
"if",
"item",
".",
"jid",
"in",
"self",
".",
"_jids",
":",
"if",
"replace",
":",
"self",
".",
"remove_item",
"(",
"item",
".",
"jid",
")",
"else",
":",
"raise",
... | 32.545455 | 14.727273 |
def QA_fetch_user(user_cookie, db=DATABASE):
"""
get the user
Arguments:
user_cookie : str the unique cookie_id for a user
Keyword Arguments:
db: database for query
Returns:
list --- [ACCOUNT]
"""
collection = DATABASE.account
return [res for res in collection... | [
"def",
"QA_fetch_user",
"(",
"user_cookie",
",",
"db",
"=",
"DATABASE",
")",
":",
"collection",
"=",
"DATABASE",
".",
"account",
"return",
"[",
"res",
"for",
"res",
"in",
"collection",
".",
"find",
"(",
"{",
"'user_cookie'",
":",
"user_cookie",
"}",
",",
... | 23.6 | 20.8 |
def auth_aliases(d):
"""Interpret user/password aliases.
"""
for alias, real in ((USER_KEY, "readonly_user"),
(PASS_KEY, "readonly_password")):
if alias in d:
d[real] = d[alias]
del d[alias] | [
"def",
"auth_aliases",
"(",
"d",
")",
":",
"for",
"alias",
",",
"real",
"in",
"(",
"(",
"USER_KEY",
",",
"\"readonly_user\"",
")",
",",
"(",
"PASS_KEY",
",",
"\"readonly_password\"",
")",
")",
":",
"if",
"alias",
"in",
"d",
":",
"d",
"[",
"real",
"]"... | 31.375 | 11.625 |
def _next(self, state_class, *args):
"""Transition into the next state.
:param type state_class: a subclass of :class:`State`. It is intialized
with the communication object and :paramref:`args`
:param args: additional arguments
"""
self._communication.state = state_cl... | [
"def",
"_next",
"(",
"self",
",",
"state_class",
",",
"*",
"args",
")",
":",
"self",
".",
"_communication",
".",
"state",
"=",
"state_class",
"(",
"self",
".",
"_communication",
",",
"*",
"args",
")"
] | 43 | 17.375 |
def plotlyFrequencyHistogram(counts):
"""
x-axis is a count of how many times a bit was active
y-axis is number of bits that have that frequency
"""
data = [
go.Histogram(
x=tuple(count for _, _, count in counts.getNonZerosSorted())
)
]
py.plot(data, filename=os.environ.get("HEATMAP_NAME",
... | [
"def",
"plotlyFrequencyHistogram",
"(",
"counts",
")",
":",
"data",
"=",
"[",
"go",
".",
"Histogram",
"(",
"x",
"=",
"tuple",
"(",
"count",
"for",
"_",
",",
"_",
",",
"count",
"in",
"counts",
".",
"getNonZerosSorted",
"(",
")",
")",
")",
"]",
"py",
... | 31.5 | 18.666667 |
def to_dict(self,include_node_id=False,no_attributes=False,track_namespaces=False):
"""
This function is currently geared very much towards writing
STIX/CybOX objects to a dictionary. That should not be the case -- the function
needs to be generic just as the from_dict function.
... | [
"def",
"to_dict",
"(",
"self",
",",
"include_node_id",
"=",
"False",
",",
"no_attributes",
"=",
"False",
",",
"track_namespaces",
"=",
"False",
")",
":",
"flat_result",
"=",
"[",
"]",
"def",
"make_ns_slug",
"(",
"name_counter",
",",
"slug",
"=",
"'n'",
")"... | 42.24031 | 25.031008 |
def labels(self, value):
"""
Setter for **self.__labels** attribute.
:param value: Attribute value.
:type value: tuple
"""
if value is not None:
assert type(value) is tuple, "'{0}' attribute: '{1}' type is not 'tuple'!".format("labels", value)
ass... | [
"def",
"labels",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"tuple",
",",
"\"'{0}' attribute: '{1}' type is not 'tuple'!\"",
".",
"format",
"(",
"\"labels\"",
",",
"value",
")",
... | 45.785714 | 23.357143 |
def parse_srs(t_srs, src_ds_list=None):
"""Parse arbitrary input t_srs
Parameters
----------
t_srs : str or gdal.Dataset or filename
Arbitrary input t_srs
src_ds_list : list of gdal.Dataset objects, optional
Needed if specifying 'first' or 'last'
Returns
-------
t_srs ... | [
"def",
"parse_srs",
"(",
"t_srs",
",",
"src_ds_list",
"=",
"None",
")",
":",
"if",
"t_srs",
"is",
"None",
"and",
"src_ds_list",
"is",
"None",
":",
"print",
"(",
"\"Input t_srs and src_ds_list are both None\"",
")",
"else",
":",
"if",
"t_srs",
"is",
"None",
"... | 34.478261 | 13.804348 |
def describe(self, req=None, resp=None, **kwargs):
"""Describe API resource using resource introspection.
Additional description on derrived resource class can be added using
keyword arguments and calling ``super().decribe()`` method call
like following:
.. code-block:: python
... | [
"def",
"describe",
"(",
"self",
",",
"req",
"=",
"None",
",",
"resp",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"description",
"=",
"{",
"'params'",
":",
"OrderedDict",
"(",
"[",
"(",
"name",
",",
"param",
".",
"describe",
"(",
")",
")",
"f... | 36.020833 | 19.75 |
def from_ast(
pyast_node, node=None, node_cls=None, Node=Node,
iter_fields=ast.iter_fields, AST=ast.AST):
'''Convert the ast tree to a tater tree.
'''
node_cls = node_cls or Node
node = node or node_cls()
name = pyast_node.__class__.__name__
attrs = []
for field, value in it... | [
"def",
"from_ast",
"(",
"pyast_node",
",",
"node",
"=",
"None",
",",
"node_cls",
"=",
"None",
",",
"Node",
"=",
"Node",
",",
"iter_fields",
"=",
"ast",
".",
"iter_fields",
",",
"AST",
"=",
"ast",
".",
"AST",
")",
":",
"node_cls",
"=",
"node_cls",
"or... | 36.1 | 11.366667 |
def is_build_needed(self, data_sink, data_src):
""" returns true if data_src needs to be rebuilt, given that data_sink
has had a rebuild requested.
"""
return (self._gettask(data_src).last_build_time == 0 or
self._gettask(data_src).last_build_time <
se... | [
"def",
"is_build_needed",
"(",
"self",
",",
"data_sink",
",",
"data_src",
")",
":",
"return",
"(",
"self",
".",
"_gettask",
"(",
"data_src",
")",
".",
"last_build_time",
"==",
"0",
"or",
"self",
".",
"_gettask",
"(",
"data_src",
")",
".",
"last_build_time"... | 50.428571 | 9.142857 |
def inferSuperimposedSequenceObjects(exp, sequenceId, objectId, sequences, objects):
"""Run inference on the given sequence."""
# Create the (loc, feat) pairs for this sequence for column 0.
objectSensations = {
0: [pair for pair in sequences[sequenceId]]
}
inferConfig = {
"object": sequenceId,
"... | [
"def",
"inferSuperimposedSequenceObjects",
"(",
"exp",
",",
"sequenceId",
",",
"objectId",
",",
"sequences",
",",
"objects",
")",
":",
"# Create the (loc, feat) pairs for this sequence for column 0.",
"objectSensations",
"=",
"{",
"0",
":",
"[",
"pair",
"for",
"pair",
... | 33.684211 | 23.842105 |
def limit_keyphrases (path, phrase_limit=20):
"""
iterator for the most significant key phrases
"""
rank_thresh = None
if isinstance(path, str):
lex = []
for meta in json_iter(path):
rl = RankedLexeme(**meta)
lex.append(rl)
else:
lex = path
... | [
"def",
"limit_keyphrases",
"(",
"path",
",",
"phrase_limit",
"=",
"20",
")",
":",
"rank_thresh",
"=",
"None",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"lex",
"=",
"[",
"]",
"for",
"meta",
"in",
"json_iter",
"(",
"path",
")",
":",
"rl",
... | 21.689655 | 20.517241 |
def ajRadicaux(self, lemme):
""" Calcule tous les radicaux du lemme l,
* en se servant des modèles, ajoute à ce lemme,
* et ensuite à la map * des radicaux de la classe Lemmat.
Ligne type de lemme
# ablŭo=ā̆blŭo|lego|ā̆blŭ|ā̆blūt|is, ere, lui, lutum
# 0 ... | [
"def",
"ajRadicaux",
"(",
"self",
",",
"lemme",
")",
":",
"m",
"=",
"self",
".",
"lemmatiseur",
".",
"modele",
"(",
"lemme",
".",
"grModele",
"(",
")",
")",
"''' insérer d'abord les radicaux définis dans lemmes.la\n qui sont prioritaires '''",
"for",
"i",
"in... | 39.403846 | 14.903846 |
def get_node_type(tree):
"""
returns the node type (leaf or span) of a subtree (i.e. Nucleus or Satellite)
Parameters
----------
tree : nltk.tree.ParentedTree
a tree representing a rhetorical structure (or a part of it)
"""
node_type = tree[0].label()
assert node_type in NODE_TY... | [
"def",
"get_node_type",
"(",
"tree",
")",
":",
"node_type",
"=",
"tree",
"[",
"0",
"]",
".",
"label",
"(",
")",
"assert",
"node_type",
"in",
"NODE_TYPES",
",",
"\"node_type: {}\"",
".",
"format",
"(",
"node_type",
")",
"return",
"node_type"
] | 30.666667 | 20.166667 |
def _filtered_walk(path, file_filter):
"""
static method that calls os.walk, but filters out
anything that doesn't match the filter
"""
for root, dirs, files in os.walk(path):
log.debug('looking in %s', root)
log.debug('files is %s', files)
file_filter.set_root(root)
files = filter(file_filter, fi... | [
"def",
"_filtered_walk",
"(",
"path",
",",
"file_filter",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"log",
".",
"debug",
"(",
"'looking in %s'",
",",
"root",
")",
"log",
".",
"debug",
"(",
"... | 32.166667 | 4.5 |
def create(self, mention, max_message_length):
"""
Create a message
:param mention: JSON object containing mention details from Twitter (or an empty dict {})
:param max_message_length: Maximum allowable length for created message
:return: A random message created using a Markov c... | [
"def",
"create",
"(",
"self",
",",
"mention",
",",
"max_message_length",
")",
":",
"message",
"=",
"[",
"]",
"def",
"message_len",
"(",
")",
":",
"return",
"sum",
"(",
"[",
"len",
"(",
"w",
")",
"+",
"1",
"for",
"w",
"in",
"message",
"]",
")",
"w... | 37.8125 | 23.0625 |
def qualify(workers, qualification, value, by_name, notify, sandbox):
"""Assign a qualification to 1 or more workers"""
if not (workers and qualification and value):
raise click.BadParameter(
"Must specify a qualification ID, value/score, and at least one worker ID"
)
mturk = _mt... | [
"def",
"qualify",
"(",
"workers",
",",
"qualification",
",",
"value",
",",
"by_name",
",",
"notify",
",",
"sandbox",
")",
":",
"if",
"not",
"(",
"workers",
"and",
"qualification",
"and",
"value",
")",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"\"M... | 38.411765 | 25.676471 |
def decode_offset_response(cls, response):
"""
Decode OffsetResponse into OffsetResponsePayloads
Arguments:
response: OffsetResponse
Returns: list of OffsetResponsePayloads
"""
return [
kafka.structs.OffsetResponsePayload(topic, partition, error,... | [
"def",
"decode_offset_response",
"(",
"cls",
",",
"response",
")",
":",
"return",
"[",
"kafka",
".",
"structs",
".",
"OffsetResponsePayload",
"(",
"topic",
",",
"partition",
",",
"error",
",",
"tuple",
"(",
"offsets",
")",
")",
"for",
"topic",
",",
"partit... | 31.571429 | 18.714286 |
def main(target, label):
"""
Semver tag triggered deployment helper
"""
check_environment(target, label)
click.secho('Fetching tags from the upstream ...')
handler = TagHandler(git.list_tags())
print_information(handler, label)
tag = handler.yield_tag(target, label)
confirm(tag) | [
"def",
"main",
"(",
"target",
",",
"label",
")",
":",
"check_environment",
"(",
"target",
",",
"label",
")",
"click",
".",
"secho",
"(",
"'Fetching tags from the upstream ...'",
")",
"handler",
"=",
"TagHandler",
"(",
"git",
".",
"list_tags",
"(",
")",
")",
... | 23.538462 | 14.307692 |
def get(self, id, **options):
'''Get a single item with the given ID'''
if not self._item_path:
raise AttributeError('get is not available for %s' % self._item_name)
target = self._item_path % id
json_data = self._redmine.get(target, **options)
data = self._redmine.un... | [
"def",
"get",
"(",
"self",
",",
"id",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"self",
".",
"_item_path",
":",
"raise",
"AttributeError",
"(",
"'get is not available for %s'",
"%",
"self",
".",
"_item_name",
")",
"target",
"=",
"self",
".",
"_ite... | 47.666667 | 13.444444 |
def getxattr(self, req, ino, name, size):
""" Set an extended attribute
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err
"""
self.reply_err(req, errno.ENOSYS) | [
"def",
"getxattr",
"(",
"self",
",",
"req",
",",
"ino",
",",
"name",
",",
"size",
")",
":",
"self",
".",
"reply_err",
"(",
"req",
",",
"errno",
".",
"ENOSYS",
")"
] | 22.7 | 14.5 |
def convert_mrf_to_syntax_mrf( mrf_lines, conversion_rules ):
''' Converts given lines from Filosoft's mrf format to syntactic analyzer's
format, using the morph-category conversion rules from conversion_rules,
and punctuation via method _convert_punctuation();
As a result of conversion, th... | [
"def",
"convert_mrf_to_syntax_mrf",
"(",
"mrf_lines",
",",
"conversion_rules",
")",
":",
"i",
"=",
"0",
"while",
"(",
"i",
"<",
"len",
"(",
"mrf_lines",
")",
")",
":",
"line",
"=",
"mrf_lines",
"[",
"i",
"]",
"if",
"line",
".",
"startswith",
"(",
"' '... | 48.140625 | 18.109375 |
async def fetch_state(self, request):
"""Fetches data from a specific address in the validator's state tree.
Request:
query:
- head: The id of the block to use as the head of the chain
- address: The 70 character address of the data to be fetched
Res... | [
"async",
"def",
"fetch_state",
"(",
"self",
",",
"request",
")",
":",
"error_traps",
"=",
"[",
"error_handlers",
".",
"InvalidAddressTrap",
",",
"error_handlers",
".",
"StateNotFoundTrap",
"]",
"address",
"=",
"request",
".",
"match_info",
".",
"get",
"(",
"'a... | 38.8125 | 19.46875 |
def toggle_settings(
toolbar=False, nbname=False, hideprompt=False, kernellogo=False):
"""Toggle main notebook toolbar (e.g., buttons), filename,
and kernel logo."""
toggle = ''
if toolbar:
toggle += 'div#maintoolbar {margin-left: 8px !important;}\n'
toggle += '.toolbar.containe... | [
"def",
"toggle_settings",
"(",
"toolbar",
"=",
"False",
",",
"nbname",
"=",
"False",
",",
"hideprompt",
"=",
"False",
",",
"kernellogo",
"=",
"False",
")",
":",
"toggle",
"=",
"''",
"if",
"toolbar",
":",
"toggle",
"+=",
"'div#maintoolbar {margin-left: 8px !imp... | 48.166667 | 28.083333 |
def send_up(self, count):
"""
Sends the given number of up key presses.
"""
for i in range(count):
self.interface.send_key(Key.UP) | [
"def",
"send_up",
"(",
"self",
",",
"count",
")",
":",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"self",
".",
"interface",
".",
"send_key",
"(",
"Key",
".",
"UP",
")"
] | 29.5 | 6.166667 |
def trackerItem( self ):
"""
Returns the tracker item for this chart.
:return <XChartTrackerItem> || None
"""
# check for the tracking enabled state
if not self.isTrackingEnabled():
return None
# generate a new tracker i... | [
"def",
"trackerItem",
"(",
"self",
")",
":",
"# check for the tracking enabled state\r",
"if",
"not",
"self",
".",
"isTrackingEnabled",
"(",
")",
":",
"return",
"None",
"# generate a new tracker item\r",
"if",
"not",
"(",
"self",
".",
"_trackerItem",
"and",
"self",
... | 31.588235 | 11.588235 |
def info():
"""Display app info.
Examples:
$ dj info
No application, try running dj init.
$ dj info
Application:
foo @ 2.7.9
Requirements:
Django == 1.10
"""
application = get_current_application()
info = application.info()
stdout.write(info)
return info | [
"def",
"info",
"(",
")",
":",
"application",
"=",
"get_current_application",
"(",
")",
"info",
"=",
"application",
".",
"info",
"(",
")",
"stdout",
".",
"write",
"(",
"info",
")",
"return",
"info"
] | 15.789474 | 21.947368 |
def _compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out).
"""
if len(shape) < 1: # Just to avoid errors for constants.
fan_in = fan_out = 1
elif len(shape) ... | [
"def",
"_compute_fans",
"(",
"shape",
")",
":",
"if",
"len",
"(",
"shape",
")",
"<",
"1",
":",
"# Just to avoid errors for constants.",
"fan_in",
"=",
"fan_out",
"=",
"1",
"elif",
"len",
"(",
"shape",
")",
"==",
"1",
":",
"fan_in",
"=",
"fan_out",
"=",
... | 29.241379 | 14.655172 |
def _format_stage_info(bar_width, stage_info, duration, timedelta_formatter=_pretty_time_delta):
"""Formats the Spark stage progress.
Parameters
----------
bar_width : int
Width of the progressbar to print out.
stage_info : :class:`pyspark.status.StageInfo`
Information about the run... | [
"def",
"_format_stage_info",
"(",
"bar_width",
",",
"stage_info",
",",
"duration",
",",
"timedelta_formatter",
"=",
"_pretty_time_delta",
")",
":",
"dur",
"=",
"timedelta_formatter",
"(",
"duration",
")",
"percent",
"=",
"(",
"stage_info",
".",
"numCompletedTasks",
... | 31.911765 | 17.941176 |
def get_pub_date(self, undefined=""):
"""
Args:
undefined (optional): Argument, which will be returned if the
`pub_date` record is not found.
Returns:
str: Date of publication (month and year usually) or `undefined` \
if `pub_date` ... | [
"def",
"get_pub_date",
"(",
"self",
",",
"undefined",
"=",
"\"\"",
")",
":",
"dates",
"=",
"self",
"[",
"\"260c \"",
"]",
"+",
"self",
"[",
"\"264c\"",
"]",
"def",
"clean_date",
"(",
"date",
")",
":",
"\"\"\"\n Clean the `date` strings from special c... | 27.333333 | 18.428571 |
def ntp_server_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
server = ET.SubElement(ntp, "server")
ip_key = ET.SubElement(server, "ip")
ip_key.text = kwarg... | [
"def",
"ntp_server_key",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ntp",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ntp\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:brocade-ntp... | 39.466667 | 10.466667 |
def get_storage_pool_by_name(self, name):
"""
Get ScaleIO StoragePool object by its name
:param name: Name of StoragePool
:return: ScaleIO StoragePool object
:raise KeyError: No StoragePool with specified name found
:rtype: StoragePool object
"""
for stora... | [
"def",
"get_storage_pool_by_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"storage_pool",
"in",
"self",
".",
"conn",
".",
"storage_pools",
":",
"if",
"storage_pool",
".",
"name",
"==",
"name",
":",
"return",
"storage_pool",
"raise",
"KeyError",
"(",
"\"S... | 40.333333 | 7 |
def MakeDynamicPotentialFunc(kBT_Gamma, density, SpringPotnlFunc):
"""
Creates the function that calculates the potential given
the position (in volts) and the radius of the particle.
Parameters
----------
kBT_Gamma : float
Value of kB*T/Gamma
density : float
density of the... | [
"def",
"MakeDynamicPotentialFunc",
"(",
"kBT_Gamma",
",",
"density",
",",
"SpringPotnlFunc",
")",
":",
"def",
"PotentialFunc",
"(",
"xdata",
",",
"Radius",
")",
":",
"\"\"\"\n calculates the potential given the position (in volts) \n and the radius of the particle.\... | 27.466667 | 17.733333 |
def get_groups_count(self, field=None):
'''
Returns 'matches' from group response.
If grouping on more than one field, provide the field argument to specify which count you are looking for.
'''
field = field if field else self._determine_group_field(field)
if 'ma... | [
"def",
"get_groups_count",
"(",
"self",
",",
"field",
"=",
"None",
")",
":",
"field",
"=",
"field",
"if",
"field",
"else",
"self",
".",
"_determine_group_field",
"(",
"field",
")",
"if",
"'matches'",
"in",
"self",
".",
"data",
"[",
"'grouped'",
"]",
"[",... | 47.1 | 26.9 |
def as_dict( self, key="id" ):
"""
Return a dictionary containing all remaining motifs, using `key`
as the dictionary key.
"""
rval = {}
for motif in self:
rval[ getattr( motif, key ) ] = motif
return rval | [
"def",
"as_dict",
"(",
"self",
",",
"key",
"=",
"\"id\"",
")",
":",
"rval",
"=",
"{",
"}",
"for",
"motif",
"in",
"self",
":",
"rval",
"[",
"getattr",
"(",
"motif",
",",
"key",
")",
"]",
"=",
"motif",
"return",
"rval"
] | 29.444444 | 13.222222 |
def strip_fhss(self, idx):
"""strip (2 byte) radiotap.fhss.hopset(1 byte) and
radiotap.fhss.pattern(1 byte)
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
fhss = collections.namedtuple('fhss', ['hopset', 'pattern'])
fhss.hopset,... | [
"def",
"strip_fhss",
"(",
"self",
",",
"idx",
")",
":",
"fhss",
"=",
"collections",
".",
"namedtuple",
"(",
"'fhss'",
",",
"[",
"'hopset'",
",",
"'pattern'",
"]",
")",
"fhss",
".",
"hopset",
",",
"fhss",
".",
"pattern",
",",
"=",
"struct",
".",
"unpa... | 36.181818 | 15 |
def sameAs(self, other):
"""
Check if this is the same location.
::
>>> l = Location(pop=5, snap=100)
>>> m = Location(pop=5.0, snap=100.0)
>>> l.sameAs(m)
0
>>> l = Location(pop=5, snap=100)
>>> m = Location(pop=5.... | [
"def",
"sameAs",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"get\"",
")",
":",
"return",
"-",
"1",
"d",
"=",
"self",
".",
"distance",
"(",
"other",
")",
"if",
"d",
"<",
"_EPSILON",
":",
"return",
"0",
"retur... | 26.5 | 14 |
def run_step(context):
"""Parse input file and substitutes {tokens} from context.
Args:
context: pypyr.context.Context. Mandatory.
The following context keys expected:
- fileFormat
- in. mandatory.
str, path-like, or an iterable... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"deprecated",
"(",
"context",
")",
"StreamRewriterStep",
"(",
"__name__",
",",
"'fileFormat'",
",",
"context",
")",
".",
"run_step",
"(",
")",
"logger",
".",
"deb... | 40.421053 | 24.605263 |
def update(self, table, columns, values):
"""Update one or more existing table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
... | [
"def",
"update",
"(",
"self",
",",
"table",
",",
"columns",
",",
"values",
")",
":",
"self",
".",
"_mutations",
".",
"append",
"(",
"Mutation",
"(",
"update",
"=",
"_make_write_pb",
"(",
"table",
",",
"columns",
",",
"values",
")",
")",
")"
] | 34.384615 | 18.461538 |
def create_virtualenv(venv=VENV, install_pip=False):
"""Creates the virtual environment and installs PIP only into the
virtual environment
"""
print 'Creating venv...',
install = ['virtualenv', '-q', venv]
run_command(install)
print 'done.'
print 'Installing pip in virtualenv...',
... | [
"def",
"create_virtualenv",
"(",
"venv",
"=",
"VENV",
",",
"install_pip",
"=",
"False",
")",
":",
"print",
"'Creating venv...'",
",",
"install",
"=",
"[",
"'virtualenv'",
",",
"'-q'",
",",
"venv",
"]",
"run_command",
"(",
"install",
")",
"print",
"'done.'",
... | 30.625 | 14.5 |
def pf_to_n(L, pf, R):
"""Returns the number of non-intersecting spheres required to achieve
as close to a given packing fraction as possible, along with the actual
achieved packing fraction. for a number of non-intersecting spheres.
Parameters
----------
L: float array, shape (d,)
Syst... | [
"def",
"pf_to_n",
"(",
"L",
",",
"pf",
",",
"R",
")",
":",
"dim",
"=",
"L",
".",
"shape",
"[",
"0",
"]",
"n",
"=",
"int",
"(",
"round",
"(",
"pf",
"*",
"np",
".",
"product",
"(",
"L",
")",
"/",
"sphere_volume",
"(",
"R",
",",
"dim",
")",
... | 31.192308 | 22.346154 |
def div_img(img1, div2):
""" Pixelwise division or divide by a number """
if is_img(div2):
return img1.get_data()/div2.get_data()
elif isinstance(div2, (float, int)):
return img1.get_data()/div2
else:
raise NotImplementedError('Cannot divide {}({}) by '
... | [
"def",
"div_img",
"(",
"img1",
",",
"div2",
")",
":",
"if",
"is_img",
"(",
"div2",
")",
":",
"return",
"img1",
".",
"get_data",
"(",
")",
"/",
"div2",
".",
"get_data",
"(",
")",
"elif",
"isinstance",
"(",
"div2",
",",
"(",
"float",
",",
"int",
")... | 43.25 | 14.25 |
def listed(self):
"""Print blacklist packages
"""
print("\nPackages in the blacklist:\n")
for black in self.get_black():
if black:
print("{0}{1}{2}".format(self.meta.color["GREEN"], black,
self.meta.color["ENDC"]))
... | [
"def",
"listed",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nPackages in the blacklist:\\n\"",
")",
"for",
"black",
"in",
"self",
".",
"get_black",
"(",
")",
":",
"if",
"black",
":",
"print",
"(",
"\"{0}{1}{2}\"",
".",
"format",
"(",
"self",
".",
"meta",
... | 34.727273 | 14.181818 |
def main(argv):
"""Train on examples and export the updated model weights."""
tf_records = argv[1:]
logging.info("Training on %s records: %s to %s",
len(tf_records), tf_records[0], tf_records[-1])
with utils.logged_timer("Training"):
train(*tf_records)
if FLAGS.export_path:
... | [
"def",
"main",
"(",
"argv",
")",
":",
"tf_records",
"=",
"argv",
"[",
"1",
":",
"]",
"logging",
".",
"info",
"(",
"\"Training on %s records: %s to %s\"",
",",
"len",
"(",
"tf_records",
")",
",",
"tf_records",
"[",
"0",
"]",
",",
"tf_records",
"[",
"-",
... | 37.571429 | 14.5 |
def normalise_reads(self):
"""
Use bbnorm from the bbmap suite of tools to perform read normalisation
"""
logging.info('Normalising reads to a kmer depth of 100')
for sample in self.metadata:
# Set the name of the normalised read files
sample.general.norma... | [
"def",
"normalise_reads",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Normalising reads to a kmer depth of 100'",
")",
"for",
"sample",
"in",
"self",
".",
"metadata",
":",
"# Set the name of the normalised read files",
"sample",
".",
"general",
".",
"normali... | 59.238095 | 27.142857 |
def _inherited_value(self, attr_name):
"""
Return the attribute value, e.g. 'width' of the base placeholder this
placeholder inherits from.
"""
base_placeholder = self._base_placeholder
if base_placeholder is None:
return None
inherited_value = getattr... | [
"def",
"_inherited_value",
"(",
"self",
",",
"attr_name",
")",
":",
"base_placeholder",
"=",
"self",
".",
"_base_placeholder",
"if",
"base_placeholder",
"is",
"None",
":",
"return",
"None",
"inherited_value",
"=",
"getattr",
"(",
"base_placeholder",
",",
"attr_nam... | 37.1 | 10.7 |
def _infer_precision(base_precision, bins):
"""Infer an appropriate precision for _round_frac
"""
for precision in range(base_precision, 20):
levels = [_round_frac(b, precision) for b in bins]
if algos.unique(levels).size == bins.size:
return precision
return base_precision | [
"def",
"_infer_precision",
"(",
"base_precision",
",",
"bins",
")",
":",
"for",
"precision",
"in",
"range",
"(",
"base_precision",
",",
"20",
")",
":",
"levels",
"=",
"[",
"_round_frac",
"(",
"b",
",",
"precision",
")",
"for",
"b",
"in",
"bins",
"]",
"... | 38.875 | 8.125 |
def imethodcallPayload(self, methodname, localnsp, **kwargs):
"""Generate the XML payload for an intrinsic methodcall."""
param_list = [pywbem.IPARAMVALUE(x[0], pywbem.tocimxml(x[1]))
for x in kwargs.items()]
payload = cim_xml.CIM(
cim_xml.MESSAGE(
... | [
"def",
"imethodcallPayload",
"(",
"self",
",",
"methodname",
",",
"localnsp",
",",
"*",
"*",
"kwargs",
")",
":",
"param_list",
"=",
"[",
"pywbem",
".",
"IPARAMVALUE",
"(",
"x",
"[",
"0",
"]",
",",
"pywbem",
".",
"tocimxml",
"(",
"x",
"[",
"1",
"]",
... | 37.526316 | 15.052632 |
def RecurseKey(recur_item, depth=15, key_path=''):
"""Flattens nested dictionaries and lists by yielding it's values.
The hierarchy of a plist file is a series of nested dictionaries and lists.
This is a helper function helps plugins navigate the structure without
having to reimplement their own recursive meth... | [
"def",
"RecurseKey",
"(",
"recur_item",
",",
"depth",
"=",
"15",
",",
"key_path",
"=",
"''",
")",
":",
"if",
"depth",
"<",
"1",
":",
"logger",
".",
"debug",
"(",
"'Recursion limit hit for key: {0:s}'",
".",
"format",
"(",
"key_path",
")",
")",
"return",
... | 33.807018 | 23.368421 |
def inverse(self):
""" returns q.conjugate()/q.norm()**2
So if the quaternion is unit length, it is the same
as the conjugate.
"""
new = self.conjugate()
tmp = self.norm()**2
new.w /= tmp
new.x /= tmp
new.y /= tmp
new.z /= tmp
... | [
"def",
"inverse",
"(",
"self",
")",
":",
"new",
"=",
"self",
".",
"conjugate",
"(",
")",
"tmp",
"=",
"self",
".",
"norm",
"(",
")",
"**",
"2",
"new",
".",
"w",
"/=",
"tmp",
"new",
".",
"x",
"/=",
"tmp",
"new",
".",
"y",
"/=",
"tmp",
"new",
... | 24.769231 | 16.307692 |
def setBrush(self, b, resize=0, proportional=None):
"""
Sets the size of the current :py:class:`Brush`.
:param brush: The :py:class:`Brush` object to use as a brush.
:param resize: An optional absolute value to resize the brush before using it.
:param proportional: An optional relative float 0-1 value to r... | [
"def",
"setBrush",
"(",
"self",
",",
"b",
",",
"resize",
"=",
"0",
",",
"proportional",
"=",
"None",
")",
":",
"if",
"proportional",
"!=",
"None",
":",
"resize",
"=",
"int",
"(",
"self",
".",
"brush",
".",
"brushSize",
"*",
"0.5",
")",
"b",
".",
... | 40.333333 | 18.866667 |
def supported_operations(self):
""" All file operations supported by the camera. """
return tuple(op for op in backend.FILE_OPS if self._operations & op) | [
"def",
"supported_operations",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"op",
"for",
"op",
"in",
"backend",
".",
"FILE_OPS",
"if",
"self",
".",
"_operations",
"&",
"op",
")"
] | 55.666667 | 15 |
def _get_sample_select(samples, keep):
"""Returns a vector of True/False to keep samples."""
k = np.ones_like(samples, dtype=bool)
if keep is not None:
k = np.array([s in keep for s in samples], dtype=bool)
if np.sum(k) == 0:
logger.warning("No samples matched the keep list")
... | [
"def",
"_get_sample_select",
"(",
"samples",
",",
"keep",
")",
":",
"k",
"=",
"np",
".",
"ones_like",
"(",
"samples",
",",
"dtype",
"=",
"bool",
")",
"if",
"keep",
"is",
"not",
"None",
":",
"k",
"=",
"np",
".",
"array",
"(",
"[",
"s",
"in",
"keep... | 40.25 | 13.125 |
def fromString( parent, xmlstring, actions = None ):
"""
Loads the xml string as xml data and then calls the fromXml method.
:param parent | <QWidget>
xmlstring | <str>
actions | {<str> name: <QAction>, .. } || None
:retu... | [
"def",
"fromString",
"(",
"parent",
",",
"xmlstring",
",",
"actions",
"=",
"None",
")",
":",
"try",
":",
"xdata",
"=",
"ElementTree",
".",
"fromstring",
"(",
"xmlstring",
")",
"except",
"ExpatError",
",",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
... | 31.388889 | 16.722222 |
def window_bohman(N):
r"""Bohman tapering window
:param N: window length
.. math:: w(n) = (1-|x|) \cos (\pi |x|) + \frac{1}{\pi} \sin(\pi |x|)
where x is a length N vector of linearly spaced values between
-1 and 1.
.. plot::
:width: 80%
:include-source:
from spectru... | [
"def",
"window_bohman",
"(",
"N",
")",
":",
"x",
"=",
"linspace",
"(",
"-",
"1",
",",
"1",
",",
"N",
")",
"w",
"=",
"(",
"1.",
"-",
"abs",
"(",
"x",
")",
")",
"*",
"cos",
"(",
"pi",
"*",
"abs",
"(",
"x",
")",
")",
"+",
"1.",
"/",
"pi",
... | 23.636364 | 23.045455 |
def addLocation(self, locationUri, weight):
"""
add relevant location to the topic page
@param locationUri: uri of the location to add
@param weight: importance of the provided location (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight value... | [
"def",
"addLocation",
"(",
"self",
",",
"locationUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
"\"lo... | 54.375 | 21.625 |
def user_path(self, team, user):
"""
Returns the path to directory with the user's package repositories.
"""
return os.path.join(self.team_path(team), user) | [
"def",
"user_path",
"(",
"self",
",",
"team",
",",
"user",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"team_path",
"(",
"team",
")",
",",
"user",
")"
] | 36.8 | 11.6 |
def create_privkey(self):
"""
This is called by post_build() for key creation.
"""
if self.group in _tls_named_ffdh_groups:
params = _ffdh_groups[_tls_named_ffdh_groups[self.group]][0]
privkey = params.generate_private_key()
self.privkey = privkey
... | [
"def",
"create_privkey",
"(",
"self",
")",
":",
"if",
"self",
".",
"group",
"in",
"_tls_named_ffdh_groups",
":",
"params",
"=",
"_ffdh_groups",
"[",
"_tls_named_ffdh_groups",
"[",
"self",
".",
"group",
"]",
"]",
"[",
"0",
"]",
"privkey",
"=",
"params",
"."... | 47.290323 | 13.870968 |
def probePlane(img, origin=(0, 0, 0), normal=(1, 0, 0)):
"""
Takes a ``vtkImageData`` and probes its scalars on a plane.
.. hint:: |probePlane| |probePlane.py|_
"""
plane = vtk.vtkPlane()
plane.SetOrigin(origin)
plane.SetNormal(normal)
planeCut = vtk.vtkCutter()
planeCut.SetInputDa... | [
"def",
"probePlane",
"(",
"img",
",",
"origin",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"normal",
"=",
"(",
"1",
",",
"0",
",",
"0",
")",
")",
":",
"plane",
"=",
"vtk",
".",
"vtkPlane",
"(",
")",
"plane",
".",
"SetOrigin",
"(",
"origin",... | 31.764706 | 17.529412 |
def contrast(image, mask = slice(None)):
r"""
Takes a simple or multi-spectral image and returns the contrast of the texture.
Fcon = standard_deviation(gray_value) / (kurtosis(gray_value)**0.25)
Parameters
----------
image : array_like or list/tuple of array_like
A single imag... | [
"def",
"contrast",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
")",
":",
"image",
"=",
"numpy",
".",
"asarray",
"(",
"image",
")",
"# set default mask or apply given mask",
"if",
"not",
"type",
"(",
"mask",
")",
"is",
"slice",
":",
"if",
... | 30.756757 | 24.189189 |
def _resolve_argn(macro, args):
"""Get argument from macro name
ie : $ARG3$ -> args[2]
:param macro: macro to parse
:type macro:
:param args: args given to command line
:type args:
:return: argument at position N-1 in args table (where N is the int parsed)
... | [
"def",
"_resolve_argn",
"(",
"macro",
",",
"args",
")",
":",
"# first, get the number of args",
"_id",
"=",
"None",
"matches",
"=",
"re",
".",
"search",
"(",
"r'ARG(?P<id>\\d+)'",
",",
"macro",
")",
"if",
"matches",
"is",
"not",
"None",
":",
"_id",
"=",
"i... | 32.681818 | 14.954545 |
def set_visible(self, visible):
""" Set the visibility of the widget.
"""
v = View.VISIBILITY_VISIBLE if visible else View.VISIBILITY_GONE
self.widget.setVisibility(v) | [
"def",
"set_visible",
"(",
"self",
",",
"visible",
")",
":",
"v",
"=",
"View",
".",
"VISIBILITY_VISIBLE",
"if",
"visible",
"else",
"View",
".",
"VISIBILITY_GONE",
"self",
".",
"widget",
".",
"setVisibility",
"(",
"v",
")"
] | 32.5 | 14.166667 |
def prior_dates(*args, **kwargs):
"""Get the prior distribution of calibrated radiocarbon dates"""
try:
chron = args[0]
except IndexError:
chron = kwargs['coredates']
d_r = np.array(kwargs['d_r'])
d_std = np.array(kwargs['d_std'])
t_a = np.array(k... | [
"def",
"prior_dates",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"chron",
"=",
"args",
"[",
"0",
"]",
"except",
"IndexError",
":",
"chron",
"=",
"kwargs",
"[",
"'coredates'",
"]",
"d_r",
"=",
"np",
".",
"array",
"(",
"kwargs",... | 31.076923 | 16.307692 |
def validate_maildirs(ctx, param, value):
""" Check that folders are maildirs. """
for path in value:
for subdir in MD_SUBDIRS:
if not os.path.isdir(os.path.join(path, subdir)):
raise click.BadParameter(
'{} is not a maildir (missing {!r} sub-directory).'.... | [
"def",
"validate_maildirs",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"for",
"path",
"in",
"value",
":",
"for",
"subdir",
"in",
"MD_SUBDIRS",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path... | 41.666667 | 12.555556 |
def make_app(global_conf, full_stack=True, **app_conf):
"""Create a Pylons WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``full_stack``
Whether or not this applicat... | [
"def",
"make_app",
"(",
"global_conf",
",",
"full_stack",
"=",
"True",
",",
"*",
"*",
"app_conf",
")",
":",
"# Configure the Pylons environment\r",
"load_environment",
"(",
"global_conf",
",",
"app_conf",
")",
"# The Pylons WSGI app\r",
"app",
"=",
"PylonsApp",
"(",... | 35.655738 | 21.52459 |
def addFilteringOptions(parser, samfileIsPositionalArg=False):
"""
Add options to an argument parser for filtering SAM/BAM.
@param samfileIsPositionalArg: If C{True} the SAM/BAM file must
be given as the final argument on the command line (without
being preceded by --sam... | [
"def",
"addFilteringOptions",
"(",
"parser",
",",
"samfileIsPositionalArg",
"=",
"False",
")",
":",
"parser",
".",
"add_argument",
"(",
"'%ssamfile'",
"%",
"(",
"''",
"if",
"samfileIsPositionalArg",
"else",
"'--'",
")",
",",
"required",
"=",
"True",
",",
"help... | 44.40678 | 23.932203 |
def updateNewCredentialValues(self):
"""
Set the new credential values to the credentials to use, and delete the new ones
"""
credentials_base = "disk.0.os.credentials."
new_credentials_base = "disk.0.os.credentials.new."
for elem in ['password', 'public_key', 'private_... | [
"def",
"updateNewCredentialValues",
"(",
"self",
")",
":",
"credentials_base",
"=",
"\"disk.0.os.credentials.\"",
"new_credentials_base",
"=",
"\"disk.0.os.credentials.new.\"",
"for",
"elem",
"in",
"[",
"'password'",
",",
"'public_key'",
",",
"'private_key'",
"]",
":",
... | 44.333333 | 23.166667 |
def setup_logging(self):
"""
Configure the logging framework.
"""
if self.config.debug:
util.setup_logging(level=logging.DEBUG)
util.activate_debug_shell_on_signal()
else:
util.setup_logging(level=logging.INFO) | [
"def",
"setup_logging",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
".",
"debug",
":",
"util",
".",
"setup_logging",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"util",
".",
"activate_debug_shell_on_signal",
"(",
")",
"else",
":",
"util",
".... | 30.888889 | 9.333333 |
async def stop_async(self):
"""
Terminiates the partition manger.
"""
self.cancellation_token.cancel()
if self.run_task and not self.run_task.done():
await self.run_task | [
"async",
"def",
"stop_async",
"(",
"self",
")",
":",
"self",
".",
"cancellation_token",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"run_task",
"and",
"not",
"self",
".",
"run_task",
".",
"done",
"(",
")",
":",
"await",
"self",
".",
"run_task"
] | 30.714286 | 5.285714 |
def get_and_cache_account(self, addr):
"""Gets and caches an account for an addres, creates blank if not
found.
:param addr:
:return:
"""
if addr in self.cache:
return self.cache[addr]
rlpdata = self.secure_trie.get(addr)
if (
rlp... | [
"def",
"get_and_cache_account",
"(",
"self",
",",
"addr",
")",
":",
"if",
"addr",
"in",
"self",
".",
"cache",
":",
"return",
"self",
".",
"cache",
"[",
"addr",
"]",
"rlpdata",
"=",
"self",
".",
"secure_trie",
".",
"get",
"(",
"addr",
")",
"if",
"(",
... | 29.333333 | 16.416667 |
def lazy_send(chainlet, chunks):
"""
Canonical version of `chainlet_send` that always takes and returns an iterable
:param chainlet: the chainlet to receive and return data
:type chainlet: chainlink.ChainLink
:param chunks: the stream slice of data to pass to ``chainlet``
:type chunks: iterable... | [
"def",
"lazy_send",
"(",
"chainlet",
",",
"chunks",
")",
":",
"fork",
",",
"join",
"=",
"chainlet",
".",
"chain_fork",
",",
"chainlet",
".",
"chain_join",
"if",
"fork",
"and",
"join",
":",
"return",
"_send_n_get_m",
"(",
"chainlet",
",",
"chunks",
")",
"... | 36.3 | 18.1 |
def set_eep(self, data):
''' Update packet data based on EEP. Input data is a dictionary with keys corresponding to the EEP. '''
self._bit_data, self._bit_status = self.eep.set_values(self._profile, self._bit_data, self._bit_status, data) | [
"def",
"set_eep",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_bit_data",
",",
"self",
".",
"_bit_status",
"=",
"self",
".",
"eep",
".",
"set_values",
"(",
"self",
".",
"_profile",
",",
"self",
".",
"_bit_data",
",",
"self",
".",
"_bit_status",
... | 84 | 54.666667 |
def assert_not_equal(first, second, msg_fmt="{msg}"):
"""Fail if first equals second, as determined by the '==' operator.
>>> assert_not_equal(5, 8)
>>> assert_not_equal(-7, -7.0)
Traceback (most recent call last):
...
AssertionError: -7 == -7.0
The following msg_fmt arguments are supp... | [
"def",
"assert_not_equal",
"(",
"first",
",",
"second",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"if",
"first",
"==",
"second",
":",
"msg",
"=",
"\"{!r} == {!r}\"",
".",
"format",
"(",
"first",
",",
"second",
")",
"fail",
"(",
"msg_fmt",
".",
"format"... | 31.388889 | 14.944444 |
def _multi_value_field(self, field):
"""
Private method that returns `True` if a field is multi-valued, else
`False`.
Required arguemnts:
`field` -- The field to lookup
Returns a boolean value indicating whether the field is multi-valued.
"""
for fie... | [
"def",
"_multi_value_field",
"(",
"self",
",",
"field",
")",
":",
"for",
"field_dict",
"in",
"self",
".",
"schema",
":",
"if",
"field_dict",
"[",
"'field_name'",
"]",
"==",
"field",
":",
"return",
"field_dict",
"[",
"'multi_valued'",
"]",
"==",
"'true'",
"... | 32.928571 | 17.5 |
def listen_tta(self, target, timeout):
"""Listen *timeout* seconds for a Type A activation at 106 kbps. The
``sens_res``, ``sdd_res``, and ``sel_res`` response data must
be provided and ``sdd_res`` must be a 4 byte UID that starts
with ``08h``. Depending on ``sel_res`` an activation may
... | [
"def",
"listen_tta",
"(",
"self",
",",
"target",
",",
"timeout",
")",
":",
"return",
"super",
"(",
"Device",
",",
"self",
")",
".",
"listen_tta",
"(",
"target",
",",
"timeout",
")"
] | 53.545455 | 20.545455 |
def timeseries(self):
"""
Load time series
It returns the actual time series used in power flow analysis. If
:attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries()` looks for time series of the according sector in
:class:`~.grid.network.Ti... | [
"def",
"timeseries",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timeseries",
"is",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"grid",
",",
"MVGrid",
")",
":",
"voltage_level",
"=",
"'mv'",
"elif",
"isinstance",
"(",
"self",
".",
"grid",
",",
... | 34.964912 | 16.964912 |
def measures(*measurements, **kwargs):
"""Decorator-maker used to declare measurements for phases.
See the measurements module docstring for examples of usage.
Args:
measurements: Measurement objects to declare, or a string name from which
to create a Measurement.
kwargs: Keyword arguments to pa... | [
"def",
"measures",
"(",
"*",
"measurements",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_maybe_make",
"(",
"meas",
")",
":",
"\"\"\"Turn strings into Measurement objects if necessary.\"\"\"",
"if",
"isinstance",
"(",
"meas",
",",
"Measurement",
")",
":",
"return",... | 40.877551 | 23 |
def get_statement_queries(stmts, **params):
"""Get queries used to search based on a statement.
In addition to the stmts, you can enter any parameters standard to the
query. See https://github.com/indralab/indra_db/rest_api for a full list.
Parameters
----------
stmts : list[Statement]
... | [
"def",
"get_statement_queries",
"(",
"stmts",
",",
"*",
"*",
"params",
")",
":",
"def",
"pick_ns",
"(",
"ag",
")",
":",
"for",
"ns",
"in",
"[",
"'HGNC'",
",",
"'FPLX'",
",",
"'CHEMBL'",
",",
"'CHEBI'",
",",
"'GO'",
",",
"'MESH'",
"]",
":",
"if",
"n... | 35.02439 | 18.439024 |
def create_tumor_bamdir(tumor, tumor_bam, normal_bam, work_dir):
"""Create expected input directory with tumor/normal BAMs in one place.
"""
bam_dir = utils.safe_makedir(os.path.join(work_dir, tumor, "in_bams"))
normal_bam_ready = os.path.join(bam_dir, os.path.basename(normal_bam))
utils.symlink_plu... | [
"def",
"create_tumor_bamdir",
"(",
"tumor",
",",
"tumor_bam",
",",
"normal_bam",
",",
"work_dir",
")",
":",
"bam_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"tumor",
",",
"\"in_bams\"",
")",
")",
"n... | 56 | 16.666667 |
def cli(env, identifier, name, all, note):
"""Capture one or all disks from a virtual server to a SoftLayer image."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
capture = vsi.capture(vs_id, name, all, note)
table = formatting.KeyValueTable(... | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"name",
",",
"all",
",",
"note",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
... | 38.473684 | 18.052632 |
def set_attributes(self, **attributes):
""" Set group of attributes without calling set between attributes regardless of global auto_set.
Set will be called only after all attributes are set based on global auto_set.
:param attributes: dictionary of <attribute, value> to set.
"""
... | [
"def",
"set_attributes",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"auto_set",
"=",
"IxeObject",
".",
"get_auto_set",
"(",
")",
"IxeObject",
".",
"set_auto_set",
"(",
"False",
")",
"for",
"name",
",",
"value",
"in",
"attributes",
".",
"items",
... | 37.133333 | 16.2 |
def str(self,local):
""" Return the string representation of the time range
:param local: if False [default] use UTC datetime. If True use localtz
"""
s = self.start_time.str(local) \
+ u" to " \
+ self.end_time.str(local)
return s | [
"def",
"str",
"(",
"self",
",",
"local",
")",
":",
"s",
"=",
"self",
".",
"start_time",
".",
"str",
"(",
"local",
")",
"+",
"u\" to \"",
"+",
"self",
".",
"end_time",
".",
"str",
"(",
"local",
")",
"return",
"s"
] | 32.444444 | 16.111111 |
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
cmap:str=None, y:Any=None, **kwargs):
"Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y`"
cmap = ifnone(cmap, defaults.cmap)
ax = show_imag... | [
"def",
"show",
"(",
"self",
",",
"ax",
":",
"plt",
".",
"Axes",
"=",
"None",
",",
"figsize",
":",
"tuple",
"=",
"(",
"3",
",",
"3",
")",
",",
"title",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"hide_axis",
":",
"bool",
"=",
"True",
... | 68.142857 | 28.142857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.