text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def template(self):
""" Get the template from: YAML or class """
# First try props
if self.props.template:
return self.props.template
else:
# Return the wtype of the widget, and we'll presume that,
# like resources, there's a .html file in that direct... | [
"def",
"template",
"(",
"self",
")",
":",
"# First try props",
"if",
"self",
".",
"props",
".",
"template",
":",
"return",
"self",
".",
"props",
".",
"template",
"else",
":",
"# Return the wtype of the widget, and we'll presume that,",
"# like resources, there's a .html... | 34.4 | 18.2 |
def ap_state(value, failure_string=None):
"""
Converts a state's name, postal abbreviation or FIPS to A.P. style.
Example usage:
>> ap_state("California")
'Calif.'
"""
try:
return statestyle.get(value).ap
except:
if failure_string:
retur... | [
"def",
"ap_state",
"(",
"value",
",",
"failure_string",
"=",
"None",
")",
":",
"try",
":",
"return",
"statestyle",
".",
"get",
"(",
"value",
")",
".",
"ap",
"except",
":",
"if",
"failure_string",
":",
"return",
"failure_string",
"else",
":",
"return",
"v... | 21.117647 | 18.764706 |
def isDiurnal(self):
""" Returns true if this chart is diurnal. """
sun = self.getObject(const.SUN)
mc = self.getAngle(const.MC)
# Get ecliptical positions and check if the
# sun is above the horizon.
lat = self.pos.lat
sunRA, sunDecl = utils.eqCoords(sun... | [
"def",
"isDiurnal",
"(",
"self",
")",
":",
"sun",
"=",
"self",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"mc",
"=",
"self",
".",
"getAngle",
"(",
"const",
".",
"MC",
")",
"# Get ecliptical positions and check if the",
"# sun is above the horizon.",
"lat... | 39.636364 | 12.181818 |
def start(self):
"""Run FIO job in thread"""
self.__thread = Threads(target=self.run, args=(True, True, False))
self.__thread.setDaemon(True)
self.__thread.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"__thread",
"=",
"Threads",
"(",
"target",
"=",
"self",
".",
"run",
",",
"args",
"=",
"(",
"True",
",",
"True",
",",
"False",
")",
")",
"self",
".",
"__thread",
".",
"setDaemon",
"(",
"True",
")... | 31.833333 | 18.666667 |
def clone(self, newname, config_path=None, flags=0, bdevtype=None,
bdevdata=None, newsize=0, hookargs=()):
"""
Clone the current container.
"""
args = {}
args['newname'] = newname
args['flags'] = flags
args['newsize'] = newsize
args['hoo... | [
"def",
"clone",
"(",
"self",
",",
"newname",
",",
"config_path",
"=",
"None",
",",
"flags",
"=",
"0",
",",
"bdevtype",
"=",
"None",
",",
"bdevdata",
"=",
"None",
",",
"newsize",
"=",
"0",
",",
"hookargs",
"=",
"(",
")",
")",
":",
"args",
"=",
"{"... | 29.954545 | 13.954545 |
def msetnx(self, key, value, *pairs):
"""Set multiple keys to multiple values,
only if none of the keys exist.
:raises TypeError: if len of pairs is not event number
"""
if len(pairs) % 2 != 0:
raise TypeError("length of pairs must be even number")
return sel... | [
"def",
"msetnx",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"pairs",
")",
":",
"if",
"len",
"(",
"pairs",
")",
"%",
"2",
"!=",
"0",
":",
"raise",
"TypeError",
"(",
"\"length of pairs must be even number\"",
")",
"return",
"self",
".",
"execute",
... | 39.111111 | 13.222222 |
def cmd2list(cmd):
''' Executes a command through the operating system and returns the output
as a list, or on error a string with the standard error.
EXAMPLE:
>>> from subprocess import Popen, PIPE
>>> CMDout2array('ls -l')
'''
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
stdout, ... | [
"def",
"cmd2list",
"(",
"cmd",
")",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"shell",
"=",
"True",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"re... | 34.692308 | 17 |
def event():
"""获取好友的动态,包括分享视频、音乐、动态等
"""
r = NCloudBot()
r.method = 'EVENT'
r.data = {"csrf_token": ""}
r.send()
return r.response | [
"def",
"event",
"(",
")",
":",
"r",
"=",
"NCloudBot",
"(",
")",
"r",
".",
"method",
"=",
"'EVENT'",
"r",
".",
"data",
"=",
"{",
"\"csrf_token\"",
":",
"\"\"",
"}",
"r",
".",
"send",
"(",
")",
"return",
"r",
".",
"response"
] | 15.2 | 20.3 |
def _write_commits_to_release_notes(self):
"""
writes commits to the releasenotes file by appending to the end
"""
with open(self.release_file, 'a') as out:
out.write("==========\n{}\n".format(self.tag))
for commit in self.commits:
try:
... | [
"def",
"_write_commits_to_release_notes",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"release_file",
",",
"'a'",
")",
"as",
"out",
":",
"out",
".",
"write",
"(",
"\"==========\\n{}\\n\"",
".",
"format",
"(",
"self",
".",
"tag",
")",
")",
"f... | 36.538462 | 10.076923 |
def upload_media(self, filename, progress=None):
"""Upload a file to be hosted on the target BMC
This will upload the specified data to
the BMC so that it will make it available to the system as an emulated
USB device.
:param filename: The filename to use, the basename of the p... | [
"def",
"upload_media",
"(",
"self",
",",
"filename",
",",
"progress",
"=",
"None",
")",
":",
"self",
".",
"oem_init",
"(",
")",
"return",
"self",
".",
"_oem",
".",
"upload_media",
"(",
"filename",
",",
"progress",
")"
] | 40.384615 | 19.615385 |
def get_color_hash(string, _min=MIN_COLOR_BRIGHT, _max=MAX_COLOR_BRIGHT):
"""
Hashes a string and returns a number between ``min`` and ``max``.
"""
hash_num = int(hashlib.sha1(string.encode('utf-8')).hexdigest()[:6], 16)
_range = _max - _min
num_in_range = hash_num % _range
return color(_min... | [
"def",
"get_color_hash",
"(",
"string",
",",
"_min",
"=",
"MIN_COLOR_BRIGHT",
",",
"_max",
"=",
"MAX_COLOR_BRIGHT",
")",
":",
"hash_num",
"=",
"int",
"(",
"hashlib",
".",
"sha1",
"(",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"... | 41.125 | 15.125 |
def run():
"""
Entry point to the law cli. Sets up all parsers, parses all arguments, and executes the
requested subprogram.
"""
# setup the main parser and sub parsers
parser = ArgumentParser(prog="law", description="The law command line tool.")
sub_parsers = parser.add_subparsers(help="sub... | [
"def",
"run",
"(",
")",
":",
"# setup the main parser and sub parsers",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"\"law\"",
",",
"description",
"=",
"\"The law command line tool.\"",
")",
"sub_parsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"help",
"=... | 31.607143 | 21.607143 |
def cache_control(self):
"""The Cache-Control general-header field is used to specify
directives that MUST be obeyed by all caching mechanisms along the
request/response chain.
"""
def on_update(cache_control):
if not cache_control and 'cache-control' in self.headers:... | [
"def",
"cache_control",
"(",
"self",
")",
":",
"def",
"on_update",
"(",
"cache_control",
")",
":",
"if",
"not",
"cache_control",
"and",
"'cache-control'",
"in",
"self",
".",
"headers",
":",
"del",
"self",
".",
"headers",
"[",
"'cache-control'",
"]",
"elif",
... | 50.615385 | 16.384615 |
def pysal_Join_Counts(self, **kwargs):
"""
Compute join count statistics for GeoRaster
Usage:
geo.pysal_Join_Counts(permutations = 1000, rook=True)
arguments passed to raster_weights() and pysal.Join_Counts
See help(gr.raster_weights), help(pysal.Join_Counts) for option... | [
"def",
"pysal_Join_Counts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"weights",
"is",
"None",
":",
"self",
".",
"raster_weights",
"(",
"*",
"*",
"kwargs",
")",
"rasterf",
"=",
"self",
".",
"raster",
".",
"flatten",
"(",
")",... | 37.266667 | 16.733333 |
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 reg_on_resume(self, callable_object, *args, **kwargs):
""" Register a function/method to be called if the system needs to
resume a previously halted or paused execution, including status
requests."""
persistent = kwargs.pop('persistent', False)
event = self._create_event(call... | [
"def",
"reg_on_resume",
"(",
"self",
",",
"callable_object",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"persistent",
"=",
"kwargs",
".",
"pop",
"(",
"'persistent'",
",",
"False",
")",
"event",
"=",
"self",
".",
"_create_event",
"(",
"callable_... | 53.625 | 16.875 |
def un_priority(op,val):
"unary expression order-of-operations helper"
if isinstance(val,BinX) and val.op < op: return bin_priority(val.op,UnX(op,val.left),val.right)
else: return UnX(op,val) | [
"def",
"un_priority",
"(",
"op",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"BinX",
")",
"and",
"val",
".",
"op",
"<",
"op",
":",
"return",
"bin_priority",
"(",
"val",
".",
"op",
",",
"UnX",
"(",
"op",
",",
"val",
".",
"left",
"... | 48.5 | 23.5 |
def isExpired(certificate):
""" Check if certificate is expired """
if isinstance(certificate, six.string_types):
certificate = json.loads(certificate)
expiry = certificate.get('expiry', 0)
return expiry < int(time.time() * 1000) + 20 * 60 | [
"def",
"isExpired",
"(",
"certificate",
")",
":",
"if",
"isinstance",
"(",
"certificate",
",",
"six",
".",
"string_types",
")",
":",
"certificate",
"=",
"json",
".",
"loads",
"(",
"certificate",
")",
"expiry",
"=",
"certificate",
".",
"get",
"(",
"'expiry'... | 43 | 6.833333 |
def new_text_cell(cell_type, source=None, rendered=None, metadata=None):
"""Create a new text cell."""
cell = NotebookNode()
# VERSIONHACK: plaintext -> raw
# handle never-released plaintext name for raw cells
if cell_type == 'plaintext':
cell_type = 'raw'
if source is not None:
... | [
"def",
"new_text_cell",
"(",
"cell_type",
",",
"source",
"=",
"None",
",",
"rendered",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"cell",
"=",
"NotebookNode",
"(",
")",
"# VERSIONHACK: plaintext -> raw",
"# handle never-released plaintext name for raw cells"... | 35.928571 | 11.714286 |
def urban_adj_factor(self):
"""
Return urban adjustment factor (UAF) used to adjust QMED and growth curves.
Methodology source: eqn. 8, Kjeldsen 2010
:return: urban adjustment factor
:rtype: float
"""
urbext = self.catchment.descriptors.urbext(self.year)
... | [
"def",
"urban_adj_factor",
"(",
"self",
")",
":",
"urbext",
"=",
"self",
".",
"catchment",
".",
"descriptors",
".",
"urbext",
"(",
"self",
".",
"year",
")",
"result",
"=",
"self",
".",
"_pruaf",
"(",
")",
"**",
"2.16",
"*",
"(",
"1",
"+",
"urbext",
... | 34.785714 | 17.642857 |
def docs():
""" Create documentation.
"""
from epydoc import cli
path('build').exists() or path('build').makedirs()
# get storage path
docs_dir = options.docs.get('docs_dir', 'docs/apidocs')
# clean up previous docs
(path(docs_dir) / "epydoc.css").exists() and path(docs_dir).rmtree()
... | [
"def",
"docs",
"(",
")",
":",
"from",
"epydoc",
"import",
"cli",
"path",
"(",
"'build'",
")",
".",
"exists",
"(",
")",
"or",
"path",
"(",
"'build'",
")",
".",
"makedirs",
"(",
")",
"# get storage path",
"docs_dir",
"=",
"options",
".",
"docs",
".",
"... | 27.5 | 19.214286 |
def dirty_ops(self, instance):
''' Returns a dict of the operations needed to update this object.
See :func:`Document.get_dirty_ops` for more details.'''
obj_value = instance._values[self._name]
if not obj_value.set:
return {}
if not obj_value.dirty and self.__ty... | [
"def",
"dirty_ops",
"(",
"self",
",",
"instance",
")",
":",
"obj_value",
"=",
"instance",
".",
"_values",
"[",
"self",
".",
"_name",
"]",
"if",
"not",
"obj_value",
".",
"set",
":",
"return",
"{",
"}",
"if",
"not",
"obj_value",
".",
"dirty",
"and",
"s... | 33.789474 | 19.684211 |
def write_http_response(
self, status: http.HTTPStatus, headers: Headers, body: Optional[bytes] = None
) -> None:
"""
Write status line and headers to the HTTP response.
This coroutine is also able to write a response body.
"""
self.response_headers = headers
... | [
"def",
"write_http_response",
"(",
"self",
",",
"status",
":",
"http",
".",
"HTTPStatus",
",",
"headers",
":",
"Headers",
",",
"body",
":",
"Optional",
"[",
"bytes",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"response_headers",
"=",
"headers... | 34.166667 | 22.75 |
def estimated_bytes_processed(self):
"""Return the estimated number of bytes processed by the query.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.estimatedBytesProcessed
:rtype: int or None
:returns: number of DML rows affected by the job,... | [
"def",
"estimated_bytes_processed",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_job_statistics",
"(",
")",
".",
"get",
"(",
"\"estimatedBytesProcessed\"",
")",
"if",
"result",
"is",
"not",
"None",
":",
"result",
"=",
"int",
"(",
"result",
")",
"re... | 37.857143 | 22.142857 |
def raw_to_bv(self):
"""
A counterpart to FP.raw_to_bv - does nothing and returns itself.
"""
if self.symbolic:
return BVS(next(iter(self.variables)).replace(self.STRING_TYPE_IDENTIFIER, self.GENERATED_BVS_IDENTIFIER), self.length)
else:
return BVV(ord(sel... | [
"def",
"raw_to_bv",
"(",
"self",
")",
":",
"if",
"self",
".",
"symbolic",
":",
"return",
"BVS",
"(",
"next",
"(",
"iter",
"(",
"self",
".",
"variables",
")",
")",
".",
"replace",
"(",
"self",
".",
"STRING_TYPE_IDENTIFIER",
",",
"self",
".",
"GENERATED_... | 42.125 | 24.875 |
def edit_mdp(mdp, new_mdp=None, extend_parameters=None, **substitutions):
"""Change values in a Gromacs mdp file.
Parameters and values are supplied as substitutions, eg ``nsteps=1000``.
By default the template mdp file is **overwritten in place**.
If a parameter does not exist in the template then i... | [
"def",
"edit_mdp",
"(",
"mdp",
",",
"new_mdp",
"=",
"None",
",",
"extend_parameters",
"=",
"None",
",",
"*",
"*",
"substitutions",
")",
":",
"if",
"new_mdp",
"is",
"None",
":",
"new_mdp",
"=",
"mdp",
"if",
"extend_parameters",
"is",
"None",
":",
"extend_... | 48.516393 | 26.245902 |
def poll(self):
"""check if the jobs are running and return a list of pids for
finished jobs
"""
finished_procs = [p for p in self.running_procs if p.poll() is not None]
self.running_procs = collections.deque([p for p in self.running_procs if p not in finished_procs])
f... | [
"def",
"poll",
"(",
"self",
")",
":",
"finished_procs",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"running_procs",
"if",
"p",
".",
"poll",
"(",
")",
"is",
"not",
"None",
"]",
"self",
".",
"running_procs",
"=",
"collections",
".",
"deque",
"(",
... | 39 | 24.857143 |
def html_singleAll(self,template="basic"):
"""generate a data view for every ABF in the project folder."""
for fname in smartSort(self.cells):
if template=="fixed":
self.html_single_fixed(fname)
else:
self.html_single_basic(fname) | [
"def",
"html_singleAll",
"(",
"self",
",",
"template",
"=",
"\"basic\"",
")",
":",
"for",
"fname",
"in",
"smartSort",
"(",
"self",
".",
"cells",
")",
":",
"if",
"template",
"==",
"\"fixed\"",
":",
"self",
".",
"html_single_fixed",
"(",
"fname",
")",
"els... | 42.285714 | 6.428571 |
async def filter_by(cls, db, offset=None, limit=None, **kwargs):
"""Query by attributes iteratively. Ordering is not supported
Example:
User.get_by(db, age=[32, 54])
User.get_by(db, age=23, name="guido")
"""
if limit and type(limit) is not int:
raise ... | [
"async",
"def",
"filter_by",
"(",
"cls",
",",
"db",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"limit",
"and",
"type",
"(",
"limit",
")",
"is",
"not",
"int",
":",
"raise",
"InvalidQuery",
"(",
... | 39.625 | 19.208333 |
def describe_lcc_csv(lcdict, returndesc=False):
'''
This describes the LCC CSV format light curve file.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str instead of ju... | [
"def",
"describe_lcc_csv",
"(",
"lcdict",
",",
"returndesc",
"=",
"False",
")",
":",
"metadata_lines",
"=",
"[",
"]",
"coldef_lines",
"=",
"[",
"]",
"if",
"'lcformat'",
"in",
"lcdict",
"and",
"'lcc-csv'",
"in",
"lcdict",
"[",
"'lcformat'",
"]",
".",
"lower... | 24.462687 | 24.850746 |
def get_signature_candidate(lines):
"""Return lines that could hold signature
The lines should:
* be among last SIGNATURE_MAX_LINES non-empty lines.
* not include first line
* be shorter than TOO_LONG_SIGNATURE_LINE
* not include more than one line that starts with dashes
"""
# non emp... | [
"def",
"get_signature_candidate",
"(",
"lines",
")",
":",
"# non empty lines indexes",
"non_empty",
"=",
"[",
"i",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
"if",
"line",
".",
"strip",
"(",
")",
"]",
"# if message is empty or just one line t... | 31.483871 | 20.774194 |
def _rgetattr(obj, key):
"""Recursive getattr for handling dots in keys."""
for k in key.split("."):
obj = getattr(obj, k)
return obj | [
"def",
"_rgetattr",
"(",
"obj",
",",
"key",
")",
":",
"for",
"k",
"in",
"key",
".",
"split",
"(",
"\".\"",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"k",
")",
"return",
"obj"
] | 29.8 | 13 |
def get_port_channel_detail_output_lacp_partner_oper_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel... | [
"def",
"get_port_channel_detail_output_lacp_partner_oper_priority",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_channel_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_port_channel_detail\"",
... | 47.076923 | 18.076923 |
def user_get_session_token(self, app_id=None, email=None, password=None,
ekey=None, fb_access_token=None,
tw_oauth_token=None,
tw_oauth_token_secret=None, api_key=None):
"""user/get_session_token
http://www.med... | [
"def",
"user_get_session_token",
"(",
"self",
",",
"app_id",
"=",
"None",
",",
"email",
"=",
"None",
",",
"password",
"=",
"None",
",",
"ekey",
"=",
"None",
",",
"fb_access_token",
"=",
"None",
",",
"tw_oauth_token",
"=",
"None",
",",
"tw_oauth_token_secret"... | 36.140351 | 19.157895 |
def xSectionLink(lines):
"""
Parse Cross Section Links Method
"""
# Constants
KEYWORDS = ('LINK',
'DX',
'TRAPEZOID',
'TRAPEZOID_ERODE',
'TRAPEZOID_SUBSURFACE',
'ERODE_TRAPEZOID',
'ERODE_SUBSURFACE',
... | [
"def",
"xSectionLink",
"(",
"lines",
")",
":",
"# Constants",
"KEYWORDS",
"=",
"(",
"'LINK'",
",",
"'DX'",
",",
"'TRAPEZOID'",
",",
"'TRAPEZOID_ERODE'",
",",
"'TRAPEZOID_SUBSURFACE'",
",",
"'ERODE_TRAPEZOID'",
",",
"'ERODE_SUBSURFACE'",
",",
"'SUBSURFACE_TRAPEZOID'",
... | 33.578947 | 11.315789 |
def subs2seqs(self) -> Dict[str, List[str]]:
"""A |collections.defaultdict| containing the node-specific
information provided by XML `sequences` element.
>>> from hydpy.auxs.xmltools import XMLInterface
>>> from hydpy import data
>>> interface = XMLInterface('single_run.xml', da... | [
"def",
"subs2seqs",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"subs2seqs",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"nodes",
"=",
"find",
"(",
"self",
".",
"find",
"(",
"'sequences'",
")",
... | 41.894737 | 13.052632 |
async def get_password_tty(device, options):
"""Get the password to unlock a device from terminal."""
# TODO: make this a TRUE async
text = _('Enter password for {0.device_presentation}: ', device)
try:
return getpass.getpass(text)
except EOFError:
print("")
return None | [
"async",
"def",
"get_password_tty",
"(",
"device",
",",
"options",
")",
":",
"# TODO: make this a TRUE async",
"text",
"=",
"_",
"(",
"'Enter password for {0.device_presentation}: '",
",",
"device",
")",
"try",
":",
"return",
"getpass",
".",
"getpass",
"(",
"text",
... | 34 | 15.333333 |
def _postprocess_hover(self, renderer, source):
"""
Limit hover tool to annular wedges only.
"""
if isinstance(renderer.glyph, AnnularWedge):
super(RadialHeatMapPlot, self)._postprocess_hover(renderer, source) | [
"def",
"_postprocess_hover",
"(",
"self",
",",
"renderer",
",",
"source",
")",
":",
"if",
"isinstance",
"(",
"renderer",
".",
"glyph",
",",
"AnnularWedge",
")",
":",
"super",
"(",
"RadialHeatMapPlot",
",",
"self",
")",
".",
"_postprocess_hover",
"(",
"render... | 35.428571 | 15.142857 |
def mean_abs_tree_shap(model, data):
""" mean(|TreeExplainer|)
color = red_blue_circle(0.25)
linestyle = solid
"""
def f(X):
v = TreeExplainer(model).shap_values(X)
if isinstance(v, list):
return [np.tile(np.abs(sv).mean(0), (X.shape[0], 1)) for sv in v]
else:
... | [
"def",
"mean_abs_tree_shap",
"(",
"model",
",",
"data",
")",
":",
"def",
"f",
"(",
"X",
")",
":",
"v",
"=",
"TreeExplainer",
"(",
"model",
")",
".",
"shap_values",
"(",
"X",
")",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"return",
"[",
... | 31.75 | 15.583333 |
def merge(self, commit_message=github.GithubObject.NotSet, commit_title=github.GithubObject.NotSet, merge_method=github.GithubObject.NotSet, sha=github.GithubObject.NotSet):
"""
:calls: `PUT /repos/:owner/:repo/pulls/:number/merge <http://developer.github.com/v3/pulls>`_
:param commit_message: s... | [
"def",
"merge",
"(",
"self",
",",
"commit_message",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"commit_title",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"merge_method",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"sha",... | 63.64 | 32.28 |
def tree2text(tree_obj, indent=4):
# type: (TreeInfo, int) -> str
"""
Return text representation of a decision tree.
"""
parts = []
def _format_node(node, depth=0):
# type: (NodeInfo, int) -> None
def p(*args):
# type: (*str) -> None
parts.append(" " * de... | [
"def",
"tree2text",
"(",
"tree_obj",
",",
"indent",
"=",
"4",
")",
":",
"# type: (TreeInfo, int) -> str",
"parts",
"=",
"[",
"]",
"def",
"_format_node",
"(",
"node",
",",
"depth",
"=",
"0",
")",
":",
"# type: (NodeInfo, int) -> None",
"def",
"p",
"(",
"*",
... | 32.651163 | 14.27907 |
def store_node_label_meta(self, x, y, tx, ty, rot):
"""
This function stored coordinates-related metadate for a node
This function should not be called by the user
:param x: x location of node label or number
:type x: np.float64
:param y: y location of node label or num... | [
"def",
"store_node_label_meta",
"(",
"self",
",",
"x",
",",
"y",
",",
"tx",
",",
"ty",
",",
"rot",
")",
":",
"# Store computed values",
"self",
".",
"node_label_coords",
"[",
"\"x\"",
"]",
".",
"append",
"(",
"x",
")",
"self",
".",
"node_label_coords",
"... | 32.522727 | 18.977273 |
def bingham_pdf(fit):
"""
From the *Encyclopedia of Paleomagnetism*
From Onstott, 1980:
Vector resultant: R is analogous to eigenvectors
of T.
Eigenvalues are analogous to |R|/N.
"""
# Uses eigenvectors of the covariance matrix
e = fit.hyperbolic_axes #singular_values
#e = sampl... | [
"def",
"bingham_pdf",
"(",
"fit",
")",
":",
"# Uses eigenvectors of the covariance matrix",
"e",
"=",
"fit",
".",
"hyperbolic_axes",
"#singular_values",
"#e = sampling_covariance(fit) # not sure",
"e",
"=",
"e",
"[",
"2",
"]",
"**",
"2",
"/",
"e",
"kappa",
"=",
"(... | 22.545455 | 22.681818 |
def getUnionTemporalPoolerInput(self):
"""
Gets the Union Temporal Pooler input from the Temporal Memory
"""
activeCells = numpy.zeros(self.tm.numberOfCells()).astype(realDType)
activeCells[list(self.tm.activeCellsIndices())] = 1
predictedActiveCells = numpy.zeros(self.tm.numberOfCells()).astyp... | [
"def",
"getUnionTemporalPoolerInput",
"(",
"self",
")",
":",
"activeCells",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"tm",
".",
"numberOfCells",
"(",
")",
")",
".",
"astype",
"(",
"realDType",
")",
"activeCells",
"[",
"list",
"(",
"self",
".",
"tm",... | 40.4 | 24.266667 |
def init(scope):
"""
Copy all values of scope into the class SinonGlobals
Args:
scope (eg. locals() or globals())
Return:
SinonGlobals instance
"""
class SinonGlobals(object): #pylint: disable=too-few-public-methods
"""
A fully empty class
External can pus... | [
"def",
"init",
"(",
"scope",
")",
":",
"class",
"SinonGlobals",
"(",
"object",
")",
":",
"#pylint: disable=too-few-public-methods",
"\"\"\"\n A fully empty class\n External can push the whole `scope` into this class through global function init()\n \"\"\"",
"pass",
... | 30.428571 | 18.047619 |
def get_zone(self, zone_name):
"""
Get the information about a particular zone
"""
for zone in self.get_zones():
if zone_name == zone['name']:
return zone
raise RuntimeError("Unknown zone") | [
"def",
"get_zone",
"(",
"self",
",",
"zone_name",
")",
":",
"for",
"zone",
"in",
"self",
".",
"get_zones",
"(",
")",
":",
"if",
"zone_name",
"==",
"zone",
"[",
"'name'",
"]",
":",
"return",
"zone",
"raise",
"RuntimeError",
"(",
"\"Unknown zone\"",
")"
] | 27.777778 | 8.888889 |
def append_text_to_shell(self, text, error, prompt):
"""
Append text to Python shell
In a way, this method overrides the method 'insert_text' when text is
inserted at the end of the text widget for a Python shell
Handles error messages and show blue underlined links
Hand... | [
"def",
"append_text_to_shell",
"(",
"self",
",",
"text",
",",
"error",
",",
"prompt",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"End",
")",
"if",
"'\\r'",
"in",
"text",
":",
"#... | 45.603175 | 16.904762 |
def split_func(string):
"""
Take a string like 'requiredIf("arg_name")'
return the function name and the argument:
(requiredIf, arg_name)
"""
ind = string.index("(")
return string[:ind], string[ind+1:-1].strip('"') | [
"def",
"split_func",
"(",
"string",
")",
":",
"ind",
"=",
"string",
".",
"index",
"(",
"\"(\"",
")",
"return",
"string",
"[",
":",
"ind",
"]",
",",
"string",
"[",
"ind",
"+",
"1",
":",
"-",
"1",
"]",
".",
"strip",
"(",
"'\"'",
")"
] | 29.375 | 8.625 |
def policy_attached(name, policyName, principal,
region=None, key=None, keyid=None, profile=None):
'''
Ensure policy is attached to the given principal.
name
The name of the state definition
policyName
Name of the policy.
principal
The principal which can be a ... | [
"def",
"policy_attached",
"(",
"name",
",",
"policyName",
",",
"principal",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"policyName",
",",
"'re... | 32.191176 | 25.867647 |
def make_rsa_keys(bits=2048, e=65537, k=64):
"""
Create RSA key pair.
Returns n, e, d, where (n, e) is the public
key and (n, e, d) is the private key (and k is
the number of rounds used in the Miller-Rabin
primality test).
"""
p, q = None, None
while p == q:
p, q = get_pri... | [
"def",
"make_rsa_keys",
"(",
"bits",
"=",
"2048",
",",
"e",
"=",
"65537",
",",
"k",
"=",
"64",
")",
":",
"p",
",",
"q",
"=",
"None",
",",
"None",
"while",
"p",
"==",
"q",
":",
"p",
",",
"q",
"=",
"get_prime",
"(",
"bits",
"//",
"2",
")",
",... | 24.941176 | 16.705882 |
def extend_env(extra_env):
"""
Copies and extends the current environment with the values present in
`extra_env`.
"""
env = os.environ.copy()
env.update(extra_env)
return env | [
"def",
"extend_env",
"(",
"extra_env",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"extra_env",
")",
"return",
"env"
] | 24.375 | 15.625 |
def visitNumericFacet(self, ctx: ShExDocParser.NumericFacetContext):
""" numericFacet: numericRange numericLiteral | numericLength INTEGER
numericRange: KW_MINEXCLUSIVE | KW_MININCLUSIVE | KW_MAXEXCLUSIVE | KW_MAXINCLUSIVE
numericLength: KW_TOTALDIGITS | KW_FRACTIONDIGITS """
if... | [
"def",
"visitNumericFacet",
"(",
"self",
",",
"ctx",
":",
"ShExDocParser",
".",
"NumericFacetContext",
")",
":",
"if",
"ctx",
".",
"numericRange",
"(",
")",
":",
"numlit",
"=",
"self",
".",
"context",
".",
"numeric_literal_to_type",
"(",
"ctx",
".",
"numeric... | 57.25 | 17.85 |
def draw_image(data, obj):
"""Returns the PGFPlots code for an image environment.
"""
content = []
filename, rel_filepath = files.new_filename(data, "img", ".png")
# store the image as in a file
img_array = obj.get_array()
dims = img_array.shape
if len(dims) == 2: # the values are gi... | [
"def",
"draw_image",
"(",
"data",
",",
"obj",
")",
":",
"content",
"=",
"[",
"]",
"filename",
",",
"rel_filepath",
"=",
"files",
".",
"new_filename",
"(",
"data",
",",
"\"img\"",
",",
"\".png\"",
")",
"# store the image as in a file",
"img_array",
"=",
"obj"... | 30.2 | 19.236364 |
def get_objective_sequencing_session(self, proxy):
"""Gets the session for sequencing objectives.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveSequencingSession``
:rtype: ``osid.learning.ObjectiveSequencingSession``
:raise: ``NullArgumen... | [
"def",
"get_objective_sequencing_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_objective_sequencing",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
... | 40.230769 | 20.115385 |
def decline_event(self, comment=None, *, send_response=True):
""" Decline the event
:param str comment: comment to add
:param bool send_response: whether or not to send response back
:return: Success / Failure
:rtype: bool
"""
if not self.object_id:
r... | [
"def",
"decline_event",
"(",
"self",
",",
"comment",
"=",
"None",
",",
"*",
",",
"send_response",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"object_id",
":",
"raise",
"RuntimeError",
"(",
"\"Can't accept event that doesn't exist\"",
")",
"url",
"=",
"... | 32.666667 | 19.083333 |
def flatten(*args):
'''Generator that recursively flattens embedded lists, tuples, etc.'''
for arg in args:
if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)):
yield from flatten(*arg)
else:
yield arg | [
"def",
"flatten",
"(",
"*",
"args",
")",
":",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"arg",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"yield",
... | 38.571429 | 24.571429 |
def to_julian_date(self):
"""
Convert Datetime Array to float64 ndarray of Julian Dates.
0 Julian date is noon January 1, 4713 BC.
http://en.wikipedia.org/wiki/Julian_day
"""
# http://mysite.verizon.net/aesir_research/date/jdalg2.htm
year = np.asarray(self.year)
... | [
"def",
"to_julian_date",
"(",
"self",
")",
":",
"# http://mysite.verizon.net/aesir_research/date/jdalg2.htm",
"year",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"year",
")",
"month",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"month",
")",
"day",
"=",
"n... | 34.444444 | 10.518519 |
def queryset(self, request, queryset):
"""Filter based on whether an update (of any sort) is available."""
if self.value() == '-1':
return queryset.filter(latest_version__isnull=True)
elif self.value() == '0':
return (
queryset
.filter(
... | [
"def",
"queryset",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"if",
"self",
".",
"value",
"(",
")",
"==",
"'-1'",
":",
"return",
"queryset",
".",
"filter",
"(",
"latest_version__isnull",
"=",
"True",
")",
"elif",
"self",
".",
"value",
"(",... | 33.72 | 14.88 |
def webui_url(args):
'''show the url of web ui'''
nni_config = Config(get_config_filename(args))
print_normal('{0} {1}'.format('Web UI url:', ' '.join(nni_config.get_config('webuiUrl')))) | [
"def",
"webui_url",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"print_normal",
"(",
"'{0} {1}'",
".",
"format",
"(",
"'Web UI url:'",
",",
"' '",
".",
"join",
"(",
"nni_config",
".",
"get_config",
... | 49 | 23 |
def wrap(item, args=None, krgs=None, **kwargs):
"""Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
"... | [
"def",
"wrap",
"(",
"item",
",",
"args",
"=",
"None",
",",
"krgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Wrap",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"item",
")",
":",
"args",
"=",
"args",
"or",
"[",
"]"... | 30.5 | 17.625 |
def parse(cls, data: bytes) -> 'MessageContent':
"""Parse the bytestring into message content.
Args:
data: The bytestring to parse.
"""
lines = cls._find_lines(data)
view = memoryview(data)
return cls._parse(data, view, lines) | [
"def",
"parse",
"(",
"cls",
",",
"data",
":",
"bytes",
")",
"->",
"'MessageContent'",
":",
"lines",
"=",
"cls",
".",
"_find_lines",
"(",
"data",
")",
"view",
"=",
"memoryview",
"(",
"data",
")",
"return",
"cls",
".",
"_parse",
"(",
"data",
",",
"view... | 27.9 | 13.3 |
def import_eit_fzj(self, filename, configfile, correction_file=None,
timestep=None, **kwargs):
"""EIT data import for FZJ Medusa systems"""
# we get not electrode positions (dummy1) and no topography data
# (dummy2)
df_emd, dummy1, dummy2 = eit_fzj.read_3p_data(
... | [
"def",
"import_eit_fzj",
"(",
"self",
",",
"filename",
",",
"configfile",
",",
"correction_file",
"=",
"None",
",",
"timestep",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# we get not electrode positions (dummy1) and no topography data",
"# (dummy2)",
"df_emd",
... | 33.5 | 18.9 |
def load_stylesheet_pyqt5():
"""
Loads the stylesheet for use in a pyqt5 application.
:param pyside: True to load the pyside rc file, False to load the PyQt rc file
:return the stylesheet string
"""
# Smart import of the rc file
import qdarkstyle.pyqt5_style_rc
# Load the stylesheet c... | [
"def",
"load_stylesheet_pyqt5",
"(",
")",
":",
"# Smart import of the rc file",
"import",
"qdarkstyle",
".",
"pyqt5_style_rc",
"# Load the stylesheet content from resources",
"from",
"PyQt5",
".",
"QtCore",
"import",
"QFile",
",",
"QTextStream",
"f",
"=",
"QFile",
"(",
... | 29.676471 | 16.911765 |
def union(rasters):
"""
Union of rasters
Usage:
union(rasters)
where:
rasters is a list of GeoRaster objects
"""
if sum([rasters[0].x_cell_size == i.x_cell_size for i in rasters]) == len(rasters) \
and sum([rasters[0].y_cell_size == i.y_cell_size for i in rasters]) == len... | [
"def",
"union",
"(",
"rasters",
")",
":",
"if",
"sum",
"(",
"[",
"rasters",
"[",
"0",
"]",
".",
"x_cell_size",
"==",
"i",
".",
"x_cell_size",
"for",
"i",
"in",
"rasters",
"]",
")",
"==",
"len",
"(",
"rasters",
")",
"and",
"sum",
"(",
"[",
"raster... | 55.625 | 33.725 |
def utc2et(utcstr):
"""
Convert an input time from Calendar or Julian Date format, UTC,
to ephemeris seconds past J2000.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/utc2et_c.html
:param utcstr: Input time string, UTC.
:type utcstr: str
:return: Output epoch, ephemeris seconds ... | [
"def",
"utc2et",
"(",
"utcstr",
")",
":",
"utcstr",
"=",
"stypes",
".",
"stringToCharP",
"(",
"utcstr",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"libspice",
".",
"utc2et_c",
"(",
"utcstr",
",",
"ctypes",
".",
"byref",
"(",
"et",
")",
")",... | 29.9375 | 16.8125 |
def as_bulk_queries(queries, bulk_size):
"""Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size
"""
stmt_dict = defaultdict(list)
for stmt, args in queries:
bulk_args = stmt_dict[stmt... | [
"def",
"as_bulk_queries",
"(",
"queries",
",",
"bulk_size",
")",
":",
"stmt_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"stmt",
",",
"args",
"in",
"queries",
":",
"bulk_args",
"=",
"stmt_dict",
"[",
"stmt",
"]",
"bulk_args",
".",
"append",
"(",
"... | 32.4375 | 10.1875 |
def has_preview_permission(self, request, obj=None):
"""
Return `True` if the user has permissions to preview a publishable
item.
NOTE: this method does not actually change who can or cannot preview
any particular item, just whether to show the preview link. The real
dci... | [
"def",
"has_preview_permission",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"# User who can publish always has preview permission.",
"if",
"self",
".",
"has_publish_permission",
"(",
"request",
",",
"obj",
"=",
"obj",
")",
":",
"return",
"True... | 38.038462 | 20.115385 |
def get_actions(actions):
"""Get actions."""
new_actions = []
if actions:
for action in actions:
action_obj = get_action(action)
if action_obj:
new_actions.append(action_obj)
return new_actions | [
"def",
"get_actions",
"(",
"actions",
")",
":",
"new_actions",
"=",
"[",
"]",
"if",
"actions",
":",
"for",
"action",
"in",
"actions",
":",
"action_obj",
"=",
"get_action",
"(",
"action",
")",
"if",
"action_obj",
":",
"new_actions",
".",
"append",
"(",
"a... | 24.9 | 15.1 |
def Network_getCertificate(self, origin):
"""
Function path: Network.getCertificate
Domain: Network
Method name: getCertificate
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'origin' (type: string) -> Origin to get certificate for.
Returns:
'table... | [
"def",
"Network_getCertificate",
"(",
"self",
",",
"origin",
")",
":",
"assert",
"isinstance",
"(",
"origin",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'origin' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"origin",
")",
"subdom_funcs"... | 29.272727 | 19.545455 |
def __set_date(self, value):
'''
Sets the invoice date.
@param value:datetime
'''
value = date_to_datetime(value)
if value > datetime.now() + timedelta(hours=14, minutes=1): #More or less 14 hours from now in case the submitted date was local
raise ValueError(... | [
"def",
"__set_date",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"date_to_datetime",
"(",
"value",
")",
"if",
"value",
">",
"datetime",
".",
"now",
"(",
")",
"+",
"timedelta",
"(",
"hours",
"=",
"14",
",",
"minutes",
"=",
"1",
")",
":",
"#Mo... | 39 | 27.461538 |
def set_servo(self, gpio, pulse_width_us):
"""
Sets a pulse-width on a gpio to repeat every subcycle
(by default every 20ms).
"""
# Make sure we can set the exact pulse_width_us
_pulse_incr_us = _PWM.get_pulse_incr_us()
if pulse_width_us % _pulse_incr_us:
... | [
"def",
"set_servo",
"(",
"self",
",",
"gpio",
",",
"pulse_width_us",
")",
":",
"# Make sure we can set the exact pulse_width_us",
"_pulse_incr_us",
"=",
"_PWM",
".",
"get_pulse_incr_us",
"(",
")",
"if",
"pulse_width_us",
"%",
"_pulse_incr_us",
":",
"# No clean division ... | 47.222222 | 18.703704 |
def _box_col_values(self, values, items):
"""
Provide boxed values for a column.
"""
klass = self._constructor_sliced
return klass(values, index=self.index, name=items, fastpath=True) | [
"def",
"_box_col_values",
"(",
"self",
",",
"values",
",",
"items",
")",
":",
"klass",
"=",
"self",
".",
"_constructor_sliced",
"return",
"klass",
"(",
"values",
",",
"index",
"=",
"self",
".",
"index",
",",
"name",
"=",
"items",
",",
"fastpath",
"=",
... | 36.333333 | 6 |
def libvlc_media_list_player_set_media_list(p_mlp, p_mlist):
'''Set the media list associated with the player.
@param p_mlp: media list player instance.
@param p_mlist: list of media.
'''
f = _Cfunctions.get('libvlc_media_list_player_set_media_list', None) or \
_Cfunction('libvlc_media_list_... | [
"def",
"libvlc_media_list_player_set_media_list",
"(",
"p_mlp",
",",
"p_mlist",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_list_player_set_media_list'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_list_player_set_media_list'",
",",
... | 48.777778 | 20.111111 |
def search(**criteria):
"""
Search registered *component* classes matching the given criteria.
:param criteria: search criteria of the form: ``a='1', b='x'``
:return: parts registered with the given criteria
:rtype: :class:`set`
Will return an empty :class:`set` if nothing is found.
::
... | [
"def",
"search",
"(",
"*",
"*",
"criteria",
")",
":",
"# Find all parts that match the given criteria",
"results",
"=",
"copy",
"(",
"class_list",
")",
"# start with full list",
"for",
"(",
"category",
",",
"value",
")",
"in",
"criteria",
".",
"items",
"(",
")",... | 31.137931 | 19.62069 |
def iter_prefix(reader, key):
"""
Creates an iterator which iterates over lines that start with prefix
'key' in a sorted text file.
"""
return itertools.takewhile(
lambda line: line.startswith(key),
search(reader, key)) | [
"def",
"iter_prefix",
"(",
"reader",
",",
"key",
")",
":",
"return",
"itertools",
".",
"takewhile",
"(",
"lambda",
"line",
":",
"line",
".",
"startswith",
"(",
"key",
")",
",",
"search",
"(",
"reader",
",",
"key",
")",
")"
] | 27.555556 | 12.666667 |
def _evaluate(self,*args,**kwargs):
"""
NAME:
__call__ (_evaluate)
PURPOSE:
evaluate the actions (jr,lz,jz)
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
1) floats: phase-space value for single object (phi is optional) (each can be ... | [
"def",
"_evaluate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"5",
":",
"#R,vR.vT, z, vz",
"R",
",",
"vR",
",",
"vT",
",",
"z",
",",
"vz",
"=",
"args",
"elif",
"len",
"(",
"args",
"... | 49.833333 | 20.198413 |
def has_logged_in(self):
"""Check whether the API has logged in"""
r = self.http.get(CHECKPOINT_URL)
if r.state is False:
return True
# If logged out, flush cache
self._reset_cache()
return False | [
"def",
"has_logged_in",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"http",
".",
"get",
"(",
"CHECKPOINT_URL",
")",
"if",
"r",
".",
"state",
"is",
"False",
":",
"return",
"True",
"# If logged out, flush cache",
"self",
".",
"_reset_cache",
"(",
")",
"r... | 31 | 10.375 |
def rename_session(self, new_name):
"""
Rename session and return new :class:`Session` object.
Parameters
----------
new_name : str
new session name
Returns
-------
:class:`Session`
Raises
------
:exc:`exc.BadSessionN... | [
"def",
"rename_session",
"(",
"self",
",",
"new_name",
")",
":",
"session_check_name",
"(",
"new_name",
")",
"proc",
"=",
"self",
".",
"cmd",
"(",
"'rename-session'",
",",
"new_name",
")",
"if",
"proc",
".",
"stderr",
":",
"if",
"has_version",
"(",
"'2.7'"... | 25.857143 | 21.828571 |
def translate_line_footnotes(line, tag=None, default_title='<NOT_FOUND>'):
r""" Find all bare-url footnotes, like "footnote:[moz.org]" and add a title like "footnote:[Moz (moz.org)]"
>>> translate_line_footnotes('*Morphemes*:: Parts of tokens or words that contain meaning in and of themselves.'\
... '... | [
"def",
"translate_line_footnotes",
"(",
"line",
",",
"tag",
"=",
"None",
",",
"default_title",
"=",
"'<NOT_FOUND>'",
")",
":",
"line_urls",
"=",
"get_line_bad_footnotes",
"(",
"line",
",",
"tag",
"=",
"tag",
")",
"urls",
"=",
"line_urls",
"[",
"1",
":",
"]... | 52.307692 | 27.410256 |
def geojson_to_dict_list(data):
"""Parse GeoJSON-formatted information in <data> to list of Python dicts"""
# return data formatted as list or dict
if type(data) in (list, dict):
return data
# read from data defined as local file address
try:
with open(data, 'r') as f:
... | [
"def",
"geojson_to_dict_list",
"(",
"data",
")",
":",
"# return data formatted as list or dict",
"if",
"type",
"(",
"data",
")",
"in",
"(",
"list",
",",
"dict",
")",
":",
"return",
"data",
"# read from data defined as local file address",
"try",
":",
"with",
"open",... | 33.45 | 23.5 |
def _download_predicate_data(self, class_, controller):
"""Get raw predicate information for given request class, and cache for
subsequent calls.
"""
self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
logger... | [
"def",
"_download_predicate_data",
"(",
"self",
",",
"class_",
",",
"controller",
")",
":",
"self",
".",
"authenticate",
"(",
")",
"url",
"=",
"(",
"'{0}{1}/modeldef/class/{2}'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"controller",
",",
"class_",
... | 28.5 | 18.25 |
def connect(self, forceReconnect=False):
"""
Check current conditions and initiate connection if possible.
This is called to check preconditions for starting a new connection,
and initating the connection itself.
If the service is not running, this will do nothing.
@pa... | [
"def",
"connect",
"(",
"self",
",",
"forceReconnect",
"=",
"False",
")",
":",
"if",
"self",
".",
"_state",
"==",
"'stopped'",
":",
"raise",
"Error",
"(",
"\"This service is not running. Not connecting.\"",
")",
"if",
"self",
".",
"_state",
"==",
"'connected'",
... | 36.075472 | 17.584906 |
def gait_regularity_symmetry(self, x, average_step_duration='autodetect', average_stride_duration='autodetect', unbias=1, normalize=2):
"""
Compute step and stride regularity and symmetry from accelerometer data with the help of steps and strides.
:param x: The time series to assess fr... | [
"def",
"gait_regularity_symmetry",
"(",
"self",
",",
"x",
",",
"average_step_duration",
"=",
"'autodetect'",
",",
"average_stride_duration",
"=",
"'autodetect'",
",",
"unbias",
"=",
"1",
",",
"normalize",
"=",
"2",
")",
":",
"if",
"(",
"average_step_duration",
"... | 49.174603 | 31.634921 |
def int_to_key(value, base=BASE62):
"""
Convert the specified integer to a key using the given base.
@param value: a positive integer.
@param base: a sequence of characters that is used to encode the
integer value.
@return: a key expressed in the specified base.
"""
def key_seq... | [
"def",
"int_to_key",
"(",
"value",
",",
"base",
"=",
"BASE62",
")",
":",
"def",
"key_sequence_generator",
"(",
"value",
",",
"base",
")",
":",
"\"\"\"\n Generator for producing sequence of characters of a key providing an\n integer value and a base of characters for... | 32.28125 | 18.71875 |
def _publish(self, obj):
'''
Publish the OC object.
'''
bin_obj = umsgpack.packb(obj)
self.pub.send(bin_obj) | [
"def",
"_publish",
"(",
"self",
",",
"obj",
")",
":",
"bin_obj",
"=",
"umsgpack",
".",
"packb",
"(",
"obj",
")",
"self",
".",
"pub",
".",
"send",
"(",
"bin_obj",
")"
] | 23.833333 | 16.166667 |
def set_col_width(self, col, tab, width):
"""Sets column width"""
try:
old_width = self.col_widths.pop((col, tab))
except KeyError:
old_width = None
if width is not None:
self.col_widths[(col, tab)] = float(width) | [
"def",
"set_col_width",
"(",
"self",
",",
"col",
",",
"tab",
",",
"width",
")",
":",
"try",
":",
"old_width",
"=",
"self",
".",
"col_widths",
".",
"pop",
"(",
"(",
"col",
",",
"tab",
")",
")",
"except",
"KeyError",
":",
"old_width",
"=",
"None",
"i... | 24.909091 | 19.727273 |
def refresh_token(token_service, refresh_token, client_id, client_secret):
"""Refreshes a token."""
data = {
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
}
resp = requests.post(token_service, data)
print resp, 'refreshin... | [
"def",
"refresh_token",
"(",
"token_service",
",",
"refresh_token",
",",
"client_id",
",",
"client_secret",
")",
":",
"data",
"=",
"{",
"'client_id'",
":",
"client_id",
",",
"'client_secret'",
":",
"client_secret",
",",
"'refresh_token'",
":",
"refresh_token",
","... | 31.454545 | 14 |
def load_to(self, last_level_load):
"""Set level where to load from."""
assert isinstance(last_level_load, Cache), \
"last_level needs to be a Cache object."
assert last_level_load.load_from is None, \
"last_level_load must be a last level cache (.load_from is None)."
... | [
"def",
"load_to",
"(",
"self",
",",
"last_level_load",
")",
":",
"assert",
"isinstance",
"(",
"last_level_load",
",",
"Cache",
")",
",",
"\"last_level needs to be a Cache object.\"",
"assert",
"last_level_load",
".",
"load_from",
"is",
"None",
",",
"\"last_level_load ... | 51 | 12 |
def my_solid_angle(center, coords):
"""
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center:
Center to measure solid angle from.
coords:
List of coords to determine solid angle.
Returns:
The solid angle.
""... | [
"def",
"my_solid_angle",
"(",
"center",
",",
"coords",
")",
":",
"o",
"=",
"np",
".",
"array",
"(",
"center",
")",
"r",
"=",
"[",
"np",
".",
"array",
"(",
"c",
")",
"-",
"o",
"for",
"c",
"in",
"coords",
"]",
"r",
".",
"append",
"(",
"r",
"[",... | 32.727273 | 19.454545 |
def getrawheader(self, name):
"""A higher-level interface to getfirstmatchingheader().
Return a string containing the literal text of the header but with the
keyword stripped. All leading, trailing and embedded whitespace is
kept in the string, however. Return None if the header does ... | [
"def",
"getrawheader",
"(",
"self",
",",
"name",
")",
":",
"lst",
"=",
"self",
".",
"getfirstmatchingheader",
"(",
"name",
")",
"if",
"not",
"lst",
":",
"return",
"None",
"lst",
"[",
"0",
"]",
"=",
"lst",
"[",
"0",
"]",
"[",
"len",
"(",
"name",
"... | 35.571429 | 20.071429 |
def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
""" Callback to move a tab to the left """
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True | [
"def",
"accel_move_tab_left",
"(",
"self",
",",
"*",
"args",
")",
":",
"# TODO KEYBINDINGS ONLY",
"pos",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"if",
"pos",
"!=",
"0",
":",
"self",
".",
"move_tab",
"(",
"pos",
",",... | 35.428571 | 9.428571 |
def transformToRef(self,ref_wcs,force=False):
""" Transform sky coords from ALL chips into X,Y coords in reference WCS.
"""
if not isinstance(ref_wcs, pywcs.WCS):
print(textutil.textbox('Reference WCS not a valid HSTWCS object'),
file=sys.stderr)
raise V... | [
"def",
"transformToRef",
"(",
"self",
",",
"ref_wcs",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"ref_wcs",
",",
"pywcs",
".",
"WCS",
")",
":",
"print",
"(",
"textutil",
".",
"textbox",
"(",
"'Reference WCS not a valid HSTWCS objec... | 52.125 | 14.125 |
def split_locale(loc):
'''
Split a locale specifier. The general format is
language[_territory][.codeset][@modifier] [charmap]
For example:
ca_ES.UTF-8@valencia UTF-8
'''
def split(st, char):
'''
Split a string `st` once by `char`; always return a two-element list
... | [
"def",
"split_locale",
"(",
"loc",
")",
":",
"def",
"split",
"(",
"st",
",",
"char",
")",
":",
"'''\n Split a string `st` once by `char`; always return a two-element list\n even if the second element is empty.\n '''",
"split_st",
"=",
"st",
".",
"split",
... | 27.615385 | 21.615385 |
def calculate_transmission(thickness_cm: np.float, atoms_per_cm3: np.float, sigma_b: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: f... | [
"def",
"calculate_transmission",
"(",
"thickness_cm",
":",
"np",
".",
"float",
",",
"atoms_per_cm3",
":",
"np",
".",
"float",
",",
"sigma_b",
":",
"np",
".",
"array",
")",
":",
"miu_per_cm",
"=",
"calculate_linear_attenuation_coefficient",
"(",
"atoms_per_cm3",
... | 38.555556 | 27.055556 |
def __authenticate(self, ad, username, password):
'''
Active Directory auth function
:param ad: LDAP connection string ('ldap://server')
:param username: username with domain ('user@domain.name')
:param password: auth password
:return: ldap connection or None if error
... | [
"def",
"__authenticate",
"(",
"self",
",",
"ad",
",",
"username",
",",
"password",
")",
":",
"result",
"=",
"None",
"conn",
"=",
"ldap",
".",
"initialize",
"(",
"ad",
")",
"conn",
".",
"protocol_version",
"=",
"3",
"conn",
".",
"set_option",
"(",
"ldap... | 39.965517 | 17.275862 |
def tf_step(self, time, variables, **kwargs):
"""
Keyword Args:
global_variables: List of global variables to apply the proposed optimization step to.
Returns:
List of delta tensors corresponding to the updates for each optimized variable.
"""
global_var... | [
"def",
"tf_step",
"(",
"self",
",",
"time",
",",
"variables",
",",
"*",
"*",
"kwargs",
")",
":",
"global_variables",
"=",
"kwargs",
"[",
"\"global_variables\"",
"]",
"assert",
"all",
"(",
"util",
".",
"shape",
"(",
"global_variable",
")",
"==",
"util",
"... | 41.878788 | 31.575758 |
def create_config_(self, index=0, update=False):
"""Create config file.
Create config file in :attr:`config_files_[index]`.
Parameters:
index(int): index of config file.
update (bool): if set to True and :attr:`config_files_` already
exists, its content ... | [
"def",
"create_config_",
"(",
"self",
",",
"index",
"=",
"0",
",",
"update",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"config_files_",
"[",
"index",
":",
"]",
":",
"return",
"path",
"=",
"self",
".",
"config_files_",
"[",
"index",
"]",
"if",... | 39.962963 | 15.333333 |
def cli(*args, **kwargs):
"""
CSVtoTable commandline utility.
"""
# Convert CSV file
content = convert.convert(kwargs["input_file"], **kwargs)
# Serve the temporary file in browser.
if kwargs["serve"]:
convert.serve(content)
# Write to output file
elif kwargs["output_file"]:... | [
"def",
"cli",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Convert CSV file",
"content",
"=",
"convert",
".",
"convert",
"(",
"kwargs",
"[",
"\"input_file\"",
"]",
",",
"*",
"*",
"kwargs",
")",
"# Serve the temporary file in browser.",
"if",
"kwar... | 34.391304 | 15.434783 |
def process_log_group(config):
"""CLI - Replay / Index
"""
from c7n.credentials import SessionFactory
factory = SessionFactory(
config.region, config.profile, assume_role=config.role)
session = factory()
client = session.client('logs')
params = dict(logGroupName=config.log_group,
... | [
"def",
"process_log_group",
"(",
"config",
")",
":",
"from",
"c7n",
".",
"credentials",
"import",
"SessionFactory",
"factory",
"=",
"SessionFactory",
"(",
"config",
".",
"region",
",",
"config",
".",
"profile",
",",
"assume_role",
"=",
"config",
".",
"role",
... | 37.577778 | 17.8 |
def confab_conformers(self, forcefield="mmff94", freeze_atoms=None,
rmsd_cutoff=0.5, energy_cutoff=50.0,
conf_cutoff=100000, verbose=False):
"""
Conformer generation based on Confab to generate all diverse low-energy
conformers for molecules. T... | [
"def",
"confab_conformers",
"(",
"self",
",",
"forcefield",
"=",
"\"mmff94\"",
",",
"freeze_atoms",
"=",
"None",
",",
"rmsd_cutoff",
"=",
"0.5",
",",
"energy_cutoff",
"=",
"50.0",
",",
"conf_cutoff",
"=",
"100000",
",",
"verbose",
"=",
"False",
")",
":",
"... | 42.7 | 21.1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.