text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def process_format(self, kind, context):
"""Handle transforming format string + arguments into Python code."""
result = None
while True:
chunk = yield result
if chunk is None:
return
# We need to split the expression defining the format string from the values to pass when formatting.
... | [
"def",
"process_format",
"(",
"self",
",",
"kind",
",",
"context",
")",
":",
"result",
"=",
"None",
"while",
"True",
":",
"chunk",
"=",
"yield",
"result",
"if",
"chunk",
"is",
"None",
":",
"return",
"# We need to split the expression defining the format string fro... | 36 | 0.041176 |
def update(self, **params):
"""
Sends locally staged mutations to Riak.
:param w: W-value, wait for this many partitions to respond
before returning to client.
:type w: integer
:param dw: DW-value, wait for this many partitions to
confirm the write before retur... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"self",
".",
"modified",
":",
"raise",
"ValueError",
"(",
"\"No operation to perform\"",
")",
"params",
".",
"setdefault",
"(",
"'return_body'",
",",
"True",
")",
"self",
".",
... | 38.064516 | 0.001653 |
def generate_examples(self):
"""
Returns complete dataset.
:return: the generated dataset
:rtype: Instances
"""
data = javabridge.call(self.jobject, "generateExamples", "()Lweka/core/Instances;")
if data is None:
return None
else:
... | [
"def",
"generate_examples",
"(",
"self",
")",
":",
"data",
"=",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"generateExamples\"",
",",
"\"()Lweka/core/Instances;\"",
")",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"else",
":",
"ret... | 27.583333 | 0.008772 |
def saelgv(vec1, vec2):
"""
Find semi-axis vectors of an ellipse generated by two arbitrary
three-dimensional vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/saelgv_c.html
:param vec1: First vector used to generate an ellipse.
:type vec1: 3-Element Array of floats
:param v... | [
"def",
"saelgv",
"(",
"vec1",
",",
"vec2",
")",
":",
"vec1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"vec1",
")",
"vec2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"vec2",
")",
"smajor",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"3",
")",
"smin... | 38.45 | 0.001269 |
def breakpoints( self ):
"""
Returns a list of lines that have breakpoints for this edit.
:return [<int>, ..]
"""
lines = []
result = self.markerFindNext(0, self._breakpointMarker + 1)
while ( result != -1 ):
lines.append(result)
... | [
"def",
"breakpoints",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"result",
"=",
"self",
".",
"markerFindNext",
"(",
"0",
",",
"self",
".",
"_breakpointMarker",
"+",
"1",
")",
"while",
"(",
"result",
"!=",
"-",
"1",
")",
":",
"lines",
".",
"appe... | 34.333333 | 0.018913 |
def moment_sequence(self):
r"""
Create a generator to calculate the population mean and
variance-convariance matrix for both :math:`x_t` and :math:`y_t`
starting at the initial condition (self.mu_0, self.Sigma_0).
Each iteration produces a 4-tuple of items (mu_x, mu_y, Sigma_x,
... | [
"def",
"moment_sequence",
"(",
"self",
")",
":",
"# == Simplify names == #",
"A",
",",
"C",
",",
"G",
",",
"H",
"=",
"self",
".",
"A",
",",
"self",
".",
"C",
",",
"self",
".",
"G",
",",
"self",
".",
"H",
"# == Initial moments == #",
"mu_x",
",",
"Sig... | 35.051282 | 0.001423 |
def parse_tag(self, dtype, count, offset_buf):
"""Interpret an Exif image tag data payload.
"""
try:
fmt = self.datatype2fmt[dtype][0] * count
payload_size = self.datatype2fmt[dtype][1] * count
except KeyError:
msg = 'Invalid TIFF tag datatype ({0}).'.... | [
"def",
"parse_tag",
"(",
"self",
",",
"dtype",
",",
"count",
",",
"offset_buf",
")",
":",
"try",
":",
"fmt",
"=",
"self",
".",
"datatype2fmt",
"[",
"dtype",
"]",
"[",
"0",
"]",
"*",
"count",
"payload_size",
"=",
"self",
".",
"datatype2fmt",
"[",
"dty... | 39.473684 | 0.001301 |
def stream_index(self, bucket, index, startkey, endkey=None,
return_terms=None, max_results=None, continuation=None,
timeout=None):
"""
Streams a secondary index query.
"""
raise NotImplementedError | [
"def",
"stream_index",
"(",
"self",
",",
"bucket",
",",
"index",
",",
"startkey",
",",
"endkey",
"=",
"None",
",",
"return_terms",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"continuation",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"r... | 38 | 0.014706 |
def traverse(self, node):
"""Traverse the document tree rooted at node.
node : docutil node
current root node to traverse
"""
self.find_replace(node)
for c in node.children:
self.traverse(c) | [
"def",
"traverse",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"find_replace",
"(",
"node",
")",
"for",
"c",
"in",
"node",
".",
"children",
":",
"self",
".",
"traverse",
"(",
"c",
")"
] | 24.111111 | 0.008889 |
def customize_ruleset(self, custom_ruleset_file=None):
"""
Updates the ruleset to include a set of custom rules. These rules will
be _added_ to the existing ruleset or replace the existing rule with
the same ID.
Args:
custom_ruleset_file (optional): The filepath to ... | [
"def",
"customize_ruleset",
"(",
"self",
",",
"custom_ruleset_file",
"=",
"None",
")",
":",
"custom_file",
"=",
"custom_ruleset_file",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"\"BOKCHOY_A11Y_CUSTOM_RULES_FILE\"",
")",
"if",
"not",
"custom_file",
":",
"return"... | 34.711538 | 0.001616 |
def im_set_topic(self, room_id, topic, **kwargs):
"""Sets the topic for the direct message"""
return self.__call_api_post('im.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) | [
"def",
"im_set_topic",
"(",
"self",
",",
"room_id",
",",
"topic",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'im.setTopic'",
",",
"roomId",
"=",
"room_id",
",",
"topic",
"=",
"topic",
",",
"kwargs",
"=",
"kwargs",
... | 64.666667 | 0.015306 |
def get_items(self, gos):
"""Given GO terms, return genes or gene products for the GOs."""
items = []
for go_id in gos:
items.extend(self.go2items.get(go_id, []))
return set(items) | [
"def",
"get_items",
"(",
"self",
",",
"gos",
")",
":",
"items",
"=",
"[",
"]",
"for",
"go_id",
"in",
"gos",
":",
"items",
".",
"extend",
"(",
"self",
".",
"go2items",
".",
"get",
"(",
"go_id",
",",
"[",
"]",
")",
")",
"return",
"set",
"(",
"ite... | 36.5 | 0.008929 |
def simplify(self, options=None):
"""
generate a simple dict representing this change data, and
collecting all of the sub-change instances (which are NOT
immediately simplified themselves)
"""
data = super(SuperChange, self).simplify(options)
show_ignored = Fals... | [
"def",
"simplify",
"(",
"self",
",",
"options",
"=",
"None",
")",
":",
"data",
"=",
"super",
"(",
"SuperChange",
",",
"self",
")",
".",
"simplify",
"(",
"options",
")",
"show_ignored",
"=",
"False",
"show_unchanged",
"=",
"False",
"if",
"options",
":",
... | 30.655172 | 0.002181 |
def parse_eggs_list(path):
"""Parse eggs list from the script at the given path
"""
with open(path, 'r') as script:
data = script.readlines()
start = 0
end = 0
for counter, line in enumerate(data):
if not start:
if 'sys.path[0:0]' in line:
... | [
"def",
"parse_eggs_list",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"script",
":",
"data",
"=",
"script",
".",
"readlines",
"(",
")",
"start",
"=",
"0",
"end",
"=",
"0",
"for",
"counter",
",",
"line",
"in",
"enumera... | 32.75 | 0.001855 |
def ManagedPreferenceProfile(self, data=None, subset=None):
"""{dynamic_docstring}"""
return self.factory.get_object(jssobjects.ManagedPreferenceProfile,
data, subset) | [
"def",
"ManagedPreferenceProfile",
"(",
"self",
",",
"data",
"=",
"None",
",",
"subset",
"=",
"None",
")",
":",
"return",
"self",
".",
"factory",
".",
"get_object",
"(",
"jssobjects",
".",
"ManagedPreferenceProfile",
",",
"data",
",",
"subset",
")"
] | 54.75 | 0.009009 |
def dots(it, label="", hide=None, every=1):
"""Progress iterator. Prints a dot for each item being iterated"""
count = 0
if not hide:
STREAM.write(label)
for i, item in enumerate(it):
if not hide:
if i % every == 0: # True every "every" updates
STREAM.write(D... | [
"def",
"dots",
"(",
"it",
",",
"label",
"=",
"\"\"",
",",
"hide",
"=",
"None",
",",
"every",
"=",
"1",
")",
":",
"count",
"=",
"0",
"if",
"not",
"hide",
":",
"STREAM",
".",
"write",
"(",
"label",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",... | 28.733333 | 0.002247 |
def realsorted(seq, key=None, reverse=False, alg=ns.DEFAULT):
"""
Convenience function to properly sort signed floats.
A signed float in a string could be "a-5.7". This is a wrapper around
``natsorted(seq, alg=ns.REAL)``.
The behavior of :func:`realsorted` for `natsort` version >= 4.0.0
was th... | [
"def",
"realsorted",
"(",
"seq",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"alg",
"=",
"ns",
".",
"DEFAULT",
")",
":",
"return",
"natsorted",
"(",
"seq",
",",
"key",
",",
"reverse",
",",
"alg",
"|",
"ns",
".",
"REAL",
")"
] | 29.960784 | 0.000634 |
def compute_overlayable_zorders(obj, path=[]):
"""
Traverses an overlayable composite container to determine which
objects are associated with specific (Nd)Overlay layers by
z-order, making sure to take DynamicMap Callables into
account. Returns a mapping between the zorders of each layer and a
... | [
"def",
"compute_overlayable_zorders",
"(",
"obj",
",",
"path",
"=",
"[",
"]",
")",
":",
"path",
"=",
"path",
"+",
"[",
"obj",
"]",
"zorder_map",
"=",
"defaultdict",
"(",
"list",
")",
"# Process non-dynamic layers",
"if",
"not",
"isinstance",
"(",
"obj",
",... | 42.824324 | 0.002159 |
def _ensure_parameters(self):
""" Attempts to load and verify the CTE node parameters. Will use
default values for all missing parameters, and raise an exception if
a parameter's value cannot be verified. This method will only
perform these actions once, and set the :attr:`_p... | [
"def",
"_ensure_parameters",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_parameters_checked\"",
")",
":",
"return",
"if",
"(",
"not",
"hasattr",
"(",
"self",
".",
"model",
",",
"\"_cte_node_table\"",
")",
"or",
"self",
".",
"model",
".",
... | 37.479167 | 0.002166 |
def CallState(self, next_state="", start_time=None):
"""This method is used to schedule a new state on a different worker.
This is basically the same as CallFlow() except we are calling
ourselves. The state will be invoked at a later time.
Args:
next_state: The state in this flow to be invoked.... | [
"def",
"CallState",
"(",
"self",
",",
"next_state",
"=",
"\"\"",
",",
"start_time",
"=",
"None",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"next_state",
")",
":",
"raise",
"ValueError",
"(",
"\"Next state %s is invalid.\"",
"%",
"next_state",
")",
... | 37.37037 | 0.001932 |
def circleconvert(amount, currentformat, newformat):
"""
Convert a circle measurement.
:type amount: number
:param amount: The number to convert.
:type currentformat: string
:param currentformat: The format of the provided value.
:type newformat: string
:param newformat: The intended ... | [
"def",
"circleconvert",
"(",
"amount",
",",
"currentformat",
",",
"newformat",
")",
":",
"# If the same format was provided",
"if",
"currentformat",
".",
"lower",
"(",
")",
"==",
"newformat",
".",
"lower",
"(",
")",
":",
"# Return the provided value",
"return",
"a... | 34.111111 | 0.000452 |
def replace_insight(self, project_key, insight_id, **kwargs):
"""Replace an insight.
:param project_key: Projrct identifier, in the form of
projectOwner/projectid
:type project_key: str
:param insight_id: Insight unique identifier.
:type insight_id: str
:param ti... | [
"def",
"replace_insight",
"(",
"self",
",",
"project_key",
",",
"insight_id",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"self",
".",
"__build_insight_obj",
"(",
"lambda",
":",
"_swagger",
".",
"InsightPutRequest",
"(",
"title",
"=",
"kwargs",
".",
... | 41.581818 | 0.000854 |
def set_default(self, section, option, default_value):
"""
Set Default value for a given (section, option)
-> called when a new (section, option) is set and no default exists
"""
section = self._check_section_option(section, option)
for sec, options in self.defaults... | [
"def",
"set_default",
"(",
"self",
",",
"section",
",",
"option",
",",
"default_value",
")",
":",
"section",
"=",
"self",
".",
"_check_section_option",
"(",
"section",
",",
"option",
")",
"for",
"sec",
",",
"options",
"in",
"self",
".",
"defaults",
":",
... | 44 | 0.009901 |
def dnld_ncbi_gene_file(fin, force_dnld=False, log=sys.stdout, loading_bar=True):
"""Download a file from NCBI Gene's ftp server."""
if not os.path.exists(fin) or force_dnld:
import gzip
fin_dir, fin_base = os.path.split(fin)
fin_gz = "{F}.gz".format(F=fin_base)
fin_gz = os.path.... | [
"def",
"dnld_ncbi_gene_file",
"(",
"fin",
",",
"force_dnld",
"=",
"False",
",",
"log",
"=",
"sys",
".",
"stdout",
",",
"loading_bar",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fin",
")",
"or",
"force_dnld",
":",
"imp... | 45.791667 | 0.008021 |
def filtany(entities, **kw):
"""Filter a set of entities based on method return. Use keyword arguments.
Example:
filtmeth(entities, id='123')
filtmeth(entities, name='bart')
Multiple filters are 'OR'.
"""
ret = set()
for k,v in kw.items():
for entity in entities:
if getattr(entity, k)(... | [
"def",
"filtany",
"(",
"entities",
",",
"*",
"*",
"kw",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"k",
",",
"v",
"in",
"kw",
".",
"items",
"(",
")",
":",
"for",
"entity",
"in",
"entities",
":",
"if",
"getattr",
"(",
"entity",
",",
"k",
")... | 23.333333 | 0.021978 |
def render_to_mail(subject, template, context, recipient, fail_silently = False, headers = None):
"""
:param subject: The subject line of the email
:param template: The name of the template to render the HTML email with
:param context: The context data to pass to the template
:param recipient: The e... | [
"def",
"render_to_mail",
"(",
"subject",
",",
"template",
",",
"context",
",",
"recipient",
",",
"fail_silently",
"=",
"False",
",",
"headers",
"=",
"None",
")",
":",
"if",
"'djcelery'",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"render_to_mail_task",
".",... | 36.848485 | 0.008013 |
def remove_volume(self):
""" Remove this volume
:return: None
"""
lvremove_cmd = ['sudo'] if self.lvm_command().sudo() is True else []
lvremove_cmd.extend(['lvremove', '-f', self.volume_path()])
subprocess.check_output(lvremove_cmd, timeout=self.__class__.__lvm_snapshot_remove_cmd_timeout__) | [
"def",
"remove_volume",
"(",
"self",
")",
":",
"lvremove_cmd",
"=",
"[",
"'sudo'",
"]",
"if",
"self",
".",
"lvm_command",
"(",
")",
".",
"sudo",
"(",
")",
"is",
"True",
"else",
"[",
"]",
"lvremove_cmd",
".",
"extend",
"(",
"[",
"'lvremove'",
",",
"'-... | 37.25 | 0.029508 |
def sync(ctx, scm, to_branch, verbose, fake):
"""Stashes unstaged changes, Fetches remote data, Performs smart
pull+merge, Pushes local commits up, and Unstashes changes.
Defaults to current branch.
"""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
... | [
"def",
"sync",
"(",
"ctx",
",",
"scm",
",",
"to_branch",
",",
"verbose",
",",
"fake",
")",
":",
"scm",
".",
"fake",
"=",
"fake",
"scm",
".",
"verbose",
"=",
"fake",
"or",
"verbose",
"scm",
".",
"repo_check",
"(",
"require_remote",
"=",
"True",
")",
... | 36.333333 | 0.001375 |
def restore_trash(cookie, tokens, fidlist):
'''从回收站中还原文件/目录.
fildlist - 要还原的文件/目录列表, fs_id.
'''
url = ''.join([
const.PAN_API_URL,
'recycle/restore?channel=chunlei&clienttype=0&web=1',
'&t=', util.timestamp(),
'&bdstoken=', tokens['bdstoken'],
])
data = 'fidlist=... | [
"def",
"restore_trash",
"(",
"cookie",
",",
"tokens",
",",
"fidlist",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_API_URL",
",",
"'recycle/restore?channel=chunlei&clienttype=0&web=1'",
",",
"'&t='",
",",
"util",
".",
"timestamp",
"(",... | 29.761905 | 0.00155 |
def _bracket_dim_suggest(self, variable):
"""Returns a dictionary of documentation for helping complete the
dimensions of a variable."""
if variable is not None:
#Look for <dimension> descriptors that are children of the variable
#in its docstrings.
dims = var... | [
"def",
"_bracket_dim_suggest",
"(",
"self",
",",
"variable",
")",
":",
"if",
"variable",
"is",
"not",
"None",
":",
"#Look for <dimension> descriptors that are children of the variable",
"#in its docstrings.",
"dims",
"=",
"variable",
".",
"doc_children",
"(",
"\"dimension... | 40 | 0.008997 |
def currentContentsWidget( self, autoadd = False ):
"""
Returns the current contents widget based on the cached index. If \
no widget is specified and autoadd is True, then a new widget will \
be added to the tab.
:param autoadd | <bool>
:r... | [
"def",
"currentContentsWidget",
"(",
"self",
",",
"autoadd",
"=",
"False",
")",
":",
"widget",
"=",
"self",
".",
"uiContentsTAB",
".",
"widget",
"(",
"self",
".",
"currentContentsIndex",
"(",
")",
")",
"if",
"(",
"not",
"isinstance",
"(",
"widget",
",",
... | 34.111111 | 0.025357 |
def denormalize(x:TensorImage, mean:FloatTensor,std:FloatTensor, do_x:bool=True)->TensorImage:
"Denormalize `x` with `mean` and `std`."
return x.cpu().float()*std[...,None,None] + mean[...,None,None] if do_x else x.cpu() | [
"def",
"denormalize",
"(",
"x",
":",
"TensorImage",
",",
"mean",
":",
"FloatTensor",
",",
"std",
":",
"FloatTensor",
",",
"do_x",
":",
"bool",
"=",
"True",
")",
"->",
"TensorImage",
":",
"return",
"x",
".",
"cpu",
"(",
")",
".",
"float",
"(",
")",
... | 75.333333 | 0.065789 |
def find_file(path):
"""
Given a path to a part in a zip file, return a path to the file and
the path to the part.
Assuming /foo.zipx exists as a file,
>>> find_file('/foo.zipx/dir/part') # doctest: +SKIP
('/foo.zipx', '/dir/part')
>>> find_file('/foo.zipx') # doctest: +SKIP
('/foo.zipx', '')
"""
path_comp... | [
"def",
"find_file",
"(",
"path",
")",
":",
"path_components",
"=",
"split_all",
"(",
"path",
")",
"def",
"get_assemblies",
"(",
")",
":",
"\"\"\"\n\t\tEnumerate the various combinations of file paths and part paths\n\t\t\"\"\"",
"for",
"n",
"in",
"range",
"(",
"len",
... | 27.230769 | 0.030014 |
def add_jars_for_targets(self, targets, conf, resolved_jars):
"""Adds jar classpath elements to the products of the provided targets.
The resolved jars are added in a way that works with excludes.
:param targets: The targets to add the jars for.
:param conf: The configuration.
:param resolved_jars:... | [
"def",
"add_jars_for_targets",
"(",
"self",
",",
"targets",
",",
"conf",
",",
"resolved_jars",
")",
":",
"classpath_entries",
"=",
"[",
"]",
"for",
"jar",
"in",
"resolved_jars",
":",
"if",
"not",
"jar",
".",
"pants_path",
":",
"raise",
"TaskError",
"(",
"'... | 44.411765 | 0.009079 |
def sample_greedy(self):
"""
Sample a point in the leaf with the max progress.
"""
if self.leafnode:
return self.sample_bounds()
else:
lp = self.lower.max_leaf_progress
gp = self.greater.max_leaf_progress
maxp =... | [
"def",
"sample_greedy",
"(",
"self",
")",
":",
"if",
"self",
".",
"leafnode",
":",
"return",
"self",
".",
"sample_bounds",
"(",
")",
"else",
":",
"lp",
"=",
"self",
".",
"lower",
".",
"max_leaf_progress",
"gp",
"=",
"self",
".",
"greater",
".",
"max_le... | 37.125 | 0.008753 |
async def _mogrify(conn, query, args):
"""Safely inline arguments to query text."""
# Introspect the target query for argument types and
# build a list of safely-quoted fully-qualified type names.
ps = await conn.prepare(query)
paramtypes = []
for t in ps.get_parameters():
if t.name.ends... | [
"async",
"def",
"_mogrify",
"(",
"conn",
",",
"query",
",",
"args",
")",
":",
"# Introspect the target query for argument types and",
"# build a list of safely-quoted fully-qualified type names.",
"ps",
"=",
"await",
"conn",
".",
"prepare",
"(",
"query",
")",
"paramtypes"... | 35.333333 | 0.00102 |
def valueAt(self, point):
"""
Returns the value within the chart for the given point.
:param point | <QPoint>
:return {<str> axis name: <variant> value, ..}
"""
chart_point = self.uiChartVIEW.mapFromParent(point)
scene_point = s... | [
"def",
"valueAt",
"(",
"self",
",",
"point",
")",
":",
"chart_point",
"=",
"self",
".",
"uiChartVIEW",
".",
"mapFromParent",
"(",
"point",
")",
"scene_point",
"=",
"self",
".",
"uiChartVIEW",
".",
"mapToScene",
"(",
"chart_point",
")",
"return",
"self",
".... | 37.727273 | 0.009412 |
def _load_outcome_models(self):
""" Create outcome models from core outcomes """
self.outcomes = []
for outcome in self.state.outcomes.values():
self._add_model(self.outcomes, outcome, OutcomeModel) | [
"def",
"_load_outcome_models",
"(",
"self",
")",
":",
"self",
".",
"outcomes",
"=",
"[",
"]",
"for",
"outcome",
"in",
"self",
".",
"state",
".",
"outcomes",
".",
"values",
"(",
")",
":",
"self",
".",
"_add_model",
"(",
"self",
".",
"outcomes",
",",
"... | 46 | 0.008547 |
def _CheckPythonModule(
module_name, version_attribute_name, minimum_version,
is_required=True, maximum_version=None, verbose_output=True):
"""Checks the availability of a Python module.
Args:
module_name (str): name of the module.
version_attribute_name (str): name of the attribute that contains
... | [
"def",
"_CheckPythonModule",
"(",
"module_name",
",",
"version_attribute_name",
",",
"minimum_version",
",",
"is_required",
"=",
"True",
",",
"maximum_version",
"=",
"None",
",",
"verbose_output",
"=",
"True",
")",
":",
"module_object",
"=",
"_ImportPythonModule",
"... | 35.389474 | 0.00897 |
def fetch_data(self):
"""Get the latest data from HydroQuebec."""
# Get http session
yield from self._get_httpsession()
# Get login page
login_url = yield from self._get_login_page()
# Post login page
yield from self._post_login_page(login_url)
# Get p_p_i... | [
"def",
"fetch_data",
"(",
"self",
")",
":",
"# Get http session",
"yield",
"from",
"self",
".",
"_get_httpsession",
"(",
")",
"# Get login page",
"login_url",
"=",
"yield",
"from",
"self",
".",
"_get_login_page",
"(",
")",
"# Post login page",
"yield",
"from",
"... | 42.864865 | 0.001541 |
def linearRegressionAnalysis(series):
"""
Returns factor and offset of linear regression function by least
squares method.
"""
n = safeLen(series)
sumI = sum([i for i, v in enumerate(series) if v is not None])
sumV = sum([v for i, v in enumerate(series) if v is not None])
sumII = sum([i... | [
"def",
"linearRegressionAnalysis",
"(",
"series",
")",
":",
"n",
"=",
"safeLen",
"(",
"series",
")",
"sumI",
"=",
"sum",
"(",
"[",
"i",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"series",
")",
"if",
"v",
"is",
"not",
"None",
"]",
")",
"sumV",
... | 38.894737 | 0.001321 |
def random_letter(self):
"""Returns a random letter (between a-z and A-Z)."""
return self.generator.random.choice(
getattr(string, 'letters', string.ascii_letters)) | [
"def",
"random_letter",
"(",
"self",
")",
":",
"return",
"self",
".",
"generator",
".",
"random",
".",
"choice",
"(",
"getattr",
"(",
"string",
",",
"'letters'",
",",
"string",
".",
"ascii_letters",
")",
")"
] | 47.25 | 0.010417 |
def _is_convertible_to_index(other):
"""
return a boolean whether I can attempt conversion to a TimedeltaIndex
"""
if isinstance(other, TimedeltaIndex):
return True
elif (len(other) > 0 and
other.inferred_type not in ('floating', 'mixed-integer', 'integer',
... | [
"def",
"_is_convertible_to_index",
"(",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"TimedeltaIndex",
")",
":",
"return",
"True",
"elif",
"(",
"len",
"(",
"other",
")",
">",
"0",
"and",
"other",
".",
"inferred_type",
"not",
"in",
"(",
"'flo... | 35.818182 | 0.002475 |
def mkneighbors_graph(observations, n_neighbours, metric, mode='connectivity', metric_params = None):
"""
Computes the (weighted) graph of mutual k-Neighbors for observations.
Notes
-----
The distance between an observation and itself is never computed and instead set to
``numpy.inf``. I.e.... | [
"def",
"mkneighbors_graph",
"(",
"observations",
",",
"n_neighbours",
",",
"metric",
",",
"mode",
"=",
"'connectivity'",
",",
"metric_params",
"=",
"None",
")",
":",
"# compute their pairwise-distances",
"pdists",
"=",
"pdist",
"(",
"observations",
",",
"metric",
... | 41.683333 | 0.008594 |
def consult(string_in):
"""
provide file:consult/1 functionality with python types
"""
# pylint: disable=eval-used
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# manually parse textual erlang data to avoid external dependencies
list_out = []
tuple_binary... | [
"def",
"consult",
"(",
"string_in",
")",
":",
"# pylint: disable=eval-used",
"# pylint: disable=too-many-branches",
"# pylint: disable=too-many-statements",
"# manually parse textual erlang data to avoid external dependencies",
"list_out",
"=",
"[",
"]",
"tuple_binary",
"=",
"False",... | 33.540541 | 0.000391 |
def destroy(vm_name, call=None):
'''
Call 'destroy' on the instance. Can be called with "-a destroy" or -d
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance1 myinstance2 ...
salt-cloud -d myinstance1 myinstance2 ...
'''
if call and call != 'action':
r... | [
"def",
"destroy",
"(",
"vm_name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"and",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d or \"-a destroy\".'",
")",
"conn",
"=",
"get_conn",
"(",
")",... | 34.631579 | 0.000739 |
def get_cursor(source, spelling):
"""Obtain a cursor from a source object.
This provides a convenient search mechanism to find a cursor with specific
spelling within a source. The first argument can be either a
TranslationUnit or Cursor instance.
If the cursor is not found, None is returned.
"... | [
"def",
"get_cursor",
"(",
"source",
",",
"spelling",
")",
":",
"children",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"source",
",",
"Cursor",
")",
":",
"children",
"=",
"source",
".",
"get_children",
"(",
")",
"else",
":",
"# Assume TU",
"children",
"=",
... | 27.615385 | 0.001346 |
def _is_exception(exceptions, before_token, after_token, token):
"""Predicate for whether the open token is in an exception context
:arg exceptions: list of strings or None
:arg before_token: the text of the function up to the token delimiter
:arg after_token: the text of the function after the token d... | [
"def",
"_is_exception",
"(",
"exceptions",
",",
"before_token",
",",
"after_token",
",",
"token",
")",
":",
"if",
"not",
"exceptions",
":",
"return",
"False",
"for",
"s",
"in",
"exceptions",
":",
"if",
"before_token",
".",
"endswith",
"(",
"s",
")",
":",
... | 31.736842 | 0.00161 |
def render_row(num, columns, widths, column_colors=None):
"""
Render the `num`th row of each column in `columns`.
:param num: Which row to render.
:type num: ``int``
:param columns: The list of columns.
:type columns: [[``str``]]
:param widths: The widths of each column.
:type widths: [... | [
"def",
"render_row",
"(",
"num",
",",
"columns",
",",
"widths",
",",
"column_colors",
"=",
"None",
")",
":",
"row_str",
"=",
"'|'",
"cell_strs",
"=",
"[",
"]",
"for",
"i",
",",
"column",
"in",
"enumerate",
"(",
"columns",
")",
":",
"try",
":",
"cell"... | 37.548387 | 0.000838 |
def wrapAtom(xml, id, title, author=None, updated=None, author_uri=None,
alt=None, alt_type="text/html"):
"""
Create an Atom entry tag and embed the passed XML within it
"""
entryTag = etree.Element(ATOM + "entry", nsmap=ATOM_NSMAP)
titleTag = etree.SubElement(entryTag, ATOM + "title")... | [
"def",
"wrapAtom",
"(",
"xml",
",",
"id",
",",
"title",
",",
"author",
"=",
"None",
",",
"updated",
"=",
"None",
",",
"author_uri",
"=",
"None",
",",
"alt",
"=",
"None",
",",
"alt_type",
"=",
"\"text/html\"",
")",
":",
"entryTag",
"=",
"etree",
".",
... | 36.609756 | 0.000649 |
def get_content(self, url, params=None, limit=0, place_holder=None,
root_field='data', thing_field='children',
after_field='after', object_filter=None, **kwargs):
"""A generator method to return reddit content from a URL.
Starts at the initial url, and fetches co... | [
"def",
"get_content",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"limit",
"=",
"0",
",",
"place_holder",
"=",
"None",
",",
"root_field",
"=",
"'data'",
",",
"thing_field",
"=",
"'children'",
",",
"after_field",
"=",
"'after'",
",",
"object... | 50.240964 | 0.000941 |
def get_iscsi_initiator_info(self):
"""Give iSCSI initiator information of iLO.
:returns: iSCSI initiator information.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the BIOS boot mode.
"""
sushy_... | [
"def",
"get_iscsi_initiator_info",
"(",
"self",
")",
":",
"sushy_system",
"=",
"self",
".",
"_get_sushy_system",
"(",
"PROLIANT_SYSTEM_ID",
")",
"if",
"(",
"self",
".",
"_is_boot_mode_uefi",
"(",
")",
")",
":",
"try",
":",
"iscsi_initiator",
"=",
"(",
"sushy_s... | 44.695652 | 0.001905 |
def _get_qemu_img_version(qemu_img_path):
"""
Gets the Qemu-img version.
:param qemu_img_path: path to Qemu-img executable.
"""
try:
output = yield from subprocess_check_output(qemu_img_path, "--version")
match = re.search("version\s+([0-9a-z\-\.]+)", ou... | [
"def",
"_get_qemu_img_version",
"(",
"qemu_img_path",
")",
":",
"try",
":",
"output",
"=",
"yield",
"from",
"subprocess_check_output",
"(",
"qemu_img_path",
",",
"\"--version\"",
")",
"match",
"=",
"re",
".",
"search",
"(",
"\"version\\s+([0-9a-z\\-\\.]+)\"",
",",
... | 39.058824 | 0.011765 |
def Inventory(cls):
"""
Returns a list of Server instances, one for each Server object
persisted in the db
"""
l = ServerSet()
rs = cls.find()
for server in rs:
l.append(server)
return l | [
"def",
"Inventory",
"(",
"cls",
")",
":",
"l",
"=",
"ServerSet",
"(",
")",
"rs",
"=",
"cls",
".",
"find",
"(",
")",
"for",
"server",
"in",
"rs",
":",
"l",
".",
"append",
"(",
"server",
")",
"return",
"l"
] | 25.3 | 0.01145 |
def mod_box_for_rotation(box, angle, undo=False):
"""The user sees left, bottom, right, and top margins on a page, but inside
the PDF and in pyPdf the page may be rotated (such as in landscape mode).
In the case of 90 degree clockwise rotation the left really modifies the
top, the top really modifies ri... | [
"def",
"mod_box_for_rotation",
"(",
"box",
",",
"angle",
",",
"undo",
"=",
"False",
")",
":",
"def",
"rotate_ninety_degrees_clockwise",
"(",
"box",
",",
"n",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"box",
"box",
"=",
"rotate_ninety_degrees_clockwise",... | 45.681818 | 0.001949 |
def insertDataset(self, businput):
"""
input dictionary must have the following keys:
dataset, primary_ds_name(name), processed_ds(name), data_tier(name),
acquisition_era(name), processing_version
It may have following keys:
physics_group(name), xtcrosssection, creation_d... | [
"def",
"insertDataset",
"(",
"self",
",",
"businput",
")",
":",
"if",
"not",
"(",
"\"primary_ds_name\"",
"in",
"businput",
"and",
"\"dataset\"",
"in",
"businput",
"and",
"\"dataset_access_type\"",
"in",
"businput",
"and",
"\"processed_ds_name\"",
"in",
"businput",
... | 65.28 | 0.010261 |
def _generate_soma(self):
'''soma'''
radius = self._obj.soma.radius
return _square_segment(radius, (0., -radius)) | [
"def",
"_generate_soma",
"(",
"self",
")",
":",
"radius",
"=",
"self",
".",
"_obj",
".",
"soma",
".",
"radius",
"return",
"_square_segment",
"(",
"radius",
",",
"(",
"0.",
",",
"-",
"radius",
")",
")"
] | 33.5 | 0.014599 |
def manifest(self):
"""The manifest definition of the stencilset as a dict."""
if not self._manifest:
with open(self.manifest_path) as man:
self._manifest = json.load(man)
return self._manifest | [
"def",
"manifest",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_manifest",
":",
"with",
"open",
"(",
"self",
".",
"manifest_path",
")",
"as",
"man",
":",
"self",
".",
"_manifest",
"=",
"json",
".",
"load",
"(",
"man",
")",
"return",
"self",
"... | 40 | 0.008163 |
def build_rrule_from_dateutil_rrule(rule):
"""
Build rrule dictionary for vRecur class from a dateutil rrule.
Dateutils rrule is a popular implementation of rrule in python.
https://pypi.org/project/python-dateutil/
this is a shortcut to interface between dateutil and icalendar.
"""
lines =... | [
"def",
"build_rrule_from_dateutil_rrule",
"(",
"rule",
")",
":",
"lines",
"=",
"str",
"(",
"rule",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"startswith",
"(",
"'DTSTART:'",
")",
":",
"continue",
"if",
"line"... | 34.8 | 0.001866 |
def add_argument(self, parser, permissive=False, **override_kwargs):
"""Add an option to a an argparse parser.
:keyword permissive: when true, build a parser that does not validate
required arguments.
"""
kwargs = {}
required = None
if self.kwargs:
... | [
"def",
"add_argument",
"(",
"self",
",",
"parser",
",",
"permissive",
"=",
"False",
",",
"*",
"*",
"override_kwargs",
")",
":",
"kwargs",
"=",
"{",
"}",
"required",
"=",
"None",
"if",
"self",
".",
"kwargs",
":",
"kwargs",
"=",
"copy",
".",
"copy",
"(... | 44.96875 | 0.00068 |
def attr_sep(self, new_sep: str) -> None:
"""Set the new value for the attribute separator.
When the new value is assigned a new tree is generated.
"""
self._attr_sep = new_sep
self._filters_tree = self._generate_filters_tree() | [
"def",
"attr_sep",
"(",
"self",
",",
"new_sep",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_attr_sep",
"=",
"new_sep",
"self",
".",
"_filters_tree",
"=",
"self",
".",
"_generate_filters_tree",
"(",
")"
] | 38.571429 | 0.01087 |
def _get_geometry(self):
""" Creates a multipolygon of bounding box polygons
"""
return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list]) | [
"def",
"_get_geometry",
"(",
"self",
")",
":",
"return",
"shapely",
".",
"geometry",
".",
"MultiPolygon",
"(",
"[",
"bbox",
".",
"geometry",
"for",
"bbox",
"in",
"self",
".",
"bbox_list",
"]",
")"
] | 45.5 | 0.016216 |
def sendstop(self):
'''
Kill process (:meth:`subprocess.Popen.terminate`).
Do not wait for command to complete.
:rtype: self
'''
if not self.is_started:
raise EasyProcessError(self, 'process was not started!')
log.debug('stopping process (pid=%s cmd=... | [
"def",
"sendstop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_started",
":",
"raise",
"EasyProcessError",
"(",
"self",
",",
"'process was not started!'",
")",
"log",
".",
"debug",
"(",
"'stopping process (pid=%s cmd=\"%s\")'",
",",
"self",
".",
"pid",
... | 31.448276 | 0.002128 |
def download(sc, age=0, path='reports', **args):
'''Report Downloader
The report downloader will pull reports down from SecurityCenter
based on the conditions provided to the path provided.
sc = SecurityCenter5 object
age = number of days old the report may be to be included in the
... | [
"def",
"download",
"(",
"sc",
",",
"age",
"=",
"0",
",",
"path",
"=",
"'reports'",
",",
"*",
"*",
"args",
")",
":",
"# if the download path doesn't exist, we need to create it.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"logger... | 41.19697 | 0.001078 |
def ReadFlowLogEntries(self,
client_id,
flow_id,
offset,
count,
with_substring=None,
cursor=None):
"""Reads flow log entries of a given flow using given query options... | [
"def",
"ReadFlowLogEntries",
"(",
"self",
",",
"client_id",
",",
"flow_id",
",",
"offset",
",",
"count",
",",
"with_substring",
"=",
"None",
",",
"cursor",
"=",
"None",
")",
":",
"query",
"=",
"(",
"\"SELECT message, UNIX_TIMESTAMP(timestamp) \"",
"\"FROM flow_log... | 32.606061 | 0.009025 |
def fromScratch(self):
"""Start a fresh experiment, from scratch.
Returns `self`."""
assert(not os.path.lexists(self.latestLink) or
os.path.islink (self.latestLink))
self.rmR(self.latestLink)
return self | [
"def",
"fromScratch",
"(",
"self",
")",
":",
"assert",
"(",
"not",
"os",
".",
"path",
".",
"lexists",
"(",
"self",
".",
"latestLink",
")",
"or",
"os",
".",
"path",
".",
"islink",
"(",
"self",
".",
"latestLink",
")",
")",
"self",
".",
"rmR",
"(",
... | 24.888889 | 0.064655 |
def dec(self,*args,**kwargs):
"""
NAME:
dec
PURPOSE:
return the declination
INPUT:
t - (optional) time at which to get dec
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
... | [
"def",
"dec",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_roSet",
"(",
"self",
",",
"kwargs",
",",
"'dec'",
")",
"radec",
"=",
"self",
".",
"_radec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"radec",... | 34.909091 | 0.013942 |
def replace(oldEl, newEl):
# type: (Union[Rule, _RuleConnectable], Union[Rule, _RuleConnectable]) -> Union[Rule, _RuleConnectable]
"""
Replace element in the parsed tree. Can be nonterminal, terminal or rule.
:param oldEl: Element already in the tree.
:param newEl: Element to rep... | [
"def",
"replace",
"(",
"oldEl",
",",
"newEl",
")",
":",
"# type: (Union[Rule, _RuleConnectable], Union[Rule, _RuleConnectable]) -> Union[Rule, _RuleConnectable]",
"if",
"isinstance",
"(",
"oldEl",
",",
"Rule",
")",
":",
"return",
"Manipulations",
".",
"replaceRule",
"(",
... | 49.25 | 0.008306 |
def get_resolve_diff(self, other):
"""Get the difference between the resolve in this context and another.
The difference is described from the point of view of the current context
- a newer package means that the package in `other` is newer than the
package in `self`.
Diffs can... | [
"def",
"get_resolve_diff",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"package_paths",
"!=",
"other",
".",
"package_paths",
":",
"from",
"difflib",
"import",
"ndiff",
"diff",
"=",
"ndiff",
"(",
"self",
".",
"package_paths",
",",
"other",
".",
... | 43.070588 | 0.001068 |
def encode(data):
'''
bytes -> str
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
data = convertbits(data, 8, 5)
checksum = calculate_checksum(riemann.net... | [
"def",
"encode",
"(",
"data",
")",
":",
"if",
"riemann",
".",
"network",
".",
"CASHADDR_PREFIX",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Network {} does not support cashaddresses.'",
".",
"format",
"(",
"riemann",
".",
"get_current_network_name",
"(",
")"... | 29.588235 | 0.001927 |
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
early_stopping_rounds=None, verbose=True):
# pylint: disable = attribute-defined-outside-init,arguments-differ
"""
Fit gradient boosting classifier
Parameters
----------
X : array_like
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
",",
"eval_set",
"=",
"None",
",",
"eval_metric",
"=",
"None",
",",
"early_stopping_rounds",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"# pylint: disable = attribut... | 43.711111 | 0.00174 |
def parse_filename(fname):
"""Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* notebook.json -> (notebook.json, no... | [
"def",
"parse_filename",
"(",
"fname",
")",
":",
"if",
"fname",
".",
"endswith",
"(",
"u'.ipynb'",
")",
":",
"format",
"=",
"u'json'",
"elif",
"fname",
".",
"endswith",
"(",
"u'.json'",
")",
":",
"format",
"=",
"u'json'",
"elif",
"fname",
".",
"endswith"... | 30.514286 | 0.000907 |
def _write_to_pipette(self, gcode, mount, data_string):
'''
Write to an attached pipette's internal memory. The gcode used
determines which portion of memory is written to.
NOTE: To enable write-access to the pipette, it's button must be held
gcode:
String (str) con... | [
"def",
"_write_to_pipette",
"(",
"self",
",",
"gcode",
",",
"mount",
",",
"data_string",
")",
":",
"allowed_mounts",
"=",
"{",
"'left'",
":",
"'L'",
",",
"'right'",
":",
"'R'",
"}",
"mount",
"=",
"allowed_mounts",
".",
"get",
"(",
"mount",
")",
"if",
"... | 44.588235 | 0.001291 |
def _init_transformer_cache(cache, hparams, batch_size, attention_init_length,
encoder_output, encoder_decoder_attention_bias,
scope_prefix):
"""Create the initial cache for Transformer fast decoding."""
key_channels = hparams.attention_key_channels or hparams... | [
"def",
"_init_transformer_cache",
"(",
"cache",
",",
"hparams",
",",
"batch_size",
",",
"attention_init_length",
",",
"encoder_output",
",",
"encoder_decoder_attention_bias",
",",
"scope_prefix",
")",
":",
"key_channels",
"=",
"hparams",
".",
"attention_key_channels",
"... | 43.360656 | 0.008133 |
def get_object(self, queryset=None):
""" Returns the considered object. """
profile, dummy = ForumProfile.objects.get_or_create(user=self.request.user)
return profile | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"profile",
",",
"dummy",
"=",
"ForumProfile",
".",
"objects",
".",
"get_or_create",
"(",
"user",
"=",
"self",
".",
"request",
".",
"user",
")",
"return",
"profile"
] | 46.75 | 0.015789 |
def get_bool(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string`.
"""
return get_bool_raw(get_string(strings, prefix,
... | [
"def",
"get_bool",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"return",... | 42 | 0.002331 |
def polar_to_cart(arr_p):
"""Return polar vectors in their cartesian representation.
Parameters
----------
arr_p: array, shape (a1, a2, ..., d)
Polar vectors, with last axis indexing the dimension,
using (radius, inclination, azimuth) convention.
Returns
-------
arr_c: arra... | [
"def",
"polar_to_cart",
"(",
"arr_p",
")",
":",
"if",
"arr_p",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"arr_c",
"=",
"arr_p",
".",
"copy",
"(",
")",
"elif",
"arr_p",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"2",
":",
"arr_c",
"=",
"n... | 33.833333 | 0.000958 |
def asBinary(self):
"""Get |ASN.1| value as a text string of bits.
"""
binString = binary.bin(self._value)[2:]
return '0' * (len(self._value) - len(binString)) + binString | [
"def",
"asBinary",
"(",
"self",
")",
":",
"binString",
"=",
"binary",
".",
"bin",
"(",
"self",
".",
"_value",
")",
"[",
"2",
":",
"]",
"return",
"'0'",
"*",
"(",
"len",
"(",
"self",
".",
"_value",
")",
"-",
"len",
"(",
"binString",
")",
")",
"+... | 39.8 | 0.009852 |
def analysis(self):
"""The list of analysis of ``words`` layer elements."""
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
return [word[ANALYSIS] for word in self.words] | [
"def",
"analysis",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"ANALYSIS",
")",
":",
"self",
".",
"tag_analysis",
"(",
")",
"return",
"[",
"word",
"[",
"ANALYSIS",
"]",
"for",
"word",
"in",
"self",
".",
"words",
"]"
] | 41.4 | 0.009479 |
def compute_bootci(x, y=None, func='pearson', method='cper', paired=False,
confidence=.95, n_boot=2000, decimals=2, seed=None,
return_dist=False):
"""Bootstrapped confidence intervals of univariate and bivariate functions.
Parameters
----------
x : 1D-array or list... | [
"def",
"compute_bootci",
"(",
"x",
",",
"y",
"=",
"None",
",",
"func",
"=",
"'pearson'",
",",
"method",
"=",
"'cper'",
",",
"paired",
"=",
"False",
",",
"confidence",
"=",
".95",
",",
"n_boot",
"=",
"2000",
",",
"decimals",
"=",
"2",
",",
"seed",
"... | 32.426606 | 0.000137 |
def f_add_parameter(self, *args, **kwargs):
""" Adds a parameter under the current node.
There are two ways to add a new parameter either by adding a parameter instance:
>>> new_parameter = Parameter('group1.group2.myparam', data=42, comment='Example!')
>>> traj.f_add_parameter(new_par... | [
"def",
"f_add_parameter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_nn_interface",
".",
"_add_generic",
"(",
"self",
",",
"type_name",
"=",
"PARAMETER",
",",
"group_type_name",
"=",
"PARAMETER_GROUP",
",",
"... | 46.875 | 0.008491 |
def print_attr_values( thing, all=False, heading=None, file=None ):
'''
Print the attributes of thing which have non-empty values,
as a vertical list of "name : value". When all=True, print
all attributes even those with empty values.
'''
if heading :
if isinstance( heading, int ) :
... | [
"def",
"print_attr_values",
"(",
"thing",
",",
"all",
"=",
"False",
",",
"heading",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"if",
"heading",
":",
"if",
"isinstance",
"(",
"heading",
",",
"int",
")",
":",
"# request for default heading",
"heading",... | 38.428571 | 0.025393 |
def get_instance(jar_filename=None, version=None,
download_if_missing=True, backend='jpype',
**extra_args):
"""This is the typical mechanism of constructing a
StanfordDependencies instance. The backend parameter determines
which backend to load (currentl... | [
"def",
"get_instance",
"(",
"jar_filename",
"=",
"None",
",",
"version",
"=",
"None",
",",
"download_if_missing",
"=",
"True",
",",
"backend",
"=",
"'jpype'",
",",
"*",
"*",
"extra_args",
")",
":",
"StanfordDependencies",
".",
"_raise_on_bad_jar_filename",
"(",
... | 50.666667 | 0.001434 |
def apply(self, word, ctx=None):
""" ignore ctx information right now """
chars = get_letters(word)
flag = True #no error assumed
reason = None #no reason
prev_char = None
for char in chars:
rule1,rule2,rule3 = False,False,False
# rule 1 : uyir fo... | [
"def",
"apply",
"(",
"self",
",",
"word",
",",
"ctx",
"=",
"None",
")",
":",
"chars",
"=",
"get_letters",
"(",
"word",
")",
"flag",
"=",
"True",
"#no error assumed",
"reason",
"=",
"None",
"#no reason",
"prev_char",
"=",
"None",
"for",
"char",
"in",
"c... | 46.037037 | 0.017336 |
def remove_capability(capability, image=None, restart=False):
'''
Uninstall a capability
Args:
capability(str): The capability to be removed
image (Optional[str]): The path to the root directory of an offline
Windows image. If `None` is passed, the running operating system is
... | [
"def",
"remove_capability",
"(",
"capability",
",",
"image",
"=",
"None",
",",
"restart",
"=",
"False",
")",
":",
"if",
"salt",
".",
"utils",
".",
"versions",
".",
"version_cmp",
"(",
"__grains__",
"[",
"'osversion'",
"]",
",",
"'10'",
")",
"==",
"-",
... | 33.384615 | 0.001493 |
def callToThread(method):
""" Wrap call to method to send it to WebCacheThread. """
def func_wrapped(self, *args, **kwargs):
self.thread.execute_queue.put_nowait((threading.get_ident(), method, args, kwargs))
return self.waitResult()
return func_wrapped | [
"def",
"callToThread",
"(",
"method",
")",
":",
"def",
"func_wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"thread",
".",
"execute_queue",
".",
"put_nowait",
"(",
"(",
"threading",
".",
"get_ident",
"(",
")",
... | 45.333333 | 0.01444 |
def get_terminal_size():
"""Get (width, height) of the current terminal."""
try:
import fcntl, termios, struct # fcntl module only available on Unix
return struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234'))
except:
return (40, 80) | [
"def",
"get_terminal_size",
"(",
")",
":",
"try",
":",
"import",
"fcntl",
",",
"termios",
",",
"struct",
"# fcntl module only available on Unix",
"return",
"struct",
".",
"unpack",
"(",
"'hh'",
",",
"fcntl",
".",
"ioctl",
"(",
"1",
",",
"termios",
".",
"TIOC... | 39 | 0.014337 |
def dnld_assc(assc_name, go2obj=None, prt=sys.stdout):
"""Download association from http://geneontology.org/gene-associations."""
# Example assc_name: "tair.gaf"
# Download the Association
dirloc, assc_base = os.path.split(assc_name)
if not dirloc:
dirloc = os.getcwd()
assc_locfile = os.... | [
"def",
"dnld_assc",
"(",
"assc_name",
",",
"go2obj",
"=",
"None",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"# Example assc_name: \"tair.gaf\"",
"# Download the Association",
"dirloc",
",",
"assc_base",
"=",
"os",
".",
"path",
".",
"split",
"(",
"assc_n... | 40.157895 | 0.00128 |
def update(self, adgroup_id, catmatch_id, max_price, is_default_price, online_status, nick=None):
'''xxxxx.xxxxx.adgroup.catmatch.update
===================================
更新一个推广组的类目出价,可以设置类目出价、是否使用默认出价、是否打开类目出价'''
request = TOPRequest('xxxxx.xxxxx.adgroup.catmatch.update')
requ... | [
"def",
"update",
"(",
"self",
",",
"adgroup_id",
",",
"catmatch_id",
",",
"max_price",
",",
"is_default_price",
",",
"online_status",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.adgroup.catmatch.update'",
")",
"request",
... | 57.615385 | 0.015769 |
def setHighlightColor(self, color):
"""
Sets the color to be used when highlighting a node.
:param color <QColor> || None
"""
color = QColor(color)
if self._palette is None:
self._palette = XNodePalette(self._scenePalette)
... | [
"def",
"setHighlightColor",
"(",
"self",
",",
"color",
")",
":",
"color",
"=",
"QColor",
"(",
"color",
")",
"if",
"self",
".",
"_palette",
"is",
"None",
":",
"self",
".",
"_palette",
"=",
"XNodePalette",
"(",
"self",
".",
"_scenePalette",
")",
"self",
... | 32.583333 | 0.00995 |
def strip_optional_suffix(string, suffix, log=None):
"""
>>> strip_optional_suffix('abcdef', 'def')
'abc'
>>> strip_optional_suffix('abcdef', '123')
'abcdef'
>>> strip_optional_suffix('abcdef', '123', PrintingLogger())
String ends with 'def', not '123'
'abcdef'
"""
if string.ends... | [
"def",
"strip_optional_suffix",
"(",
"string",
",",
"suffix",
",",
"log",
"=",
"None",
")",
":",
"if",
"string",
".",
"endswith",
"(",
"suffix",
")",
":",
"return",
"string",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"]",
"if",
"log",
":",
"log",
"... | 31 | 0.002088 |
def attach_container(self, path=None, save="all",
mode="w", nbuffer=50, force=False):
"""add a Container to the simulation which allows some
persistance to the simulation.
Parameters
----------
path : str or None (default: None)
path for the ... | [
"def",
"attach_container",
"(",
"self",
",",
"path",
"=",
"None",
",",
"save",
"=",
"\"all\"",
",",
"mode",
"=",
"\"w\"",
",",
"nbuffer",
"=",
"50",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"_container",
"=",
"TriflowContainer",
"(",
"\"%s/%s... | 46 | 0.002129 |
def _8bit_oper(op1, op2=None, reversed_=False):
""" Returns pop sequence for 8 bits operands
1st operand in H, 2nd operand in A (accumulator)
For some operations (like comparisons), you can swap
operands extraction by setting reversed = True
"""
output = []
if op2 is not None and reversed_... | [
"def",
"_8bit_oper",
"(",
"op1",
",",
"op2",
"=",
"None",
",",
"reversed_",
"=",
"False",
")",
":",
"output",
"=",
"[",
"]",
"if",
"op2",
"is",
"not",
"None",
"and",
"reversed_",
":",
"tmp",
"=",
"op1",
"op1",
"=",
"op2",
"op2",
"=",
"tmp",
"op",... | 24.647059 | 0.000382 |
def main(argv=None):
"""ben-csv entry point"""
arguments = cli_common(__doc__, argv=argv)
csv_export = CSVExporter(arguments['CAMPAIGN-DIR'], arguments['--output'])
if arguments['--peek']:
csv_export.peek()
else:
fieldsstr = arguments.get('--fields')
fields = fieldsstr.split(... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"csv_export",
"=",
"CSVExporter",
"(",
"arguments",
"[",
"'CAMPAIGN-DIR'",
"]",
",",
"arguments",
"[",
"'--output'",
"]",
")... | 35.083333 | 0.002315 |
def get_temp_filename(suffix=None):
""" return a string in the form of temp_X, where X is a large integer """
file = tempfile.mkstemp(suffix=suffix or "", prefix="temp_", dir=os.getcwd()) # or "" for Python 2 compatibility
os.close(file[0])
return file[1] | [
"def",
"get_temp_filename",
"(",
"suffix",
"=",
"None",
")",
":",
"file",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"suffix",
"or",
"\"\"",
",",
"prefix",
"=",
"\"temp_\"",
",",
"dir",
"=",
"os",
".",
"getcwd",
"(",
")",
")",
"# or \"\" for ... | 53.4 | 0.01107 |
def emit_arg(keywordstr, stmt, fd, indent, indentstep, max_line_len, line_len):
"""Heuristically pretty print the argument string with double quotes"""
arg = escape_str(stmt.arg)
lines = arg.splitlines(True)
if len(lines) <= 1:
if len(arg) > 0 and arg[-1] == '\n':
arg = arg[:-1] + r'... | [
"def",
"emit_arg",
"(",
"keywordstr",
",",
"stmt",
",",
"fd",
",",
"indent",
",",
"indentstep",
",",
"max_line_len",
",",
"line_len",
")",
":",
"arg",
"=",
"escape_str",
"(",
"stmt",
".",
"arg",
")",
"lines",
"=",
"arg",
".",
"splitlines",
"(",
"True",... | 36.531915 | 0.001134 |
def register_view(self, view):
"""Register callbacks for button press events and selection changed"""
super(ListViewController, self).register_view(view)
self.tree_view.connect('button_press_event', self.mouse_click) | [
"def",
"register_view",
"(",
"self",
",",
"view",
")",
":",
"super",
"(",
"ListViewController",
",",
"self",
")",
".",
"register_view",
"(",
"view",
")",
"self",
".",
"tree_view",
".",
"connect",
"(",
"'button_press_event'",
",",
"self",
".",
"mouse_click",
... | 59.25 | 0.008333 |
def load_messages(self, directory, catalogue):
"""
Loads translation found in a directory.
@type directory: string
@param directory: The directory to search
@type catalogue: MessageCatalogue
@param catalogue: The message catalogue to dump
@raises: ValueError
... | [
"def",
"load_messages",
"(",
"self",
",",
"directory",
",",
"catalogue",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"raise",
"ValueError",
"(",
"\"{0} is not a directory\"",
".",
"format",
"(",
"directory",
")",
")"... | 35.8 | 0.002176 |
def get_string_plus_property_value(value):
# type: (Any) -> Optional[List[str]]
"""
Converts a string or list of string into a list of strings
:param value: A string or a list of strings
:return: A list of strings or None
"""
if value:
if isinstance(value, str):
return [... | [
"def",
"get_string_plus_property_value",
"(",
"value",
")",
":",
"# type: (Any) -> Optional[List[str]]",
"if",
"value",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"[",
"value",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")"... | 26.823529 | 0.002119 |
def select_with_main_images(self, limit=None, **kwargs):
''' Select all objects with filters passed as kwargs.
For each object it's main image instance is accessible as ``object.main_image``.
Results can be limited using ``limit`` parameter.
Selection is performed using on... | [
"def",
"select_with_main_images",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"objects",
"=",
"self",
".",
"get_query_set",
"(",
")",
".",
"filter",
"(",
"*",
"*",
"kwargs",
")",
"[",
":",
"limit",
"]",
"self",
".",
"... | 59 | 0.012987 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.