text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def is_tone(char, strict=True):
"""
Check whether the character is a tone or word accent symbol. In strict mode
return True only for the symbols listed in the last group of the chart. If
strict=False, also accept symbols that belong to the Modifier Tone Letters
Unicode block [1].
[1]: http://www.unicode.org/char... | [
"def",
"is_tone",
"(",
"char",
",",
"strict",
"=",
"True",
")",
":",
"if",
"char",
"in",
"chart",
".",
"tones",
":",
"return",
"True",
"if",
"not",
"strict",
":",
"return",
"0xA700",
"<=",
"ord",
"(",
"char",
")",
"<=",
"0xA71F",
"return",
"False"
] | 27.25 | 0.028825 |
def _listen(self):
"""Listen for messages passed from parent
This method distributes messages received via stdin to their
corresponding channel. Based on the format of the incoming
message, the message is forwarded to its corresponding channel
to be processed by its correspondin... | [
"def",
"_listen",
"(",
"self",
")",
":",
"def",
"_listen",
"(",
")",
":",
"\"\"\"This runs in a thread\"\"\"",
"for",
"line",
"in",
"iter",
"(",
"sys",
".",
"stdin",
".",
"readline",
",",
"b\"\"",
")",
":",
"try",
":",
"response",
"=",
"json",
".",
"lo... | 38.534884 | 0.001177 |
def sum(context, key, value, multiplier=1):
"""
Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TO... | [
"def",
"sum",
"(",
"context",
",",
"key",
",",
"value",
",",
"multiplier",
"=",
"1",
")",
":",
"if",
"key",
"not",
"in",
"context",
".",
"dicts",
"[",
"0",
"]",
":",
"context",
".",
"dicts",
"[",
"0",
"]",
"[",
"key",
"]",
"=",
"0",
"context",
... | 26.529412 | 0.002141 |
def date_line_to_text(self, date_line):
"""
Return the textual representation of the given :class:`~taxi.timesheet.lines.DateLine` instance. The date
format is set by the `date_format` parameter given when instanciating the parser instance.
"""
# Changing the date in a dateline i... | [
"def",
"date_line_to_text",
"(",
"self",
",",
"date_line",
")",
":",
"# Changing the date in a dateline is not supported yet, but if it gets implemented someday this will need to be",
"# changed",
"if",
"date_line",
".",
"_text",
"is",
"not",
"None",
":",
"return",
"date_line",... | 52.181818 | 0.010274 |
def view_graph(graph_str, parent=None, prune_to=None):
"""View a graph."""
from rezgui.dialogs.ImageViewerDialog import ImageViewerDialog
from rez.config import config
# check for already written tempfile
h = hash((graph_str, prune_to))
filepath = graph_file_lookup.get(h)
if filepath and no... | [
"def",
"view_graph",
"(",
"graph_str",
",",
"parent",
"=",
"None",
",",
"prune_to",
"=",
"None",
")",
":",
"from",
"rezgui",
".",
"dialogs",
".",
"ImageViewerDialog",
"import",
"ImageViewerDialog",
"from",
"rez",
".",
"config",
"import",
"config",
"# check for... | 32.04 | 0.001212 |
def Stat(self, device_filename):
"""Get a file's stat() information."""
connection = self.protocol_handler.Open(self._handle, destination=b'sync:')
mode, size, mtime = self.filesync_handler.Stat(
connection, device_filename)
connection.Close()
return mode, size, mtime | [
"def",
"Stat",
"(",
"self",
",",
"device_filename",
")",
":",
"connection",
"=",
"self",
".",
"protocol_handler",
".",
"Open",
"(",
"self",
".",
"_handle",
",",
"destination",
"=",
"b'sync:'",
")",
"mode",
",",
"size",
",",
"mtime",
"=",
"self",
".",
"... | 44.857143 | 0.009375 |
def persist(name, value, config=None):
'''
Assign and persist a simple sysctl parameter for this minion. If ``config``
is not specified, a sensible default will be chosen using
:mod:`sysctl.default_config <salt.modules.linux_sysctl.default_config>`.
CLI Example:
.. code-block:: bash
s... | [
"def",
"persist",
"(",
"name",
",",
"value",
",",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"default_config",
"(",
")",
"edited",
"=",
"False",
"# If the sysctl.conf is not present, add it",
"if",
"not",
"os",
".",
... | 36.444444 | 0.000297 |
def normalize_parameters(params):
""" Normalize parameters """
params = params or {}
normalized_parameters = OrderedDict()
def get_value_like_as_php(val):
""" Prepare value for quote """
try:
base = basestring
except NameError:
... | [
"def",
"normalize_parameters",
"(",
"params",
")",
":",
"params",
"=",
"params",
"or",
"{",
"}",
"normalized_parameters",
"=",
"OrderedDict",
"(",
")",
"def",
"get_value_like_as_php",
"(",
"val",
")",
":",
"\"\"\" Prepare value for quote \"\"\"",
"try",
":",
"base... | 33.233333 | 0.001949 |
def set(self, value):
"""
Sets the value of the object
:param value:
A unicode string containing an IPv4 address, IPv4 address with CIDR,
an IPv6 address or IPv6 address with CIDR
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(... | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str_cls",
")",
":",
"raise",
"TypeError",
"(",
"unwrap",
"(",
"'''\n %s value must be a unicode string, not %s\n '''",
",",
"type_name",
"... | 30.928571 | 0.001791 |
def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn):
"""
Attempt to send a broker-agnostic request to one of the available
brokers. Keep trying until you succeed.
"""
hosts = set()
for broker in self.brokers.values():
host, port, afi = get... | [
"def",
"_send_broker_unaware_request",
"(",
"self",
",",
"payloads",
",",
"encoder_fn",
",",
"decoder_fn",
")",
":",
"hosts",
"=",
"set",
"(",
")",
"for",
"broker",
"in",
"self",
".",
"brokers",
".",
"values",
"(",
")",
":",
"host",
",",
"port",
",",
"... | 34.444444 | 0.002353 |
def get_dump_names(self, names, dumps=None):
"""
Find and return all dump names required (by dependancies) for a given
dump names list
Beware, the returned name list does not respect order, you should only
use it when walking throught the "original" dict builded by OrderedDict
... | [
"def",
"get_dump_names",
"(",
"self",
",",
"names",
",",
"dumps",
"=",
"None",
")",
":",
"# Default value for dumps argument is an empty set (setting directly",
"# as a python argument would result as a shared value between",
"# instances)",
"if",
"dumps",
"is",
"None",
":",
... | 36.823529 | 0.001556 |
def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not no... | [
"def",
"get_or_guess_labels",
"(",
"self",
",",
"x",
",",
"kwargs",
")",
":",
"if",
"'y'",
"in",
"kwargs",
"and",
"'y_target'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Can not set both 'y' and 'y_target'.\"",
")",
"elif",
"'y'",
"in",
"kwargs",
":"... | 40.357143 | 0.009507 |
def format_as_html(explanation, # type: Explanation
include_styles=True, # type: bool
force_weights=True, # type: bool
show=fields.ALL,
preserve_density=None, # type: Optional[bool]
highlight_spaces=None, # type: Optiona... | [
"def",
"format_as_html",
"(",
"explanation",
",",
"# type: Explanation",
"include_styles",
"=",
"True",
",",
"# type: bool",
"force_weights",
"=",
"True",
",",
"# type: bool",
"show",
"=",
"fields",
".",
"ALL",
",",
"preserve_density",
"=",
"None",
",",
"# type: O... | 48.536585 | 0.002216 |
def _add_non_batch(self, TX_nodes, PmtInf_nodes):
"""
Method to add a transaction as non batch, will fold the transaction
together with the payment info node and append to the main xml.
"""
PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode'])
PmtInf_nodes['PmtI... | [
"def",
"_add_non_batch",
"(",
"self",
",",
"TX_nodes",
",",
"PmtInf_nodes",
")",
":",
"PmtInf_nodes",
"[",
"'PmtInfNode'",
"]",
".",
"append",
"(",
"PmtInf_nodes",
"[",
"'PmtInfIdNode'",
"]",
")",
"PmtInf_nodes",
"[",
"'PmtInfNode'",
"]",
".",
"append",
"(",
... | 52.592593 | 0.001728 |
def as_xml(self,parent):
"""
Create XML representation of `self`.
:Parameters:
- `parent`: the element to which the created node should be linked to.
:Types:
- `parent`: `libxml2.xmlNode`
:return: an XML node.
:returntype: `libxml2.xmlNode`
... | [
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"status\"",
",",
"None",
")",
"n",
".",
"setProp",
"(",
"\"code\"",
",",
"\"%03i\"",
"%",
"(",
"self",
".",
"code",
",",
")",
")",
"re... | 28.2 | 0.018307 |
def parse_headers(self, req: Request, name: str, field: Field) -> typing.Any:
"""Pull a value from the header data."""
return core.get_value(req.headers, name, field) | [
"def",
"parse_headers",
"(",
"self",
",",
"req",
":",
"Request",
",",
"name",
":",
"str",
",",
"field",
":",
"Field",
")",
"->",
"typing",
".",
"Any",
":",
"return",
"core",
".",
"get_value",
"(",
"req",
".",
"headers",
",",
"name",
",",
"field",
"... | 60 | 0.010989 |
def debug_text_simple(self, text: str):
""" Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'. """
self._debug_texts.append(self.to_debug_message(text)) | [
"def",
"debug_text_simple",
"(",
"self",
",",
"text",
":",
"str",
")",
":",
"self",
".",
"_debug_texts",
".",
"append",
"(",
"self",
".",
"to_debug_message",
"(",
"text",
")",
")"
] | 85.333333 | 0.011628 |
def get_read_buffers(self, size):
"""Get buffer(s) from which we can read data.
When done reading, use :meth:`advance_read_index` to make the
memory available for writing again.
:param size: The number of elements desired.
:type size: int
:returns:
* The nu... | [
"def",
"get_read_buffers",
"(",
"self",
",",
"size",
")",
":",
"ptr1",
"=",
"self",
".",
"_ffi",
".",
"new",
"(",
"'void**'",
")",
"ptr2",
"=",
"self",
".",
"_ffi",
".",
"new",
"(",
"'void**'",
")",
"size1",
"=",
"self",
".",
"_ffi",
".",
"new",
... | 38.56 | 0.002024 |
def total_size(obj):
"""Returns the approximate total memory footprint an object."""
seen = set()
def sizeof(current_obj):
try:
return _sizeof(current_obj)
except Exception: # pylint: disable=broad-except
# Not sure what just happened, but let's assume it's a reference.
return struct.ca... | [
"def",
"total_size",
"(",
"obj",
")",
":",
"seen",
"=",
"set",
"(",
")",
"def",
"sizeof",
"(",
"current_obj",
")",
":",
"try",
":",
"return",
"_sizeof",
"(",
"current_obj",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"# Not sure what jus... | 37.466667 | 0.01301 |
def RetryOnUnavailable(func):
"""Function decorator to retry on a service unavailable exception."""
@functools.wraps(func)
def Wrapper(*args, **kwargs):
while True:
try:
response = func(*args, **kwargs)
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
time.... | [
"def",
"RetryOnUnavailable",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"Wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"response",
"=",
"func",
"(",
"*",
"args"... | 30.545455 | 0.018759 |
def _execute_callback(self, status, message, job, res, err, stacktrace):
"""Execute the callback.
:param status: Job status. Possible values are "invalid" (job could not
be deserialized or was malformed), "failure" (job raised an error),
"timeout" (job timed out), or "success" (... | [
"def",
"_execute_callback",
"(",
"self",
",",
"status",
",",
"message",
",",
"job",
",",
"res",
",",
"err",
",",
"stacktrace",
")",
":",
"if",
"self",
".",
"_callback",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_logger",
".",
"info",
"(",
... | 47.384615 | 0.001591 |
def without(seq1, seq2):
r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2]
"""
if isSet(seq2): d2 = seq2
else: d2 = set(seq2)
return [elt for elt in seq1 if elt not in d2] | [
"def",
"without",
"(",
"seq1",
",",
"seq2",
")",
":",
"if",
"isSet",
"(",
"seq2",
")",
":",
"d2",
"=",
"seq2",
"else",
":",
"d2",
"=",
"set",
"(",
"seq2",
")",
"return",
"[",
"elt",
"for",
"elt",
"in",
"seq1",
"if",
"elt",
"not",
"in",
"d2",
... | 23.5 | 0.010239 |
def add_arguments(self, parser):
"""Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add... | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"True",
")",
"group",
".",
"add_argument",
"(",
"'-l'",
",",
"'--list'",
",",
"nargs",
"=",
"'?'",
",",
"type",... | 41.8 | 0.002339 |
def _validate(self):
"""
The purpose of this method is to verify that the user has set sensible
values for the training program before rendering. The user will still
be able to render, but error messages will be printed. This method:
* Validates that the average ... | [
"def",
"_validate",
"(",
"self",
")",
":",
"# Validate the intensity",
"if",
"max",
"(",
"[",
"s",
"*",
"self",
".",
"intensity",
"for",
"s",
"in",
"self",
".",
"_intensity_scalers",
"]",
")",
">",
"85",
":",
"warnings",
".",
"warn",
"(",
"'\\nWARNING: A... | 49.156863 | 0.001955 |
def _init_sys_auto_lookup(self):
"""Return a list of tuples of available init systems on the
current machine.
Note that in some situations (Ubuntu 14.04 for instance) more than
one init system can be found.
"""
# TODO: Instead, check for executables for systemd and upsta... | [
"def",
"_init_sys_auto_lookup",
"(",
"self",
")",
":",
"# TODO: Instead, check for executables for systemd and upstart",
"# systemctl for systemd and initctl for upstart.",
"# An alternative might be to check the second answer here:",
"# http://unix.stackexchange.com/questions/196166/how-to-find-o... | 48.55 | 0.00202 |
def set_status(self, value):
"""
Set the status of the motor to the specified value if not already set.
"""
if not self._status == value:
old = self._status
self._status = value
logger.info("{} changing status from {} to {}".format(self, old.name, valu... | [
"def",
"set_status",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_status",
"==",
"value",
":",
"old",
"=",
"self",
".",
"_status",
"self",
".",
"_status",
"=",
"value",
"logger",
".",
"info",
"(",
"\"{} changing status from {} to {}\"",... | 40.444444 | 0.008065 |
def get(self, orig_key):
"""Get cache entry for key, or return None."""
resp = requests.Response()
key = self._clean_key(orig_key)
path = os.path.join(self.cache_dir, key)
try:
with open(path, 'rb') as f:
# read lines one at a time
wh... | [
"def",
"get",
"(",
"self",
",",
"orig_key",
")",
":",
"resp",
"=",
"requests",
".",
"Response",
"(",
")",
"key",
"=",
"self",
".",
"_clean_key",
"(",
"orig_key",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
... | 42.444444 | 0.002047 |
def store(self, key, pk, value):
"""Store the value/pk in the sorted set index
For the parameters, see BaseRangeIndex.store
We simple store the pk as a member of the sorted set with the value being the score
"""
self.connection.zadd(key, value, pk) | [
"def",
"store",
"(",
"self",
",",
"key",
",",
"pk",
",",
"value",
")",
":",
"self",
".",
"connection",
".",
"zadd",
"(",
"key",
",",
"value",
",",
"pk",
")"
] | 31.444444 | 0.010309 |
def from_xarray(da, crs=None, apply_transform=False, nan_nodata=False, **kwargs):
"""
Returns an RGB or Image element given an xarray DataArray
loaded using xr.open_rasterio.
If a crs attribute is present on the loaded data it will
attempt to decode it into a cartopy projection otherwise it
wil... | [
"def",
"from_xarray",
"(",
"da",
",",
"crs",
"=",
"None",
",",
"apply_transform",
"=",
"False",
",",
"nan_nodata",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"crs",
":",
"kwargs",
"[",
"'crs'",
"]",
"=",
"crs",
"elif",
"hasattr",
"(",
"... | 33.159091 | 0.001997 |
def post_document(self, data):
"""
Create and analyze a new document
data -- A Dictionary representing the new document
"""
data.update({ 'client' : CLIENT })
return self._call('POST', self._generate_url_path('documents'), data) | [
"def",
"post_document",
"(",
"self",
",",
"data",
")",
":",
"data",
".",
"update",
"(",
"{",
"'client'",
":",
"CLIENT",
"}",
")",
"return",
"self",
".",
"_call",
"(",
"'POST'",
",",
"self",
".",
"_generate_url_path",
"(",
"'documents'",
")",
",",
"data... | 35.142857 | 0.015873 |
def start(self):
"""
Start animation thread.
"""
self.thread = threading.Thread(target=self._animate)
self.thread.start()
return | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_animate",
")",
"self",
".",
"thread",
".",
"start",
"(",
")",
"return"
] | 24.285714 | 0.011364 |
def _request(self, req_and_resp, **kwargs):
""" Take a request_and_response object from pyswagger.App and
check auth, token, headers, prepare the actual request and fill the
response
Note on performance : if you need more performance (because you are
using this in a batch)... | [
"def",
"_request",
"(",
"self",
",",
"req_and_resp",
",",
"*",
"*",
"kwargs",
")",
":",
"opt",
"=",
"kwargs",
".",
"pop",
"(",
"'opt'",
",",
"{",
"}",
")",
"# reset the request and response to reuse existing req_and_resp\r",
"req_and_resp",
"[",
"0",
"]",
".",... | 38.891892 | 0.000678 |
def node(self, parent=None, tag='g', attrib=None, **extras):
"""Make a new svg node"""
if parent is None:
parent = self.root
attrib = attrib or {}
attrib.update(extras)
def in_attrib_and_number(key):
return key in attrib and isinstance(attrib[key], Number... | [
"def",
"node",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"tag",
"=",
"'g'",
",",
"attrib",
"=",
"None",
",",
"*",
"*",
"extras",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"self",
".",
"root",
"attrib",
"=",
"attrib",
"or",
... | 37.068966 | 0.001813 |
def predict_variant_effect_on_transcript(variant, transcript):
"""Return the transcript effect (such as FrameShift) that results from
applying this genomic variant to a particular transcript.
Parameters
----------
transcript : Transcript
Transcript we're going to ap... | [
"def",
"predict_variant_effect_on_transcript",
"(",
"variant",
",",
"transcript",
")",
":",
"if",
"transcript",
".",
"__class__",
"is",
"not",
"Transcript",
":",
"raise",
"TypeError",
"(",
"\"Expected %s : %s to have type Transcript\"",
"%",
"(",
"transcript",
",",
"t... | 40.242991 | 0.001133 |
async def print_what_is_playing(loop):
"""Connect to device and print what is playing."""
details = conf.AppleTV(ADDRESS, NAME)
details.add_service(conf.DmapService(HSGID))
print('Connecting to {}'.format(details.address))
atv = pyatv.connect_to_apple_tv(details, loop)
try:
print((awai... | [
"async",
"def",
"print_what_is_playing",
"(",
"loop",
")",
":",
"details",
"=",
"conf",
".",
"AppleTV",
"(",
"ADDRESS",
",",
"NAME",
")",
"details",
".",
"add_service",
"(",
"conf",
".",
"DmapService",
"(",
"HSGID",
")",
")",
"print",
"(",
"'Connecting to ... | 31.384615 | 0.002381 |
def generate_fileattr_metadata(local_path, metadata):
# type: (blobxfer.models.upload.LocalPath, dict) -> dict
"""Generate file attribute metadata dict
:param blobxfer.models.upload.LocalPath local_path: local path
:param dict metadata: existing metadata dict
:rtype: dict
:return: merged metadat... | [
"def",
"generate_fileattr_metadata",
"(",
"local_path",
",",
"metadata",
")",
":",
"# type: (blobxfer.models.upload.LocalPath, dict) -> dict",
"if",
"blobxfer",
".",
"util",
".",
"on_windows",
"(",
")",
":",
"global",
"_FILEATTR_WARNED_ON_WINDOWS",
"if",
"not",
"_FILEATTR... | 38.777778 | 0.000932 |
def is_docstring(tokens, previous_logical):
"""Return found docstring
'A docstring is a string literal that occurs as the first statement in a
module, function, class,'
http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
"""
for token_type, text, start, _, _ in tokens:
if token... | [
"def",
"is_docstring",
"(",
"tokens",
",",
"previous_logical",
")",
":",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"_",
",",
"_",
"in",
"tokens",
":",
"if",
"token_type",
"==",
"tokenize",
".",
"STRING",
":",
"break",
"elif",
"token_type",
"!=... | 34.3 | 0.001418 |
def _unpack_msg(self, *msg):
"""
Convert all message elements to string
"""
l = []
for m in msg:
l.append(str(m))
return " ".join(l) | [
"def",
"_unpack_msg",
"(",
"self",
",",
"*",
"msg",
")",
":",
"l",
"=",
"[",
"]",
"for",
"m",
"in",
"msg",
":",
"l",
".",
"append",
"(",
"str",
"(",
"m",
")",
")",
"return",
"\" \"",
".",
"join",
"(",
"l",
")"
] | 23.125 | 0.015625 |
def write(self, chunk: Union[str, bytes, dict]) -> None:
"""Writes the given chunk to the output buffer.
To write the output to the network, use the `flush()` method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``applicat... | [
"def",
"write",
"(",
"self",
",",
"chunk",
":",
"Union",
"[",
"str",
",",
"bytes",
",",
"dict",
"]",
")",
"->",
"None",
":",
"if",
"self",
".",
"_finished",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot write() after finish()\"",
")",
"if",
"not",
"isinst... | 49.387097 | 0.001281 |
def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be c... | [
"def",
"DateTimeField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_DATETIME_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
... | 54.888889 | 0.000995 |
def createStyle(self, body, verbose=None):
"""
Creates a new Visual Style using the message body.
Returns the title of the new Visual Style. If the title of the Visual Style already existed in the session, a new one will be automatically generated and returned.
:param body: The... | [
"def",
"createStyle",
"(",
"self",
",",
"body",
",",
"verbose",
"=",
"None",
")",
":",
"PARAMS",
"=",
"set_param",
"(",
"[",
"'body'",
"]",
",",
"[",
"body",
"]",
")",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'styles'",... | 40.4 | 0.012903 |
def obfn_reg(self):
r"""Compute regularisation term, :math:`\| x \|_1`, and
contribution to objective function.
"""
l1 = np.sum(mp_wl1*np.abs(self.obfn_gvar()))
return (self.lmbda*l1, l1) | [
"def",
"obfn_reg",
"(",
"self",
")",
":",
"l1",
"=",
"np",
".",
"sum",
"(",
"mp_wl1",
"*",
"np",
".",
"abs",
"(",
"self",
".",
"obfn_gvar",
"(",
")",
")",
")",
"return",
"(",
"self",
".",
"lmbda",
"*",
"l1",
",",
"l1",
")"
] | 37 | 0.008811 |
def scaled_pressure2_encode(self, time_boot_ms, press_abs, press_diff, temperature):
'''
Barometer readings for 2nd barometer
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
press_abs : Absolute pressure (... | [
"def",
"scaled_pressure2_encode",
"(",
"self",
",",
"time_boot_ms",
",",
"press_abs",
",",
"press_diff",
",",
"temperature",
")",
":",
"return",
"MAVLink_scaled_pressure2_message",
"(",
"time_boot_ms",
",",
"press_abs",
",",
"press_diff",
",",
"temperature",
")"
] | 58.909091 | 0.012158 |
def tob32(val):
"""Return provided 32 bit value as a string of four bytes."""
ret = bytearray(4)
ret[0] = (val>>24)&M8
ret[1] = (val>>16)&M8
ret[2] = (val>>8)&M8
ret[3] = val&M8
return ret | [
"def",
"tob32",
"(",
"val",
")",
":",
"ret",
"=",
"bytearray",
"(",
"4",
")",
"ret",
"[",
"0",
"]",
"=",
"(",
"val",
">>",
"24",
")",
"&",
"M8",
"ret",
"[",
"1",
"]",
"=",
"(",
"val",
">>",
"16",
")",
"&",
"M8",
"ret",
"[",
"2",
"]",
"=... | 26.125 | 0.037037 |
def html_table_from_query(rows: Iterable[Iterable[Optional[str]]],
descriptions: Iterable[Optional[str]]) -> str:
"""
Converts rows from an SQL query result to an HTML table.
Suitable for processing output from the defunct function
``rnc_db.fetchall_with_fieldnames(sql)``.
... | [
"def",
"html_table_from_query",
"(",
"rows",
":",
"Iterable",
"[",
"Iterable",
"[",
"Optional",
"[",
"str",
"]",
"]",
"]",
",",
"descriptions",
":",
"Iterable",
"[",
"Optional",
"[",
"str",
"]",
"]",
")",
"->",
"str",
":",
"html",
"=",
"u\"<table>\\n\"",... | 26.964286 | 0.001279 |
def squared_error(y, y_pred):
"""Calculates the sum of the squared
differences between target and prediction.
Parameters:
-----------
y : vector, shape (n_samples,)
The target values.
y_pred : vector, shape (n_samples,)
The predicted values.
Returns:
--------
error... | [
"def",
"squared_error",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"return",
"np",
".",
"sum",
"(",
"(",
"y",
"-",
"y_pred",
")",
"**",
"2",
")"
] | 22.761905 | 0.008032 |
def eigenvalues(T, k=None, reversible=False, mu=None):
r"""Compute eigenvalues of given transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
reversible : bool, op... | [
"def",
"eigenvalues",
"(",
"T",
",",
"k",
"=",
"None",
",",
"reversible",
"=",
"False",
",",
"mu",
"=",
"None",
")",
":",
"if",
"reversible",
":",
"try",
":",
"evals",
"=",
"eigenvalues_rev",
"(",
"T",
",",
"k",
"=",
"k",
",",
"mu",
"=",
"mu",
... | 29.592593 | 0.001211 |
def stage_pywbem_args(self, method, **kwargs):
"""
Log request method and all args.
Normally called before the cmd is executed to record request
parameters.
This method does not support the summary detail_level because
that seems to add little info to the log that is not ... | [
"def",
"stage_pywbem_args",
"(",
"self",
",",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"_pywbem_method",
"=",
"method",
"if",
"self",
".",
"enabled",
"and",
"self",
".",
"api_detail_level",
"is",... | 46.151515 | 0.001286 |
def weather_at_places(self, pattern, searchtype, limit=None):
"""
Queries the OWM Weather API for the currently observed weather in all the
locations whose name is matching the specified text search parameters.
A twofold search can be issued: *'accurate'* (exact matching) and
*'l... | [
"def",
"weather_at_places",
"(",
"self",
",",
"pattern",
",",
"searchtype",
",",
"limit",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"pattern",
",",
"str",
")",
",",
"\"'pattern' must be a str\"",
"assert",
"isinstance",
"(",
"searchtype",
",",
"str",... | 56.780488 | 0.001689 |
def hover(self):
"""
Hovers the element
"""
def do_hover():
"""
Perform hover
"""
ActionChains(self.driver_wrapper.driver).move_to_element(self.element).perform()
return self.execute_and_handle_webelement_exceptions(do_hover, 'hover... | [
"def",
"hover",
"(",
"self",
")",
":",
"def",
"do_hover",
"(",
")",
":",
"\"\"\"\n Perform hover\n \"\"\"",
"ActionChains",
"(",
"self",
".",
"driver_wrapper",
".",
"driver",
")",
".",
"move_to_element",
"(",
"self",
".",
"element",
")",
".... | 31.3 | 0.009317 |
def new_mountpoint(self, name):
"""Create a new mountpoint"""
url = posixpath.join(self.path, name)
r = self._jfs.post(url, extra_headers={'content-type': 'application/x-www-form-urlencoded'})
return r | [
"def",
"new_mountpoint",
"(",
"self",
",",
"name",
")",
":",
"url",
"=",
"posixpath",
".",
"join",
"(",
"self",
".",
"path",
",",
"name",
")",
"r",
"=",
"self",
".",
"_jfs",
".",
"post",
"(",
"url",
",",
"extra_headers",
"=",
"{",
"'content-type'",
... | 45.8 | 0.012876 |
def have_same_structure(d1, d2):
"""
Given two dictionaries (possibly with other nested dictionaries as
values), this function checks whether they have the same key structure.
>>> from sem import DatabaseManager
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'a': [], 'b': 3}
... | [
"def",
"have_same_structure",
"(",
"d1",
",",
"d2",
")",
":",
"# Keys of this level are the same",
"if",
"set",
"(",
"d1",
".",
"keys",
"(",
")",
")",
"!=",
"set",
"(",
"d2",
".",
"keys",
"(",
")",
")",
":",
"return",
"False",
"# Check nested dictionaries"... | 36.74359 | 0.00136 |
def _ord2ymd(n):
"ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
# n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
# repeats exactly every 400 years. The basic strategy is to find the
# closest 400-year boundary at or before n, then work with the offset
# f... | [
"def",
"_ord2ymd",
"(",
"n",
")",
":",
"# n is a 1-based index, starting at 1-Jan-1. The pattern of leap years",
"# repeats exactly every 400 years. The basic strategy is to find the",
"# closest 400-year boundary at or before n, then work with the offset",
"# from that boundary to n. Life is m... | 43.344262 | 0.00037 |
def is_rigid(matrix):
"""
Check to make sure a homogeonous transformation matrix is
a rigid body transform.
Parameters
-----------
matrix: possibly a transformation matrix
Returns
-----------
check: bool, True if matrix is a valid (4,4) rigid body transform.
"""
matrix = n... | [
"def",
"is_rigid",
"(",
"matrix",
")",
":",
"matrix",
"=",
"np",
".",
"asanyarray",
"(",
"matrix",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"matrix",
".",
"shape",
"!=",
"(",
"4",
",",
"4",
")",
":",
"return",
"False",
"if",
"not",
"np... | 22.038462 | 0.001672 |
def get_os_codename_install_source(src):
'''Derive OpenStack release codename from a given installation source.'''
ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
rel = ''
if src is None:
return rel
if src in ['distro', 'distro-proposed', 'proposed']:
try:
rel = UBUNTU_OPE... | [
"def",
"get_os_codename_install_source",
"(",
"src",
")",
":",
"ubuntu_rel",
"=",
"lsb_release",
"(",
")",
"[",
"'DISTRIB_CODENAME'",
"]",
"rel",
"=",
"''",
"if",
"src",
"is",
"None",
":",
"return",
"rel",
"if",
"src",
"in",
"[",
"'distro'",
",",
"'distro-... | 33.444444 | 0.001076 |
def join(self, glue=" "):
""" Javascript's join implementation
"""
j = glue.join([str(x) for x in self.obj])
return self._wrap(j) | [
"def",
"join",
"(",
"self",
",",
"glue",
"=",
"\" \"",
")",
":",
"j",
"=",
"glue",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"obj",
"]",
")",
"return",
"self",
".",
"_wrap",
"(",
"j",
")"
] | 31.4 | 0.012422 |
def handle_input(self, input_hdr):
"""
This method tries to ensure that the input data has the correct dimensions.
INPUTS:
input_hdr (no default) Header from which data shape is to be extracted.
"""
input_slice = input_hdr['NAXIS']*[0]
for i in range(input... | [
"def",
"handle_input",
"(",
"self",
",",
"input_hdr",
")",
":",
"input_slice",
"=",
"input_hdr",
"[",
"'NAXIS'",
"]",
"*",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"input_hdr",
"[",
"'NAXIS'",
"]",
")",
":",
"if",
"input_hdr",
"[",
"'CTYPE%d'",
... | 32.941176 | 0.010417 |
def _auth(profile=None):
'''
Set up neutron credentials
'''
credentials = __salt__['config.option'](profile)
kwargs = {
'username': credentials['keystone.user'],
'password': credentials['keystone.password'],
'tenant_name': credentials['keystone.tenant'],
'auth_url': c... | [
"def",
"_auth",
"(",
"profile",
"=",
"None",
")",
":",
"credentials",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",
")",
"kwargs",
"=",
"{",
"'username'",
":",
"credentials",
"[",
"'keystone.user'",
"]",
",",
"'password'",
":",
"credentials",... | 34.466667 | 0.001883 |
def LL(n):
"""constructs the LL context"""
if (n<=0):return Context('0')
else:
LL1=LL(n-1)
r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1
r2 = LL1 - LL1 - LL1
return r1 + r2 | [
"def",
"LL",
"(",
"n",
")",
":",
"if",
"(",
"n",
"<=",
"0",
")",
":",
"return",
"Context",
"(",
"'0'",
")",
"else",
":",
"LL1",
"=",
"LL",
"(",
"n",
"-",
"1",
")",
"r1",
"=",
"C1",
"(",
"3",
"**",
"(",
"n",
"-",
"1",
")",
",",
"2",
"*... | 25.25 | 0.028708 |
def decrypt(receiver_prvhex: str, msg: bytes) -> bytes:
"""
Decrypt with eth private key
Parameters
----------
receiver_pubhex: str
Receiver's ethereum private key hex string
msg: bytes
Data to decrypt
Returns
-------
bytes
Plain text
"""
pubkey = ms... | [
"def",
"decrypt",
"(",
"receiver_prvhex",
":",
"str",
",",
"msg",
":",
"bytes",
")",
"->",
"bytes",
":",
"pubkey",
"=",
"msg",
"[",
"0",
":",
"65",
"]",
"# pubkey's length is 65 bytes",
"encrypted",
"=",
"msg",
"[",
"65",
":",
"]",
"sender_public_key",
"... | 24.863636 | 0.001761 |
def reset (self):
"""
Initialize FTP url data.
"""
super(FtpUrl, self).reset()
# list of files for recursion
self.files = []
# last part of URL filename
self.filename = None
self.filename_encoding = 'iso-8859-1' | [
"def",
"reset",
"(",
"self",
")",
":",
"super",
"(",
"FtpUrl",
",",
"self",
")",
".",
"reset",
"(",
")",
"# list of files for recursion",
"self",
".",
"files",
"=",
"[",
"]",
"# last part of URL filename",
"self",
".",
"filename",
"=",
"None",
"self",
".",... | 27.4 | 0.010601 |
def get_all(jail=None):
'''
Return a list of all available services
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = []
service = _cmd(jail)
for srv in __salt__['cmd.run']('{0} -l'.forma... | [
"def",
"get_all",
"(",
"jail",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"service",
"=",
"_cmd",
"(",
"jail",
")",
"for",
"srv",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} -l'",
".",
"format",
"(",
"service",
")",
")",
".",
"splitlines"... | 20.35 | 0.002347 |
def computePCsPlink(plink_path,k,out_dir,bfile,ffile):
"""
computing the covariance matrix via plink
"""
print("Using plink to compute principal components")
cmd = '%s --bfile %s --pca %d '%(plink_path,bfile,k)
cmd+= '--out %s'%(os.path.join(out_dir,'plink'))
subprocess.call(cmd,shell=True)
... | [
"def",
"computePCsPlink",
"(",
"plink_path",
",",
"k",
",",
"out_dir",
",",
"bfile",
",",
"ffile",
")",
":",
"print",
"(",
"\"Using plink to compute principal components\"",
")",
"cmd",
"=",
"'%s --bfile %s --pca %d '",
"%",
"(",
"plink_path",
",",
"bfile",
",",
... | 35.5 | 0.035294 |
def detect(self, G):
"""Detect a single core-periphery pair using the Borgatti-Everett algorithm.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> be = c... | [
"def",
"detect",
"(",
"self",
",",
"G",
")",
":",
"node_pairs",
",",
"w",
",",
"node2id",
",",
"id2node",
"=",
"self",
".",
"_to_edge_list",
"(",
"G",
")",
"cppairs",
"=",
"_cp",
".",
"detect_be",
"(",
"edges",
"=",
"node_pairs",
",",
"ws",
"=",
"w... | 26.730769 | 0.045833 |
def display_event(div, attributes=[]):
"""
Function to build a suitable CustomJS to display the current event
in the div model.
"""
style = 'float: left; clear: left; font-size: 10pt'
return CustomJS(args=dict(div=div), code="""
var attrs = %s;
var args = [];
for (var i =... | [
"def",
"display_event",
"(",
"div",
",",
"attributes",
"=",
"[",
"]",
")",
":",
"style",
"=",
"'float: left; clear: left; font-size: 10pt'",
"return",
"CustomJS",
"(",
"args",
"=",
"dict",
"(",
"div",
"=",
"div",
")",
",",
"code",
"=",
"\"\"\"\n var att... | 38.636364 | 0.002296 |
def add_server(self,address,port=default_port,password=None,speed=None,valid_times=None,invalid_times=None):
'''
:address: remote address of server, or special string ``local`` to
run the command locally
:valid_times: times when this server is availabl... | [
"def",
"add_server",
"(",
"self",
",",
"address",
",",
"port",
"=",
"default_port",
",",
"password",
"=",
"None",
",",
"speed",
"=",
"None",
",",
"valid_times",
"=",
"None",
",",
"invalid_times",
"=",
"None",
")",
":",
"for",
"t",
"in",
"[",
"valid_tim... | 48.351351 | 0.014247 |
def get(self, jid=None): # pylint: disable=W0221
'''
A convenience URL for getting lists of previously run jobs or getting
the return from a single job
.. http:get:: /jobs/(jid)
List jobs or show a single job from the job cache.
:status 200: |200|
... | [
"def",
"get",
"(",
"self",
",",
"jid",
"=",
"None",
")",
":",
"# pylint: disable=W0221",
"# if you aren't authenticated, redirect to login",
"if",
"not",
"self",
".",
"_verify_auth",
"(",
")",
":",
"self",
".",
"redirect",
"(",
"'/login'",
")",
"return",
"if",
... | 24 | 0.000808 |
def train_transform(self, images, surpress_mapping_check = False):
r"""
See also
--------
train, transform
"""
ret = self.train(images)
outputs = [self.transform(i, surpress_mapping_check) for i in images]
return ret, outputs | [
"def",
"train_transform",
"(",
"self",
",",
"images",
",",
"surpress_mapping_check",
"=",
"False",
")",
":",
"ret",
"=",
"self",
".",
"train",
"(",
"images",
")",
"outputs",
"=",
"[",
"self",
".",
"transform",
"(",
"i",
",",
"surpress_mapping_check",
")",
... | 31.222222 | 0.013841 |
def queriessam2dalignbed(cfg):
"""
Processes SAM file to get the genomic coordinates in BED format
step#2
:param cfg: configuration dict
"""
datatmpd=cfg['datatmpd']
alignmentbedp=cfg['alignmentbedp']
dalignbedp=cfg['dalignbedp']
logging.info(basename(dalignbedp))
if not exists(... | [
"def",
"queriessam2dalignbed",
"(",
"cfg",
")",
":",
"datatmpd",
"=",
"cfg",
"[",
"'datatmpd'",
"]",
"alignmentbedp",
"=",
"cfg",
"[",
"'alignmentbedp'",
"]",
"dalignbedp",
"=",
"cfg",
"[",
"'dalignbedp'",
"]",
"logging",
".",
"info",
"(",
"basename",
"(",
... | 46.851852 | 0.016258 |
def is_prune(self):
"""
Return True, if `git fetch --prune` is allowed.
Because of possible incompatibilities, this requires special
treatment.
"""
required_version = "1.6.6"
config_value = self.settings['fetch.prune']
if self.git.is_version_mi... | [
"def",
"is_prune",
"(",
"self",
")",
":",
"required_version",
"=",
"\"1.6.6\"",
"config_value",
"=",
"self",
".",
"settings",
"[",
"'fetch.prune'",
"]",
"if",
"self",
".",
"git",
".",
"is_version_min",
"(",
"required_version",
")",
":",
"return",
"config_value... | 38.619048 | 0.002407 |
def __we_c(cls, calib, tc, temp, we_v, ae_v):
"""
Compute weC from sensor temperature compensation of weV, aeV
"""
we_t = we_v - (calib.we_elc_mv / 1000.0) # remove electronic we zero
ae_t = ae_v - (calib.ae_elc_mv / 1000.0) # remove electronic ae zero
we_c... | [
"def",
"__we_c",
"(",
"cls",
",",
"calib",
",",
"tc",
",",
"temp",
",",
"we_v",
",",
"ae_v",
")",
":",
"we_t",
"=",
"we_v",
"-",
"(",
"calib",
".",
"we_elc_mv",
"/",
"1000.0",
")",
"# remove electronic we zero",
"ae_t",
"=",
"ae_v",
"-",
"(",
"calib"... | 38.75 | 0.010504 |
def _parse_args(func, variables, annotations=None):
"""Return a list of arguments with the variable it reads.
NOTE: Multiple arguments may read the same variable.
"""
arg_read_var = []
for arg_name, anno in (annotations or func.__annotations__).items():
if arg_name == 'return':
... | [
"def",
"_parse_args",
"(",
"func",
",",
"variables",
",",
"annotations",
"=",
"None",
")",
":",
"arg_read_var",
"=",
"[",
"]",
"for",
"arg_name",
",",
"anno",
"in",
"(",
"annotations",
"or",
"func",
".",
"__annotations__",
")",
".",
"items",
"(",
")",
... | 37.923077 | 0.00198 |
def get_response(self, url, timeout=None):
"""Return http request response.
"""
if not timeout:
timeout = self.default_timeout
if self.default_sleeptime:
time.sleep(self.default_sleeptime)
try:
return self.auth.get(url, headers=self.default_h... | [
"def",
"get_response",
"(",
"self",
",",
"url",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"timeout",
":",
"timeout",
"=",
"self",
".",
"default_timeout",
"if",
"self",
".",
"default_sleeptime",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"de... | 29.538462 | 0.010101 |
def popleft(self):
"""Removes and returns the oldest read pulse."""
self._mq.send("^", True, type=1)
message = self._wait_receive_msg()
reply = int(message[0].decode('utf-8'))
#print(reply)
if reply == -1:
raise IndexError("pop from empty list")
return... | [
"def",
"popleft",
"(",
"self",
")",
":",
"self",
".",
"_mq",
".",
"send",
"(",
"\"^\"",
",",
"True",
",",
"type",
"=",
"1",
")",
"message",
"=",
"self",
".",
"_wait_receive_msg",
"(",
")",
"reply",
"=",
"int",
"(",
"message",
"[",
"0",
"]",
".",
... | 35.333333 | 0.009202 |
def _sort_layers(self):
"""Sort the layers by depth."""
self._layers = OrderedDict(sorted(self._layers.items(), key=lambda t: t[0])) | [
"def",
"_sort_layers",
"(",
"self",
")",
":",
"self",
".",
"_layers",
"=",
"OrderedDict",
"(",
"sorted",
"(",
"self",
".",
"_layers",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
")"
] | 48.666667 | 0.02027 |
def is_ambiguous(self, dt, idx=None):
"""
Whether or not the "wall time" of a given datetime is ambiguous in this
zone.
:param dt:
A :py:class:`datetime.datetime`, naive or time zone aware.
:return:
Returns ``True`` if ambiguous, ``False`` otherwise.
... | [
"def",
"is_ambiguous",
"(",
"self",
",",
"dt",
",",
"idx",
"=",
"None",
")",
":",
"if",
"idx",
"is",
"None",
":",
"idx",
"=",
"self",
".",
"_find_last_transition",
"(",
"dt",
")",
"# Calculate the difference in offsets from current to previous",
"timestamp",
"="... | 27.964286 | 0.002469 |
def validatefeatures(self,features):
"""Returns features in validated form, or raises an Exception. Mostly for internal use"""
validatedfeatures = []
for feature in features:
if isinstance(feature, int) or isinstance(feature, float):
validatedfeatures.append( str(feat... | [
"def",
"validatefeatures",
"(",
"self",
",",
"features",
")",
":",
"validatedfeatures",
"=",
"[",
"]",
"for",
"feature",
"in",
"features",
":",
"if",
"isinstance",
"(",
"feature",
",",
"int",
")",
"or",
"isinstance",
"(",
"feature",
",",
"float",
")",
":... | 53.538462 | 0.012712 |
def average_neighbor_distance(points, num_neigh):
"""!
@brief Returns average distance for establish links between specified number of nearest neighbors.
@param[in] points (list): Input data, list of points where each point represented by list.
@param[in] num_neigh (uint): Number of neighbors ... | [
"def",
"average_neighbor_distance",
"(",
"points",
",",
"num_neigh",
")",
":",
"if",
"num_neigh",
">",
"len",
"(",
"points",
")",
"-",
"1",
":",
"raise",
"NameError",
"(",
"'Impossible to calculate average distance to neighbors when number of object is less than number of n... | 44.6 | 0.021214 |
def convert_to_shape(x):
"""Converts input to a Shape.
Args:
x: Shape, str, or None.
Returns:
Shape or None.
Raises:
ValueError: If x cannot be converted to a Shape.
"""
if x is None:
return None
if isinstance(x, Shape):
return x
if isinstance(x, str):
x = _parse_string_to_lis... | [
"def",
"convert_to_shape",
"(",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"x",
",",
"Shape",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"x",
"=",
"_parse_string_to_list_o... | 18.631579 | 0.016129 |
def image_update(id=None, name=None, profile=None, **kwargs): # pylint: disable=C0103
'''
Update properties of given image.
Known to work for:
- min_ram (in MB)
- protected (bool)
- visibility ('public' or 'private')
CLI Example:
.. code-block:: bash
salt '*' glance.image_upd... | [
"def",
"image_update",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"if",
"id",
":",
"image",
"=",
"image_show",
"(",
"id",
"=",
"id",
",",
"profile",
"="... | 31.3 | 0.001239 |
def notify_barriers(self,
slot_key,
cursor,
use_barrier_indexes,
max_to_notify=_MAX_BARRIERS_TO_NOTIFY):
"""Searches for barriers affected by a slot and triggers completed ones.
Args:
slot_key: db.Key or stringified k... | [
"def",
"notify_barriers",
"(",
"self",
",",
"slot_key",
",",
"cursor",
",",
"use_barrier_indexes",
",",
"max_to_notify",
"=",
"_MAX_BARRIERS_TO_NOTIFY",
")",
":",
"if",
"not",
"isinstance",
"(",
"slot_key",
",",
"db",
".",
"Key",
")",
":",
"slot_key",
"=",
"... | 42.275862 | 0.009563 |
def dict_to_nvlist(dict):
'''Convert a dictionary into a CORBA namevalue list.'''
result = []
for item in list(dict.keys()):
result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item])))
return result | [
"def",
"dict_to_nvlist",
"(",
"dict",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"list",
"(",
"dict",
".",
"keys",
"(",
")",
")",
":",
"result",
".",
"append",
"(",
"SDOPackage",
".",
"NameValue",
"(",
"item",
",",
"omniORB",
".",
"any... | 39.333333 | 0.008299 |
def tcp_server(tcp_addr, settings):
"""Start up the tcp server, send the settings."""
family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
sock.bind(tcp_addr)
sock.listen(1)
logging.info("Waiting for connection on %s", tcp_ad... | [
"def",
"tcp_server",
"(",
"tcp_addr",
",",
"settings",
")",
":",
"family",
"=",
"socket",
".",
"AF_INET6",
"if",
"\":\"",
"in",
"tcp_addr",
".",
"ip",
"else",
"socket",
".",
"AF_INET",
"sock",
"=",
"socket",
".",
"socket",
"(",
"family",
",",
"socket",
... | 43.375 | 0.021157 |
def split_unescaped(char, string, include_empty_strings=False):
'''
:param char: The character on which to split the string
:type char: string
:param string: The string to split
:type string: string
:returns: List of substrings of *string*
:rtype: list of strings
Splits *string* wheneve... | [
"def",
"split_unescaped",
"(",
"char",
",",
"string",
",",
"include_empty_strings",
"=",
"False",
")",
":",
"words",
"=",
"[",
"]",
"pos",
"=",
"len",
"(",
"string",
")",
"lastpos",
"=",
"pos",
"while",
"pos",
">=",
"0",
":",
"pos",
"=",
"get_last_pos_... | 31.148148 | 0.001153 |
def _elimination_trees(theta, decision_variables):
"""From Theta and the decision variables, determine the elimination order and the induced
trees.
"""
# auxiliary variables are any variables that are not decision
auxiliary_variables = set(n for n in theta.linear if n not in decision_variables)
... | [
"def",
"_elimination_trees",
"(",
"theta",
",",
"decision_variables",
")",
":",
"# auxiliary variables are any variables that are not decision",
"auxiliary_variables",
"=",
"set",
"(",
"n",
"for",
"n",
"in",
"theta",
".",
"linear",
"if",
"n",
"not",
"in",
"decision_va... | 32.930233 | 0.002058 |
def unset_value(self, key):
# type: (str) -> None
"""Unset a value in the configuration.
"""
self._ensure_have_load_only()
if key not in self._config[self.load_only]:
raise ConfigurationError("No such key - {}".format(key))
fname, parser = self._get_parser_t... | [
"def",
"unset_value",
"(",
"self",
",",
"key",
")",
":",
"# type: (str) -> None",
"self",
".",
"_ensure_have_load_only",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_config",
"[",
"self",
".",
"load_only",
"]",
":",
"raise",
"ConfigurationError",
"(",
... | 33.710526 | 0.002276 |
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', na... | [
"def",
"wrap_as_node",
"(",
"self",
",",
"func",
")",
":",
"name",
"=",
"self",
".",
"get_name",
"(",
"func",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"'wrapped version of func'",
"me... | 38.4 | 0.001693 |
def add_to_typedef(typedef_curr, obo_line):
"""Add new fields to the current typedef."""
if obo_line[:4] == "id: ":
assert not typedef_curr.item_id
item_id = obo_line[4:]
typedef_curr.item_id = item_id
elif obo_line[:6] == "name: ":
assert not typedef_curr.name
typede... | [
"def",
"add_to_typedef",
"(",
"typedef_curr",
",",
"obo_line",
")",
":",
"if",
"obo_line",
"[",
":",
"4",
"]",
"==",
"\"id: \"",
":",
"assert",
"not",
"typedef_curr",
".",
"item_id",
"item_id",
"=",
"obo_line",
"[",
"4",
":",
"]",
"typedef_curr",
".",
"i... | 42.578947 | 0.001209 |
def _import_module(module_name, warn=True, prefix='_py_', ignore='_'):
"""Try import all public attributes from module into global namespace.
Existing attributes with name clashes are renamed with prefix.
Attributes starting with underscore are ignored by default.
Return True on successful import.
... | [
"def",
"_import_module",
"(",
"module_name",
",",
"warn",
"=",
"True",
",",
"prefix",
"=",
"'_py_'",
",",
"ignore",
"=",
"'_'",
")",
":",
"try",
":",
"module",
"=",
"__import__",
"(",
"module_name",
")",
"except",
"ImportError",
":",
"if",
"warn",
":",
... | 35 | 0.001112 |
def setMinimumPixmapSize(self, size):
"""
Sets the minimum pixmap size that will be displayed to the user
for the dock widget.
:param size | <int>
"""
self._minimumPixmapSize = size
position = self.position()
self._position = None
... | [
"def",
"setMinimumPixmapSize",
"(",
"self",
",",
"size",
")",
":",
"self",
".",
"_minimumPixmapSize",
"=",
"size",
"position",
"=",
"self",
".",
"position",
"(",
")",
"self",
".",
"_position",
"=",
"None",
"self",
".",
"setPosition",
"(",
"position",
")"
] | 31.090909 | 0.008523 |
def set_dword_at_offset(self, offset, dword):
"""Set the double word value at the given file offset."""
return self.set_bytes_at_offset(offset, self.get_data_from_dword(dword)) | [
"def",
"set_dword_at_offset",
"(",
"self",
",",
"offset",
",",
"dword",
")",
":",
"return",
"self",
".",
"set_bytes_at_offset",
"(",
"offset",
",",
"self",
".",
"get_data_from_dword",
"(",
"dword",
")",
")"
] | 63.333333 | 0.015625 |
def collect(self, dataset_readers_list):
"""collect results
Returns:
a list of results
"""
ret = [ ]
for i, collector in enumerate(self.components):
report = ProgressReport(name='collecting results', done=(i + 1), total=len(self.components))
... | [
"def",
"collect",
"(",
"self",
",",
"dataset_readers_list",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"i",
",",
"collector",
"in",
"enumerate",
"(",
"self",
".",
"components",
")",
":",
"report",
"=",
"ProgressReport",
"(",
"name",
"=",
"'collecting results'"... | 35.625 | 0.010256 |
def createSynapses(self):
"""Add an exponentially decaying synapse """
synsoma = h.ExpSyn(self.soma(0.5))
synsoma.tau = 2
synsoma.e = 0
syndend = h.ExpSyn(self.dend(0.5))
syndend.tau = 2
syndend.e = 0
self.synlist.append(synsoma) # synlist is defined in Ce... | [
"def",
"createSynapses",
"(",
"self",
")",
":",
"synsoma",
"=",
"h",
".",
"ExpSyn",
"(",
"self",
".",
"soma",
"(",
"0.5",
")",
")",
"synsoma",
".",
"tau",
"=",
"2",
"synsoma",
".",
"e",
"=",
"0",
"syndend",
"=",
"h",
".",
"ExpSyn",
"(",
"self",
... | 35 | 0.008357 |
def run_conditional_decorators(self, context):
"""Evaluate the step decorators to decide whether to run step or not.
Use pypyr.dsl.Step.run_step if you intend on executing the step the
same way pypyr does.
Args:
context: (pypyr.context.Context) The pypyr context. This arg w... | [
"def",
"run_conditional_decorators",
"(",
"self",
",",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"starting\"",
")",
"# The decorator attributes might contain formatting expressions that",
"# change whether they evaluate True or False, thus apply formatting at",
"# last poss... | 41.27907 | 0.001101 |
def save_function_tuple(self, func):
""" Pickles an actual func object.
A func comprises: code, globals, defaults, closure, and dict. We
extract and save these, injecting reducing functions at certain points
to recreate the func object. Keep in mind that some of these pieces
... | [
"def",
"save_function_tuple",
"(",
"self",
",",
"func",
")",
":",
"if",
"is_tornado_coroutine",
"(",
"func",
")",
":",
"self",
".",
"save_reduce",
"(",
"_rebuild_tornado_coroutine",
",",
"(",
"func",
".",
"__wrapped__",
",",
")",
",",
"obj",
"=",
"func",
"... | 38.175439 | 0.001344 |
def get_parent_tag(mention):
"""Return the HTML tag of the Mention's parent.
These may be tags such as 'p', 'h2', 'table', 'div', etc.
If a candidate is passed in, only the tag of its first Mention is returned.
:param mention: The Mention to evaluate
:rtype: string
"""
span = _to_span(ment... | [
"def",
"get_parent_tag",
"(",
"mention",
")",
":",
"span",
"=",
"_to_span",
"(",
"mention",
")",
"i",
"=",
"_get_node",
"(",
"span",
".",
"sentence",
")",
"return",
"str",
"(",
"i",
".",
"getparent",
"(",
")",
".",
"tag",
")",
"if",
"i",
".",
"getp... | 34.916667 | 0.002326 |
def constrain_centers(self):
"""
Constrain the centers of linked `EPSFStar` objects (i.e. the
same physical star) to have the same sky coordinate.
Only `EPSFStar` objects that have not been excluded during the
ePSF build process will be used to constrain the centers.
Th... | [
"def",
"constrain_centers",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_data",
")",
"<",
"2",
":",
"# no linked stars",
"return",
"idx",
"=",
"np",
".",
"logical_not",
"(",
"self",
".",
"_excluded_from_fit",
")",
".",
"nonzero",
"(",
")",
"... | 37.102041 | 0.001072 |
def _get_type(points, soma_class):
'''get the type of the soma
Args:
points: Soma points
soma_class(str): one of 'contour' or 'cylinder' to specify the type
'''
assert soma_class in (SOMA_CONTOUR, SOMA_CYLINDER)
npoints = len(points)
if soma_class == SOMA_CONTOUR:
retur... | [
"def",
"_get_type",
"(",
"points",
",",
"soma_class",
")",
":",
"assert",
"soma_class",
"in",
"(",
"SOMA_CONTOUR",
",",
"SOMA_CYLINDER",
")",
"npoints",
"=",
"len",
"(",
"points",
")",
"if",
"soma_class",
"==",
"SOMA_CONTOUR",
":",
"return",
"{",
"0",
":",... | 34.366667 | 0.000943 |
def restore_catalog_to_ckan(catalog, origin_portal_url, destination_portal_url,
apikey, download_strategy=None,
generate_new_access_url=None):
"""Restaura los datasets de un catálogo original al portal pasado
por parámetro. Si hay temas presentes en el ... | [
"def",
"restore_catalog_to_ckan",
"(",
"catalog",
",",
"origin_portal_url",
",",
"destination_portal_url",
",",
"apikey",
",",
"download_strategy",
"=",
"None",
",",
"generate_new_access_url",
"=",
"None",
")",
":",
"catalog",
"[",
"'homepage'",
"]",
"=",
"catalog",... | 45.218182 | 0.000394 |
def howPlotArgs(goodFormat):
'''plots using argparse if can, if not uses howPlotask()
Arguments:
goodFormat {dict} -- module : [results for module]
'''
if args.exportplots is not None:
exportPlotsPath = pathlib.Path(args.exportplots)
if args.showplots:
plotter(expor... | [
"def",
"howPlotArgs",
"(",
"goodFormat",
")",
":",
"if",
"args",
".",
"exportplots",
"is",
"not",
"None",
":",
"exportPlotsPath",
"=",
"pathlib",
".",
"Path",
"(",
"args",
".",
"exportplots",
")",
"if",
"args",
".",
"showplots",
":",
"plotter",
"(",
"exp... | 29.941176 | 0.001905 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.