text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def move(self, direction, n_windows):
"""
Move the cursor up or down by the given increment.
Params:
direction (int): `1` will move the cursor down one item and `-1`
will move the cursor up one item.
n_windows (int): The number of items that are currently... | [
"def",
"move",
"(",
"self",
",",
"direction",
",",
"n_windows",
")",
":",
"assert",
"direction",
"in",
"(",
"-",
"1",
",",
"1",
")",
"valid",
",",
"redraw",
"=",
"True",
",",
"False",
"forward",
"=",
"(",
"(",
"direction",
"*",
"self",
".",
"step",... | 38.380952 | 16.539683 |
def contribute_to_class(model_class, name='slots', descriptor=None):
"""
Function that adds a description to a model Class.
:param model_class: The model class the descriptor is to be added
to.
:param name: The attribute name the descriptor will be assigned to.
:param descriptor: The descriptor... | [
"def",
"contribute_to_class",
"(",
"model_class",
",",
"name",
"=",
"'slots'",
",",
"descriptor",
"=",
"None",
")",
":",
"rel_obj",
"=",
"descriptor",
"or",
"PlaceholderDescriptor",
"(",
")",
"rel_obj",
".",
"contribute_to_class",
"(",
"model_class",
",",
"name"... | 38.3125 | 18.6875 |
def autoUseMyMetrics(ttGlyph, glyphName, hmtx):
""" Set the "USE_MY_METRICS" flag on the first component having the
same advance width as the composite glyph, no transform and no
horizontal shift (but allow it to shift vertically).
This forces the composite glyph to use the possibly hint... | [
"def",
"autoUseMyMetrics",
"(",
"ttGlyph",
",",
"glyphName",
",",
"hmtx",
")",
":",
"width",
"=",
"hmtx",
"[",
"glyphName",
"]",
"[",
"0",
"]",
"for",
"component",
"in",
"ttGlyph",
".",
"components",
":",
"try",
":",
"baseName",
",",
"transform",
"=",
... | 45.521739 | 16.217391 |
def encode_many(chord_labels, reduce_extended_chords=False):
"""Translate a set of chord labels to numerical representations for sane
evaluation.
Parameters
----------
chord_labels : list
Set of chord labels to encode.
reduce_extended_chords : bool
Whether to map the upper voici... | [
"def",
"encode_many",
"(",
"chord_labels",
",",
"reduce_extended_chords",
"=",
"False",
")",
":",
"num_items",
"=",
"len",
"(",
"chord_labels",
")",
"roots",
",",
"basses",
"=",
"np",
".",
"zeros",
"(",
"[",
"2",
",",
"num_items",
"]",
",",
"dtype",
"=",... | 35.294118 | 15.441176 |
def serie(self, serie):
"""Make serie node"""
return dict(
plot=self.node(
self.graph.nodes['plot'],
class_='series serie-%d color-%d' % (serie.index, serie.index)
),
overlay=self.node(
self.graph.nodes['overlay'],
... | [
"def",
"serie",
"(",
"self",
",",
"serie",
")",
":",
"return",
"dict",
"(",
"plot",
"=",
"self",
".",
"node",
"(",
"self",
".",
"graph",
".",
"nodes",
"[",
"'plot'",
"]",
",",
"class_",
"=",
"'series serie-%d color-%d'",
"%",
"(",
"serie",
".",
"inde... | 36.375 | 18.9375 |
def untrace_class(cls):
"""
Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool
"""
for name, method in inspect.getmembers(cls, inspect.ismethod):
untrace_method(cls, method)
for name, function in inspect.getmembe... | [
"def",
"untrace_class",
"(",
"cls",
")",
":",
"for",
"name",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"cls",
",",
"inspect",
".",
"ismethod",
")",
":",
"untrace_method",
"(",
"cls",
",",
"method",
")",
"for",
"name",
",",
"function",
"in... | 24 | 21.818182 |
def move_item_behind(self, item_id, assessment_part_id, reference_id):
"""Reorders items in an assessment part by moving the specified item behind of a reference item.
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: assessment_part_id (osid.id.Id): ``Id of the
Asses... | [
"def",
"move_item_behind",
"(",
"self",
",",
"item_id",
",",
"assessment_part_id",
",",
"reference_id",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"assessment_part_id",
",",
"ABCId",
")",
"and",
"assessment_part_id",
".",
"get_identifier_namespace",
"(",
")",
... | 57.565217 | 25 |
def color_table(color, N=1, sort=False, sort_values=False, inline=False, as_html=False):
"""
Generates a colour table
Parameters:
-----------
color : string | list | dict
Color representation in rgba|rgb|hex
If a list of colors is passed then these
... | [
"def",
"color_table",
"(",
"color",
",",
"N",
"=",
"1",
",",
"sort",
"=",
"False",
",",
"sort_values",
"=",
"False",
",",
"inline",
"=",
"False",
",",
"as_html",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"color",
",",
"list",
")",
":",
"c_",... | 34.27381 | 17.511905 |
def thumbnail(self, id):
"""Get the 100x100 thumbnail of a file. Return the raw PNG data.
Parameters:
* id: The Puush ID of the file to get the thumbnail of.
"""
res = self._raw_api_request('thumb', data={'i': id})
if not res:
raise PuushError("Ge... | [
"def",
"thumbnail",
"(",
"self",
",",
"id",
")",
":",
"res",
"=",
"self",
".",
"_raw_api_request",
"(",
"'thumb'",
",",
"data",
"=",
"{",
"'i'",
":",
"id",
"}",
")",
"if",
"not",
"res",
":",
"raise",
"PuushError",
"(",
"\"Getting thumbnail failed.\"",
... | 35.5 | 17.6 |
def MaxLikeInterval(self, percentage=90):
"""Returns the maximum-likelihood credible interval.
If percentage=90, computes a 90% CI containing the values
with the highest likelihoods.
percentage: float between 0 and 100
Returns: list of values from the suite
"""
... | [
"def",
"MaxLikeInterval",
"(",
"self",
",",
"percentage",
"=",
"90",
")",
":",
"interval",
"=",
"[",
"]",
"total",
"=",
"0",
"t",
"=",
"[",
"(",
"prob",
",",
"val",
")",
"for",
"val",
",",
"prob",
"in",
"self",
".",
"Items",
"(",
")",
"]",
"t",... | 25.869565 | 18.347826 |
def set_empty_region(self, region_id, type_id, generated_at,
error_if_orders_present=True):
"""
Prepares for the given region+item combo by instantiating a
:py:class:`MarketItemsInRegionList` instance, which will track
region ID, type ID, and generated time. This... | [
"def",
"set_empty_region",
"(",
"self",
",",
"region_id",
",",
"type_id",
",",
"generated_at",
",",
"error_if_orders_present",
"=",
"True",
")",
":",
"key",
"=",
"'%s_%s'",
"%",
"(",
"region_id",
",",
"type_id",
")",
"if",
"error_if_orders_present",
"and",
"se... | 48.518519 | 20.740741 |
def custom_req(session, request):
"""
Utility for sending a predefined request and printing response as well
as storing messages in a list, useful for testing
Parameters
----------
session: blpapi.session.Session
request: blpapi.request.Request
Request to be sent
Returns
--... | [
"def",
"custom_req",
"(",
"session",
",",
"request",
")",
":",
"# flush event queue in case previous call errored out",
"while",
"(",
"session",
".",
"tryNextEvent",
"(",
")",
")",
":",
"pass",
"print",
"(",
"\"Sending Request:\\n %s\"",
"%",
"request",
")",
"sessio... | 28.818182 | 17.424242 |
def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = s... | [
"def",
"_collect_all_files",
"(",
"self",
",",
"files",
"=",
"None",
")",
":",
"if",
"files",
"is",
"None",
":",
"files",
"=",
"self",
".",
"_root_elements",
"collected",
"=",
"set",
"(",
")",
"for",
"entry",
"in",
"files",
":",
"collected",
".",
"add"... | 33.357143 | 14.071429 |
def printSequences(x, formatString="%d"):
"""
Print a bunch of sequences stored in a 2D numpy array.
"""
[seqLen, numElements] = x.shape
for i in range(seqLen):
s = ""
for j in range(numElements):
s += formatString % x[i][j]
print s | [
"def",
"printSequences",
"(",
"x",
",",
"formatString",
"=",
"\"%d\"",
")",
":",
"[",
"seqLen",
",",
"numElements",
"]",
"=",
"x",
".",
"shape",
"for",
"i",
"in",
"range",
"(",
"seqLen",
")",
":",
"s",
"=",
"\"\"",
"for",
"j",
"in",
"range",
"(",
... | 25.1 | 11.3 |
def print(self, *objects, **kwargs):
"""Micmic print interface"""
file = kwargs.get("file")
if file is not None and file is not sys.stdout:
PRINT(*objects, **kwargs)
else:
sep = STR(kwargs.get("sep", " "))
end = STR(kwargs.get("end", "\n"))
text = sep.join(STR(o) for o in objects)
self.imp_pr... | [
"def",
"print",
"(",
"self",
",",
"*",
"objects",
",",
"*",
"*",
"kwargs",
")",
":",
"file",
"=",
"kwargs",
".",
"get",
"(",
"\"file\"",
")",
"if",
"file",
"is",
"not",
"None",
"and",
"file",
"is",
"not",
"sys",
".",
"stdout",
":",
"PRINT",
"(",
... | 21.823529 | 19 |
def eglGetDisplay(display=EGL_DEFAULT_DISPLAY):
""" Connect to the EGL display server.
"""
res = _lib.eglGetDisplay(display)
if not res or res == EGL_NO_DISPLAY:
raise RuntimeError('Could not create display')
return res | [
"def",
"eglGetDisplay",
"(",
"display",
"=",
"EGL_DEFAULT_DISPLAY",
")",
":",
"res",
"=",
"_lib",
".",
"eglGetDisplay",
"(",
"display",
")",
"if",
"not",
"res",
"or",
"res",
"==",
"EGL_NO_DISPLAY",
":",
"raise",
"RuntimeError",
"(",
"'Could not create display'",... | 34.428571 | 7.142857 |
def add_factuality(self,my_fact):
"""
Adds a factuality to the factuality layer
@type my_fact: L{Cfactuality}
@param my_fact: factuality object
"""
if self.factuality_layer is None:
self.factuality_layer = Cfactualities()
self.root.append(self.fact... | [
"def",
"add_factuality",
"(",
"self",
",",
"my_fact",
")",
":",
"if",
"self",
".",
"factuality_layer",
"is",
"None",
":",
"self",
".",
"factuality_layer",
"=",
"Cfactualities",
"(",
")",
"self",
".",
"root",
".",
"append",
"(",
"self",
".",
"factuality_lay... | 38.9 | 6.7 |
def object_hook(obj):
"""Checks to see if the `__type`-hinting field is available in the object being de-serialized. If present, and
the class referenced has a `from_json` function it will return the generated object, else a standard dic
will be returned
Args:
obj: Object to... | [
"def",
"object_hook",
"(",
"obj",
")",
":",
"try",
":",
"if",
"'__type'",
"in",
"obj",
":",
"obj_type",
"=",
"obj",
"[",
"'__type'",
"]",
"cls",
"=",
"getattr",
"(",
"cloud_inquisitor",
".",
"schema",
",",
"obj_type",
")",
"if",
"hasattr",
"(",
"cls",
... | 34.484848 | 16.272727 |
def cookie(data, key_salt='', secret=None, digestmod=None):
""" Encodes or decodes a signed cookie.
@data: cookie data
@key_salt: HMAC key signing salt
@secret: HMAC signing secret key
@digestmod: hashing algorithm to sign with, recommended >=sha256
-> HMAC signed or unsigne... | [
"def",
"cookie",
"(",
"data",
",",
"key_salt",
"=",
"''",
",",
"secret",
"=",
"None",
",",
"digestmod",
"=",
"None",
")",
":",
"digestmod",
"=",
"digestmod",
"or",
"sha256",
"if",
"not",
"data",
":",
"return",
"None",
"try",
":",
"# Decode signed cookie"... | 38.681818 | 17.5 |
def write_template_to_file(conf, template_body):
"""Writes the template to disk
"""
template_file_name = _get_stack_name(conf) + '-generated-cf-template.json'
with open(template_file_name, 'w') as opened_file:
opened_file.write(template_body)
print('wrote cf-template for %s to disk: %s' % (
... | [
"def",
"write_template_to_file",
"(",
"conf",
",",
"template_body",
")",
":",
"template_file_name",
"=",
"_get_stack_name",
"(",
"conf",
")",
"+",
"'-generated-cf-template.json'",
"with",
"open",
"(",
"template_file_name",
",",
"'w'",
")",
"as",
"opened_file",
":",
... | 42.333333 | 9.333333 |
def read_table(filename, sheetname, index_col=None):
"""
Return the contents of an Excel table as a pandas DataFrame.
Parameters
----------
filename : str
Name of the Excel file to read.
sheetname : str or int
Name or index of the sheet inside the Excel file to read.
index_c... | [
"def",
"read_table",
"(",
"filename",
",",
"sheetname",
",",
"index_col",
"=",
"None",
")",
":",
"# Catch sheetname as list or None",
"if",
"sheetname",
"is",
"None",
"or",
"(",
"hasattr",
"(",
"sheetname",
",",
"'__iter__'",
")",
"and",
"not",
"isinstance",
"... | 34.763636 | 19.418182 |
def saved_xids(self):
"""Return previously saved xids."""
if self._saved_xids is None:
self._saved_xids = []
if self.debug:
fpfn = os.path.join(self.tcex.args.tc_temp_path, 'xids-saved')
if os.path.isfile(fpfn) and os.access(fpfn, os.R_OK):
... | [
"def",
"saved_xids",
"(",
"self",
")",
":",
"if",
"self",
".",
"_saved_xids",
"is",
"None",
":",
"self",
".",
"_saved_xids",
"=",
"[",
"]",
"if",
"self",
".",
"debug",
":",
"fpfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tcex",
".... | 44.4 | 14.7 |
def createDeviceObjects(self, interface_id):
"""Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass."""
global WORKING
WORKING = True
remote = interface_id.split('-')[-1]
LOG.debug(
"RPCFunctions.createDeviceObject... | [
"def",
"createDeviceObjects",
"(",
"self",
",",
"interface_id",
")",
":",
"global",
"WORKING",
"WORKING",
"=",
"True",
"remote",
"=",
"interface_id",
".",
"split",
"(",
"'-'",
")",
"[",
"-",
"1",
"]",
"LOG",
".",
"debug",
"(",
"\"RPCFunctions.createDeviceObj... | 57.04 | 23.32 |
def _ufo_logging_ref(ufo):
"""Return a string that can identify this UFO in logs."""
if ufo.path:
return os.path.basename(ufo.path)
return ufo.info.styleName | [
"def",
"_ufo_logging_ref",
"(",
"ufo",
")",
":",
"if",
"ufo",
".",
"path",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"ufo",
".",
"path",
")",
"return",
"ufo",
".",
"info",
".",
"styleName"
] | 34.6 | 10 |
def flush(self, index=None, params=None):
"""
Explicitly flush one or more indices.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-flush.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
string for all indices
:a... | [
"def",
"flush",
"(",
"self",
",",
"index",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"POST\"",
",",
"_make_path",
"(",
"index",
",",
"\"_flush\"",
")",
",",
"params",
"=",
"par... | 57.678571 | 26.392857 |
def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None:
"""
Dumps some connection info, as an SQL comment. Obscures passwords.
Args:
engine: the SQLAlchemy :class:`Engine` to dump metadata information
from
fileobj: the file-like object (default ``sys.stdo... | [
"def",
"dump_connection_info",
"(",
"engine",
":",
"Engine",
",",
"fileobj",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
")",
"->",
"None",
":",
"meta",
"=",
"MetaData",
"(",
"bind",
"=",
"engine",
")",
"writeline_nl",
"(",
"fileobj",
",",
"sql_comment",
"... | 38.666667 | 23.666667 |
def str(name, default=None, allow_none=False, fallback=None):
"""Get a string based environment value or the default.
Args:
name: The environment variable name
default: The default value to use if no environment variable is found
allow_none: If the return value can be `None` (i.e. optio... | [
"def",
"str",
"(",
"name",
",",
"default",
"=",
"None",
",",
"allow_none",
"=",
"False",
",",
"fallback",
"=",
"None",
")",
":",
"value",
"=",
"read",
"(",
"name",
",",
"default",
",",
"allow_none",
",",
"fallback",
"=",
"fallback",
")",
"if",
"value... | 37.923077 | 18.538462 |
def new(self):
# type: () -> None
'''
Create a new Rock Ridge Platform Dependent record.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('PD record already initialized!')
... | [
"def",
"new",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'PD record already initialized!'",
")",
"self",
".",
"_initialized",
"=",
"True",
"self",
".",
"paddi... | 24.133333 | 24.8 |
def _format_function_arguments(self, opts):
"""Format a series of function arguments in a Mothur script."""
params = [self.Parameters[x] for x in opts]
return ', '.join(filter(None, map(str, params))) | [
"def",
"_format_function_arguments",
"(",
"self",
",",
"opts",
")",
":",
"params",
"=",
"[",
"self",
".",
"Parameters",
"[",
"x",
"]",
"for",
"x",
"in",
"opts",
"]",
"return",
"', '",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"map",
"(",
"str",
... | 55.25 | 7.5 |
def playlist_songs_move(
self,
playlist_songs,
*,
after=None,
before=None,
index=None,
position=None
):
"""Move songs in a playlist.
Note:
* Provide no optional arguments to move to end.
* Provide playlist song dicts for ``after`` and/or ``before``.
* Provide a zero-based ``index``.
* Pr... | [
"def",
"playlist_songs_move",
"(",
"self",
",",
"playlist_songs",
",",
"*",
",",
"after",
"=",
"None",
",",
"before",
"=",
"None",
",",
"index",
"=",
"None",
",",
"position",
"=",
"None",
")",
":",
"if",
"not",
"more_itertools",
".",
"all_equal",
"(",
... | 26.27027 | 22.256757 |
def create(self, **kwargs):
"""
Creates a new post.
When the `markdown` property is present, it will be
automatically converted to `mobiledoc` on v1.+ of the server.
:param kwargs: The properties of the post
:return: The created `Post` object
"""
return ... | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"PostController",
",",
"self",
")",
".",
"create",
"(",
"*",
"*",
"self",
".",
"_with_markdown",
"(",
"kwargs",
")",
")"
] | 34.090909 | 18.636364 |
def open_filechooser(title, parent=None, patterns=None,
folder=None, filter=None, multiple=False,
_before_run=None, action=None):
"""An open dialog.
:param parent: window or None
:param patterns: file match patterns
:param folder: initial folder
:param filt... | [
"def",
"open_filechooser",
"(",
"title",
",",
"parent",
"=",
"None",
",",
"patterns",
"=",
"None",
",",
"folder",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"multiple",
"=",
"False",
",",
"_before_run",
"=",
"None",
",",
"action",
"=",
"None",
")",
... | 33.396226 | 17.528302 |
def remove_fetcher(self, fetcher):
"""Remove a running fetcher from the list of active fetchers.
:Parameters:
- `fetcher`: fetcher instance.
:Types:
- `fetcher`: `CacheFetcher`"""
self._lock.acquire()
try:
for t, f in list(self._active_fetcher... | [
"def",
"remove_fetcher",
"(",
"self",
",",
"fetcher",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"for",
"t",
",",
"f",
"in",
"list",
"(",
"self",
".",
"_active_fetchers",
")",
":",
"if",
"f",
"is",
"fetcher",
":",
"self",... | 32 | 13.6875 |
def crawl(self,
feeder_kwargs=None,
parser_kwargs=None,
downloader_kwargs=None):
"""Start crawling
This method will start feeder, parser and download and wait
until all threads exit.
Args:
feeder_kwargs (dict, optional): Arguments t... | [
"def",
"crawl",
"(",
"self",
",",
"feeder_kwargs",
"=",
"None",
",",
"parser_kwargs",
"=",
"None",
",",
"downloader_kwargs",
"=",
"None",
")",
":",
"self",
".",
"signal",
".",
"reset",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'start crawling..... | 37.372549 | 18.27451 |
def isfinite(val):
"""
Helper function to determine if scalar or array value is finite extending
np.isfinite with support for None, string, datetime types.
"""
if not np.isscalar(val):
val = asarray(val, strict=False)
if val is None:
return False
elif isinstance(val, np.ndar... | [
"def",
"isfinite",
"(",
"val",
")",
":",
"if",
"not",
"np",
".",
"isscalar",
"(",
"val",
")",
":",
"val",
"=",
"asarray",
"(",
"val",
",",
"strict",
"=",
"False",
")",
"if",
"val",
"is",
"None",
":",
"return",
"False",
"elif",
"isinstance",
"(",
... | 33.217391 | 13.565217 |
def center(self):
"""Center of the bounding box around all data present in the scene"""
bounds = self.bounds
x = (bounds[1] + bounds[0])/2
y = (bounds[3] + bounds[2])/2
z = (bounds[5] + bounds[4])/2
return [x, y, z] | [
"def",
"center",
"(",
"self",
")",
":",
"bounds",
"=",
"self",
".",
"bounds",
"x",
"=",
"(",
"bounds",
"[",
"1",
"]",
"+",
"bounds",
"[",
"0",
"]",
")",
"/",
"2",
"y",
"=",
"(",
"bounds",
"[",
"3",
"]",
"+",
"bounds",
"[",
"2",
"]",
")",
... | 36.714286 | 8.571429 |
def getRedisPool(params):
'''
getRedisPool - Returns and possibly also creates a Redis connection pool
based on the REDIS_CONNECTION_PARAMS passed in.
The goal of this method is to keep a small connection pool rolling
to each unique Redis instance, otherwise during network issues etc
python-redis will l... | [
"def",
"getRedisPool",
"(",
"params",
")",
":",
"global",
"RedisPools",
"global",
"_defaultRedisConnectionParams",
"global",
"_redisManagedConnectionParams",
"if",
"not",
"params",
":",
"params",
"=",
"_defaultRedisConnectionParams",
"isDefaultParams",
"=",
"True",
"else"... | 33.329897 | 23.865979 |
def get_submodules_from_dpath(dpath, only_packages=False, recursive=True):
r"""
Args:
dpath (str): directory path
only_packages (bool): if True returns only package directories,
otherwise returns module files. (default = False)
Returns:
list: submod_fpaths
CommandLi... | [
"def",
"get_submodules_from_dpath",
"(",
"dpath",
",",
"only_packages",
"=",
"False",
",",
"recursive",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"submod_dpaths",
"=",
"[",
"d",
"for",
"d",
"in",
"ut",
".",
"ls_dirs",
"(",
"dpath",
")",
"if",... | 38.027027 | 21.837838 |
def _from_matrix(cls, matrix):
"""Initialise from matrix representation
Create a Quaternion by specifying the 3x3 rotation or 4x4 transformation matrix
(as a numpy array) from which the quaternion's rotation should be created.
"""
try:
shape = matrix.shape
e... | [
"def",
"_from_matrix",
"(",
"cls",
",",
"matrix",
")",
":",
"try",
":",
"shape",
"=",
"matrix",
".",
"shape",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"\"Invalid matrix type: Input must be a 3x3 or 4x4 numpy array or matrix\"",
")",
"if",
"shape",
... | 46.613333 | 26.413333 |
def is_businessperiod(cls, in_period):
"""
:param in_period: object to be checked
:type in_period: object, str, timedelta
:return: True if cast works
:rtype: Boolean
checks is argument con becasted to BusinessPeriod
"""
try: # to be removed
i... | [
"def",
"is_businessperiod",
"(",
"cls",
",",
"in_period",
")",
":",
"try",
":",
"# to be removed",
"if",
"str",
"(",
"in_period",
")",
".",
"upper",
"(",
")",
"==",
"'0D'",
":",
"return",
"True",
"else",
":",
"p",
"=",
"BusinessPeriod",
"(",
"str",
"("... | 33.823529 | 15.117647 |
def get_access_token(client_id, client_secret):
'''
Name: token
Parameters: client_id, client_secret
Return: dictionary
'''
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {
'client_id': client_id,
'client_secret': client_secret
}
request = requests.post(token_url, data=payload,... | [
"def",
"get_access_token",
"(",
"client_id",
",",
"client_secret",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
"}",
"payload",
"=",
"{",
"'client_id'",
":",
"client_id",
",",
"'client_secret'",
":",
"client_secret",
"... | 24.052632 | 24.473684 |
def detachRequestMsOriginating():
"""DETACH REQUEST Section 9.4.5.2"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x5) # 00000101
c = DetachTypeAndSpareHalfOctets()
packet = a / b / c
return packet | [
"def",
"detachRequestMsOriginating",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x5",
")",
"# 00000101",
"c",
"=",
"DetachTypeAndSpareHalfOctets",
"(",
")",
"packet",
"=",
"a",
"/",
"b",
... | 30.571429 | 10.571429 |
def selectlanguage(self, event):
"""Store client's selection of a new translation"""
self.log('Language selection event:', event.client, pretty=True)
if event.data not in all_languages():
self.log('Unavailable language selected:', event.data, lvl=warn)
language = None
... | [
"def",
"selectlanguage",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"'Language selection event:'",
",",
"event",
".",
"client",
",",
"pretty",
"=",
"True",
")",
"if",
"event",
".",
"data",
"not",
"in",
"all_languages",
"(",
")",
":",
... | 30.736842 | 19.421053 |
def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit:
"""Circuit equivalent of 1-qubit ZYZ gate"""
circ = Circuit()
circ += TZ(t0, q0)
circ += TY(t1, q0)
circ += TZ(t2, q0)
return circ | [
"def",
"zyz_circuit",
"(",
"t0",
":",
"float",
",",
"t1",
":",
"float",
",",
"t2",
":",
"float",
",",
"q0",
":",
"Qubit",
")",
"->",
"Circuit",
":",
"circ",
"=",
"Circuit",
"(",
")",
"circ",
"+=",
"TZ",
"(",
"t0",
",",
"q0",
")",
"circ",
"+=",
... | 31.428571 | 18.571429 |
def current_state(self):
"""
Returns a ``field -> value`` dict of the current state of the instance.
"""
field_names = set()
[field_names.add(f.name) for f in self._meta.local_fields]
[field_names.add(f.attname) for f in self._meta.local_fields]
return dict([(fiel... | [
"def",
"current_state",
"(",
"self",
")",
":",
"field_names",
"=",
"set",
"(",
")",
"[",
"field_names",
".",
"add",
"(",
"f",
".",
"name",
")",
"for",
"f",
"in",
"self",
".",
"_meta",
".",
"local_fields",
"]",
"[",
"field_names",
".",
"add",
"(",
"... | 47.375 | 21.875 |
def is_valid_mpls_labels(labels):
"""Returns True if the given value is a list of valid MPLS labels.
"""
if not isinstance(labels, (list, tuple)):
return False
for label in labels:
if not is_valid_mpls_label(label):
return False
return True | [
"def",
"is_valid_mpls_labels",
"(",
"labels",
")",
":",
"if",
"not",
"isinstance",
"(",
"labels",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"False",
"for",
"label",
"in",
"labels",
":",
"if",
"not",
"is_valid_mpls_label",
"(",
"label",
")"... | 25.454545 | 15.545455 |
def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args) | [
"def",
"output_dir",
"(",
"self",
",",
"*",
"args",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_dir",
",",
"'output'",
",",
"*",
"args",
")"
] | 48 | 9 |
def serialize_md_inst(self, md_inst, md_class):
"""Serialize object ``md_inst`` by transforming it into an
``lxml.etree._ElementTree``. If it already is such, return it. If not,
make sure it is the correct type and return the output of calling
``seriaize()`` on it.
"""
va... | [
"def",
"serialize_md_inst",
"(",
"self",
",",
"md_inst",
",",
"md_class",
")",
":",
"valid_insts",
"=",
"tuple",
"(",
"chain",
"(",
"(",
"etree",
".",
"_ElementTree",
",",
"etree",
".",
"_Element",
")",
",",
"six",
".",
"string_types",
")",
")",
"if",
... | 42.875 | 17.1875 |
def facettupletrees(table, key, start='start', stop='stop', value=None):
"""
Construct faceted interval trees for the given table, where each node in
the tree is a row of the table.
"""
import intervaltree
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
assert star... | [
"def",
"facettupletrees",
"(",
"table",
",",
"key",
",",
"start",
"=",
"'start'",
",",
"stop",
"=",
"'stop'",
",",
"value",
"=",
"None",
")",
":",
"import",
"intervaltree",
"it",
"=",
"iter",
"(",
"table",
")",
"hdr",
"=",
"next",
"(",
"it",
")",
"... | 32.3125 | 16.9375 |
def get_authorize_url(self, callback_url):
"""
Returns the Authorize URL as returned by QB, and specified by OAuth 1.0a.
:return URI:
"""
self.authorize_url = self.authorize_url[:self.authorize_url.find('?')] \
if '?' in self.authorize_url else self.authorize_url
... | [
"def",
"get_authorize_url",
"(",
"self",
",",
"callback_url",
")",
":",
"self",
".",
"authorize_url",
"=",
"self",
".",
"authorize_url",
"[",
":",
"self",
".",
"authorize_url",
".",
"find",
"(",
"'?'",
")",
"]",
"if",
"'?'",
"in",
"self",
".",
"authorize... | 37.36 | 20.16 |
def split(zpool, newzpool, **kwargs):
'''
.. versionadded:: 2018.3.0
Splits devices off pool creating newpool.
.. note::
All vdevs in pool must be mirrors. At the time of the split,
``newzpool`` will be a replica of ``zpool``.
After splitting, do not forget to import the new... | [
"def",
"split",
"(",
"zpool",
",",
"newzpool",
",",
"*",
"*",
"kwargs",
")",
":",
"## Configure pool",
"# NOTE: initialize the defaults",
"opts",
"=",
"{",
"}",
"# NOTE: push pool and filesystem properties",
"pool_properties",
"=",
"kwargs",
".",
"get",
"(",
"'prope... | 24.542169 | 24.855422 |
def update_qos_policy(self, qos_policy, body=None):
"""Updates a qos policy."""
return self.put(self.qos_policy_path % qos_policy,
body=body) | [
"def",
"update_qos_policy",
"(",
"self",
",",
"qos_policy",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"qos_policy_path",
"%",
"qos_policy",
",",
"body",
"=",
"body",
")"
] | 44.5 | 8.75 |
def AddPorts(self,ports):
"""Create one or more port access policies.
Include a list of dicts with protocol, port, and port_to (optional - for range) keys.
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
.AddPorts([{'protocol': 'TCP', 'port': '80' },
{'protocol': 'UDP', 'port': '100... | [
"def",
"AddPorts",
"(",
"self",
",",
"ports",
")",
":",
"for",
"port",
"in",
"ports",
":",
"if",
"'port_to'",
"in",
"port",
":",
"self",
".",
"ports",
".",
"append",
"(",
"Port",
"(",
"self",
",",
"port",
"[",
"'protocol'",
"]",
",",
"port",
"[",
... | 34.117647 | 29.882353 |
def _get_service_names(self):
"""
Get a list of service names from Sentinel. Tries Sentinel hosts until one succeeds; if none succeed,
raises a ConnectionError.
:return: the list of service names from Sentinel.
"""
master_info = None
connection_errors = []
... | [
"def",
"_get_service_names",
"(",
"self",
")",
":",
"master_info",
"=",
"None",
"connection_errors",
"=",
"[",
"]",
"for",
"sentinel",
"in",
"self",
".",
"_sentinel",
".",
"sentinels",
":",
"# Unfortunately, redis.sentinel.Sentinel does not support sentinel_masters, so we... | 44.695652 | 22.695652 |
def contains_only(self, *items):
"""Asserts that val contains only the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
else:
extra = []
for i in self.val:
if i not in items:
ext... | [
"def",
"contains_only",
"(",
"self",
",",
"*",
"items",
")",
":",
"if",
"len",
"(",
"items",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'one or more args must be given'",
")",
"else",
":",
"extra",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
... | 42.315789 | 23.842105 |
def export_kappa_im(model, fname=None):
"""Return a networkx graph representing the model's Kappa influence map.
Parameters
----------
model : pysb.core.Model
A PySB model to be exported into a Kappa IM.
fname : Optional[str]
A file name, typically with .png or .pdf extension in whi... | [
"def",
"export_kappa_im",
"(",
"model",
",",
"fname",
"=",
"None",
")",
":",
"from",
".",
"kappa_util",
"import",
"im_json_to_graph",
"kappa",
"=",
"_prepare_kappa",
"(",
"model",
")",
"imap",
"=",
"kappa",
".",
"analyses_influence_map",
"(",
")",
"im",
"=",... | 29.068966 | 15.931034 |
def count_mismatches_after_variant(reference_suffix, cdna_suffix):
"""
Computes the number of mismatching nucleotides between two cDNA sequences after a variant locus.
Parameters
----------
reference_suffix : str
cDNA sequence of a reference transcript after a variant locus
cdna_suffix... | [
"def",
"count_mismatches_after_variant",
"(",
"reference_suffix",
",",
"cdna_suffix",
")",
":",
"len_diff",
"=",
"len",
"(",
"cdna_suffix",
")",
"-",
"len",
"(",
"reference_suffix",
")",
"# if the reference is shorter than the read, the read runs into the intron - these count a... | 36 | 29.555556 |
def extract_and_render_all_symbol_masks(self, raw_data_directory: str, destination_directory: str):
"""
Extracts all symbols from the raw XML documents and generates individual symbols from the masks
:param raw_data_directory: The directory, that contains the xml-files and matching images
... | [
"def",
"extract_and_render_all_symbol_masks",
"(",
"self",
",",
"raw_data_directory",
":",
"str",
",",
"destination_directory",
":",
"str",
")",
":",
"print",
"(",
"\"Extracting Symbols from Muscima++ Dataset...\"",
")",
"xml_files",
"=",
"self",
".",
"get_all_xml_file_pa... | 62.461538 | 39.230769 |
def validate_schema(schema: GraphQLSchema) -> List[GraphQLError]:
"""Validate a GraphQL schema.
Implements the "Type Validation" sub-sections of the specification's "Type System"
section.
Validation runs synchronously, returning a list of encountered errors, or an empty
list if no errors were enco... | [
"def",
"validate_schema",
"(",
"schema",
":",
"GraphQLSchema",
")",
"->",
"List",
"[",
"GraphQLError",
"]",
":",
"# First check to ensure the provided value is in fact a GraphQLSchema.",
"assert_schema",
"(",
"schema",
")",
"# If this Schema has already been validated, return the... | 36.62069 | 22.344828 |
def use_edns(self, edns=0, ednsflags=0, payload=1280, request_payload=None, options=None):
"""Configure EDNS behavior.
@param edns: The EDNS level to use. Specifying None, False, or -1
means 'do not use EDNS', and in this case the other parameters are
ignored. Specifying True is equiva... | [
"def",
"use_edns",
"(",
"self",
",",
"edns",
"=",
"0",
",",
"ednsflags",
"=",
"0",
",",
"payload",
"=",
"1280",
",",
"request_payload",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"edns",
"is",
"None",
"or",
"edns",
"is",
"False",
":"... | 39.756098 | 15.560976 |
def signing_text(self):
"""Return the text to be signed when signing the query."""
result = "%s\n%s\n%s\n%s" % (self.endpoint.method,
self.endpoint.get_canonical_host(),
self.endpoint.path,
sel... | [
"def",
"signing_text",
"(",
"self",
")",
":",
"result",
"=",
"\"%s\\n%s\\n%s\\n%s\"",
"%",
"(",
"self",
".",
"endpoint",
".",
"method",
",",
"self",
".",
"endpoint",
".",
"get_canonical_host",
"(",
")",
",",
"self",
".",
"endpoint",
".",
"path",
",",
"se... | 52.428571 | 19 |
def unshare(self, con):
"""Decrease the share of a connection in the shared cache."""
self._lock.acquire()
try:
con.unshare()
shared = con.shared
if not shared: # connection is idle,
try: # so try to remove it
self._shared... | [
"def",
"unshare",
"(",
"self",
",",
"con",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"con",
".",
"unshare",
"(",
")",
"shared",
"=",
"con",
".",
"shared",
"if",
"not",
"shared",
":",
"# connection is idle,",
"try",
":",
... | 38.2 | 13.333333 |
def main(self, args=None, prog_name=None, complete_var=None,
standalone_mode=True, **extra):
"""This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, ``Syste... | [
"def",
"main",
"(",
"self",
",",
"args",
"=",
"None",
",",
"prog_name",
"=",
"None",
",",
"complete_var",
"=",
"None",
",",
"standalone_mode",
"=",
"True",
",",
"*",
"*",
"extra",
")",
":",
"# If we are in Python 3, we will verify that the environment is",
"# sa... | 45.952381 | 21.535714 |
def configure(self, inputs, outputs):
"""Configure activity input and output.
You need to provide a list of input and output :class:`Property`. Does not work with lists of propery id's.
:param inputs: iterable of input property models
:type inputs: list(:class:`Property`)
:para... | [
"def",
"configure",
"(",
"self",
",",
"inputs",
",",
"outputs",
")",
":",
"url",
"=",
"self",
".",
"_client",
".",
"_build_url",
"(",
"'activity'",
",",
"activity_id",
"=",
"self",
".",
"id",
")",
"r",
"=",
"self",
".",
"_client",
".",
"_request",
"(... | 43.7 | 24.1 |
def do_read(self, args):
"""read <addr> <objid> <prop> [ <indx> ]"""
args = args.split()
if _debug: ReadPropertyConsoleCmd._debug("do_read %r", args)
try:
addr, obj_id, prop_id = args[:3]
obj_id = ObjectIdentifier(obj_id).value
datatype = get_datatyp... | [
"def",
"do_read",
"(",
"self",
",",
"args",
")",
":",
"args",
"=",
"args",
".",
"split",
"(",
")",
"if",
"_debug",
":",
"ReadPropertyConsoleCmd",
".",
"_debug",
"(",
"\"do_read %r\"",
",",
"args",
")",
"try",
":",
"addr",
",",
"obj_id",
",",
"prop_id",... | 38.557143 | 21.857143 |
def hide_routemap_holder_route_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElement(hide_routemap_holder, "... | [
"def",
"hide_routemap_holder_route_map_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hide-routemap-holder\"",
",",
... | 48.066667 | 17.866667 |
def badge_svg_text(self):
"""The badge SVG text."""
# Identify whether template is a file or the actual template text
if len(self.template.split('\n')) == 1:
with open(self.template, mode='r') as file_handle:
badge_text = file_handle.read()
else:
... | [
"def",
"badge_svg_text",
"(",
"self",
")",
":",
"# Identify whether template is a file or the actual template text",
"if",
"len",
"(",
"self",
".",
"template",
".",
"split",
"(",
"'\\n'",
")",
")",
"==",
"1",
":",
"with",
"open",
"(",
"self",
".",
"template",
... | 54.583333 | 25.208333 |
def _EccZmaxRperiRap(self,*args,**kwargs):
"""
NAME:
EccZmaxRperiRap (_EccZmaxRperiRap)
PURPOSE:
evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the Staeckel approximation
INPUT:
Either:
a) R,vR,vT,z,vz[,phi... | [
"def",
"_EccZmaxRperiRap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"5",
":",
"#R,vR.vT, z, vz",
"R",
",",
"vR",
",",
"vT",
",",
"z",
",",
"vz",
"=",
"args",
"elif",
"len",
"(",
"arg... | 58.00813 | 25.796748 |
def _tag(element):
"""Return element.tag with xmlns stripped away."""
tag = element.tag
if tag[0] == "{":
uri, tag = tag[1:].split("}")
return tag | [
"def",
"_tag",
"(",
"element",
")",
":",
"tag",
"=",
"element",
".",
"tag",
"if",
"tag",
"[",
"0",
"]",
"==",
"\"{\"",
":",
"uri",
",",
"tag",
"=",
"tag",
"[",
"1",
":",
"]",
".",
"split",
"(",
"\"}\"",
")",
"return",
"tag"
] | 27.5 | 14.833333 |
def execution_history_focus(self, model, prop_name, info):
""" Arranges to put execution-history widget page to become top page in notebook when execution starts and stops
and resets the boolean of modification_history_was_focused to False each time this notification are observed.
"""
if... | [
"def",
"execution_history_focus",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"if",
"state_machine_execution_engine",
".",
"status",
".",
"execution_mode",
"in",
"[",
"StateMachineExecutionStatus",
".",
"STARTED",
",",
"StateMachineExecutionSta... | 65.3125 | 33.875 |
def draw_widget(self, item):
"""Create a preview of the selected treeview item"""
if item:
self.filter_remove(remember=True)
selected_id = self.treedata[item]['id']
item = self.get_toplevel_parent(item)
widget_id = self.treedata[item]['id']
wcl... | [
"def",
"draw_widget",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
":",
"self",
".",
"filter_remove",
"(",
"remember",
"=",
"True",
")",
"selected_id",
"=",
"self",
".",
"treedata",
"[",
"item",
"]",
"[",
"'id'",
"]",
"item",
"=",
"self",
".",
... | 46.416667 | 11.916667 |
def _read_plain(self, lines):
"""
Read text fragments from a plain format text file.
:param list lines: the lines of the plain text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
:raises: ValueError: ... | [
"def",
"_read_plain",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"log",
"(",
"u\"Parsing fragments from plain text format\"",
")",
"id_format",
"=",
"self",
".",
"_get_id_format",
"(",
")",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"... | 36.7 | 14.3 |
def save_scenario(self):
"""Save current scenario to text file."""
from safe.gui.tools.save_scenario import SaveScenarioDialog
dialog = SaveScenarioDialog(
iface=self.iface,
dock=self.dock_widget)
dialog.save_scenario() | [
"def",
"save_scenario",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"save_scenario",
"import",
"SaveScenarioDialog",
"dialog",
"=",
"SaveScenarioDialog",
"(",
"iface",
"=",
"self",
".",
"iface",
",",
"dock",
"=",
"self",
".",
"doc... | 33.625 | 14.25 |
def _svrg_grads_update_rule(self, g_curr_batch_curr_weight, g_curr_batch_special_weight,
g_special_weight_all_batch):
"""Calculates the gradient based on the SVRG update rule.
Parameters
----------
g_curr_batch_curr_weight : NDArray
gradients o... | [
"def",
"_svrg_grads_update_rule",
"(",
"self",
",",
"g_curr_batch_curr_weight",
",",
"g_curr_batch_special_weight",
",",
"g_special_weight_all_batch",
")",
":",
"for",
"index",
",",
"grad",
"in",
"enumerate",
"(",
"g_curr_batch_curr_weight",
")",
":",
"grad",
"-=",
"g... | 48.666667 | 21.428571 |
def wncond(left, right, window):
"""
Contract each of the intervals of a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncond_c.html
:param left: Amount added to each left endpoint.
:type left: float
:param right: Amount subtracted from each right endpoint. ... | [
"def",
"wncond",
"(",
"left",
",",
"right",
",",
"window",
")",
":",
"assert",
"isinstance",
"(",
"window",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"window",
".",
"dtype",
"==",
"1",
"left",
"=",
"ctypes",
".",
"c_double",
"(",
"left",
")",
"... | 35 | 15.571429 |
def reqContractDetails(self, contract: Contract) -> List[ContractDetails]:
"""
Get a list of contract details that match the given contract.
If the returned list is empty then the contract is not known;
If the list has multiple values then the contract is ambiguous.
The fully qu... | [
"def",
"reqContractDetails",
"(",
"self",
",",
"contract",
":",
"Contract",
")",
"->",
"List",
"[",
"ContractDetails",
"]",
":",
"return",
"self",
".",
"_run",
"(",
"self",
".",
"reqContractDetailsAsync",
"(",
"contract",
")",
")"
] | 37.941176 | 24.294118 |
def send(self,cmd,*args,arg_formats=None):
"""
Send a command (which may or may not have associated arguments) to an
arduino using the CmdMessage protocol. The command and any parameters
should be passed as direct arguments to send.
arg_formats is an optional string that spe... | [
"def",
"send",
"(",
"self",
",",
"cmd",
",",
"*",
"args",
",",
"arg_formats",
"=",
"None",
")",
":",
"# Turn the command into an integer.",
"try",
":",
"command_as_int",
"=",
"self",
".",
"_cmd_name_to_int",
"[",
"cmd",
"]",
"except",
"KeyError",
":",
"err",... | 40.62963 | 23.592593 |
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True | [
"def",
"has_instance",
"(",
"name",
",",
"provider",
"=",
"None",
")",
":",
"data",
"=",
"get_instance",
"(",
"name",
",",
"provider",
")",
"if",
"data",
"is",
"None",
":",
"return",
"False",
"return",
"True"
] | 20.928571 | 22.928571 |
def add_interface_router(self, router, subnet):
'''
Adds an internal network interface to the specified router
'''
router_id = self._find_router_id(router)
subnet_id = self._find_subnet_id(subnet)
return self.network_conn.add_interface_router(
router=router_id... | [
"def",
"add_interface_router",
"(",
"self",
",",
"router",
",",
"subnet",
")",
":",
"router_id",
"=",
"self",
".",
"_find_router_id",
"(",
"router",
")",
"subnet_id",
"=",
"self",
".",
"_find_subnet_id",
"(",
"subnet",
")",
"return",
"self",
".",
"network_co... | 43.125 | 17.625 |
def _compute_smooth_during_construction(self, xi):
"""
Evaluate value of smooth at x-value xi.
Parameters
----------
xi : float
Value of x where smooth value is desired
Returns
-------
smooth_here : float
Value of smooth s(xi)
... | [
"def",
"_compute_smooth_during_construction",
"(",
"self",
",",
"xi",
")",
":",
"if",
"self",
".",
"_variance_in_window",
":",
"beta",
"=",
"self",
".",
"_covariance_in_window",
"/",
"self",
".",
"_variance_in_window",
"alpha",
"=",
"self",
".",
"_mean_y_in_window... | 30.333333 | 17.285714 |
def my_init(self):
"""
Method automatically called from base class constructor.
"""
self._start_time = time.time()
self._stats = {}
self._stats_lock = threading.Lock() | [
"def",
"my_init",
"(",
"self",
")",
":",
"self",
".",
"_start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_stats",
"=",
"{",
"}",
"self",
".",
"_stats_lock",
"=",
"threading",
".",
"Lock",
"(",
")"
] | 29.857143 | 9.571429 |
def _count_async(self, limit=None, **q_options):
"""Internal version of count_async()."""
# TODO: Support offset by incorporating it to the limit.
if 'offset' in q_options:
raise NotImplementedError('.count() and .count_async() do not support '
'offsets at present.')
... | [
"def",
"_count_async",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"q_options",
")",
":",
"# TODO: Support offset by incorporating it to the limit.",
"if",
"'offset'",
"in",
"q_options",
":",
"raise",
"NotImplementedError",
"(",
"'.count() and .count_async() ... | 44 | 14.810811 |
def createEditor(self, delegate, parent, option):
""" Creates a FloatCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return FloatCtiEditor(self, delegate, parent=parent) | [
"def",
"createEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
",",
"option",
")",
":",
"return",
"FloatCtiEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
"=",
"parent",
")"
] | 46.8 | 13.2 |
def deploy_deb(self,
file_name,
distribution,
component,
architecture,
parameters={}):
"""
Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file th... | [
"def",
"deploy_deb",
"(",
"self",
",",
"file_name",
",",
"distribution",
",",
"component",
",",
"architecture",
",",
"parameters",
"=",
"{",
"}",
")",
":",
"params",
"=",
"{",
"'deb.distribution'",
":",
"distribution",
",",
"'deb.component'",
":",
"component",... | 33.583333 | 14.25 |
def save_prep(cls, instance_or_instances):
"""Preprocess the object before the object is saved. This
automatically gets called when the save method gets called.
"""
instances = make_obj_list(instance_or_instances)
tokens = set(cls.objects.get_available_tokens(
count... | [
"def",
"save_prep",
"(",
"cls",
",",
"instance_or_instances",
")",
":",
"instances",
"=",
"make_obj_list",
"(",
"instance_or_instances",
")",
"tokens",
"=",
"set",
"(",
"cls",
".",
"objects",
".",
"get_available_tokens",
"(",
"count",
"=",
"len",
"(",
"instanc... | 33 | 15.388889 |
def check_api_key(email, api_key):
"""Check the API key of the user."""
table = boto3.resource("dynamodb").Table(os.environ['people'])
user = table.get_item(Key={'email': email})
if not user:
return False
user = user.get("Item")
if api_key != user.get('api_key', None):
return Fal... | [
"def",
"check_api_key",
"(",
"email",
",",
"api_key",
")",
":",
"table",
"=",
"boto3",
".",
"resource",
"(",
"\"dynamodb\"",
")",
".",
"Table",
"(",
"os",
".",
"environ",
"[",
"'people'",
"]",
")",
"user",
"=",
"table",
".",
"get_item",
"(",
"Key",
"... | 32.9 | 14.5 |
def page(self, number, *args, **kwargs):
"""Return a standard ``Page`` instance with custom, digg-specific
page ranges attached.
"""
page = super().page(number, *args, **kwargs)
number = int(number) # we know this will work
# easier access
num_pages, body, tail,... | [
"def",
"page",
"(",
"self",
",",
"number",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"page",
"=",
"super",
"(",
")",
".",
"page",
"(",
"number",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"number",
"=",
"int",
"(",
"number",
"... | 46.52 | 22.173333 |
def resolve(self, context, provider):
"""Recursively resolve any lookups with the Variable.
Args:
context (:class:`stacker.context.Context`): Current context for
building the stack
provider (:class:`stacker.provider.base.BaseProvider`): subclass of
... | [
"def",
"resolve",
"(",
"self",
",",
"context",
",",
"provider",
")",
":",
"try",
":",
"self",
".",
"_value",
".",
"resolve",
"(",
"context",
",",
"provider",
")",
"except",
"FailedLookup",
"as",
"e",
":",
"raise",
"FailedVariableLookup",
"(",
"self",
"."... | 36.142857 | 19.285714 |
def _set_mark(self, v, load=False):
"""
Setter method for mark, mapped from YANG variable /qos/map/dscp_mutation/mark (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mark is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_mark",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 113.954545 | 54.909091 |
def get_config(self):
"""
function to get current configuration
"""
config = {
'location': self.location,
'language': self.language,
'topic': self.topic,
}
return config | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"{",
"'location'",
":",
"self",
".",
"location",
",",
"'language'",
":",
"self",
".",
"language",
",",
"'topic'",
":",
"self",
".",
"topic",
",",
"}",
"return",
"config"
] | 24.4 | 10.8 |
def token(self, token_address: Address) -> Token:
""" Return a proxy to interact with a token. """
if not is_binary_address(token_address):
raise ValueError('token_address must be a valid address')
with self._token_creation_lock:
if token_address not in self.address_to_t... | [
"def",
"token",
"(",
"self",
",",
"token_address",
":",
"Address",
")",
"->",
"Token",
":",
"if",
"not",
"is_binary_address",
"(",
"token_address",
")",
":",
"raise",
"ValueError",
"(",
"'token_address must be a valid address'",
")",
"with",
"self",
".",
"_token... | 43 | 16.714286 |
def get(self, path, watch=None):
"""Returns the data of the specified node."""
_log.debug(
"ZK: Getting {path}".format(path=path),
)
return self.zk.get(path, watch) | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"watch",
"=",
"None",
")",
":",
"_log",
".",
"debug",
"(",
"\"ZK: Getting {path}\"",
".",
"format",
"(",
"path",
"=",
"path",
")",
",",
")",
"return",
"self",
".",
"zk",
".",
"get",
"(",
"path",
",",
"... | 33.833333 | 12 |
def crust_type_at(lat=None, lon=None):
"""
lat, lon (degrees)
"""
# Get lon into appropriate format
lats = np.array(lat)
lons = np.array(lon%360)
iVals = ((90.0-lats)%180).astype(np.int)
jVals = (lons%360.0).astype(int)
# i = int((-lat+90.0)%180)
# j = int(lon)
t = _c1_cr... | [
"def",
"crust_type_at",
"(",
"lat",
"=",
"None",
",",
"lon",
"=",
"None",
")",
":",
"# Get lon into appropriate format",
"lats",
"=",
"np",
".",
"array",
"(",
"lat",
")",
"lons",
"=",
"np",
".",
"array",
"(",
"lon",
"%",
"360",
")",
"iVals",
"=",
"("... | 16.148148 | 22 |
def find_args(self, text, start=None):
"""implementation details"""
if start is None:
start = 0
first_occurance = text.find(self.__begin, start)
if first_occurance == -1:
return self.NOT_FOUND
previous_found, found = first_occurance + 1, 0
while Tr... | [
"def",
"find_args",
"(",
"self",
",",
"text",
",",
"start",
"=",
"None",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"0",
"first_occurance",
"=",
"text",
".",
"find",
"(",
"self",
".",
"__begin",
",",
"start",
")",
"if",
"first_occuranc... | 37.125 | 11.125 |
def random_peptides(num, length=9, distribution=None):
"""
Generate random peptides (kmers).
Parameters
----------
num : int
Number of peptides to return
length : int
Length of each peptide
distribution : pandas.Series
Maps 1-letter amino acid abbreviations to
... | [
"def",
"random_peptides",
"(",
"num",
",",
"length",
"=",
"9",
",",
"distribution",
"=",
"None",
")",
":",
"if",
"num",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"distribution",
"is",
"None",
":",
"distribution",
"=",
"pandas",
".",
"Series",
"(",
"1... | 22.810811 | 18.324324 |
def update_unique(self, table_name, fields, data, cond=None, unique_fields=None,
*, raise_if_not_found=False):
"""Update the unique matching element to have a given set of fields.
Parameters
----------
table_name: str
fields: dict or function[dict -> None]... | [
"def",
"update_unique",
"(",
"self",
",",
"table_name",
",",
"fields",
",",
"data",
",",
"cond",
"=",
"None",
",",
"unique_fields",
"=",
"None",
",",
"*",
",",
"raise_if_not_found",
"=",
"False",
")",
":",
"eid",
"=",
"find_unique",
"(",
"self",
".",
"... | 30.439024 | 23.195122 |
def cut_nodes_edges2(graph):
"""Bi-connected components, alternative recursive implementation
:param graph: undirected graph. in listlist format. Cannot be in listdict format.
:assumes: graph has about 5000 vertices at most, otherwise memory limit is reached
:returns: a tuple with the list of cut-nodes... | [
"def",
"cut_nodes_edges2",
"(",
"graph",
")",
":",
"N",
"=",
"len",
"(",
"graph",
")",
"assert",
"N",
"<=",
"5000",
"recursionlimit",
"=",
"getrecursionlimit",
"(",
")",
"setrecursionlimit",
"(",
"max",
"(",
"recursionlimit",
",",
"N",
"+",
"42",
")",
")... | 40.291667 | 18.854167 |
def match(license):
'''Returns True if given license field is correct
Taken from rpmlint.
It's named match() to mimic a compiled regexp.'''
if license not in VALID_LICENSES:
for l1 in _split_license(license):
if l1 in VALID_LICENSES:
continue
for l2 in _s... | [
"def",
"match",
"(",
"license",
")",
":",
"if",
"license",
"not",
"in",
"VALID_LICENSES",
":",
"for",
"l1",
"in",
"_split_license",
"(",
"license",
")",
":",
"if",
"l1",
"in",
"VALID_LICENSES",
":",
"continue",
"for",
"l2",
"in",
"_split_license",
"(",
"... | 32.857143 | 12 |
def timestamp(datetime_obj):
"""Return Unix timestamp as float.
The number of seconds that have elapsed since January 1, 1970.
"""
start_of_time = datetime.datetime(1970, 1, 1)
diff = datetime_obj - start_of_time
return diff.total_seconds() | [
"def",
"timestamp",
"(",
"datetime_obj",
")",
":",
"start_of_time",
"=",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"diff",
"=",
"datetime_obj",
"-",
"start_of_time",
"return",
"diff",
".",
"total_seconds",
"(",
")"
] | 32.25 | 12.125 |
def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'filenumber':
plugin.filenumber_handle()
elif plugin.args.option == 'fileage':
plugin.fileage_handle()
elif plugin.args.option == 'sqlserverlocks':
plugin.sqlserverlo... | [
"def",
"main",
"(",
")",
":",
"plugin",
"=",
"Register",
"(",
")",
"if",
"plugin",
".",
"args",
".",
"option",
"==",
"'filenumber'",
":",
"plugin",
".",
"filenumber_handle",
"(",
")",
"elif",
"plugin",
".",
"args",
".",
"option",
"==",
"'fileage'",
":"... | 34.090909 | 9.727273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.