text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def init_runner(**kwargs):
'''
Initialize the Runner() instance
This function will properly initialize both run() and run_async()
functions in the same way and return a value instance of Runner.
See parameters given to :py:func:`ansible_runner.interface.run`
'''
dump_artifacts(kwargs)
... | [
"def",
"init_runner",
"(",
"*",
"*",
"kwargs",
")",
":",
"dump_artifacts",
"(",
"kwargs",
")",
"debug",
"=",
"kwargs",
".",
"pop",
"(",
"'debug'",
",",
"None",
")",
"logfile",
"=",
"kwargs",
".",
"pop",
"(",
"'logfile'",
",",
"None",
")",
"if",
"not"... | 33.947368 | 23.157895 |
def add_view(self, row=None, col=None, row_span=1, col_span=1,
**kwargs):
"""
Create a new ViewBox and add it as a child widget.
Parameters
----------
row : int
The row in which to add the widget (0 is the topmost row)
col : int
T... | [
"def",
"add_view",
"(",
"self",
",",
"row",
"=",
"None",
",",
"col",
"=",
"None",
",",
"row_span",
"=",
"1",
",",
"col_span",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"viewbox",
"import",
"ViewBox",
"view",
"=",
"ViewBox",
"(",
"... | 37.571429 | 20.142857 |
def _add_to_cache(key, value):
"""
Internal method to add a new key-value to the local cache.
:param str key: The new url to add to the cache
:param str value: The HTTP response for this key.
:returns: void
"""
if key in _CACHE:
_CACHE[key].append(value)
else:
_CACHE[key]... | [
"def",
"_add_to_cache",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"_CACHE",
":",
"_CACHE",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")",
"else",
":",
"_CACHE",
"[",
"key",
"]",
"=",
"[",
"_PATTERN",
",",
"value",
"]",
"_CACHE_COUN... | 30.083333 | 12.083333 |
def writeMultiByte(self, value, charset):
"""
Writes a multibyte string to the datastream using the
specified character set.
@type value: C{str}
@param value: The string value to be written.
@type charset: C{str}
@param charset: The string denoting the character ... | [
"def",
"writeMultiByte",
"(",
"self",
",",
"value",
",",
"charset",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"unicode",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"charset",
")",
"self",
".",
"stream",
".",
"write",
"(",
"value",
")"
] | 38.388889 | 15.944444 |
def make_query(catalog):
"""A function to prepare a query
"""
query = {}
request = api.get_request()
index = get_search_index_for(catalog)
limit = request.form.get("limit")
q = request.form.get("q")
if len(q) > 0:
query[index] = q + "*"
else:
return None
portal_... | [
"def",
"make_query",
"(",
"catalog",
")",
":",
"query",
"=",
"{",
"}",
"request",
"=",
"api",
".",
"get_request",
"(",
")",
"index",
"=",
"get_search_index_for",
"(",
"catalog",
")",
"limit",
"=",
"request",
".",
"form",
".",
"get",
"(",
"\"limit\"",
"... | 24.083333 | 15.791667 |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
TARFileEntry: file entry.
"""
path_spec = tar_path_spec.TARPathSpec(
location=self.LOCATION_ROOT, parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | [
"def",
"GetRootFileEntry",
"(",
"self",
")",
":",
"path_spec",
"=",
"tar_path_spec",
".",
"TARPathSpec",
"(",
"location",
"=",
"self",
".",
"LOCATION_ROOT",
",",
"parent",
"=",
"self",
".",
"_path_spec",
".",
"parent",
")",
"return",
"self",
".",
"GetFileEnt... | 30.222222 | 14.222222 |
def _extract_title(self):
""" Extract the title and remove it from the document.
If title has already been extracted, this method will do nothing.
If removal cannot happen or fails, the document is left untouched.
"""
if self.title:
return
for pattern in s... | [
"def",
"_extract_title",
"(",
"self",
")",
":",
"if",
"self",
".",
"title",
":",
"return",
"for",
"pattern",
"in",
"self",
".",
"config",
".",
"title",
":",
"items",
"=",
"self",
".",
"parsed_tree",
".",
"xpath",
"(",
"pattern",
")",
"if",
"not",
"it... | 34.266667 | 23.616667 |
def get_bmus(self, activation_map):
"""Returns Best Matching Units indexes of the activation map.
:param activation_map: Activation map computed with self.get_surface_state()
:type activation_map: 2D numpy.array
:returns: The bmus indexes corresponding to this activation map
... | [
"def",
"get_bmus",
"(",
"self",
",",
"activation_map",
")",
":",
"Y",
",",
"X",
"=",
"np",
".",
"unravel_index",
"(",
"activation_map",
".",
"argmin",
"(",
"axis",
"=",
"1",
")",
",",
"(",
"self",
".",
"_n_rows",
",",
"self",
".",
"_n_columns",
")",
... | 40.5 | 20.642857 |
def comment_count(self):
"""
Counts total number of comments on ModelBase object.
Comments should always be recorded on ModelBase objects.
"""
# Get the comment model.
comment_model = comments.get_model()
modelbase_content_type = ContentType.objects.get(app_label... | [
"def",
"comment_count",
"(",
"self",
")",
":",
"# Get the comment model.",
"comment_model",
"=",
"comments",
".",
"get_model",
"(",
")",
"modelbase_content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"\"panya\"",
",",
"model",
"... | 42.758621 | 21.310345 |
def debug_async(self, conn_id, cmd_name, cmd_args, progress_callback, callback):
"""Asynchronously complete a named debug command.
The command name and arguments are passed to the underlying device adapter
and interpreted there. If the command is long running, progress_callback
may be ... | [
"def",
"debug_async",
"(",
"self",
",",
"conn_id",
",",
"cmd_name",
",",
"cmd_args",
",",
"progress_callback",
",",
"callback",
")",
":",
"known_commands",
"=",
"{",
"'dump_ram'",
":",
"JLinkControlThread",
".",
"DUMP_ALL_RAM",
",",
"'program_flash'",
":",
"JLin... | 51.7 | 32.2 |
def _replace_auth_key(
user,
key,
enc='ssh-rsa',
comment='',
options=None,
config='.ssh/authorized_keys'):
'''
Replace an existing key
'''
auth_line = _format_auth_line(key, enc, comment, options or [])
lines = []
full = _get_config_file(user, co... | [
"def",
"_replace_auth_key",
"(",
"user",
",",
"key",
",",
"enc",
"=",
"'ssh-rsa'",
",",
"comment",
"=",
"''",
",",
"options",
"=",
"None",
",",
"config",
"=",
"'.ssh/authorized_keys'",
")",
":",
"auth_line",
"=",
"_format_auth_line",
"(",
"key",
",",
"enc"... | 35.244444 | 20.577778 |
def poll(self):
"""Return the run IDs of the finished jobs
Returns
-------
list(str)
The list of the run IDs of the finished jobs
"""
clusterids = clusterprocids2clusterids(self.clusterprocids_outstanding)
clusterprocid_status_list = query_status_fo... | [
"def",
"poll",
"(",
"self",
")",
":",
"clusterids",
"=",
"clusterprocids2clusterids",
"(",
"self",
".",
"clusterprocids_outstanding",
")",
"clusterprocid_status_list",
"=",
"query_status_for",
"(",
"clusterids",
")",
"# e.g., [['1730126.0', 2], ['1730127.0', 2], ['1730129.1',... | 37.470588 | 25.794118 |
def tabbar_toggled(self, settings, key, user_data):
"""If the gconf var use_tabbar be changed, this method will be
called and will show/hide the tabbar.
"""
if settings.get_boolean(key):
for n in self.guake.notebook_manager.iter_notebooks():
n.set_property("sh... | [
"def",
"tabbar_toggled",
"(",
"self",
",",
"settings",
",",
"key",
",",
"user_data",
")",
":",
"if",
"settings",
".",
"get_boolean",
"(",
"key",
")",
":",
"for",
"n",
"in",
"self",
".",
"guake",
".",
"notebook_manager",
".",
"iter_notebooks",
"(",
")",
... | 45.8 | 11.7 |
def destroy(name):
'''
removes a container [stops a container if it's running and]
raises ContainerNotExists exception if the specified name is not created
'''
if not exists(name):
raise ContainerNotExists("The container (%s) does not exist!" % name)
cmd = ['lxc-destroy', '-f', '-... | [
"def",
"destroy",
"(",
"name",
")",
":",
"if",
"not",
"exists",
"(",
"name",
")",
":",
"raise",
"ContainerNotExists",
"(",
"\"The container (%s) does not exist!\"",
"%",
"name",
")",
"cmd",
"=",
"[",
"'lxc-destroy'",
",",
"'-f'",
",",
"'-n'",
",",
"name",
... | 39.222222 | 23.666667 |
def _compile_arithmetic_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] = None... | [
"def",
"_compile_arithmetic_expression",
"(",
"self",
",",
"expr",
":",
"Expression",
",",
"scope",
":",
"Dict",
"[",
"str",
",",
"TensorFluent",
"]",
",",
"batch_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"noise",
":",
"Optional",
"[",
"... | 37.265306 | 24.408163 |
def dt_to_struct_time(dt):
"""
Convert a `datetime.date` or `datetime.datetime` to a `struct_time`
representation *with zero values* for data fields that we cannot always
rely on for ancient or far-future dates: tm_wday, tm_yday, tm_isdst
NOTE: If it wasn't for the requirement that the extra fields... | [
"def",
"dt_to_struct_time",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
":",
"return",
"struct_time",
"(",
"[",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
",",
"dt",
".",
"hour",
",",
"dt",
".... | 38.714286 | 21.666667 |
async def fetchrow(self, *args, timeout=None):
"""Execute the statement and return the first row.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: The first row as a :class:`Record` instance.
"""... | [
"async",
"def",
"fetchrow",
"(",
"self",
",",
"*",
"args",
",",
"timeout",
"=",
"None",
")",
":",
"data",
"=",
"await",
"self",
".",
"__bind_execute",
"(",
"args",
",",
"1",
",",
"timeout",
")",
"if",
"not",
"data",
":",
"return",
"None",
"return",
... | 33.461538 | 16.307692 |
def unique(self):
"""
Return the ``Categorical`` which ``categories`` and ``codes`` are
unique. Unused categories are NOT returned.
- unordered category: values and categories are sorted by appearance
order.
- ordered category: values are sorted by appearance order, ca... | [
"def",
"unique",
"(",
"self",
")",
":",
"# unlike np.unique, unique1d does not sort",
"unique_codes",
"=",
"unique1d",
"(",
"self",
".",
"codes",
")",
"cat",
"=",
"self",
".",
"copy",
"(",
")",
"# keep nan in codes",
"cat",
".",
"_codes",
"=",
"unique_codes",
... | 28.036364 | 20.690909 |
def cos(duration: int, amp: complex, freq: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates cosine wave `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than... | [
"def",
"cos",
"(",
"duration",
":",
"int",
",",
"amp",
":",
"complex",
",",
"freq",
":",
"float",
"=",
"None",
",",
"phase",
":",
"float",
"=",
"0",
",",
"name",
":",
"str",
"=",
"None",
")",
"->",
"SamplePulse",
":",
"if",
"freq",
"is",
"None",
... | 35.882353 | 23.764706 |
def _verify_same_spaces(self):
"""Verifies that all the envs have the same observation and action space."""
# Pre-conditions: self._envs is initialized.
if self._envs is None:
raise ValueError("Environments not initialized.")
if not isinstance(self._envs, list):
tf.logging.warning("Not ch... | [
"def",
"_verify_same_spaces",
"(",
"self",
")",
":",
"# Pre-conditions: self._envs is initialized.",
"if",
"self",
".",
"_envs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Environments not initialized.\"",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_e... | 39.810811 | 21.648649 |
def sign_transaction(provider: Provider, unsigned: MutableTransaction,
key: Kutil) -> Transaction:
'''sign transaction with Kutil'''
parent_outputs = [find_parent_outputs(provider, i) for i in unsigned.ins]
return key.sign_transaction(parent_outputs, unsigned) | [
"def",
"sign_transaction",
"(",
"provider",
":",
"Provider",
",",
"unsigned",
":",
"MutableTransaction",
",",
"key",
":",
"Kutil",
")",
"->",
"Transaction",
":",
"parent_outputs",
"=",
"[",
"find_parent_outputs",
"(",
"provider",
",",
"i",
")",
"for",
"i",
"... | 48.166667 | 22.5 |
def alleles_to_retrieve(df):
"""Alleles to retrieve from genome fasta
Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be
retrieved from the genome contig.
Args:
df (pandas.DataFrame): blastn results dataframe
Returns:
{str:... | [
"def",
"alleles_to_retrieve",
"(",
"df",
")",
":",
"contig_blastn_records",
"=",
"defaultdict",
"(",
"list",
")",
"markers",
"=",
"df",
".",
"marker",
".",
"unique",
"(",
")",
"for",
"m",
"in",
"markers",
":",
"dfsub",
"=",
"df",
"[",
"df",
".",
"marke... | 37.090909 | 22.863636 |
def download_current_dataset(self, dest_path=".", dest_filename=None,
unzip=True, tournament=1):
"""Download dataset for the current active round.
Args:
dest_path (str, optional): destination folder, defaults to `.`
dest_filename (str, optional):... | [
"def",
"download_current_dataset",
"(",
"self",
",",
"dest_path",
"=",
"\".\"",
",",
"dest_filename",
"=",
"None",
",",
"unzip",
"=",
"True",
",",
"tournament",
"=",
"1",
")",
":",
"# set up download path",
"if",
"dest_filename",
"is",
"None",
":",
"round_numb... | 38.152174 | 20.369565 |
def conv_cy(self, cy_cl):
"""Convert cycles (cy/CL) to other units, such as FLOP/s or It/s."""
if not isinstance(cy_cl, PrefixedUnit):
cy_cl = PrefixedUnit(cy_cl, '', 'cy/CL')
clock = self.machine['clock']
element_size = self.kernel.datatypes_size[self.kernel.datatype]
... | [
"def",
"conv_cy",
"(",
"self",
",",
"cy_cl",
")",
":",
"if",
"not",
"isinstance",
"(",
"cy_cl",
",",
"PrefixedUnit",
")",
":",
"cy_cl",
"=",
"PrefixedUnit",
"(",
"cy_cl",
",",
"''",
",",
"'cy/CL'",
")",
"clock",
"=",
"self",
".",
"machine",
"[",
"'cl... | 41.947368 | 12.789474 |
def compute_disagg(sitecol, sources, cmaker, iml4, trti, bin_edges,
oqparam, monitor):
# see https://bugs.launchpad.net/oq-engine/+bug/1279247 for an explanation
# of the algorithm used
"""
:param sitecol:
a :class:`openquake.hazardlib.site.SiteCollection` instance
:param ... | [
"def",
"compute_disagg",
"(",
"sitecol",
",",
"sources",
",",
"cmaker",
",",
"iml4",
",",
"trti",
",",
"bin_edges",
",",
"oqparam",
",",
"monitor",
")",
":",
"# see https://bugs.launchpad.net/oq-engine/+bug/1279247 for an explanation",
"# of the algorithm used",
"result",... | 38.756098 | 14.609756 |
def create_shortcuts(self):
"""Create shortcuts for ipyconsole."""
inspect = config_shortcut(self._control.inspect_current_object,
context='Console',
name='Inspect current object', parent=self)
clear_console = config_shortcut(se... | [
"def",
"create_shortcuts",
"(",
"self",
")",
":",
"inspect",
"=",
"config_shortcut",
"(",
"self",
".",
"_control",
".",
"inspect_current_object",
",",
"context",
"=",
"'Console'",
",",
"name",
"=",
"'Inspect current object'",
",",
"parent",
"=",
"self",
")",
"... | 63.785714 | 27.357143 |
def get_int_or_uuid(value):
"""Check if a value is valid as UUID or an integer.
This method is mainly used to convert floating IP id to the
appropriate type. For floating IP id, integer is used in Nova's
original implementation, but UUID is used in Neutron based one.
"""
try:
uuid.UUID(... | [
"def",
"get_int_or_uuid",
"(",
"value",
")",
":",
"try",
":",
"uuid",
".",
"UUID",
"(",
"value",
")",
"return",
"value",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
":",
"return",
"int",
"(",
"value",
")"
] | 33.583333 | 17.75 |
def add_plugin_filepaths(self, filepaths, except_blacklisted=True):
"""
Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing
in absolute filepaths. Method will attempt to convert to
absolute paths if they are not already.
`filepaths` can be a single object or an it... | [
"def",
"add_plugin_filepaths",
"(",
"self",
",",
"filepaths",
",",
"except_blacklisted",
"=",
"True",
")",
":",
"filepaths",
"=",
"util",
".",
"to_absolute_paths",
"(",
"filepaths",
")",
"if",
"except_blacklisted",
":",
"filepaths",
"=",
"util",
".",
"remove_fro... | 41.117647 | 19.823529 |
def alter_zero_tip_allowed_states(tree, feature):
"""
Alters the bottom-up likelihood arrays for zero-distance tips
to make sure they do not contradict with other zero-distance tip siblings.
:param tree: ete3.Tree, the tree of interest
:param feature: str, character for which the likelihood is alte... | [
"def",
"alter_zero_tip_allowed_states",
"(",
"tree",
",",
"feature",
")",
":",
"zero_parent2tips",
"=",
"defaultdict",
"(",
"list",
")",
"allowed_state_feature",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
"ALLOWED_STATES",
")",
"for",
"tip",
"in",
"t... | 41.2 | 21.1 |
def from_json(self, document):
"""Create a model database object from a given Json document.
Parameters
----------
document : JSON
Json representation of the object
Returns
ModelHandle
"""
# The timestamp is optional (e.g., in cases where mod... | [
"def",
"from_json",
"(",
"self",
",",
"document",
")",
":",
"# The timestamp is optional (e.g., in cases where model definitions are",
"# loaded from file).",
"if",
"'timestamp'",
"in",
"document",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
... | 31.464286 | 16.75 |
def parse_json_feed_file(filename: str) -> JSONFeed:
"""Parse a JSON feed from a local json file."""
with open(filename) as f:
try:
root = json.load(f)
except json.decoder.JSONDecodeError:
raise FeedJSONError('Not a valid JSON document')
return parse_json_feed(root) | [
"def",
"parse_json_feed_file",
"(",
"filename",
":",
"str",
")",
"->",
"JSONFeed",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"try",
":",
"root",
"=",
"json",
".",
"load",
"(",
"f",
")",
"except",
"json",
".",
"decoder",
".",
"JSONDec... | 34.555556 | 14.666667 |
def with_dependencies(cls, model_expr, dependency_model, **init_kwargs):
"""
Initiate a model whose components depend on another model. For example::
>>> x, y, z = variables('x, y, z')
>>> dependency_model = Model({y: x**2})
>>> model_dict = {z: y**2}
>>>... | [
"def",
"with_dependencies",
"(",
"cls",
",",
"model_expr",
",",
"dependency_model",
",",
"*",
"*",
"init_kwargs",
")",
":",
"model",
"=",
"cls",
"(",
"model_expr",
",",
"*",
"*",
"init_kwargs",
")",
"# Initiate model instance.",
"if",
"any",
"(",
"var",
"in"... | 54.795918 | 22.387755 |
def _clean_text(text):
"""
Clean up a multiple-line, potentially multiple-paragraph text
string. This is used to extract the first paragraph of a string
and eliminate line breaks and indentation. Lines will be joined
together by a single space.
:param text: The text string to clean up. It is... | [
"def",
"_clean_text",
"(",
"text",
")",
":",
"desc",
"=",
"[",
"]",
"for",
"line",
"in",
"(",
"text",
"or",
"''",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"# Clean up the line...",
"line",
"=",
"line",
".",
"strip",
"(",
... | 26.88 | 21.84 |
def add_bonds(self, neighbors, center, color=None, opacity=None,
radius=0.1):
"""
Adds bonds for a site.
Args:
neighbors: Neighbors of the site.
center: The site in the center for all bonds.
color: Color of the tubes representing the bonds
... | [
"def",
"add_bonds",
"(",
"self",
",",
"neighbors",
",",
"center",
",",
"color",
"=",
"None",
",",
"opacity",
"=",
"None",
",",
"radius",
"=",
"0.1",
")",
":",
"points",
"=",
"vtk",
".",
"vtkPoints",
"(",
")",
"points",
".",
"InsertPoint",
"(",
"0",
... | 33.928571 | 14.02381 |
def _get_file(src):
""" Return content from local or remote file. """
try:
if '://' in src or src[0:2] == '//': # Most likely this is remote file
response = urllib2.urlopen(src)
return response.read()
else:
with open(src, 'rb') as fh:
return f... | [
"def",
"_get_file",
"(",
"src",
")",
":",
"try",
":",
"if",
"'://'",
"in",
"src",
"or",
"src",
"[",
"0",
":",
"2",
"]",
"==",
"'//'",
":",
"# Most likely this is remote file",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"src",
")",
"return",
"resp... | 38 | 16.636364 |
def _get_pypirc_command(self):
"""
Get the distutils command for interacting with PyPI configurations.
:return: the command.
"""
from distutils.core import Distribution
from distutils.config import PyPIRCCommand
d = Distribution()
return PyPIRCCommand(d) | [
"def",
"_get_pypirc_command",
"(",
"self",
")",
":",
"from",
"distutils",
".",
"core",
"import",
"Distribution",
"from",
"distutils",
".",
"config",
"import",
"PyPIRCCommand",
"d",
"=",
"Distribution",
"(",
")",
"return",
"PyPIRCCommand",
"(",
"d",
")"
] | 34.444444 | 10.666667 |
def main(args, prog_name):
"""
main entry point for the script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
list.
"""
... | [
"def",
"main",
"(",
"args",
",",
"prog_name",
")",
":",
"# get options and arguments",
"ui",
"=",
"getUI",
"(",
"args",
",",
"prog_name",
")",
"if",
"ui",
".",
"optionIsSet",
"(",
"\"test\"",
")",
":",
"# just run unit tests",
"unittest",
".",
"main",
"(",
... | 31.510638 | 20.148936 |
def flush(self):
"""Flush file contents to 'disk'."""
self._check_open_file()
if self.allow_update and not self.is_stream:
contents = self._io.getvalue()
if self._append:
self._sync_io()
old_contents = (self.file_object.byte_contents
... | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"_check_open_file",
"(",
")",
"if",
"self",
".",
"allow_update",
"and",
"not",
"self",
".",
"is_stream",
":",
"contents",
"=",
"self",
".",
"_io",
".",
"getvalue",
"(",
")",
"if",
"self",
".",
"_app... | 42.807692 | 14.269231 |
def show(self, delete_after=20, scale=10, border=None, color='#000',
background='#fff'): # pragma: no cover
"""\
Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (by default
wit... | [
"def",
"show",
"(",
"self",
",",
"delete_after",
"=",
"20",
",",
"scale",
"=",
"10",
",",
"border",
"=",
"None",
",",
"color",
"=",
"'#000'",
",",
"background",
"=",
"'#fff'",
")",
":",
"# pragma: no cover",
"import",
"os",
"import",
"time",
"import",
... | 34.960784 | 20.784314 |
def _log(code, message, level, domain):
"""Call this to add an entry in the journal"""
entry = LogEntry(level, domain, code, message)
Logger.journal.append(entry)
if Logger.silent:
return
if level >= Logger._verbosity:
_print_entry(entry) | [
"def",
"_log",
"(",
"code",
",",
"message",
",",
"level",
",",
"domain",
")",
":",
"entry",
"=",
"LogEntry",
"(",
"level",
",",
"domain",
",",
"code",
",",
"message",
")",
"Logger",
".",
"journal",
".",
"append",
"(",
"entry",
")",
"if",
"Logger",
... | 29.5 | 14.7 |
def acquire_discharge(self, cav, payload):
''' Request a discharge macaroon from the caveat location
as an HTTP URL.
@param cav Third party {pymacaroons.Caveat} to be discharged.
@param payload External caveat data {bytes}.
@return The acquired macaroon {macaroonbakery.Macaroon}
... | [
"def",
"acquire_discharge",
"(",
"self",
",",
"cav",
",",
"payload",
")",
":",
"resp",
"=",
"self",
".",
"_acquire_discharge_with_token",
"(",
"cav",
",",
"payload",
",",
"None",
")",
"# TODO Fabrice what is the other http response possible ??",
"if",
"resp",
".",
... | 46 | 18.411765 |
def forward(self, is_train=False, **kwargs):
"""Calculate the outputs specified by the bound symbol.
Parameters
----------
is_train: bool, optional
Whether this forward is for evaluation purpose. If True,
a backward call is expected to follow.
**kwargs
... | [
"def",
"forward",
"(",
"self",
",",
"is_train",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"0",
":",
"arg_dict",
"=",
"self",
".",
"arg_dict",
"for",
"name",
",",
"array",
"in",
"kwargs",
".",
"items",
... | 40.95 | 19.6 |
def _build_response(data, renderer=None):
"""
Build a response using the renderer from the data
:return:
"""
if isinstance(data, Response) or isinstance(data, BaseResponse):
return data
if not renderer:
raise AttributeError(" Renderer is required")
if isinstance(data, dict) o... | [
"def",
"_build_response",
"(",
"data",
",",
"renderer",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"Response",
")",
"or",
"isinstance",
"(",
"data",
",",
"BaseResponse",
")",
":",
"return",
"data",
"if",
"not",
"renderer",
":",
"raise",... | 34.1 | 12.5 |
def defaultBuilder(value, nt):
"""Reasonably sensible default handling of put builder
"""
if callable(value):
def logbuilder(V):
try:
value(V)
except:
_log.exception("Error in Builder")
raise # will be logged again
retu... | [
"def",
"defaultBuilder",
"(",
"value",
",",
"nt",
")",
":",
"if",
"callable",
"(",
"value",
")",
":",
"def",
"logbuilder",
"(",
"V",
")",
":",
"try",
":",
"value",
"(",
"V",
")",
"except",
":",
"_log",
".",
"exception",
"(",
"\"Error in Builder\"",
"... | 29.68 | 14.44 |
def set_minimum_level(self, level=0, stdoutFlag=True, fileFlag=True):
"""
Set the minimum logging level. All levels below the minimum will be ignored at logging.
:Parameters:
#. level (None, number, str): The minimum level of logging.
If None, minimum level checking is ... | [
"def",
"set_minimum_level",
"(",
"self",
",",
"level",
"=",
"0",
",",
"stdoutFlag",
"=",
"True",
",",
"fileFlag",
"=",
"True",
")",
":",
"# check flags",
"assert",
"isinstance",
"(",
"stdoutFlag",
",",
"bool",
")",
",",
"\"stdoutFlag must be boolean\"",
"asser... | 51.459459 | 25.837838 |
def _handle_eio_message(self, sid, data):
"""Dispatch Engine.IO messages."""
if sid in self._binary_packet:
pkt = self._binary_packet[sid]
if pkt.add_attachment(data):
del self._binary_packet[sid]
if pkt.packet_type == packet.BINARY_EVENT:
... | [
"def",
"_handle_eio_message",
"(",
"self",
",",
"sid",
",",
"data",
")",
":",
"if",
"sid",
"in",
"self",
".",
"_binary_packet",
":",
"pkt",
"=",
"self",
".",
"_binary_packet",
"[",
"sid",
"]",
"if",
"pkt",
".",
"add_attachment",
"(",
"data",
")",
":",
... | 49.703704 | 14.888889 |
def _customer_lifetime_value(
transaction_prediction_model, frequency, recency, T, monetary_value, time=12, discount_rate=0.01, freq="D"
):
"""
Compute the average lifetime value for a group of one or more customers.
This method computes the average lifetime value for a group of one or more customers.
... | [
"def",
"_customer_lifetime_value",
"(",
"transaction_prediction_model",
",",
"frequency",
",",
"recency",
",",
"T",
",",
"monetary_value",
",",
"time",
"=",
"12",
",",
"discount_rate",
"=",
"0.01",
",",
"freq",
"=",
"\"D\"",
")",
":",
"df",
"=",
"pd",
".",
... | 40.478261 | 28 |
def update_time_reset_passwd(user_name, the_time):
'''
Update the time when user reset passwd.
'''
entry = TabMember.update(
time_reset_passwd=the_time,
).where(TabMember.user_name == user_name)
try:
entry.execute()
return True
... | [
"def",
"update_time_reset_passwd",
"(",
"user_name",
",",
"the_time",
")",
":",
"entry",
"=",
"TabMember",
".",
"update",
"(",
"time_reset_passwd",
"=",
"the_time",
",",
")",
".",
"where",
"(",
"TabMember",
".",
"user_name",
"==",
"user_name",
")",
"try",
":... | 28.416667 | 15.916667 |
def events(self):
'''check for events a list of events'''
ret = []
while self.out_queue.qsize():
ret.append(self.out_queue.get())
return ret | [
"def",
"events",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"while",
"self",
".",
"out_queue",
".",
"qsize",
"(",
")",
":",
"ret",
".",
"append",
"(",
"self",
".",
"out_queue",
".",
"get",
"(",
")",
")",
"return",
"ret"
] | 29.833333 | 13.833333 |
def total_proper_motion(pmra, pmdecl, decl):
'''This calculates the total proper motion of an object.
Parameters
----------
pmra : float or array-like
The proper motion(s) in right ascension, measured in mas/yr.
pmdecl : float or array-like
The proper motion(s) in declination, me... | [
"def",
"total_proper_motion",
"(",
"pmra",
",",
"pmdecl",
",",
"decl",
")",
":",
"pm",
"=",
"np",
".",
"sqrt",
"(",
"pmdecl",
"*",
"pmdecl",
"+",
"pmra",
"*",
"pmra",
"*",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"decl",
")",
")",
"*",
... | 24.333333 | 26.925926 |
def find_blocked_reactions(model,
reaction_list=None,
zero_cutoff=None,
open_exchanges=False,
processes=None):
"""
Find reactions that cannot carry any flux.
The question whether or not a reaction is... | [
"def",
"find_blocked_reactions",
"(",
"model",
",",
"reaction_list",
"=",
"None",
",",
"zero_cutoff",
"=",
"None",
",",
"open_exchanges",
"=",
"False",
",",
"processes",
"=",
"None",
")",
":",
"zero_cutoff",
"=",
"normalize_cutoff",
"(",
"model",
",",
"zero_cu... | 38.380952 | 20.095238 |
def get(self, attr: FetchAttribute) -> MaybeBytes:
"""Return the bytes representation of the given message attribue.
Args:
attr: The fetch attribute.
Raises:
:class:`NotFetchable`
"""
attr_name = attr.value.decode('ascii')
method = getattr(self,... | [
"def",
"get",
"(",
"self",
",",
"attr",
":",
"FetchAttribute",
")",
"->",
"MaybeBytes",
":",
"attr_name",
"=",
"attr",
".",
"value",
".",
"decode",
"(",
"'ascii'",
")",
"method",
"=",
"getattr",
"(",
"self",
",",
"'_get_'",
"+",
"attr_name",
".",
"repl... | 28.846154 | 18.384615 |
def read_many(self, start_sequence, min_count, max_count):
"""
Reads a batch of items from the Ringbuffer. If the number of available items after the first read item is
smaller than the max_count, these items are returned. So it could be the number of items read is smaller than
the max_c... | [
"def",
"read_many",
"(",
"self",
",",
"start_sequence",
",",
"min_count",
",",
"max_count",
")",
":",
"check_not_negative",
"(",
"start_sequence",
",",
"\"sequence can't be smaller than 0\"",
")",
"check_true",
"(",
"max_count",
">=",
"min_count",
",",
"\"max count sh... | 71.25 | 42.15 |
def _species_subdir(
ensembl_release,
species="homo_sapiens",
filetype="gtf",
server=ENSEMBL_FTP_SERVER):
"""
Assume ensembl_release has already been normalize by calling function
but species might be either a common name or latin name.
"""
return SPECIES_SUBDIR_TEMPL... | [
"def",
"_species_subdir",
"(",
"ensembl_release",
",",
"species",
"=",
"\"homo_sapiens\"",
",",
"filetype",
"=",
"\"gtf\"",
",",
"server",
"=",
"ENSEMBL_FTP_SERVER",
")",
":",
"return",
"SPECIES_SUBDIR_TEMPLATE",
"%",
"{",
"\"release\"",
":",
"ensembl_release",
",",... | 29.571429 | 13.285714 |
def elbv2_load_balancer_arn_suffix(self, lookup, default=None):
"""
Args:
lookup: the friendly name of the v2 elb to look up
default: value to return in case of no match
Returns:
The shorthand fragment of the ALB's ARN, of the form `app/*/*`
"""
try:
elb = self._elbv2_load_ba... | [
"def",
"elbv2_load_balancer_arn_suffix",
"(",
"self",
",",
"lookup",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"elb",
"=",
"self",
".",
"_elbv2_load_balancer",
"(",
"lookup",
")",
"m",
"=",
"re",
".",
"search",
"(",
"r'.+?(app\\/[^\\/]+\\/[^\\/]+)$'",... | 33.142857 | 18.571429 |
def integers(num, minimum, maximum, base=10):
# TODO: Ensure numbers within bounds
"""Random integers within specified interval.
The integer generator generates truly random integers in the specified
interval.
Parameters
----------
num : int, bounds=[1, 1E4]
Total number of integ... | [
"def",
"integers",
"(",
"num",
",",
"minimum",
",",
"maximum",
",",
"base",
"=",
"10",
")",
":",
"# TODO: Ensure numbers within bounds",
"function",
"=",
"'integers'",
"num",
",",
"minimum",
",",
"maximum",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"[",
... | 29.197183 | 20.267606 |
def GetFileSystemReferenceCount(self, path_spec):
"""Retrieves the reference count of a cached file system object.
Args:
path_spec (PathSpec): path specification.
Returns:
int: reference count or None if there is no file system object for
the corresponding path specification cached.
... | [
"def",
"GetFileSystemReferenceCount",
"(",
"self",
",",
"path_spec",
")",
":",
"identifier",
"=",
"self",
".",
"_GetFileSystemCacheIdentifier",
"(",
"path_spec",
")",
"cache_value",
"=",
"self",
".",
"_file_system_cache",
".",
"GetCacheValue",
"(",
"identifier",
")"... | 32.8125 | 20.75 |
def add_wf(self,wf_obj):
"""
Adds a token to the text layer
@type wf_obj: L{Cwf}
@param wf_obj: the token object
"""
if self.text_layer is None:
self.text_layer = Ctext(type=self.type)
self.root.append(self.text_layer.get_node())
self.text_... | [
"def",
"add_wf",
"(",
"self",
",",
"wf_obj",
")",
":",
"if",
"self",
".",
"text_layer",
"is",
"None",
":",
"self",
".",
"text_layer",
"=",
"Ctext",
"(",
"type",
"=",
"self",
".",
"type",
")",
"self",
".",
"root",
".",
"append",
"(",
"self",
".",
... | 33.1 | 6.5 |
def hardware_info(self, mask=0xFFFFFFFF):
"""Returns a list of 32 integer values corresponding to the bitfields
specifying the power consumption of the target.
The values returned by this function only have significance if the
J-Link is powering the target.
The words, indexed, ... | [
"def",
"hardware_info",
"(",
"self",
",",
"mask",
"=",
"0xFFFFFFFF",
")",
":",
"buf",
"=",
"(",
"ctypes",
".",
"c_uint32",
"*",
"32",
")",
"(",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_GetHWInfo",
"(",
"mask",
",",
"ctypes",
".",
"byref",... | 39.142857 | 17.828571 |
def diff_iter(base, other, options=None, **kwargs):
"""Compare a Record with another object (usually a record of the same
type), and yield differences as :py:class:`DiffInfo` instances.
args:
``base=``\ *Record*
The 'base' object to compare against. The enumeration in
:py:c... | [
"def",
"diff_iter",
"(",
"base",
",",
"other",
",",
"options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"DiffOptions",
"(",
"*",
"*",
"kwargs",
")",
"elif",
"len",
"(",
"kwargs",
")",
":",
... | 39.275862 | 21.896552 |
def upload_file(body):
"""accepts file uploads"""
# <body> is a simple dictionary of {filename: b'content'}
print('body: ', body)
return {'filename': list(body.keys()).pop(), 'filesize': len(list(body.values()).pop())} | [
"def",
"upload_file",
"(",
"body",
")",
":",
"# <body> is a simple dictionary of {filename: b'content'}",
"print",
"(",
"'body: '",
",",
"body",
")",
"return",
"{",
"'filename'",
":",
"list",
"(",
"body",
".",
"keys",
"(",
")",
")",
".",
"pop",
"(",
")",
","... | 46 | 21.2 |
def save_file_data(self, path):
""" Implements the abstract method of the ExternalEditor class.
"""
try:
# just create file with empty text first; this command also creates the whole path to the file
filesystem.write_file(os.path.join(path, storage.SCRIPT_FILE), "", creat... | [
"def",
"save_file_data",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"# just create file with empty text first; this command also creates the whole path to the file",
"filesystem",
".",
"write_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"storage",
... | 65.181818 | 33.909091 |
def paginate(self, url, key, params=None):
"""
Fetch a sequence of paginated resources from the API endpoint. The
initial request to ``url`` and all subsequent requests must respond
with a JSON object; the field specified by ``key`` must be a list,
whose elements will be yielded... | [
"def",
"paginate",
"(",
"self",
",",
"url",
",",
"key",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"self",
".",
"per_page",
"is",
"not",
"None",
"and",
"\"per_page\"",
"not",
"in",
"param... | 46.425 | 19.975 |
def _add_observation(self, x_to_add, y_to_add):
"""Add observation to window, updating means/variance efficiently."""
self._add_observation_to_means(x_to_add, y_to_add)
self._add_observation_to_variances(x_to_add, y_to_add)
self.window_size += 1 | [
"def",
"_add_observation",
"(",
"self",
",",
"x_to_add",
",",
"y_to_add",
")",
":",
"self",
".",
"_add_observation_to_means",
"(",
"x_to_add",
",",
"y_to_add",
")",
"self",
".",
"_add_observation_to_variances",
"(",
"x_to_add",
",",
"y_to_add",
")",
"self",
".",... | 54.6 | 11.6 |
def get_first_unanswered_question(self, assessment_section_id):
"""Gets the first unanswered question in this assesment section.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
return: (osid.assessment.Question) - the first unanswered
... | [
"def",
"get_first_unanswered_question",
"(",
"self",
",",
"assessment_section_id",
")",
":",
"questions",
"=",
"self",
".",
"get_unanswered_questions",
"(",
"assessment_section_id",
")",
"if",
"not",
"questions",
".",
"available",
"(",
")",
":",
"raise",
"errors",
... | 49 | 21.45 |
def is_compatible_assembly_level(self, ncbi_assembly_level):
"""Check if a given ncbi assembly level string matches the configured assembly levels."""
configured_ncbi_strings = [self._LEVELS[level] for level in self.assembly_level]
return ncbi_assembly_level in configured_ncbi_strings | [
"def",
"is_compatible_assembly_level",
"(",
"self",
",",
"ncbi_assembly_level",
")",
":",
"configured_ncbi_strings",
"=",
"[",
"self",
".",
"_LEVELS",
"[",
"level",
"]",
"for",
"level",
"in",
"self",
".",
"assembly_level",
"]",
"return",
"ncbi_assembly_level",
"in... | 76.5 | 22.25 |
def code_to_session(self, js_code):
"""
登录凭证校验。通过 wx.login() 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见 小程序登录
详情请参考
https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html
:param js_code:
:return:
"""
return self._get(
'sns/j... | [
"def",
"code_to_session",
"(",
"self",
",",
"js_code",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'sns/jscode2session'",
",",
"params",
"=",
"{",
"'appid'",
":",
"self",
".",
"appid",
",",
"'secret'",
":",
"self",
".",
"secret",
",",
"'js_code'",
":"... | 29.222222 | 17.333333 |
def moral_graph(model, format='raw', prog='dot', path=None, name=None):
"""
moral_graph(model,format='raw', prog='dot', path=None)
Draws the moral graph for this model and writes it to path with filename name.
Returns the pydot 'dot' object for further user manipulation.
GraphViz and PyDot must be... | [
"def",
"moral_graph",
"(",
"model",
",",
"format",
"=",
"'raw'",
",",
"prog",
"=",
"'dot'",
",",
"path",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"pydot_imported",
":",
"raise",
"ImportError",
"(",
"'PyDot must be installed to use the mo... | 32.647887 | 19.915493 |
def getNumberOfRequiredVerifications(self):
"""Returns the number of required verifications a test for this
analysis requires before being transitioned to 'verified' state
:returns: number of required verifications
"""
num = self.getField('NumberOfRequiredVerifications').get(self... | [
"def",
"getNumberOfRequiredVerifications",
"(",
"self",
")",
":",
"num",
"=",
"self",
".",
"getField",
"(",
"'NumberOfRequiredVerifications'",
")",
".",
"get",
"(",
"self",
")",
"if",
"num",
"<",
"1",
":",
"return",
"self",
".",
"bika_setup",
".",
"getNumber... | 46.888889 | 16.222222 |
def submit_tasks(self, wait=False):
"""
Submits the task in self and wait.
TODO: change name.
"""
for task in self:
task.start()
if wait:
for task in self: task.wait() | [
"def",
"submit_tasks",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"for",
"task",
"in",
"self",
":",
"task",
".",
"start",
"(",
")",
"if",
"wait",
":",
"for",
"task",
"in",
"self",
":",
"task",
".",
"wait",
"(",
")"
] | 23.1 | 11.7 |
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
"""
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result | [
"def",
"assert_transform_exists",
"(",
"cli",
",",
"transform_path",
")",
":",
"result",
"=",
"commands",
".",
"query_transform_exists",
"(",
"cli",
",",
"transform_path",
")",
"assert",
"result",
"is",
"True",
"return",
"result"
] | 26.1 | 14.1 |
def update_snapshots(self, snapshots_data: List[Tuple[str, int]]):
"""Given a list of snapshot data, update them in the DB
The snapshots_data should be a list of tuples of snapshots data
and identifiers in that order.
"""
cursor = self.conn.cursor()
cursor.executemany(
... | [
"def",
"update_snapshots",
"(",
"self",
",",
"snapshots_data",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"int",
"]",
"]",
")",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"executemany",
"(",
"'UPDATE state_snapshot ... | 36.666667 | 16.666667 |
def shrink_pool(arg, opts, shell_opts):
""" Shrink a pool by removing the ranges in opts from it
"""
if not pool:
print("No pool with name '%s' found." % arg, file=sys.stderr)
sys.exit(1)
if 'remove' in opts:
res = Prefix.list({'prefix': opts['remove'], 'pool_id': pool.id})
... | [
"def",
"shrink_pool",
"(",
"arg",
",",
"opts",
",",
"shell_opts",
")",
":",
"if",
"not",
"pool",
":",
"print",
"(",
"\"No pool with name '%s' found.\"",
"%",
"arg",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
... | 34.956522 | 19.782609 |
def create_entry(self, json):
"""Create :class:`.resources.Entry` from JSON.
:param json: JSON dict.
:return: Entry instance.
"""
sys = json['sys']
ct = sys['contentType']['sys']['id']
fields = json['fields']
raw_fields = copy.deepcopy(fields)
# ... | [
"def",
"create_entry",
"(",
"self",
",",
"json",
")",
":",
"sys",
"=",
"json",
"[",
"'sys'",
"]",
"ct",
"=",
"sys",
"[",
"'contentType'",
"]",
"[",
"'sys'",
"]",
"[",
"'id'",
"]",
"fields",
"=",
"json",
"[",
"'fields'",
"]",
"raw_fields",
"=",
"cop... | 32.578947 | 15.026316 |
def file_hash(load, fnd):
'''
Return an MD5 file hash
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
ret = {}
if 'saltenv' not in load:
return ret
if 'path' not in fnd or 'bucket' not in fnd or not fnd['path']:
return ret
... | [
"def",
"file_hash",
"(",
"load",
",",
"fnd",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"ret",
"=",
"{",
"}",
"if",
"'saltenv'",
"not",
"in",
"load",
":",
"return",
"... | 22.307692 | 23 |
def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | [
"def",
"sendcommand",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"\"sending command %s(**%s)\"",
"%",
"(",
"name",
",",
"kwargs",
")",
")",
"self",
".",
"channel",
".",
"send",
"(",
"(",
"name",
",",
"kwargs... | 52 | 6 |
def u128(self, name, value=None, align=None):
"""Add an unsigned 16 byte integer field to template.
This is an convenience method that simply calls `Uint` keyword with predefined length."""
self.uint(16, name, value, align) | [
"def",
"u128",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"align",
"=",
"None",
")",
":",
"self",
".",
"uint",
"(",
"16",
",",
"name",
",",
"value",
",",
"align",
")"
] | 48.8 | 9.2 |
def encode_grib2_percentile(self):
"""
Encodes member percentile data to GRIB2 format.
Returns:
Series of GRIB2 messages
"""
lscale = 1e6
grib_id_start = [7, 0, 14, 14, 2]
gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.in... | [
"def",
"encode_grib2_percentile",
"(",
"self",
")",
":",
"lscale",
"=",
"1e6",
"grib_id_start",
"=",
"[",
"7",
",",
"0",
",",
"14",
",",
"14",
",",
"2",
"]",
"gdsinfo",
"=",
"np",
".",
"array",
"(",
"[",
"0",
",",
"np",
".",
"product",
"(",
"self... | 60.396825 | 27.920635 |
def _run_program(self, bin, fastafile, params=None):
"""
Run XXmotif and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict,... | [
"def",
"_run_program",
"(",
"self",
",",
"bin",
",",
"fastafile",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_parse_params",
"(",
"params",
")",
"outfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tmpdir",
",",
... | 27.833333 | 18.833333 |
def get(self, request, enterprise_uuid, program_uuid):
"""
Show Program Landing page for the Enterprise's Program.
Render the Enterprise's Program Enrollment page for a specific program.
The Enterprise and Program are both selected by their respective UUIDs.
Unauthenticated lea... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"enterprise_uuid",
",",
"program_uuid",
")",
":",
"verify_edx_resources",
"(",
")",
"enterprise_customer",
"=",
"get_enterprise_customer_or_404",
"(",
"enterprise_uuid",
")",
"context_data",
"=",
"get_global_context",
"(... | 49.952381 | 29.380952 |
def avg(self, key=None):
"""
Get the average value of a given key.
:param key: The key to get the average for
:type key: mixed
:rtype: float or int
"""
count = self.count()
if count:
return self.sum(key) / count | [
"def",
"avg",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"count",
"=",
"self",
".",
"count",
"(",
")",
"if",
"count",
":",
"return",
"self",
".",
"sum",
"(",
"key",
")",
"/",
"count"
] | 21.384615 | 16.461538 |
def cnst_A1(self, X, Xf=None):
r"""Compute :math:`A_1 \mathbf{x}` component of ADMM problem
constraint. In this case :math:`A_1 \mathbf{x} = (\Gamma_0^T \;\;
\Gamma_1^T \;\; \ldots )^T \mathbf{x}`.
"""
if Xf is None:
Xf = sl.rfftn(X, axes=self.cri.axisN)
retu... | [
"def",
"cnst_A1",
"(",
"self",
",",
"X",
",",
"Xf",
"=",
"None",
")",
":",
"if",
"Xf",
"is",
"None",
":",
"Xf",
"=",
"sl",
".",
"rfftn",
"(",
"X",
",",
"axes",
"=",
"self",
".",
"cri",
".",
"axisN",
")",
"return",
"sl",
".",
"irfftn",
"(",
... | 41 | 14.545455 |
def collection(self, *collection_path):
"""Get a reference to a collection.
For a top-level collection:
.. code-block:: python
>>> client.collection('top')
For a sub-collection:
.. code-block:: python
>>> client.collection('mydocs/doc/subcol')
... | [
"def",
"collection",
"(",
"self",
",",
"*",
"collection_path",
")",
":",
"if",
"len",
"(",
"collection_path",
")",
"==",
"1",
":",
"path",
"=",
"collection_path",
"[",
"0",
"]",
".",
"split",
"(",
"_helpers",
".",
"DOCUMENT_PATH_DELIMITER",
")",
"else",
... | 29.085714 | 22.514286 |
def add_omim_info(genes, alias_genes, genemap_lines, mim2gene_lines):
"""Add omim information
We collect information on what phenotypes that are associated with a gene,
what inheritance models that are associated and the correct omim id.
Args:
genes(dict): Dictionary with all genes
... | [
"def",
"add_omim_info",
"(",
"genes",
",",
"alias_genes",
",",
"genemap_lines",
",",
"mim2gene_lines",
")",
":",
"LOG",
".",
"info",
"(",
"\"Add omim info\"",
")",
"omim_genes",
"=",
"get_mim_genes",
"(",
"genemap_lines",
",",
"mim2gene_lines",
")",
"for",
"hgnc... | 38.464286 | 22.25 |
def _limit_is_valid_or_none(self, params):
"""
Validates that a given limit is not present or is well-formed.
:param params: Query params.
:return: Returns True if a limit is present or is well-formed.
"""
if not "limit" in params or not params["limit"]:
retu... | [
"def",
"_limit_is_valid_or_none",
"(",
"self",
",",
"params",
")",
":",
"if",
"not",
"\"limit\"",
"in",
"params",
"or",
"not",
"params",
"[",
"\"limit\"",
"]",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"params",
"[",
"\"limit\"",
"]",
",",
"... | 35.214286 | 16.214286 |
def add_resource(self, resource):
"""Add a resource to the list of interesting resources"""
if resource.exists():
self.resources[resource] = self.timekeeper.get_indicator(resource)
else:
self.resources[resource] = None | [
"def",
"add_resource",
"(",
"self",
",",
"resource",
")",
":",
"if",
"resource",
".",
"exists",
"(",
")",
":",
"self",
".",
"resources",
"[",
"resource",
"]",
"=",
"self",
".",
"timekeeper",
".",
"get_indicator",
"(",
"resource",
")",
"else",
":",
"sel... | 43.5 | 14.333333 |
def get(self):
"""Return the file content as a string."""
r = self._session.get(self.content, headers={'Accept': '*/*'})
return r.content | [
"def",
"get",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"self",
".",
"content",
",",
"headers",
"=",
"{",
"'Accept'",
":",
"'*/*'",
"}",
")",
"return",
"r",
".",
"content"
] | 39.5 | 18 |
def resolve_zone_file_to_profile(zone_file, address_or_public_key):
""" Resolves a zone file to a profile and checks to makes sure the tokens
are signed with a key that corresponds to the address or public key
provided.
"""
if is_profile_in_legacy_format(zone_file):
return zone_file
... | [
"def",
"resolve_zone_file_to_profile",
"(",
"zone_file",
",",
"address_or_public_key",
")",
":",
"if",
"is_profile_in_legacy_format",
"(",
"zone_file",
")",
":",
"return",
"zone_file",
"try",
":",
"token_file_url",
"=",
"get_token_file_url_from_zone_file",
"(",
"zone_file... | 35.266667 | 25.066667 |
def set_default_locators_and_formatters(self, axis):
"""
Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters.
"""
axis.set_major_locator(_LogicleLocator(self._tra... | [
"def",
"set_default_locators_and_formatters",
"(",
"self",
",",
"axis",
")",
":",
"axis",
".",
"set_major_locator",
"(",
"_LogicleLocator",
"(",
"self",
".",
"_transform",
")",
")",
"axis",
".",
"set_minor_locator",
"(",
"_LogicleLocator",
"(",
"self",
".",
"_tr... | 37.4 | 20.333333 |
def cee_map_remap_fabric_priority_fabric_remapped_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name_key... | [
"def",
"cee_map_remap_fabric_priority_fabric_remapped_priority",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"cee_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"cee-map\"",
",",
"xmln... | 50.785714 | 21 |
async def websocket_disconnect(self, message):
"""
Handle the disconnect message.
This is propagated to all upstream applications.
"""
# set this flag so as to ensure we don't send a downstream `websocket.close` message due to all
# child applications closing.
se... | [
"async",
"def",
"websocket_disconnect",
"(",
"self",
",",
"message",
")",
":",
"# set this flag so as to ensure we don't send a downstream `websocket.close` message due to all",
"# child applications closing.",
"self",
".",
"closing",
"=",
"True",
"# inform all children",
"await",
... | 37.5 | 13.833333 |
def dict(self):
'''Returns a dictionary representing this query.'''
d = dict()
d['key'] = str(self.key)
if self.limit is not None:
d['limit'] = self.limit
if self.offset > 0:
d['offset'] = self.offset
if self.offset_key:
d['offset_key'] = str(self.offset_key)
if len(self.f... | [
"def",
"dict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
")",
"d",
"[",
"'key'",
"]",
"=",
"str",
"(",
"self",
".",
"key",
")",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"d",
"[",
"'limit'",
"]",
"=",
"self",
".",
"limit",
"... | 28.058824 | 18.411765 |
def check_credentials(self):
"""
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
"""
if self.username is None or self.password is None:
raise DistlibException('username and password must be set')
pm = HTTPPasswordMgr()
... | [
"def",
"check_credentials",
"(",
"self",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
"or",
"self",
".",
"password",
"is",
"None",
":",
"raise",
"DistlibException",
"(",
"'username and password must be set'",
")",
"pm",
"=",
"HTTPPasswordMgr",
"(",
"... | 44.454545 | 16.454545 |
def highlightSubsequence(sequence, x1, x2, start=' [', stop = '] ') :
"""returns a sequence where the subsequence in [x1, x2[ is placed
in bewteen 'start' and 'stop'"""
seq = list(sequence)
print x1, x2-1, len(seq)
seq[x1] = start + seq[x1]
seq[x2-1] = seq[x2-1] + stop
return ''.join(seq) | [
"def",
"highlightSubsequence",
"(",
"sequence",
",",
"x1",
",",
"x2",
",",
"start",
"=",
"' ['",
",",
"stop",
"=",
"'] '",
")",
":",
"seq",
"=",
"list",
"(",
"sequence",
")",
"print",
"x1",
",",
"x2",
"-",
"1",
",",
"len",
"(",
"seq",
")",
"seq",... | 32.222222 | 16.444444 |
def retrieve_outputs(self):
""" Declare the outputs of the algorithms as attributes: x_final,
y_final, metrics.
"""
metrics = {}
for obs in self._observers['cv_metrics']:
metrics[obs.name] = obs.retrieve_metrics()
self.metrics = metrics | [
"def",
"retrieve_outputs",
"(",
"self",
")",
":",
"metrics",
"=",
"{",
"}",
"for",
"obs",
"in",
"self",
".",
"_observers",
"[",
"'cv_metrics'",
"]",
":",
"metrics",
"[",
"obs",
".",
"name",
"]",
"=",
"obs",
".",
"retrieve_metrics",
"(",
")",
"self",
... | 32.111111 | 13.444444 |
def portfolio_performance(
expected_returns, cov_matrix, weights, verbose=False, risk_free_rate=0.02
):
"""
After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param expected_returns: e... | [
"def",
"portfolio_performance",
"(",
"expected_returns",
",",
"cov_matrix",
",",
"weights",
",",
"verbose",
"=",
"False",
",",
"risk_free_rate",
"=",
"0.02",
")",
":",
"if",
"isinstance",
"(",
"weights",
",",
"dict",
")",
":",
"if",
"isinstance",
"(",
"expec... | 44.3 | 18.3 |
def crossover(self, chromosome, point1, point2=None):
"""
Exchange DNA with another chromosome of equal length at one or two common points.
For example, consider chromosomes:
1. 11110000
2. 00001111
If the crossover point is 4, the exchange results... | [
"def",
"crossover",
"(",
"self",
",",
"chromosome",
",",
"point1",
",",
"point2",
"=",
"None",
")",
":",
"assert",
"self",
".",
"length",
"==",
"chromosome",
".",
"length",
"if",
"point2",
"is",
"None",
":",
"new_dna",
"=",
"self",
".",
"dna",
"[",
"... | 37.75 | 25.083333 |
def _key(self, username, frozen=False):
"""Translate a username into a key for Redis."""
if frozen:
return self.frozen + username
return self.prefix + username | [
"def",
"_key",
"(",
"self",
",",
"username",
",",
"frozen",
"=",
"False",
")",
":",
"if",
"frozen",
":",
"return",
"self",
".",
"frozen",
"+",
"username",
"return",
"self",
".",
"prefix",
"+",
"username"
] | 38.2 | 5.4 |
def _collapse_transcripts(in_file, window, data, out_dir, include_gene_names=True):
"""Collapse transcripts into min/max coordinates and optionally add windows.
"""
if out_dir is None:
out_dir = os.path.dirname(in_file)
out_file = os.path.join(out_dir,
"%s-transcripts... | [
"def",
"_collapse_transcripts",
"(",
"in_file",
",",
"window",
",",
"data",
",",
"out_dir",
",",
"include_gene_names",
"=",
"True",
")",
":",
"if",
"out_dir",
"is",
"None",
":",
"out_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"in_file",
")",
"out... | 57.194444 | 22.444444 |
def nic_list(self, bridge):
"""
List nics attached to bridge
:param bridge: bridge name
"""
args = {
'name': bridge,
}
self._bridge_chk.check(args)
return self._client.json('bridge.nic-list', args) | [
"def",
"nic_list",
"(",
"self",
",",
"bridge",
")",
":",
"args",
"=",
"{",
"'name'",
":",
"bridge",
",",
"}",
"self",
".",
"_bridge_chk",
".",
"check",
"(",
"args",
")",
"return",
"self",
".",
"_client",
".",
"json",
"(",
"'bridge.nic-list'",
",",
"a... | 18.857143 | 19.428571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.