text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def mac_move_detect_enable(self, **kwargs):
"""Enable mac move detect enable on vdx switches
Args:
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the mac-move-detect-enable.
(True, False)
callback... | [
"def",
"mac_move_detect_enable",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"self",
".",
"_callback",
")",
"mac_move",
"=",
"getattr",
"(",
"self",
".",
"_mac_address_table",
",",
"'mac_ad... | 43.225 | 0.001131 |
def task_context(self):
"""A thread-local that contains the following attributes.
current_task_id: For the main thread, this field is the ID of this
worker's current running task; for other threads, this field is a
fake random ID.
task_index: The number of tasks that hav... | [
"def",
"task_context",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"_task_context",
",",
"\"initialized\"",
")",
":",
"# Initialize task_context for the current thread.",
"if",
"ray",
".",
"utils",
".",
"is_main_thread",
"(",
")",
":",
"# If... | 51.361111 | 0.001062 |
def addon(self, name):
"""Set up an addon"""
cmd = ["heroku", "addons:create", name, "--app", self.name]
self._run(cmd) | [
"def",
"addon",
"(",
"self",
",",
"name",
")",
":",
"cmd",
"=",
"[",
"\"heroku\"",
",",
"\"addons:create\"",
",",
"name",
",",
"\"--app\"",
",",
"self",
".",
"name",
"]",
"self",
".",
"_run",
"(",
"cmd",
")"
] | 35 | 0.013986 |
def extend(self, xs: Union['List[T]', typing.List[T]]) -> 'List[T]': # type: ignore
"""doufo.List.extend
Args:
`self`
`xs` (`Union['List[T]', typing.List[T]]`): Another List object or Typing.List
Returns:
extented `List` (`List[T]`)
"""
... | [
"def",
"extend",
"(",
"self",
",",
"xs",
":",
"Union",
"[",
"'List[T]'",
",",
"typing",
".",
"List",
"[",
"T",
"]",
"]",
")",
"->",
"'List[T]'",
":",
"# type: ignore",
"return",
"type",
"(",
"self",
")",
"(",
"self",
".",
"unbox",
"(",
")",
"+",
... | 40.666667 | 0.024064 |
def getheaders(self, name):
"""Get all values for a header.
This returns a list of values for headers given more than once; each
value in the result list is stripped in the same way as the result of
getheader(). If the header is not given, return an empty list.
"""
resu... | [
"def",
"getheaders",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"[",
"]",
"current",
"=",
"''",
"have_header",
"=",
"0",
"for",
"s",
"in",
"self",
".",
"getallmatchingheaders",
"(",
"name",
")",
":",
"if",
"s",
"[",
"0",
"]",
".",
"isspace"... | 35.166667 | 0.002307 |
def _matcher(self, other):
"""
CGRContainer < CGRContainer
"""
if isinstance(other, CGRContainer):
return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y)
raise TypeError('only cgr-cgr possible') | [
"def",
"_matcher",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"CGRContainer",
")",
":",
"return",
"GraphMatcher",
"(",
"other",
",",
"self",
",",
"lambda",
"x",
",",
"y",
":",
"x",
"==",
"y",
",",
"lambda",
"x",
","... | 37.142857 | 0.011278 |
def decode_obj_table(table_entries, plugin):
"""Return root of obj table. Converts user-class objects"""
entries = []
for entry in table_entries:
if isinstance(entry, Container):
assert not hasattr(entry, '__recursion_lock__')
user_obj_def = plugin.user_objects[entry.classID]... | [
"def",
"decode_obj_table",
"(",
"table_entries",
",",
"plugin",
")",
":",
"entries",
"=",
"[",
"]",
"for",
"entry",
"in",
"table_entries",
":",
"if",
"isinstance",
"(",
"entry",
",",
"Container",
")",
":",
"assert",
"not",
"hasattr",
"(",
"entry",
",",
"... | 43.857143 | 0.001595 |
def __parse_addr(self, addr):
""" Parse email addresses
"""
from email.utils import parseaddr
value = parseaddr(addr)
return value[0], value[1] | [
"def",
"__parse_addr",
"(",
"self",
",",
"addr",
")",
":",
"from",
"email",
".",
"utils",
"import",
"parseaddr",
"value",
"=",
"parseaddr",
"(",
"addr",
")",
"return",
"value",
"[",
"0",
"]",
",",
"value",
"[",
"1",
"]"
] | 22.25 | 0.010811 |
def autodoc_skip(app, what, name, obj, skip, options):
"""Hook that tells autodoc to include or exclude certain fields.
Sadly, it doesn't give a reference to the parent object,
so only the ``name`` can be used for referencing.
:type app: sphinx.application.Sphinx
:param what: The parent type, ``cl... | [
"def",
"autodoc_skip",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"skip",
",",
"options",
")",
":",
"if",
"name",
"in",
"config",
".",
"EXCLUDE_MEMBERS",
":",
"return",
"True",
"if",
"name",
"in",
"config",
".",
"INCLUDE_MEMBERS",
":",
"ret... | 33.5 | 0.002418 |
def getDigitalChannelData(self,ChNumber):
"""
Returns an array of numbers (0 or 1) containing the values of the
digital channel status.
ChNumber: digital channel number.
"""
if not self.DatFileContent:
print "No data file content. Use the method Rea... | [
"def",
"getDigitalChannelData",
"(",
"self",
",",
"ChNumber",
")",
":",
"if",
"not",
"self",
".",
"DatFileContent",
":",
"print",
"\"No data file content. Use the method ReadDataFile first\"",
"return",
"0",
"if",
"(",
"ChNumber",
">",
"self",
".",
"D",
")",
":",
... | 41.428571 | 0.010668 |
def ct2mu(im):
'''HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images,
'''
# convert nans to -1024 for the HU values only
im[np.isnan(im)] = -1024
# constants
muwat... | [
"def",
"ct2mu",
"(",
"im",
")",
":",
"# convert nans to -1024 for the HU values only",
"im",
"[",
"np",
".",
"isnan",
"(",
"im",
")",
"]",
"=",
"-",
"1024",
"# constants",
"muwater",
"=",
"0.096",
"mubone",
"=",
"0.172",
"rhowater",
"=",
"0.184",
"rhobone",
... | 32.684211 | 0.020344 |
def niplot():
"""
This script extends the native matplolib keyboard bindings.
This script allows to use the `up`, `down`, `left`, and `right` keys
to move the visualization window. Zooming can be performed using the `+`
and `-` keys. Finally, the scroll wheel can be used to zoom under cursor.
R... | [
"def",
"niplot",
"(",
")",
":",
"fig",
"=",
"gcf",
"(",
")",
"cid",
"=",
"fig",
".",
"canvas",
".",
"mpl_connect",
"(",
"'key_press_event'",
",",
"# @UnusedVariable",
"on_key_press",
")",
"cid",
"=",
"fig",
".",
"canvas",
".",
"mpl_connect",
"(",
"'key_r... | 37.764706 | 0.00152 |
def maybe_future(x):
"""Converts ``x`` into a `.Future`.
If ``x`` is already a `.Future`, it is simply returned; otherwise
it is wrapped in a new `.Future`. This is suitable for use as
``result = yield gen.maybe_future(f())`` when you don't know whether
``f()`` returns a `.Future` or not.
.. ... | [
"def",
"maybe_future",
"(",
"x",
")",
":",
"if",
"is_future",
"(",
"x",
")",
":",
"return",
"x",
"else",
":",
"fut",
"=",
"Future",
"(",
")",
"fut",
".",
"set_result",
"(",
"x",
")",
"return",
"fut"
] | 34.894737 | 0.001468 |
def CreateSmartShoppingAd(client, ad_group_id):
"""Adds a new Smart Shopping ad.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID for an ad group.
"""
ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
# Create an AdGroup Ad.
adgroup_ad = {
'adGr... | [
"def",
"CreateSmartShoppingAd",
"(",
"client",
",",
"ad_group_id",
")",
":",
"ad_group_ad_service",
"=",
"client",
".",
"GetService",
"(",
"'AdGroupAdService'",
",",
"version",
"=",
"'v201809'",
")",
"# Create an AdGroup Ad.",
"adgroup_ad",
"=",
"{",
"'adGroupId'",
... | 28.925926 | 0.012392 |
def crypto_validator(func):
"""
This a decorator to be used for any method relying on the cryptography library. # noqa: E501
Its behaviour depends on the 'crypto_valid' attribute of the global 'conf'.
"""
def func_in(*args, **kwargs):
if not conf.crypto_valid:
raise ImportError(... | [
"def",
"crypto_validator",
"(",
"func",
")",
":",
"def",
"func_in",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"conf",
".",
"crypto_valid",
":",
"raise",
"ImportError",
"(",
"\"Cannot execute crypto-related method! \"",
"\"Please install p... | 45.727273 | 0.001949 |
def _is_aborted(self, cycle, statustext, total_elements=None, freq=None):
"""Displays progress and returns True if abort
Parameters
----------
cycle: Integer
\tThe current operation cycle
statustext: String
\tLeft text in statusbar to be displayed
total_... | [
"def",
"_is_aborted",
"(",
"self",
",",
"cycle",
",",
"statustext",
",",
"total_elements",
"=",
"None",
",",
"freq",
"=",
"None",
")",
":",
"if",
"total_elements",
"is",
"None",
":",
"statustext",
"+=",
"_",
"(",
"\"{nele} elements processed. Press <Esc> to abor... | 31.055556 | 0.001734 |
def binning(keys, start, end, count, axes=None):
"""Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10)
"""
if isinstance(keys, tuple):
n_keys = len(keys)
e... | [
"def",
"binning",
"(",
"keys",
",",
"start",
",",
"end",
",",
"count",
",",
"axes",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"keys",
",",
"tuple",
")",
":",
"n_keys",
"=",
"len",
"(",
"keys",
")",
"else",
":",
"n_keys",
"=",
"1",
"bins",
... | 23.15 | 0.002075 |
def prepare_parser(program):
"""Create and populate an argument parser."""
parser = ArgumentParser(
description=PROG_DESCRIPTION, prog=program,
formatter_class=HelpFormatter,
add_help=False)
parser.add_argument(
"-h", "--help", action=MinimalHelpAction, help=argparse.SUPPRESS... | [
"def",
"prepare_parser",
"(",
"program",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"PROG_DESCRIPTION",
",",
"prog",
"=",
"program",
",",
"formatter_class",
"=",
"HelpFormatter",
",",
"add_help",
"=",
"False",
")",
"parser",
".",
"add_... | 30.851852 | 0.001164 |
def fn_device_dependency(name, device=""):
"""Add control deps for name and device."""
key = name + "_" + device
outs = []
def body():
with tf.control_dependencies(fn_device_dependency_dict()[key]):
yield outs
assert outs
deps = outs
if isinstance(outs[0], (list, tuple)):
a... | [
"def",
"fn_device_dependency",
"(",
"name",
",",
"device",
"=",
"\"\"",
")",
":",
"key",
"=",
"name",
"+",
"\"_\"",
"+",
"device",
"outs",
"=",
"[",
"]",
"def",
"body",
"(",
")",
":",
"with",
"tf",
".",
"control_dependencies",
"(",
"fn_device_dependency_... | 22.714286 | 0.026157 |
def indicate_fulfillment_fcp(self, wwpn, lun, host_port):
"""
Indicate completion of :term:`fulfillment` for this FCP storage volume
and provide identifying information (WWPN and LUN) about the actual
storage volume on the storage subsystem.
Manually indicating fulfillment is re... | [
"def",
"indicate_fulfillment_fcp",
"(",
"self",
",",
"wwpn",
",",
"lun",
",",
"host_port",
")",
":",
"# The operation requires exactly 16 characters in lower case",
"wwpn_16",
"=",
"format",
"(",
"int",
"(",
"wwpn",
",",
"16",
")",
",",
"'016x'",
")",
"lun_16",
... | 40.142857 | 0.000695 |
def block_idxmat_shuffle(numdraws, numblocks, random_state=None):
"""Create K columns with unique random integers from 0 to N-1
Purpose:
--------
- Create K blocks for k-fold cross-validation
Parameters:
-----------
numdraws : int
number of observations N or sample size N
numb... | [
"def",
"block_idxmat_shuffle",
"(",
"numdraws",
",",
"numblocks",
",",
"random_state",
"=",
"None",
")",
":",
"# load modules",
"import",
"numpy",
"as",
"np",
"# minimum block size: bz=int(N/K)",
"blocksize",
"=",
"int",
"(",
"numdraws",
"/",
"numblocks",
")",
"# ... | 27.2 | 0.000546 |
def daemonize(pid_file=None, cwd=None):
"""
Detach a process from the controlling terminal and run it in the
background as a daemon.
Modified version of:
code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/
author = "Chad J. Schroeder"
copyright = "Copyright (C) 2005 C... | [
"def",
"daemonize",
"(",
"pid_file",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"cwd",
"=",
"cwd",
"or",
"'/'",
"try",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"Exception",
"(",
"\"%s [%d]\"",... | 30.960784 | 0.000614 |
def fit_gen(self, model, data, layer_opt, n_cycle, cycle_len=None, cycle_mult=1, cycle_save_name=None, best_save_name=None,
use_clr=None, use_clr_beta=None, metrics=None, callbacks=None, use_wd_sched=False, norm_wds=False,
wds_sched_mult=None, use_swa=False, swa_start=1, swa... | [
"def",
"fit_gen",
"(",
"self",
",",
"model",
",",
"data",
",",
"layer_opt",
",",
"n_cycle",
",",
"cycle_len",
"=",
"None",
",",
"cycle_mult",
"=",
"1",
",",
"cycle_save_name",
"=",
"None",
",",
"best_save_name",
"=",
"None",
",",
"use_clr",
"=",
"None",
... | 56.01626 | 0.009412 |
def get(self, setting_name, warn_only_if_overridden=False,
accept_deprecated='', suppress_warnings=False,
enforce_type=None, check_if_setting_deprecated=True,
warning_stacklevel=3):
"""
Returns a setting value for the setting named by ``setting_name``. The
ret... | [
"def",
"get",
"(",
"self",
",",
"setting_name",
",",
"warn_only_if_overridden",
"=",
"False",
",",
"accept_deprecated",
"=",
"''",
",",
"suppress_warnings",
"=",
"False",
",",
"enforce_type",
"=",
"None",
",",
"check_if_setting_deprecated",
"=",
"True",
",",
"wa... | 48.513274 | 0.000894 |
def page_context(request, site, **criterias):
'Returns the context dictionary for a page view.'
try: page = int(request.GET.get('page', 1))
except ValueError: page = 1
feed, tag = criterias.get('feed'), criterias.get('tag')
if feed:
try: feed = models.Feed.objects.get(pk=feed)
except ObjectDoesNotExist: raise... | [
"def",
"page_context",
"(",
"request",
",",
"site",
",",
"*",
"*",
"criterias",
")",
":",
"try",
":",
"page",
"=",
"int",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"'page'",
",",
"1",
")",
")",
"except",
"ValueError",
":",
"page",
"=",
"1",
"f... | 33.6 | 0.045898 |
def intersection(self, keys):
"""
Return the intersection of the segmentlists associated with
the keys in keys.
"""
keys = set(keys)
if not keys:
return segmentlist()
seglist = _shallowcopy(self[keys.pop()])
for key in keys:
seglist &= self[key]
return seglist | [
"def",
"intersection",
"(",
"self",
",",
"keys",
")",
":",
"keys",
"=",
"set",
"(",
"keys",
")",
"if",
"not",
"keys",
":",
"return",
"segmentlist",
"(",
")",
"seglist",
"=",
"_shallowcopy",
"(",
"self",
"[",
"keys",
".",
"pop",
"(",
")",
"]",
")",
... | 22.75 | 0.045775 |
def _generate_nodes(self, name, command, templates=None):
"""Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of the config to be documented, e... | [
"def",
"_generate_nodes",
"(",
"self",
",",
"name",
",",
"command",
",",
"templates",
"=",
"None",
")",
":",
"# the source name",
"source_name",
"=",
"name",
"# Title",
"section",
"=",
"nodes",
".",
"section",
"(",
"''",
",",
"nodes",
".",
"title",
"(",
... | 26.317073 | 0.001787 |
def handle_split(self, asset, ratio):
"""
Update the position by the split ratio, and return the resulting
fractional share that will be converted into cash.
Returns the unused cash.
"""
if self.asset != asset:
raise Exception("updating split with the wrong a... | [
"def",
"handle_split",
"(",
"self",
",",
"asset",
",",
"ratio",
")",
":",
"if",
"self",
".",
"asset",
"!=",
"asset",
":",
"raise",
"Exception",
"(",
"\"updating split with the wrong asset!\"",
")",
"# adjust the # of shares by the ratio",
"# (if we had 100 shares, and t... | 32.974359 | 0.001511 |
def contains_frame(data):
"""
Read the frame length from the start of `data` and check if the data is
long enough to contain the entire frame.
"""
if len(data) < 2:
return False
b2 = struct.unpack('!B', data[1])[0]
payload_len = b2 & 0x7F
payload_start = 2
if payload_len ==... | [
"def",
"contains_frame",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"<",
"2",
":",
"return",
"False",
"b2",
"=",
"struct",
".",
"unpack",
"(",
"'!B'",
",",
"data",
"[",
"1",
"]",
")",
"[",
"0",
"]",
"payload_len",
"=",
"b2",
"&",
"0x... | 25.541667 | 0.001572 |
def snap_install_requested():
""" Determine if installing from snaps
If openstack-origin is of the form snap:track/channel[/branch]
and channel is in SNAPS_CHANNELS return True.
"""
origin = config('openstack-origin') or ""
if not origin.startswith('snap:'):
return False
_src = ori... | [
"def",
"snap_install_requested",
"(",
")",
":",
"origin",
"=",
"config",
"(",
"'openstack-origin'",
")",
"or",
"\"\"",
"if",
"not",
"origin",
".",
"startswith",
"(",
"'snap:'",
")",
":",
"return",
"False",
"_src",
"=",
"origin",
"[",
"5",
":",
"]",
"if",... | 28.705882 | 0.001984 |
def _warn_if_not_at_expected_pos(self, expected_pos, end_of, start_of):
""" Helper function to warn about unknown bytes found in the file"""
diff = expected_pos - self.stream.tell()
if diff != 0:
logger.warning(
"There are {} bytes between {} and {}".format(diff, end_... | [
"def",
"_warn_if_not_at_expected_pos",
"(",
"self",
",",
"expected_pos",
",",
"end_of",
",",
"start_of",
")",
":",
"diff",
"=",
"expected_pos",
"-",
"self",
".",
"stream",
".",
"tell",
"(",
")",
"if",
"diff",
"!=",
"0",
":",
"logger",
".",
"warning",
"("... | 48.714286 | 0.008646 |
def set_grade(
self,
assignment_id,
student_id,
grade_value,
gradebook_id='',
**kwargs
):
"""Set numerical grade for student and assignment.
Set a numerical grade for for a student and assignment. Additional
options
... | [
"def",
"set_grade",
"(",
"self",
",",
"assignment_id",
",",
"student_id",
",",
"grade_value",
",",
"gradebook_id",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=too-many-arguments",
"# numericGradeValue stringified because 'x' is a possible",
"# value f... | 33.666667 | 0.00111 |
def with_read_ligolw(func=None, contenthandler=None):
"""Decorate a LIGO_LW-reading function to open a filepath if needed
``func`` should be written to presume a
:class:`~ligo.lw.ligolw.Document` as the first positional argument
"""
def decorator(func_):
# pylint: disable=missing-docstring
... | [
"def",
"with_read_ligolw",
"(",
"func",
"=",
"None",
",",
"contenthandler",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func_",
")",
":",
"# pylint: disable=missing-docstring",
"@",
"wraps",
"(",
"func_",
")",
"def",
"decorated_func",
"(",
"source",
",",
... | 39.777778 | 0.000909 |
def trmm(L, B, alpha = 1.0, trans = 'N', nrhs = None, offsetB = 0, ldB = None):
r"""
Multiplication with sparse triangular matrix. Computes
.. math::
B &:= \alpha L B \text{ if trans is 'N'} \\
B &:= \alpha L^T B \text{ if trans is 'T'}
where :math:`L` is a :py:class:`cspmatrix` fac... | [
"def",
"trmm",
"(",
"L",
",",
"B",
",",
"alpha",
"=",
"1.0",
",",
"trans",
"=",
"'N'",
",",
"nrhs",
"=",
"None",
",",
"offsetB",
"=",
"0",
",",
"ldB",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"L",
",",
"cspmatrix",
")",
"and",
"L",
... | 33.196429 | 0.0269 |
def play(self, audio, **kwargs):
"""
Start another thread playing the given audio sample iterable (e.g. a
list, a generator, a NumPy np.ndarray with samples), and play it.
The arguments are used to customize behaviour of the new thread, as
parameters directly sent to PyAudio's new stream opening met... | [
"def",
"play",
"(",
"self",
",",
"audio",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"finished",
":",
"raise",
"threading",
".",
"ThreadError",
"(",
"\"Trying to play an audio stream while \"",
"\"halting the AudioI... | 43.25 | 0.008487 |
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
... | [
"def",
"_parse_openssl_crl",
"(",
"crl_filename",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'openssl'",
")",
":",
"raise",
"salt",
".",
"exceptions",
".",
"SaltInvocationError",
"(",
"'openssl binary not found in path'",
")",
... | 38.915493 | 0.000353 |
def jsonify(self, status_code=None, message=None, headers=None):
"""
Returns a representation of the error in a jsonic form that is
compatible with flask's error handling.
Keyword arguments allow custom error handlers to override parts of the
exception when it is jsonified
... | [
"def",
"jsonify",
"(",
"self",
",",
"status_code",
"=",
"None",
",",
"message",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"status_code",
"is",
"None",
":",
"status_code",
"=",
"self",
".",
"status_code",
"if",
"message",
"is",
"None",
"... | 34.708333 | 0.002336 |
def parse(self,
sheet_name=0,
header=0,
names=None,
index_col=None,
usecols=None,
squeeze=False,
converters=None,
true_values=None,
false_values=None,
skiprows=None,
... | [
"def",
"parse",
"(",
"self",
",",
"sheet_name",
"=",
"0",
",",
"header",
"=",
"0",
",",
"names",
"=",
"None",
",",
"index_col",
"=",
"None",
",",
"usecols",
"=",
"None",
",",
"squeeze",
"=",
"False",
",",
"converters",
"=",
"None",
",",
"true_values"... | 41.557377 | 0.008478 |
def handle_arguments(self, string, root, opening, closing):
"""
Handles phrase-arguments.
Sets the override and increment flags if found. Also makes
sure that the argument sequence is at the start of the phrase
and else warns about the unescaped meta characters. If the
arguments are indeed at the start bu... | [
"def",
"handle_arguments",
"(",
"self",
",",
"string",
",",
"root",
",",
"opening",
",",
"closing",
")",
":",
"# The actual argument string (ignore whitespace)",
"args",
"=",
"string",
"[",
"opening",
"+",
"1",
":",
"closing",
"]",
".",
"replace",
"(",
"\" \""... | 31.508197 | 0.023713 |
def function_present(name, FunctionName, Runtime, Role, Handler, ZipFile=None,
S3Bucket=None, S3Key=None, S3ObjectVersion=None,
Description='', Timeout=3, MemorySize=128,
Permissions=None, RoleRetries=5, region=None, key=None,
keyid=Non... | [
"def",
"function_present",
"(",
"name",
",",
"FunctionName",
",",
"Runtime",
",",
"Role",
",",
"Handler",
",",
"ZipFile",
"=",
"None",
",",
"S3Bucket",
"=",
"None",
",",
"S3Key",
"=",
"None",
",",
"S3ObjectVersion",
"=",
"None",
",",
"Description",
"=",
... | 40.017778 | 0.001842 |
def pow(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and
raises the datapoint by the power of the constant provided at each point.
Example::
&target=pow(Server.instance01.threads.busy,10)
&target=pow(Server.instance*.threads... | [
"def",
"pow",
"(",
"requestContext",
",",
"seriesList",
",",
"factor",
")",
":",
"for",
"series",
"in",
"seriesList",
":",
"series",
".",
"name",
"=",
"\"pow(%s,%g)\"",
"%",
"(",
"series",
".",
"name",
",",
"float",
"(",
"factor",
")",
")",
"series",
"... | 33.764706 | 0.001695 |
def iterable(self, iterable_name, *, collection, attribute, word, func=None,
operation=None):
""" Performs a filter with the OData 'iterable_name' keyword
on the collection
For example:
q.iterable('any', collection='email_addresses', attribute='address',
operati... | [
"def",
"iterable",
"(",
"self",
",",
"iterable_name",
",",
"*",
",",
"collection",
",",
"attribute",
",",
"word",
",",
"func",
"=",
"None",
",",
"operation",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
"and",
"operation",
"is",
"None",
":",
"r... | 37.469388 | 0.002123 |
def counter_clockwise(cx, cy):
"""Put contour coordinates into counter-clockwise order
Parameters
----------
cx, cy: 1d ndarrays
The x- and y-coordinates of the contour
Returns
-------
cx_cc, cy_cc:
The x- and y-coordinates of the contour in
counter-clockwise orient... | [
"def",
"counter_clockwise",
"(",
"cx",
",",
"cy",
")",
":",
"# test orientation",
"angles",
"=",
"np",
".",
"unwrap",
"(",
"np",
".",
"arctan2",
"(",
"cy",
",",
"cx",
")",
")",
"grad",
"=",
"np",
".",
"gradient",
"(",
"angles",
")",
"if",
"np",
"."... | 24.095238 | 0.001901 |
def collection(self, path):
"""To return all items generated by get collection."""
data = []
for item in self.get_collection(path):
data.append(item)
return data | [
"def",
"collection",
"(",
"self",
",",
"path",
")",
":",
"data",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"get_collection",
"(",
"path",
")",
":",
"data",
".",
"append",
"(",
"item",
")",
"return",
"data"
] | 33.333333 | 0.009756 |
def load_dale_chall(self):
"""Create the dictionary of words, and grade dictionary, for the Dale-Chall readability test."""
self.dale_chall_dict = os.path.join(self.base_dir, 'dicts', 'dale_chall.txt')
with open(self.dale_chall_dict) as words_file:
data = words_file.read()
se... | [
"def",
"load_dale_chall",
"(",
"self",
")",
":",
"self",
".",
"dale_chall_dict",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base_dir",
",",
"'dicts'",
",",
"'dale_chall.txt'",
")",
"with",
"open",
"(",
"self",
".",
"dale_chall_dict",
")",
"a... | 59.833333 | 0.010989 |
def acp_users_edit():
"""Edit an user account."""
global current_user
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
data = request.form
form = UserEditForm()
if n... | [
"def",
"acp_users_edit",
"(",
")",
":",
"global",
"current_user",
"if",
"not",
"current_user",
".",
"is_admin",
":",
"return",
"error",
"(",
"\"Not authorized to edit users.\"",
",",
"401",
")",
"if",
"not",
"db",
":",
"return",
"error",
"(",
"'The ACP is not av... | 32.619718 | 0.000419 |
def check_to_generate_or_run(argv, sim):
"""
Useful method for calling in main method after network and simulation are
generated, to handle some standard export options like -jnml, -graph etc.
"""
print_v("Checking arguments: %s to see whether anything should be run in simulation %s (net: %s).... | [
"def",
"check_to_generate_or_run",
"(",
"argv",
",",
"sim",
")",
":",
"print_v",
"(",
"\"Checking arguments: %s to see whether anything should be run in simulation %s (net: %s)...\"",
"%",
"(",
"argv",
",",
"sim",
".",
"id",
",",
"sim",
".",
"network",
")",
")",
"if",... | 37 | 0.011409 |
def simxSetObjectOrientation(clientID, objectHandle, relativeToObjectHandle, eulerAngles, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
angles = (ct.c_float*3)(*eulerAngles)
return c_SetObjectOrientation(clientID, objectHandle, relativ... | [
"def",
"simxSetObjectOrientation",
"(",
"clientID",
",",
"objectHandle",
",",
"relativeToObjectHandle",
",",
"eulerAngles",
",",
"operationMode",
")",
":",
"angles",
"=",
"(",
"ct",
".",
"c_float",
"*",
"3",
")",
"(",
"*",
"eulerAngles",
")",
"return",
"c_SetO... | 50.428571 | 0.011142 |
def load_character(tile_map, gamescreen):
"""Create an instance of the main character and return it."""
tile_obj = thc.TileHeroCharacter(tile_map, gamescreen)
tile_obj.load_texture("..//Textures//character.png")
tile_obj.origin = r.Vector2(0, 0)
tile_obj.hazard_touched_method = hazard_touched_method... | [
"def",
"load_character",
"(",
"tile_map",
",",
"gamescreen",
")",
":",
"tile_obj",
"=",
"thc",
".",
"TileHeroCharacter",
"(",
"tile_map",
",",
"gamescreen",
")",
"tile_obj",
".",
"load_texture",
"(",
"\"..//Textures//character.png\"",
")",
"tile_obj",
".",
"origin... | 49.25 | 0.002494 |
def _readfile(cls, filename):
""" Reads a file a utf-8 file,
and retuns character tokens.
:param filename: Name of file to be read.
"""
f = codecs.open(filename, encoding='utf-8')
filedata = f.read()
f.close()
tokenz = LM.tokenize(filedata, mode='... | [
"def",
"_readfile",
"(",
"cls",
",",
"filename",
")",
":",
"f",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"filedata",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"tokenz",
"=",
"LM",
".",... | 29.666667 | 0.008174 |
def get_completions(prefix, paths=None, family_only=False):
"""Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str):... | [
"def",
"get_completions",
"(",
"prefix",
",",
"paths",
"=",
"None",
",",
"family_only",
"=",
"False",
")",
":",
"op",
"=",
"None",
"if",
"prefix",
":",
"if",
"prefix",
"[",
"0",
"]",
"in",
"(",
"'!'",
",",
"'~'",
")",
":",
"if",
"family_only",
":",... | 26.481481 | 0.000674 |
def cli(ctx, feature_id, organism="", sequence=""):
"""Get the GFF3 associated with a feature
Output:
GFF3 text content
"""
return ctx.gi.annotations.get_gff3(feature_id, organism=organism, sequence=sequence) | [
"def",
"cli",
"(",
"ctx",
",",
"feature_id",
",",
"organism",
"=",
"\"\"",
",",
"sequence",
"=",
"\"\"",
")",
":",
"return",
"ctx",
".",
"gi",
".",
"annotations",
".",
"get_gff3",
"(",
"feature_id",
",",
"organism",
"=",
"organism",
",",
"sequence",
"=... | 27.375 | 0.00885 |
def load_labeled_intervals(filename, delimiter=r'\s+'):
r"""Import labeled intervals from an annotation file. The file should consist
of three columns: Two consisting of numeric values corresponding to start
and end time of each interval and a third corresponding to the label of
each interval. This is... | [
"def",
"load_labeled_intervals",
"(",
"filename",
",",
"delimiter",
"=",
"r'\\s+'",
")",
":",
"# Use our universal function to load in the events",
"starts",
",",
"ends",
",",
"labels",
"=",
"load_delimited",
"(",
"filename",
",",
"[",
"float",
",",
"float",
",",
... | 36.171429 | 0.001538 |
def idle_task(self):
'''called on idle'''
if mp_util.has_wxpython and (not self.menu_added_console and self.module('console') is not None):
self.menu_added_console = True
# we don't dynamically update these yet due to a wx bug
self.menu_add.items = [ MPMenuItem(p, p, ... | [
"def",
"idle_task",
"(",
"self",
")",
":",
"if",
"mp_util",
".",
"has_wxpython",
"and",
"(",
"not",
"self",
".",
"menu_added_console",
"and",
"self",
".",
"module",
"(",
"'console'",
")",
"is",
"not",
"None",
")",
":",
"self",
".",
"menu_added_console",
... | 62.25 | 0.011873 |
def randomfill(a):
"""Fill masked areas with random noise
This is needed for any fft-based operations
"""
a = checkma(a)
#For data that have already been normalized,
#This provides a proper normal distribution with mean=0 and std=1
#a = (a - a.mean()) / a.std()
#noise = a.mask * (np... | [
"def",
"randomfill",
"(",
"a",
")",
":",
"a",
"=",
"checkma",
"(",
"a",
")",
"#For data that have already been normalized,",
"#This provides a proper normal distribution with mean=0 and std=1",
"#a = (a - a.mean()) / a.std()",
"#noise = a.mask * (np.random.randn(*a.shape))",
"noise",... | 32.642857 | 0.014894 |
def configure_and_build(self, show_progress=True, optimized=True,
skip_configuration=False):
"""
Configure and build the ns-3 code.
Args:
show_progress (bool): whether or not to display a progress bar
during compilation.
optimi... | [
"def",
"configure_and_build",
"(",
"self",
",",
"show_progress",
"=",
"True",
",",
"optimized",
"=",
"True",
",",
"skip_configuration",
"=",
"False",
")",
":",
"# Only configure if necessary",
"if",
"not",
"skip_configuration",
":",
"configuration_command",
"=",
"["... | 42.829787 | 0.002428 |
def get_nodes_positions(self):
"""
Getter method for nodes positions.
:return: A dictionary with nodes as keys and positions as values
"""
nodes = self.get_nodes()
output = {}
for node in nodes:
output[node[0]] = (float(node[1][consts.Consts.x]), floa... | [
"def",
"get_nodes_positions",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"get_nodes",
"(",
")",
"output",
"=",
"{",
"}",
"for",
"node",
"in",
"nodes",
":",
"output",
"[",
"node",
"[",
"0",
"]",
"]",
"=",
"(",
"float",
"(",
"node",
"[",
"1"... | 32.727273 | 0.008108 |
def _get_area_def_uniform_sampling(self, lon0, channel):
"""Get area definition with uniform sampling"""
logger.debug('Computing area definition')
if lon0 is not None:
# Define proj4 projection parameters
proj_dict = {'a': EQUATOR_RADIUS,
'b': PO... | [
"def",
"_get_area_def_uniform_sampling",
"(",
"self",
",",
"lon0",
",",
"channel",
")",
":",
"logger",
".",
"debug",
"(",
"'Computing area definition'",
")",
"if",
"lon0",
"is",
"not",
"None",
":",
"# Define proj4 projection parameters",
"proj_dict",
"=",
"{",
"'a... | 40.560976 | 0.002349 |
def inkscape_export(input_file, output_file, export_flag="-A", dpi=90, inkscape_binpath=None):
""" Call Inkscape to export the input_file to output_file using the
specific export argument flag for the output file type.
Parameters
----------
input_file: str
Path to the input file
outpu... | [
"def",
"inkscape_export",
"(",
"input_file",
",",
"output_file",
",",
"export_flag",
"=",
"\"-A\"",
",",
"dpi",
"=",
"90",
",",
"inkscape_binpath",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"input_file",
")",
":",
"log",
... | 28.486486 | 0.001835 |
def _CreateZMQSocket(self):
"""Creates a ZeroMQ socket as well as a regular queue and a thread."""
super(ZeroMQBufferedQueue, self)._CreateZMQSocket()
if not self._zmq_thread:
thread_name = '{0:s}_zmq_responder'.format(self.name)
self._zmq_thread = threading.Thread(
target=self._ZeroMQ... | [
"def",
"_CreateZMQSocket",
"(",
"self",
")",
":",
"super",
"(",
"ZeroMQBufferedQueue",
",",
"self",
")",
".",
"_CreateZMQSocket",
"(",
")",
"if",
"not",
"self",
".",
"_zmq_thread",
":",
"thread_name",
"=",
"'{0:s}_zmq_responder'",
".",
"format",
"(",
"self",
... | 49 | 0.010025 |
def fast_ordering(self, structure, num_remove_dict, num_to_return=1):
"""
This method uses the matrix form of ewaldsum to calculate the ewald
sums of the potential structures. This is on the order of 4 orders of
magnitude faster when there are large numbers of permutations to
con... | [
"def",
"fast_ordering",
"(",
"self",
",",
"structure",
",",
"num_remove_dict",
",",
"num_to_return",
"=",
"1",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Performing fast ordering\"",
")",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"self",
... | 42.44 | 0.000921 |
def update(name, profile="splunk", **kwargs):
'''
Update a splunk search
CLI Example:
splunk_search.update 'my search name' sharing=app
'''
client = _get_splunk(profile)
search = client.saved_searches[name]
props = _get_splunk_search_props(search)
updates = kwargs
update_ne... | [
"def",
"update",
"(",
"name",
",",
"profile",
"=",
"\"splunk\"",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"search",
"=",
"client",
".",
"saved_searches",
"[",
"name",
"]",
"props",
"=",
"_get_splunk_search_props... | 30.65625 | 0.000988 |
def get_process_list(mc, x_=None, y_=None, p_=None,
app_ids=None, applications=None, states=None):
"""Scan a SpiNNaker system's cores filtering by the specified features.
Generates
-------
(x, y, core, state, runtime_exception, application, app_id)
"""
system_info = mc.get... | [
"def",
"get_process_list",
"(",
"mc",
",",
"x_",
"=",
"None",
",",
"y_",
"=",
"None",
",",
"p_",
"=",
"None",
",",
"app_ids",
"=",
"None",
",",
"applications",
"=",
"None",
",",
"states",
"=",
"None",
")",
":",
"system_info",
"=",
"mc",
".",
"get_s... | 38.74359 | 0.000646 |
def printSkosTree(self, element = None, showids=False, labels=False, showtype=False):
"""
Print nicely into stdout the SKOS tree of an ontology
Note: indentation is made so that ids up to 3 digits fit in, plus a space.
[123]1--
[1]123--
[12]12--
"""
TYPE_... | [
"def",
"printSkosTree",
"(",
"self",
",",
"element",
"=",
"None",
",",
"showids",
"=",
"False",
",",
"labels",
"=",
"False",
",",
"showtype",
"=",
"False",
")",
":",
"TYPE_MARGIN",
"=",
"13",
"# length for skos:concept",
"if",
"not",
"element",
":",
"# fir... | 35.470588 | 0.012924 |
def system_methodHelp(self, method_name):
"""system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method."""
method = None
if method_name in self.funcs:
method = self.funcs[method_name]
elif self.instan... | [
"def",
"system_methodHelp",
"(",
"self",
",",
"method_name",
")",
":",
"method",
"=",
"None",
"if",
"method_name",
"in",
"self",
".",
"funcs",
":",
"method",
"=",
"self",
".",
"funcs",
"[",
"method_name",
"]",
"elif",
"self",
".",
"instance",
"is",
"not"... | 40.4 | 0.001612 |
def quadraticSolver(a, b, c):
"""return solution(s) for x, to the quadratic equation a*x^2 + b*x + c
when it equals zero using the quadratic formula"""
if a == 0:
if b == 0: return [] # attempting to solve an equation with infinite (0=0) or impossible (0=3) solutions for x
else: retur... | [
"def",
"quadraticSolver",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"if",
"a",
"==",
"0",
":",
"if",
"b",
"==",
"0",
":",
"return",
"[",
"]",
"# attempting to solve an equation with infinite (0=0) or impossible (0=3) solutions for x",
"else",
":",
"return",
"[",
... | 54 | 0.024272 |
def tarjan(graph):
"""Strongly connected components by Tarjan, iterative implementation
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear
"""
n = len(graph)
dfs_num = [None] * n
dfs_min = [n] * n
waitin... | [
"def",
"tarjan",
"(",
"graph",
")",
":",
"n",
"=",
"len",
"(",
"graph",
")",
"dfs_num",
"=",
"[",
"None",
"]",
"*",
"n",
"dfs_min",
"=",
"[",
"n",
"]",
"*",
"n",
"waiting",
"=",
"[",
"]",
"waits",
"=",
"[",
"False",
"]",
"*",
"n",
"# invarian... | 44.32 | 0.000442 |
def boxify_points(geom, rast):
"""
Point and MultiPoint don't play well with GDALRasterize
convert them into box polygons 99% cellsize, centered on the raster cell
"""
if 'Point' not in geom.type:
raise ValueError("Points or multipoints only")
buff = -0.01 * abs(min(rast.affine.a, rast.... | [
"def",
"boxify_points",
"(",
"geom",
",",
"rast",
")",
":",
"if",
"'Point'",
"not",
"in",
"geom",
".",
"type",
":",
"raise",
"ValueError",
"(",
"\"Points or multipoints only\"",
")",
"buff",
"=",
"-",
"0.01",
"*",
"abs",
"(",
"min",
"(",
"rast",
".",
"... | 30.952381 | 0.001493 |
def ttime(timestamp=None, tzone=None, fail="", fmt="%Y-%m-%d %H:%M:%S"):
"""Translate timestamp into human-readable: %Y-%m-%d %H:%M:%S.
:param timestamp: the timestamp float, or `time.time()` by default.
:param tzone: time compensation, int(-time.timezone / 3600) by default,
(can be set wit... | [
"def",
"ttime",
"(",
"timestamp",
"=",
"None",
",",
"tzone",
"=",
"None",
",",
"fail",
"=",
"\"\"",
",",
"fmt",
"=",
"\"%Y-%m-%d %H:%M:%S\"",
")",
":",
"tzone",
"=",
"Config",
".",
"TIMEZONE",
"if",
"tzone",
"is",
"None",
"else",
"tzone",
"fix_tz",
"="... | 34.25 | 0.001775 |
def is_unknown(self, path):
'''Is the node pointed to by @ref path an unknown object?'''
node = self.get_node(path)
if not node:
return True
return node.is_unknown | [
"def",
"is_unknown",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"path",
")",
"if",
"not",
"node",
":",
"return",
"True",
"return",
"node",
".",
"is_unknown"
] | 33.666667 | 0.009662 |
def _split_path(self, path):
"""Return (tableName, primaryKey) tuple for a request path."""
if path.strip() in (None, "", "/"):
return (None, None)
tableName, primKey = util.save_split(path.strip("/"), "/", 1)
# _logger.debug("'%s' -> ('%s', '%s')" % (path, tableName, ... | [
"def",
"_split_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
".",
"strip",
"(",
")",
"in",
"(",
"None",
",",
"\"\"",
",",
"\"/\"",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"tableName",
",",
"primKey",
"=",
"util",
".",
"save_... | 51.285714 | 0.008219 |
def _initializer_wrapper(actual_initializer, *rest):
"""
We ignore SIGINT. It's up to our parent to kill us in the typical
condition of this arising from ``^C`` on a terminal. If someone is
manually killing us with that signal, well... nothing will happen.
"""
signal.signal(signal.SIGINT, signa... | [
"def",
"_initializer_wrapper",
"(",
"actual_initializer",
",",
"*",
"rest",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"if",
"actual_initializer",
"is",
"not",
"None",
":",
"actual_initializer",
"(",
... | 39.4 | 0.002481 |
def queryset(self, request):
"""Returns a Queryset of all model instances that can be edited by the
admin site. This is used by changelist_view."""
query_set = self.model._default_manager.all_with_deleted()
ordering = self.ordering or ()
if ordering:
query_set = quer... | [
"def",
"queryset",
"(",
"self",
",",
"request",
")",
":",
"query_set",
"=",
"self",
".",
"model",
".",
"_default_manager",
".",
"all_with_deleted",
"(",
")",
"ordering",
"=",
"self",
".",
"ordering",
"or",
"(",
")",
"if",
"ordering",
":",
"query_set",
"=... | 45.375 | 0.008108 |
def map2rpn(map, obj):
"""
Convert a Mongodb-like dictionary to a RPN list of operands and operators.
Reverse Polish notation (RPN) is a mathematical notation in which every
operator follows all of its operands, e.g.
3 - 4 + 5 --> 3 4 - 5 +
>>> d = {2.0: {'$eq': 1.0}}
>>> assert map2rpn... | [
"def",
"map2rpn",
"(",
"map",
",",
"obj",
")",
":",
"rpn",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"map",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"_ALL_OPS",
":",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"abc",
".",
"Ma... | 28.616667 | 0.002252 |
def ExtendAnomalies(self, other):
"""Merge anomalies from another CheckResult."""
for o in other:
if o is not None:
self.anomaly.Extend(list(o.anomaly)) | [
"def",
"ExtendAnomalies",
"(",
"self",
",",
"other",
")",
":",
"for",
"o",
"in",
"other",
":",
"if",
"o",
"is",
"not",
"None",
":",
"self",
".",
"anomaly",
".",
"Extend",
"(",
"list",
"(",
"o",
".",
"anomaly",
")",
")"
] | 34 | 0.011494 |
def ra(self,*args,**kwargs):
"""
NAME:
ra
PURPOSE:
return the right ascension
INPUT:
t - (optional) time at which to get ra
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
... | [
"def",
"ra",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_roSet",
"(",
"self",
",",
"kwargs",
",",
"'ra'",
")",
"radec",
"=",
"self",
".",
"_radec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"radec",
... | 34.863636 | 0.013959 |
def _find_usage_security_groups(self):
"""find usage for elasticache security groups"""
num_groups = 0
# If EC2-Classic isn't available (e.g., a new account)
# this method will fail with:
# Code: "InvalidParameterValue"
# Message: "Use of cache security groups is n... | [
"def",
"_find_usage_security_groups",
"(",
"self",
")",
":",
"num_groups",
"=",
"0",
"# If EC2-Classic isn't available (e.g., a new account)",
"# this method will fail with:",
"# Code: \"InvalidParameterValue\"",
"# Message: \"Use of cache security groups is not permitted in",
"# ... | 43.04 | 0.001818 |
def load_hands():
"""
加载hand扩展插件
:return: 返回hand注册字典(单例)
:rtype: HandDict
"""
# 优先进行自带 hand 的注册加载
import mohand.decorator # noqa
# 注册hand插件
mgr = stevedore.ExtensionManager(
namespace=env.plugin_namespace,
invoke_on_load=True)
def register_hand(ext):
_... | [
"def",
"load_hands",
"(",
")",
":",
"# 优先进行自带 hand 的注册加载",
"import",
"mohand",
".",
"decorator",
"# noqa",
"# 注册hand插件",
"mgr",
"=",
"stevedore",
".",
"ExtensionManager",
"(",
"namespace",
"=",
"env",
".",
"plugin_namespace",
",",
"invoke_on_load",
"=",
"True",
... | 22.137931 | 0.001493 |
def resolve_topic(topic):
"""Return class described by given topic.
Args:
topic: A string describing a class.
Returns:
A class.
Raises:
TopicResolutionError: If there is no such class.
"""
try:
module_name, _, class_name = topic.partition('#')
module = ... | [
"def",
"resolve_topic",
"(",
"topic",
")",
":",
"try",
":",
"module_name",
",",
"_",
",",
"class_name",
"=",
"topic",
".",
"partition",
"(",
"'#'",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"except",
"ImportError",
"as... | 26.863636 | 0.001634 |
def intersect_exposure_and_aggregate_hazard(self):
"""This function intersects the exposure with the aggregate hazard.
If the the exposure is a continuous raster exposure, this function
will set the aggregate hazard layer.
However, this function will set the impact layer.
""... | [
"def",
"intersect_exposure_and_aggregate_hazard",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'ANALYSIS : Intersect Exposure and Aggregate Hazard'",
")",
"if",
"is_raster_layer",
"(",
"self",
".",
"exposure",
")",
":",
"self",
".",
"set_state_process",
"(",
"'... | 46.208791 | 0.000466 |
def start_all_linking(self, link_type, group_id):
"""Start all linking"""
self.logger.info("Start_all_linking for device %s type %s group %s",
self.device_id, link_type, group_id)
self.hub.direct_command(self.device_id, '02', '64' + link_type + group_id) | [
"def",
"start_all_linking",
"(",
"self",
",",
"link_type",
",",
"group_id",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Start_all_linking for device %s type %s group %s\"",
",",
"self",
".",
"device_id",
",",
"link_type",
",",
"group_id",
")",
"self",
... | 59.8 | 0.009901 |
def tocsv(table, source=None, encoding=None, errors='strict', write_header=True,
**csvargs):
"""
Write the table to a CSV file. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
... | [
"def",
"tocsv",
"(",
"table",
",",
"source",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"write_header",
"=",
"True",
",",
"*",
"*",
"csvargs",
")",
":",
"source",
"=",
"write_source_from_arg",
"(",
"source",
")",
"c... | 34.212121 | 0.001723 |
def language(l):
''' Use this as a decorator (implicitly or explicitly). '''
# Usage: @language('en') or function = language('en')(function)
def decorator(f):
''' Decorator used to prepend the language as an argument. '''
@wraps(f)
def wrapper(*args, **kwargs):
return f(l, *args, **kwargs)
return wrapp... | [
"def",
"language",
"(",
"l",
")",
":",
"# Usage: @language('en') or function = language('en')(function)",
"def",
"decorator",
"(",
"f",
")",
":",
"''' Decorator used to prepend the language as an argument. '''",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"... | 23.428571 | 0.032258 |
def line_iter(xo: int, yo: int, xd: int, yd: int) -> Iterator[Tuple[int, int]]:
""" returns an Iterable
This Iterable does not include the origin point.
Args:
xo (int): X starting point.
yo (int): Y starting point.
xd (int): X destination point.
yd (int): Y destination poin... | [
"def",
"line_iter",
"(",
"xo",
":",
"int",
",",
"yo",
":",
"int",
",",
"xd",
":",
"int",
",",
"yd",
":",
"int",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"data",
"=",
"ffi",
".",
"new",
"(",
"\"TCOD_bresenham_d... | 29.714286 | 0.001553 |
def _init_metadata(self):
"""stub"""
super(TextAnswerFormRecord, self)._init_metadata()
self._min_string_length_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'min-strin... | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"super",
"(",
"TextAnswerFormRecord",
",",
"self",
")",
".",
"_init_metadata",
"(",
")",
"self",
".",
"_min_string_length_metadata",
"=",
"{",
"'element_id'",
":",
"Id",
"(",
"self",
".",
"my_osid_object_form",
"... | 40.485714 | 0.001378 |
def reactions_to_files(model, dest, writer, split_subsystem):
"""Turn the reaction subsystems into their own files.
If a subsystem has a number of reactions over the threshold, it gets its
own YAML file. All other reactions, those that don't have a subsystem or
are in a subsystem that falls below the t... | [
"def",
"reactions_to_files",
"(",
"model",
",",
"dest",
",",
"writer",
",",
"split_subsystem",
")",
":",
"def",
"safe_file_name",
"(",
"origin_name",
")",
":",
"safe_name",
"=",
"re",
".",
"sub",
"(",
"r'\\W+'",
",",
"'_'",
",",
"origin_name",
",",
"flags"... | 41.085714 | 0.00034 |
def assert_match(actual_char_or_str, expected_char_or_str):
"""If values don't match, print them and raise a ValueError, otherwise,
continue
Raises: ValueError if argumetns do not match"""
if expected_char_or_str != actual_char_or_str:
print("Expected")
pprint(expected_char_or_str)
... | [
"def",
"assert_match",
"(",
"actual_char_or_str",
",",
"expected_char_or_str",
")",
":",
"if",
"expected_char_or_str",
"!=",
"actual_char_or_str",
":",
"print",
"(",
"\"Expected\"",
")",
"pprint",
"(",
"expected_char_or_str",
")",
"print",
"(",
"\"\"",
")",
"print",... | 36.818182 | 0.00241 |
def wrap_iterable(cls, url_or_urls):
"""Given a string or :class:`Link` or iterable, return an iterable of :class:`Link` objects.
:param url_or_urls: A string or :class:`Link` object, or iterable of string or :class:`Link`
objects.
:returns: A list of :class:`Link` objects.
"""
try:
ret... | [
"def",
"wrap_iterable",
"(",
"cls",
",",
"url_or_urls",
")",
":",
"try",
":",
"return",
"[",
"cls",
".",
"wrap",
"(",
"url_or_urls",
")",
"]",
"except",
"ValueError",
":",
"pass",
"if",
"isinstance",
"(",
"url_or_urls",
",",
"Iterable",
")",
":",
"return... | 39.071429 | 0.0125 |
def assertDateTimesLagEqual(self, sequence, lag, msg=None):
'''Fail unless max element in ``sequence`` is separated from
the present by ``lag`` as determined by the '==' operator.
If the max element is a datetime, "present" is defined as
``datetime.now()``; if the max element is a date,... | [
"def",
"assertDateTimesLagEqual",
"(",
"self",
",",
"sequence",
",",
"lag",
",",
"msg",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"sequence",
",",
"collections",
".",
"Iterable",
")",
":",
"raise",
"TypeError",
"(",
"'First argument is not iterabl... | 36.977273 | 0.001198 |
def uv_at_xy(self, x, y, x0, y0, s0):
"""Returns two arrays of u, v"""
dx, dy = self.distance(x0, y0, x, y)
#print 'dx, dy:', dx, dy
rr2 = (dx**2 + dy**2)**-1
u = - s0 * dy * r_twopi * rr2
v = s0 * dx * r_twopi * rr2
#print 'u, v', u, v
return u, v | [
"def",
"uv_at_xy",
"(",
"self",
",",
"x",
",",
"y",
",",
"x0",
",",
"y0",
",",
"s0",
")",
":",
"dx",
",",
"dy",
"=",
"self",
".",
"distance",
"(",
"x0",
",",
"y0",
",",
"x",
",",
"y",
")",
"#print 'dx, dy:', dx, dy",
"rr2",
"=",
"(",
"dx",
"*... | 33.777778 | 0.012821 |
def clean_up_omim_genes(self):
'''
Attempt to limit omim links to diseases and not genes/locus
'''
# get all the omim ids
allomim_curie = set()
for omia in self.omia_omim_map:
allomim_curie.update(self.omia_omim_map[omia])
# strip the curie prefix
... | [
"def",
"clean_up_omim_genes",
"(",
"self",
")",
":",
"# get all the omim ids",
"allomim_curie",
"=",
"set",
"(",
")",
"for",
"omia",
"in",
"self",
".",
"omia_omim_map",
":",
"allomim_curie",
".",
"update",
"(",
"self",
".",
"omia_omim_map",
"[",
"omia",
"]",
... | 40.916667 | 0.001657 |
def send_document(self, peer: Peer, document: str, reply: int=None, on_success: callable=None,
reply_markup: botapi.ReplyMarkup=None):
"""
Send document to peer.
:param peer: Peer to send message to.
:param document: File path to document to send.
:param rep... | [
"def",
"send_document",
"(",
"self",
",",
"peer",
":",
"Peer",
",",
"document",
":",
"str",
",",
"reply",
":",
"int",
"=",
"None",
",",
"on_success",
":",
"callable",
"=",
"None",
",",
"reply_markup",
":",
"botapi",
".",
"ReplyMarkup",
"=",
"None",
")"... | 40.25 | 0.020243 |
def apply_empty_result(self):
"""
we have an empty result; at least 1 axis is 0
we will try to apply the function to an empty
series in order to see if this is a reduction function
"""
# we are not asked to reduce or infer reduction
# so just return a copy of th... | [
"def",
"apply_empty_result",
"(",
"self",
")",
":",
"# we are not asked to reduce or infer reduction",
"# so just return a copy of the existing object",
"if",
"self",
".",
"result_type",
"not",
"in",
"[",
"'reduce'",
",",
"None",
"]",
":",
"return",
"self",
".",
"obj",
... | 30.066667 | 0.002148 |
def _parse_sot_segment(self, fptr):
"""Parse the SOT segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
SOTSegment
The current SOT segment.
"""
offset = fptr.tell() - 2
read_buffer = fptr... | [
"def",
"_parse_sot_segment",
"(",
"self",
",",
"fptr",
")",
":",
"offset",
"=",
"fptr",
".",
"tell",
"(",
")",
"-",
"2",
"read_buffer",
"=",
"fptr",
".",
"read",
"(",
"10",
")",
"data",
"=",
"struct",
".",
"unpack",
"(",
"'>HHIBB'",
",",
"read_buffer... | 26 | 0.001951 |
def _refresh(self):
"""Refreshes the cursor with more data from the server.
Returns the length of self.__data after refresh. Will exit early if
self.__data is already non-empty. Raises OperationFailure when the
cursor cannot be refreshed due to an error on the query.
"""
... | [
"def",
"_refresh",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"__data",
")",
"or",
"self",
".",
"__killed",
":",
"return",
"len",
"(",
"self",
".",
"__data",
")",
"if",
"self",
".",
"__id",
":",
"# Get More",
"dbname",
",",
"collname",
"... | 35.956522 | 0.002356 |
def from_href(cls, href, **kw):
"""Convert from a url to Package.
:param href: The url to parse
:type href: string
:returns: A Package object if a valid concrete implementation exists, otherwise None.
"""
package = cls._HREF_TO_PACKAGE_CACHE.get(href)
if package is not None:
return pa... | [
"def",
"from_href",
"(",
"cls",
",",
"href",
",",
"*",
"*",
"kw",
")",
":",
"package",
"=",
"cls",
".",
"_HREF_TO_PACKAGE_CACHE",
".",
"get",
"(",
"href",
")",
"if",
"package",
"is",
"not",
"None",
":",
"return",
"package",
"link_href",
"=",
"Link",
... | 30.7 | 0.009479 |
def _create_sequence_maps(self):
'''Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc.'''
if self.sifts:
self.sifts_atom_to_seqres_sequence_maps = self.sifts.atom_to_seqres_sequence_maps
self.sifts_seqres_to_uniparc_sequence_maps = self.sifts.seqre... | [
"def",
"_create_sequence_maps",
"(",
"self",
")",
":",
"if",
"self",
".",
"sifts",
":",
"self",
".",
"sifts_atom_to_seqres_sequence_maps",
"=",
"self",
".",
"sifts",
".",
"atom_to_seqres_sequence_maps",
"self",
".",
"sifts_seqres_to_uniparc_sequence_maps",
"=",
"self"... | 66.6875 | 0.008314 |
def _progress_ret(self, progress, out):
'''
Print progress events
'''
import salt.output
# Get the progress bar
if not hasattr(self, 'progress_bar'):
try:
self.progress_bar = salt.output.get_progress(self.config, out, progress)
exce... | [
"def",
"_progress_ret",
"(",
"self",
",",
"progress",
",",
"out",
")",
":",
"import",
"salt",
".",
"output",
"# Get the progress bar",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'progress_bar'",
")",
":",
"try",
":",
"self",
".",
"progress_bar",
"=",
"salt... | 45.615385 | 0.009917 |
def build_json_resource_obj(cls, fields, resource, resource_instance, resource_name,
force_type_resolution=False):
"""
Builds the resource object (type, id, attributes) and extracts relationships.
"""
# Determine type from the instance if the underlying mo... | [
"def",
"build_json_resource_obj",
"(",
"cls",
",",
"fields",
",",
"resource",
",",
"resource_instance",
",",
"resource_name",
",",
"force_type_resolution",
"=",
"False",
")",
":",
"# Determine type from the instance if the underlying model is polymorphic",
"if",
"force_type_r... | 56.714286 | 0.009083 |
def set_record(self, record, **kw):
"""
check the record is valid and set keys in the dict
parameters
----------
record: string
Dict representing a record or a string representing a FITS header
card
"""
if isstring(record):
ca... | [
"def",
"set_record",
"(",
"self",
",",
"record",
",",
"*",
"*",
"kw",
")",
":",
"if",
"isstring",
"(",
"record",
")",
":",
"card",
"=",
"FITSCard",
"(",
"record",
")",
"self",
".",
"update",
"(",
"card",
")",
"self",
".",
"verify",
"(",
")",
"els... | 30 | 0.001899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.