text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _deserializeNT(data, glob):
"""
Deserialize special kinds of dicts from _serializeNT().
"""
if isinstance(data, list):
return [_deserializeNT(item, glob) for item in data]
elif isinstance(data, tuple):
return tuple(_deserializeNT(item, glob) for item in data)
elif isinstanc... | [
"def",
"_deserializeNT",
"(",
"data",
",",
"glob",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"[",
"_deserializeNT",
"(",
"item",
",",
"glob",
")",
"for",
"item",
"in",
"data",
"]",
"elif",
"isinstance",
"(",
"data",
... | 27.657143 | 0.000998 |
def simxSetIntegerParameter(clientID, paramIdentifier, paramValue, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
return c_SetIntegerParameter(clientID, paramIdentifier, paramValue, operationMode) | [
"def",
"simxSetIntegerParameter",
"(",
"clientID",
",",
"paramIdentifier",
",",
"paramValue",
",",
"operationMode",
")",
":",
"return",
"c_SetIntegerParameter",
"(",
"clientID",
",",
"paramIdentifier",
",",
"paramValue",
",",
"operationMode",
")"
] | 45.166667 | 0.014493 |
def rank_environment_and_phenotypes(environment, phenotypes, k=15):
"""
Clusters sets of resources/tasks using a weighted hamming distance such
that you can have few enough values to give each group of similar things a
different color. This function is designed for cases when you want to
color both ... | [
"def",
"rank_environment_and_phenotypes",
"(",
"environment",
",",
"phenotypes",
",",
"k",
"=",
"15",
")",
":",
"environment",
"=",
"convert_world_to_phenotype",
"(",
"environment",
")",
"ranks",
"=",
"get_ranks_for_environment_and_phenotypes",
"(",
"environment",
",",
... | 46.814815 | 0.000775 |
def get_session_key(limedict):
"""This function receive a dictionary with connection parameters.
{ "url": "full path for remote control",
"username: "account name to be used"
"password" "password for account"}"""
url = limedict['url']
user = limedict['username']
password = li... | [
"def",
"get_session_key",
"(",
"limedict",
")",
":",
"url",
"=",
"limedict",
"[",
"'url'",
"]",
"user",
"=",
"limedict",
"[",
"'username'",
"]",
"password",
"=",
"limedict",
"[",
"'password'",
"]",
"params",
"=",
"{",
"'username'",
":",
"user",
",",
"'pa... | 46.333333 | 0.001764 |
def find_inputs_and_params(node):
'''Walk a computation graph and extract root variables.
Parameters
----------
node : Theano expression
A symbolic Theano expression to walk.
Returns
-------
inputs : list Theano variables
A list of candidate inputs for this graph. Inputs ar... | [
"def",
"find_inputs_and_params",
"(",
"node",
")",
":",
"queue",
",",
"seen",
",",
"inputs",
",",
"params",
"=",
"[",
"node",
"]",
",",
"set",
"(",
")",
",",
"set",
"(",
")",
",",
"set",
"(",
")",
"while",
"queue",
":",
"node",
"=",
"queue",
".",... | 36.071429 | 0.001929 |
def os_deployment_servers(self):
"""
Gets the Os Deployment Servers API client.
Returns:
OsDeploymentServers:
"""
if not self.__os_deployment_servers:
self.__os_deployment_servers = OsDeploymentServers(self.__connection)
return self.__os_deploymen... | [
"def",
"os_deployment_servers",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__os_deployment_servers",
":",
"self",
".",
"__os_deployment_servers",
"=",
"OsDeploymentServers",
"(",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__os_deployment_server... | 32 | 0.009119 |
def downgrade(engine, desired_version):
"""Downgrades the assets db at the given engine to the desired version.
Parameters
----------
engine : Engine
An SQLAlchemy engine to the assets database.
desired_version : int
The desired resulting version for the assets database.
"""
... | [
"def",
"downgrade",
"(",
"engine",
",",
"desired_version",
")",
":",
"# Check the version of the db at the engine",
"with",
"engine",
".",
"begin",
"(",
")",
"as",
"conn",
":",
"metadata",
"=",
"sa",
".",
"MetaData",
"(",
"conn",
")",
"metadata",
".",
"reflect... | 35.377778 | 0.000611 |
def _parse_posts(element):
"""
Returns a list with posts.
"""
posts = []
items = element.findall("item")
for item in items:
title = item.find("./title").text
link = item.find("./link").text
pub_date = item.find("./pubDate").text
creator = item.find("./{%s}creato... | [
"def",
"_parse_posts",
"(",
"element",
")",
":",
"posts",
"=",
"[",
"]",
"items",
"=",
"element",
".",
"findall",
"(",
"\"item\"",
")",
"for",
"item",
"in",
"items",
":",
"title",
"=",
"item",
".",
"find",
"(",
"\"./title\"",
")",
".",
"text",
"link"... | 36.242857 | 0.000384 |
def save_collection(png_filename_base, numpy_data, start_layers_at=1):
"""
Export a numpy array to a set of png files, with each Z-index 2D
array as its own 2D file.
Arguments:
png_filename_base: A filename template, such as "my-image-*.png"
which will lead t... | [
"def",
"save_collection",
"(",
"png_filename_base",
",",
"numpy_data",
",",
"start_layers_at",
"=",
"1",
")",
":",
"file_ext",
"=",
"png_filename_base",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"if",
"file_ext",
"in",
"[",
"'png'",
"]",
":",
"#... | 34.513514 | 0.000762 |
def find_mip(self, direction, mechanism, purview):
"""Return the minimum information partition for a mechanism over a
purview.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The nodes in the mechanism.
purview (tuple[int]): The node... | [
"def",
"find_mip",
"(",
"self",
",",
"direction",
",",
"mechanism",
",",
"purview",
")",
":",
"if",
"not",
"purview",
":",
"return",
"_null_ria",
"(",
"direction",
",",
"mechanism",
",",
"purview",
")",
"# Calculate the unpartitioned repertoire to compare against th... | 39.689655 | 0.000848 |
def _validate_config(config):
"""Verifies that a config dict for an attenuator device is valid.
Args:
config: A dict that is the configuration for an attenuator device.
Raises:
attenuator.Error: A config is not valid.
"""
required_keys = [KEY_ADDRESS, KEY_MODEL, KEY_PORT, KEY_PATHS... | [
"def",
"_validate_config",
"(",
"config",
")",
":",
"required_keys",
"=",
"[",
"KEY_ADDRESS",
",",
"KEY_MODEL",
",",
"KEY_PORT",
",",
"KEY_PATHS",
"]",
"for",
"key",
"in",
"required_keys",
":",
"if",
"key",
"not",
"in",
"config",
":",
"raise",
"Error",
"("... | 33.785714 | 0.002058 |
def get_fields(model_class, field_name='', path=''):
""" Get fields and meta data from a model
:param model_class: A django model class
:param field_name: The field name to get sub fields from
:param path: path of our field in format
field_name__second_field_name__ect__
:returns: Returns fi... | [
"def",
"get_fields",
"(",
"model_class",
",",
"field_name",
"=",
"''",
",",
"path",
"=",
"''",
")",
":",
"fields",
"=",
"get_direct_fields_from_model",
"(",
"model_class",
")",
"app_label",
"=",
"model_class",
".",
"_meta",
".",
"app_label",
"if",
"field_name"... | 31.868421 | 0.000801 |
def hasannotation(self,Class,set=None):
"""Returns an integer indicating whether such as annotation exists, and if so, how many.
See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters."""
return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations)) | [
"def",
"hasannotation",
"(",
"self",
",",
"Class",
",",
"set",
"=",
"None",
")",
":",
"return",
"sum",
"(",
"1",
"for",
"_",
"in",
"self",
".",
"select",
"(",
"Class",
",",
"set",
",",
"True",
",",
"default_ignore_annotations",
")",
")"
] | 62.8 | 0.034591 |
def list(self):
"""List collection items."""
if self.is_fake:
return
for item in self.collection.list():
yield item.uid + self.content_suffix | [
"def",
"list",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"for",
"item",
"in",
"self",
".",
"collection",
".",
"list",
"(",
")",
":",
"yield",
"item",
".",
"uid",
"+",
"self",
".",
"content_suffix"
] | 26.285714 | 0.010526 |
def surface_intersections(edge_nodes1, edge_nodes2, all_intersections):
"""Find all intersections among edges of two surfaces.
This treats intersections which have ``s == 1.0`` or ``t == 1.0``
as duplicates. The duplicates may be checked by the caller, e.g.
by :func:`verify_duplicates`.
Args:
... | [
"def",
"surface_intersections",
"(",
"edge_nodes1",
",",
"edge_nodes2",
",",
"all_intersections",
")",
":",
"# NOTE: There is no corresponding \"enable\", but the disable only applies",
"# in this lexical scope.",
"# pylint: disable=too-many-locals",
"intersections",
"=",
"[",
... | 40.327586 | 0.000417 |
def find_msvcrt():
"""
Likely useless and will return None, see https://bugs.python.org/issue23606
Offered for full compatibility, though.
"""
# Compile Python command for wine-python
command = '"from ctypes.util import find_msvcrt; print(find_msvcrt())"'
# Start wine-python
winepython_p = subprocess.Popen(
... | [
"def",
"find_msvcrt",
"(",
")",
":",
"# Compile Python command for wine-python",
"command",
"=",
"'\"from ctypes.util import find_msvcrt; print(find_msvcrt())\"'",
"# Start wine-python",
"winepython_p",
"=",
"subprocess",
".",
"Popen",
"(",
"'wine-python -c'",
"+",
"command",
"... | 24.214286 | 0.042553 |
def approximate_density(
dist,
xloc,
parameters=None,
cache=None,
eps=1.e-7
):
"""
Approximate the probability density function.
Args:
dist : Dist
Distribution in question. May not be an advanced variable.
xloc : numpy.ndarray
... | [
"def",
"approximate_density",
"(",
"dist",
",",
"xloc",
",",
"parameters",
"=",
"None",
",",
"cache",
"=",
"None",
",",
"eps",
"=",
"1.e-7",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"dist",
".",
"prm",
".",
"copy",
"(",
")"... | 30.854545 | 0.000571 |
def other_object_webhook_handler(event):
"""Handle updates to transfer, charge, invoice, invoiceitem, plan, product and source objects.
Docs for:
- charge: https://stripe.com/docs/api#charges
- coupon: https://stripe.com/docs/api#coupons
- invoice: https://stripe.com/docs/api#invoices
- invoiceitem: https://stri... | [
"def",
"other_object_webhook_handler",
"(",
"event",
")",
":",
"if",
"event",
".",
"parts",
"[",
":",
"2",
"]",
"==",
"[",
"\"charge\"",
",",
"\"dispute\"",
"]",
":",
"# Do not attempt to handle charge.dispute.* events.",
"# We do not have a Dispute model yet.",
"target... | 32.733333 | 0.027695 |
def _register_allocator(self, plugin_name, plugin_instance):
"""
Register an allocator.
:param plugin_name: Allocator name
:param plugin_instance: RunPluginBase
:return:
"""
for allocator in plugin_instance.get_allocators().keys():
if allocator in sel... | [
"def",
"_register_allocator",
"(",
"self",
",",
"plugin_name",
",",
"plugin_instance",
")",
":",
"for",
"allocator",
"in",
"plugin_instance",
".",
"get_allocators",
"(",
")",
".",
"keys",
"(",
")",
":",
"if",
"allocator",
"in",
"self",
".",
"_allocators",
":... | 46.461538 | 0.008117 |
def tags(self, where, archiver="", timeout=DEFAULT_TIMEOUT):
"""
Retrieves tags for all streams matching the given WHERE clause
Arguments:
[where]: the where clause (e.g. 'path like "keti"', 'SourceName = "TED Main"')
[archiver]: if specified, this is the archiver to use. Else, ... | [
"def",
"tags",
"(",
"self",
",",
"where",
",",
"archiver",
"=",
"\"\"",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"return",
"self",
".",
"query",
"(",
"\"select * where {0}\"",
".",
"format",
"(",
"where",
")",
",",
"archiver",
",",
"timeout",
")... | 54 | 0.009934 |
def update_instrument_config(
instrument, measured_center) -> Tuple[Point, float]:
"""
Update config and pose tree with instrument's x and y offsets
and tip length based on delta between probe center and measured_center,
persist updated config and return it
"""
from copy import deepcopy
... | [
"def",
"update_instrument_config",
"(",
"instrument",
",",
"measured_center",
")",
"->",
"Tuple",
"[",
"Point",
",",
"float",
"]",
":",
"from",
"copy",
"import",
"deepcopy",
"from",
"opentrons",
".",
"trackers",
".",
"pose_tracker",
"import",
"update",
"robot",
... | 38.605263 | 0.000665 |
def write_maxjobs(self,fh,category):
"""
Write the DAG entry for this category's maxjobs to the DAG file descriptor.
@param fh: descriptor of open DAG file.
@param category: tuple containing type of jobs to set a maxjobs limit for
and the maximum number of jobs of that type to run at once.
"... | [
"def",
"write_maxjobs",
"(",
"self",
",",
"fh",
",",
"category",
")",
":",
"fh",
".",
"write",
"(",
"'MAXJOBS '",
"+",
"str",
"(",
"category",
"[",
"0",
"]",
")",
"+",
"' '",
"+",
"str",
"(",
"category",
"[",
"1",
"]",
")",
"+",
"'\\n'",
")"
] | 49.25 | 0.014963 |
def build_directories(root_dir):
"""Constructs the subdirectories output, stderr, stdout, and jobs in the
passed root directory. These subdirectories have the following roles:
jobs Stores the scripts for each job
stderr Stores the stderr output from SGE
stdout ... | [
"def",
"build_directories",
"(",
"root_dir",
")",
":",
"# If the root directory doesn't exist, create it",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"root_dir",
")",
":",
"os",
".",
"mkdir",
"(",
"root_dir",
")",
"# Create subdirectories",
"directories",
... | 42.6 | 0.001148 |
def resolve_feats(feat_list, seqin, seqref, start, locus, missing, verbose=False, verbosity=0):
"""
resolve_feats - Resolves features from alignments
:param feat_list: List of the found features
:type feat_list: ``List``
:param seqin: The input sequence
:type seqin: ``str``
:param locus: Th... | [
"def",
"resolve_feats",
"(",
"feat_list",
",",
"seqin",
",",
"seqref",
",",
"start",
",",
"locus",
",",
"missing",
",",
"verbose",
"=",
"False",
",",
"verbosity",
"=",
"0",
")",
":",
"structures",
"=",
"get_structures",
"(",
")",
"logger",
"=",
"logging"... | 38.405405 | 0.000915 |
def update_config(config):
"""Update bigchaindb.config with whatever is in the provided config dict,
and then set bigchaindb.config['CONFIGURED'] = True
Args:
config (dict): the config dict to read for changes
to the default config
"""
# Update the default config wit... | [
"def",
"update_config",
"(",
"config",
")",
":",
"# Update the default config with whatever is in the passed config",
"update",
"(",
"bigchaindb",
".",
"config",
",",
"update_types",
"(",
"config",
",",
"bigchaindb",
".",
"config",
")",
")",
"bigchaindb",
".",
"config... | 38.083333 | 0.002137 |
def show_lowstate(**kwargs):
'''
List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate
'''
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SS... | [
"def",
"show_lowstate",
"(",
"*",
"*",
"kwargs",
")",
":",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"opts",
"=",
"salt",
".",
"utils",
".",
"state",
".",
"get_sls_opts",
"(",
"__opts__",
",",
"*",
"*",
"kwargs",
")",
"st_",
"=",
"salt",
"... | 25.190476 | 0.001821 |
def merge_base(self, left='master', right='HEAD'):
"""Returns the merge-base of master and HEAD in bash: `git merge-base left right`"""
return self._check_output(['merge-base', left, right], raise_type=Scm.LocalException) | [
"def",
"merge_base",
"(",
"self",
",",
"left",
"=",
"'master'",
",",
"right",
"=",
"'HEAD'",
")",
":",
"return",
"self",
".",
"_check_output",
"(",
"[",
"'merge-base'",
",",
"left",
",",
"right",
"]",
",",
"raise_type",
"=",
"Scm",
".",
"LocalException",... | 75.666667 | 0.0131 |
def returns_something(return_node):
"""Check if a return node returns a value other than None.
:param return_node: The return node to check.
:type return_node: astroid.Return
:rtype: bool
:return: True if the return node returns a value other than None,
False otherwise.
"""
returns... | [
"def",
"returns_something",
"(",
"return_node",
")",
":",
"returns",
"=",
"return_node",
".",
"value",
"if",
"returns",
"is",
"None",
":",
"return",
"False",
"return",
"not",
"(",
"isinstance",
"(",
"returns",
",",
"astroid",
".",
"Const",
")",
"and",
"ret... | 28.125 | 0.002151 |
def transmit(self, channel, msg):
r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('/me is feeling fine today').grou... | [
"def",
"transmit",
"(",
"self",
",",
"channel",
",",
"msg",
")",
":",
"is_action",
",",
"msg",
"=",
"self",
".",
"action_pattern",
".",
"match",
"(",
"msg",
")",
".",
"groups",
"(",
")",
"func",
"=",
"self",
".",
"_conn",
".",
"action",
"if",
"is_a... | 29.482759 | 0.032843 |
def create_commit(self, message, tree, parents, author={}, committer={}):
"""Create a commit on this repository.
:param str message: (required), commit message
:param str tree: (required), SHA of the tree object this
commit points to
:param list parents: (required), SHAs of ... | [
"def",
"create_commit",
"(",
"self",
",",
"message",
",",
"tree",
",",
"parents",
",",
"author",
"=",
"{",
"}",
",",
"committer",
"=",
"{",
"}",
")",
":",
"json",
"=",
"None",
"if",
"message",
"and",
"tree",
"and",
"isinstance",
"(",
"parents",
",",
... | 53.037037 | 0.001372 |
def clear(path):
'''
Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: ba... | [
"def",
"clear",
"(",
"path",
")",
":",
"cmd",
"=",
"'xattr -c \"{0}\"'",
".",
"format",
"(",
"path",
")",
"try",
":",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
")",
"except",
"CommandExecutionError",
"as",
"exc",
":... | 29.68 | 0.001305 |
def get_flight_rules(vis: Number, ceiling: Cloud) -> int:
"""
Returns int based on current flight rules from parsed METAR data
0=VFR, 1=MVFR, 2=IFR, 3=LIFR
Note: Common practice is to report IFR if visibility unavailable
"""
# Parse visibility
if not vis:
return 2
if vis.repr =... | [
"def",
"get_flight_rules",
"(",
"vis",
":",
"Number",
",",
"ceiling",
":",
"Cloud",
")",
"->",
"int",
":",
"# Parse visibility",
"if",
"not",
"vis",
":",
"return",
"2",
"if",
"vis",
".",
"repr",
"==",
"'CAVOK'",
"or",
"vis",
".",
"repr",
".",
"startswi... | 31.466667 | 0.001028 |
def indent_text(text,
nb_tabs=0,
tab_str=" ",
linebreak_input="\n",
linebreak_output="\n",
wrap=False):
r"""Add tabs to each line of text.
:param text: the text to indent
:param nb_tabs: number of tabs to add
:param tab_st... | [
"def",
"indent_text",
"(",
"text",
",",
"nb_tabs",
"=",
"0",
",",
"tab_str",
"=",
"\" \"",
",",
"linebreak_input",
"=",
"\"\\n\"",
",",
"linebreak_output",
"=",
"\"\\n\"",
",",
"wrap",
"=",
"False",
")",
":",
"if",
"not",
"wrap",
":",
"lines",
"=",
"t... | 35.222222 | 0.001024 |
def validate(args):
"""
%prog validate outdir genome.fasta
Validate current folder after MAKER run and check for failures. Failed batch
will be written to a directory for additional work.
"""
from jcvi.utils.counter import Counter
p = OptionParser(validate.__doc__)
opts, args = p.parse... | [
"def",
"validate",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"counter",
"import",
"Counter",
"p",
"=",
"OptionParser",
"(",
"validate",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"le... | 31.578947 | 0.001078 |
def run_zone(self, minutes, zone=None):
"""
Run or stop a zone or all zones for an amount of time.
:param minutes: The number of minutes to run.
:type minutes: int
:param zone: The zone number to run. If no zone is specified then run
all zones.
:type... | [
"def",
"run_zone",
"(",
"self",
",",
"minutes",
",",
"zone",
"=",
"None",
")",
":",
"if",
"zone",
"is",
"None",
":",
"zone_cmd",
"=",
"'runall'",
"relay_id",
"=",
"None",
"else",
":",
"if",
"zone",
"<",
"0",
"or",
"zone",
">",
"(",
"len",
"(",
"s... | 31.71875 | 0.001912 |
def generate_rest_view(config, model_cls, attrs=None, es_based=True,
attr_view=False, singular=False):
""" Generate REST view for a model class.
:param model_cls: Generated DB model class.
:param attr: List of strings that represent names of view methods, new
generated view s... | [
"def",
"generate_rest_view",
"(",
"config",
",",
"model_cls",
",",
"attrs",
"=",
"None",
",",
"es_based",
"=",
"True",
",",
"attr_view",
"=",
"False",
",",
"singular",
"=",
"False",
")",
":",
"valid_attrs",
"=",
"(",
"list",
"(",
"collection_methods",
".",... | 37.844444 | 0.000572 |
def start_(name):
'''
Start a container
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing the prior state of the container as
well as the new state
- ``result`` - A boolean noting whet... | [
"def",
"start_",
"(",
"name",
")",
":",
"orig_state",
"=",
"state",
"(",
"name",
")",
"if",
"orig_state",
"==",
"'paused'",
":",
"return",
"{",
"'result'",
":",
"False",
",",
"'state'",
":",
"{",
"'old'",
":",
"orig_state",
",",
"'new'",
":",
"orig_sta... | 26.483871 | 0.001175 |
def dock(self, other):
'''
The opposite of concatenation. Remove a common suffix from the present
pattern; that is, from each of its constituent concs.
AYZ|BYZ|CYZ - YZ = A|B|C.
'''
return pattern(*[c.dock(other) for c in self.concs]) | [
"def",
"dock",
"(",
"self",
",",
"other",
")",
":",
"return",
"pattern",
"(",
"*",
"[",
"c",
".",
"dock",
"(",
"other",
")",
"for",
"c",
"in",
"self",
".",
"concs",
"]",
")"
] | 34.714286 | 0.032129 |
def get_attribute(self, app=None, key=None):
"""Returns an application attribute
:param app: application id
:param key: attribute key or None to retrieve all values for the
given application
:returns: attribute value if key was specified, or an array of tuples
(k... | [
"def",
"get_attribute",
"(",
"self",
",",
"app",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"path",
"=",
"'getattribute'",
"if",
"app",
"is",
"not",
"None",
":",
"path",
"+=",
"'/'",
"+",
"parse",
".",
"quote",
"(",
"app",
",",
"''",
")",
"i... | 38.525 | 0.001266 |
def svd_affine(inp, n_outmaps, r, base_axis=1, uv_init=None,
b_init=None, fix_parameters=False, rng=None,
with_bias=True):
"""SVD affine is a low rank approximation of the affine layer. It can
be seen as two consecutive affine layers with a bottleneck. It
computes:
.. math... | [
"def",
"svd_affine",
"(",
"inp",
",",
"n_outmaps",
",",
"r",
",",
"base_axis",
"=",
"1",
",",
"uv_init",
"=",
"None",
",",
"b_init",
"=",
"None",
",",
"fix_parameters",
"=",
"False",
",",
"rng",
"=",
"None",
",",
"with_bias",
"=",
"True",
")",
":",
... | 38.233871 | 0.001645 |
def rescaleX(self):
'''Rescales the horizontal axes to make the lengthscales equal.'''
self.ratio = self.figure.get_size_inches()[0]/float(self.figure.get_size_inches()[1])
self.axes.set_xlim(-self.ratio,self.ratio)
self.axes.set_ylim(-1,1) | [
"def",
"rescaleX",
"(",
"self",
")",
":",
"self",
".",
"ratio",
"=",
"self",
".",
"figure",
".",
"get_size_inches",
"(",
")",
"[",
"0",
"]",
"/",
"float",
"(",
"self",
".",
"figure",
".",
"get_size_inches",
"(",
")",
"[",
"1",
"]",
")",
"self",
"... | 53.6 | 0.018382 |
def generate_fixtures(datasets, reuses):
'''Build sample fixture data (users, datasets and reuses).'''
user = UserFactory()
log.info('Generated user "{user.email}".'.format(user=user))
organization = OrganizationFactory(members=[Member(user=user)])
log.info('Generated organization "{org.name}".'.fo... | [
"def",
"generate_fixtures",
"(",
"datasets",
",",
"reuses",
")",
":",
"user",
"=",
"UserFactory",
"(",
")",
"log",
".",
"info",
"(",
"'Generated user \"{user.email}\".'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"organization",
"=",
"OrganizationFact... | 44.4 | 0.001471 |
def classes_can_admin(self):
"""Return all the classes (sorted) that this user can admin."""
if self.is_admin:
return sorted(Session.query(Class).all())
else:
return sorted(self.admin_for) | [
"def",
"classes_can_admin",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_admin",
":",
"return",
"sorted",
"(",
"Session",
".",
"query",
"(",
"Class",
")",
".",
"all",
"(",
")",
")",
"else",
":",
"return",
"sorted",
"(",
"self",
".",
"admin_for",
")"... | 38.5 | 0.008475 |
def mergecsv(args):
"""
%prog mergecsv *.tsv
Merge a set of tsv files.
"""
p = OptionParser(mergecsv.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
tsvfiles = args
outfile = opts.outfile
if op.exists(outfile... | [
"def",
"mergecsv",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mergecsv",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"... | 20 | 0.001704 |
def addPathVariables(self, pathvars):
""" Adds path variables to the pathvars map property"""
if type(pathvars) is dict:
self._pathvars = merge(self._pathvars, pathvars) | [
"def",
"addPathVariables",
"(",
"self",
",",
"pathvars",
")",
":",
"if",
"type",
"(",
"pathvars",
")",
"is",
"dict",
":",
"self",
".",
"_pathvars",
"=",
"merge",
"(",
"self",
".",
"_pathvars",
",",
"pathvars",
")"
] | 48.5 | 0.010152 |
def bam_conversion(job, samfile, sample_type, univ_options):
"""
This module converts SAMFILE from sam to bam
ARGUMENTS
1. samfile: <JSid for a sam file>
2. sample_type: string of 'tumor_dna' or 'normal_dna'
3. univ_options: Dict of universal arguments used by almost all tools
univ_opt... | [
"def",
"bam_conversion",
"(",
"job",
",",
"samfile",
",",
"sample_type",
",",
"univ_options",
")",
":",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Running sam2bam on %s:%s'",
"%",
"(",
"univ_options",
"[",
"'patient'",
"]",
",",
"sample_type",
")",
")... | 42.34375 | 0.002165 |
def as_dictionary(self):
"""
Return the parameter as a dictionary.
:return: dict
"""
return {
"name": self.name,
"type": self.type,
"value": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value
} | [
"def",
"as_dictionary",
"(",
"self",
")",
":",
"return",
"{",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"type\"",
":",
"self",
".",
"type",
",",
"\"value\"",
":",
"remove_0x_prefix",
"(",
"self",
".",
"value",
")",
"if",
"self",
".",
"type",
"==",
... | 26.181818 | 0.010067 |
def get_networks_by_name(self, name: str) -> List[Network]:
"""Get all networks with the given name. Useful for getting all versions of a given network."""
return self.session.query(Network).filter(Network.name.like(name)).all() | [
"def",
"get_networks_by_name",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"List",
"[",
"Network",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Network",
")",
".",
"filter",
"(",
"Network",
".",
"name",
".",
"like",
"(",
"name... | 80.666667 | 0.016393 |
def IndexedDB_clearObjectStore(self, securityOrigin, databaseName,
objectStoreName):
"""
Function path: IndexedDB.clearObjectStore
Domain: IndexedDB
Method name: clearObjectStore
Parameters:
Required arguments:
'securityOrigin' (type: string) -> Security origin.
'databaseName' (type: ... | [
"def",
"IndexedDB_clearObjectStore",
"(",
"self",
",",
"securityOrigin",
",",
"databaseName",
",",
"objectStoreName",
")",
":",
"assert",
"isinstance",
"(",
"securityOrigin",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'securityOrigin' must be of type '['str']'. Re... | 38.62069 | 0.043554 |
def obtain_to(filename, compressed=True):
"""
Return the linke turbidity projected to the lat lon matrix coordenates.
Keyword arguments:
filename -- the name of a netcdf file.
"""
files = glob.glob(filename)
root, _ = nc.open(filename)
lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(r... | [
"def",
"obtain_to",
"(",
"filename",
",",
"compressed",
"=",
"True",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"filename",
")",
"root",
",",
"_",
"=",
"nc",
".",
"open",
"(",
"filename",
")",
"lat",
",",
"lon",
"=",
"nc",
".",
"getvar",
"... | 40.5 | 0.00905 |
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Tak... | [
"def",
"search",
"(",
"name",
")",
":",
"name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
"all_ports",
"=",
"list_all",
"(",
")",
"if",
"'/'",
"in",
"name",
":",
"if",
"name",
".",
"count",
"(",
"'/'",
")",
">",
"1",
":",
"raise",
"SaltInvo... | 24.909091 | 0.001171 |
def get_location(opts=None, provider=None):
'''
Return the region to use, in this order:
opts['location']
provider['location']
get_region_from_metadata()
DEFAULT_LOCATION
'''
if opts is None:
opts = {}
ret = opts.get('location')
if ret is None and provider... | [
"def",
"get_location",
"(",
"opts",
"=",
"None",
",",
"provider",
"=",
"None",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"{",
"}",
"ret",
"=",
"opts",
".",
"get",
"(",
"'location'",
")",
"if",
"ret",
"is",
"None",
"and",
"provider",
... | 26.777778 | 0.002004 |
def set_content_type (self):
"""Return URL content type, or an empty string if content
type could not be found."""
if self.url:
self.content_type = mimeutil.guess_mimetype(self.url, read=self.get_content)
else:
self.content_type = u"" | [
"def",
"set_content_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
":",
"self",
".",
"content_type",
"=",
"mimeutil",
".",
"guess_mimetype",
"(",
"self",
".",
"url",
",",
"read",
"=",
"self",
".",
"get_content",
")",
"else",
":",
"self",
".",
... | 40.571429 | 0.013793 |
def import_source(self, CachableSource):
"""Updates cache area and returns number of items updated with all available entries in ICachableSource"""
_count = 0
for item in CachableSource.items():
if self.cache(item):
_count += 1
return _count | [
"def",
"import_source",
"(",
"self",
",",
"CachableSource",
")",
":",
"_count",
"=",
"0",
"for",
"item",
"in",
"CachableSource",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"cache",
"(",
"item",
")",
":",
"_count",
"+=",
"1",
"return",
"_count"
] | 42.142857 | 0.009967 |
def _select_index(self, row, col):
"""Change the selection index, and make sure it stays in the right range
A little more complicated than just dooing modulo the number of row columns
to be sure to cycle through all element.
horizontaly, the element are maped like this :
to r <... | [
"def",
"_select_index",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"nr",
",",
"nc",
"=",
"self",
".",
"_size",
"nr",
"=",
"nr",
"-",
"1",
"nc",
"=",
"nc",
"-",
"1",
"# case 1",
"if",
"(",
"row",
">",
"nr",
"and",
"col",
">=",
"nc",
")",
... | 31.431818 | 0.009818 |
def to_dict(self):
"""
Convert current Task into a dictionary
:return: python dictionary
"""
task_desc_as_dict = {
'uid': self._uid,
'name': self._name,
'state': self._state,
'state_history': self._state_history,
'pre... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"task_desc_as_dict",
"=",
"{",
"'uid'",
":",
"self",
".",
"_uid",
",",
"'name'",
":",
"self",
".",
"_name",
",",
"'state'",
":",
"self",
".",
"_state",
",",
"'state_history'",
":",
"self",
".",
"_state_history",
... | 31.146341 | 0.001519 |
def _check_stream(self):
"""Determines which output stream (stdout, stderr, or custom) to use"""
if self.stream:
try:
supported = ('PYCHARM_HOSTED' in os.environ or
os.isatty(sys.stdout.fileno()))
# a fix for IPython notebook "IOStre... | [
"def",
"_check_stream",
"(",
"self",
")",
":",
"if",
"self",
".",
"stream",
":",
"try",
":",
"supported",
"=",
"(",
"'PYCHARM_HOSTED'",
"in",
"os",
".",
"environ",
"or",
"os",
".",
"isatty",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
")",
... | 40.8 | 0.001596 |
def insert_vlan(
self,
environment_id,
name,
number,
description,
acl_file,
acl_file_v6,
network_ipv4,
network_ipv6,
vrf=None):
"""Create new VLAN
:param environment_id: ID for Enviro... | [
"def",
"insert_vlan",
"(",
"self",
",",
"environment_id",
",",
"name",
",",
"number",
",",
"description",
",",
"acl_file",
",",
"acl_file_v6",
",",
"network_ipv4",
",",
"network_ipv6",
",",
"vrf",
"=",
"None",
")",
":",
"if",
"not",
"is_valid_int_param",
"("... | 38.076923 | 0.002363 |
def get_jira_key_from_scenario(scenario):
"""Extract Jira Test Case key from scenario tags.
Two tag formats are allowed:
@jira('PROJECT-32')
@jira=PROJECT-32
:param scenario: behave scenario
:returns: Jira test case key
"""
jira_regex = re.compile('jira[=\(\']*([A-Z]+\-[0-9]+)[\'\)]*$')... | [
"def",
"get_jira_key_from_scenario",
"(",
"scenario",
")",
":",
"jira_regex",
"=",
"re",
".",
"compile",
"(",
"'jira[=\\(\\']*([A-Z]+\\-[0-9]+)[\\'\\)]*$'",
")",
"for",
"tag",
"in",
"scenario",
".",
"tags",
":",
"match",
"=",
"jira_regex",
".",
"search",
"(",
"t... | 29.533333 | 0.008753 |
def parse_public(data):
"""
Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
EC public keys. For RSA keys, both the old RSAPublicKey and
SubjectPublicKeyInfo structures are supported. Also allows extracting a
public key from an X.509 certificate.
:param data:
A... | [
"def",
"parse_public",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n data must be a byte string, not %s\n '''",
",",
"type_name",
"(",
"data",
... | 33.042254 | 0.001242 |
def declallfuncs(self):
"""generator on all declaration of function"""
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)):
yield f | [
"def",
"declallfuncs",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"body",
":",
"if",
"(",
"hasattr",
"(",
"f",
",",
"'_ctype'",
")",
"and",
"isinstance",
"(",
"f",
".",
"_ctype",
",",
"FuncType",
")",
")",
":",
"yield",
"f"
] | 36.5 | 0.008929 |
def _get_enterprise_enrollment_api_admin_users_batch(self, start, end): # pylint: disable=invalid-name
"""
Returns a batched queryset of User objects.
"""
LOGGER.info('Fetching new batch of enterprise enrollment admin users from indexes: %s to %s', start, end)
return User.obj... | [
"def",
"_get_enterprise_enrollment_api_admin_users_batch",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"# pylint: disable=invalid-name",
"LOGGER",
".",
"info",
"(",
"'Fetching new batch of enterprise enrollment admin users from indexes: %s to %s'",
",",
"start",
",",
"end"... | 67.666667 | 0.012165 |
def from_btl(fname):
"""
DataFrame constructor to open Seabird CTD BTL-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl'))
... | [
"def",
"from_btl",
"(",
"fname",
")",
":",
"f",
"=",
"_read_file",
"(",
"fname",
")",
"metadata",
"=",
"_parse_seabird",
"(",
"f",
".",
"readlines",
"(",
")",
",",
"ftype",
"=",
"\"btl\"",
")",
"f",
".",
"seek",
"(",
"0",
")",
"df",
"=",
"pd",
".... | 29.708333 | 0.001357 |
def tangelo_import(*args, **kwargs):
"""
When we are asked to import a module, if we get an import error and the
calling script is one we are serving (not one in the python libraries), try
again in the same directory as the script that is calling import.
It seems like we should use sys.meta_path... | [
"def",
"tangelo_import",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"builtin_import",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"ImportError",
":",
"if",
"not",
"hasattr",
"(",
"cherrypy",
".",
"thread_da... | 41.878788 | 0.001414 |
def get_context_data(self, **kwargs):
'''
Adds a 'base_template' attribute to context for the page_detail to
extend from
'''
context = super(PageList, self).get_context_data(**kwargs)
page_base_template = "nupages/base.html"
# if MultiTenantMiddleware is used, us... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"PageList",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"page_base_template",
"=",
"\"nupages/base.html\"",
"# if MultiTenantM... | 42.875 | 0.008559 |
def domain_xml(identifier, xml, mounts, network_name=None):
"""Fills the XML file with the required fields.
@param identifier: (str) UUID of the Environment.
@param xml: (str) XML configuration of the domain.
@param filesystem: (tuple) ((source, target), (source, target))
* name
* uuid
... | [
"def",
"domain_xml",
"(",
"identifier",
",",
"xml",
",",
"mounts",
",",
"network_name",
"=",
"None",
")",
":",
"domain",
"=",
"etree",
".",
"fromstring",
"(",
"xml",
")",
"subelement",
"(",
"domain",
",",
"'.//name'",
",",
"'name'",
",",
"identifier",
")... | 34.766667 | 0.001866 |
def load_stylesheet_pyqt5():
"""
Loads the stylesheet for use in a pyqt5 application.
:param pyside: True to load the pyside rc file, False to load the PyQt rc file
:return the stylesheet string
"""
# Smart import of the rc file
import qdarkstyle.pyqt5_style_rc
# Load the stylesheet c... | [
"def",
"load_stylesheet_pyqt5",
"(",
")",
":",
"# Smart import of the rc file",
"import",
"qdarkstyle",
".",
"pyqt5_style_rc",
"# Load the stylesheet content from resources",
"from",
"PyQt5",
".",
"QtCore",
"import",
"QFile",
",",
"QTextStream",
"f",
"=",
"QFile",
"(",
... | 29.676471 | 0.001919 |
def connection_string_parser(uri: str) -> list:
"""
Parse Connection string to extract host and port.
:param uri: full URI for redis connection in the form of host:port
:returns: list of RedisConnection objects
"""
redis_connections = []
raw_connections = uri.sp... | [
"def",
"connection_string_parser",
"(",
"uri",
":",
"str",
")",
"->",
"list",
":",
"redis_connections",
"=",
"[",
"]",
"raw_connections",
"=",
"uri",
".",
"split",
"(",
"','",
")",
"connections",
"=",
"[",
"connection",
"for",
"connection",
"in",
"raw_connec... | 34.242424 | 0.001721 |
def replace(self, *args, **kargs):
"""
lst.replace(<field>,[<oldvalue>,]<newvalue>)
lst.replace( (fld,[ov],nv),(fld,[ov,]nv),...)
if ov is None, all values are replaced
ex:
lst.replace( IP.src, "192.168.1.1", "10.0.0.1" )
lst.replace( IP.ttl, 64 )
... | [
"def",
"replace",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"delete_checksums",
"=",
"kargs",
".",
"get",
"(",
"\"delete_checksums\"",
",",
"False",
")",
"x",
"=",
"PacketList",
"(",
"name",
"=",
"\"Replaced %s\"",
"%",
"self",
"... | 40.59375 | 0.001504 |
def run (self):
"""Handle keyboard interrupt and other errors."""
try:
self.run_checked()
except KeyboardInterrupt:
thread.interrupt_main()
except Exception:
self.internal_error() | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"run_checked",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"thread",
".",
"interrupt_main",
"(",
")",
"except",
"Exception",
":",
"self",
".",
"internal_error",
"(",
")"
] | 30 | 0.012146 |
def request(self, method, url_parts, headers=None, data=None):
""" Method for making requests to the Optimizely API
"""
if method in self.ALLOWED_REQUESTS:
# add request token header
headers = headers or {}
# test if Oauth token
if self.token_type... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url_parts",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"method",
"in",
"self",
".",
"ALLOWED_REQUESTS",
":",
"# add request token header",
"headers",
"=",
"headers",
"or",
"{",... | 41.233333 | 0.00158 |
def get_blobstore(layout):
"""Return Blobstore instance for a given storage layout
Args:
layout (StorageLayout): Target storage layout.
"""
if layout.is_s3:
from wal_e.blobstore import s3
blobstore = s3
elif layout.is_wabs:
from wal_e.blobstore import wabs
blo... | [
"def",
"get_blobstore",
"(",
"layout",
")",
":",
"if",
"layout",
".",
"is_s3",
":",
"from",
"wal_e",
".",
"blobstore",
"import",
"s3",
"blobstore",
"=",
"s3",
"elif",
"layout",
".",
"is_wabs",
":",
"from",
"wal_e",
".",
"blobstore",
"import",
"wabs",
"bl... | 28.761905 | 0.001603 |
def is_valid_intensity_measure_types(self):
"""
If the IMTs and levels are extracted from the risk models,
they must not be set directly. Moreover, if
`intensity_measure_types_and_levels` is set directly,
`intensity_measure_types` must not be set.
"""
if self.grou... | [
"def",
"is_valid_intensity_measure_types",
"(",
"self",
")",
":",
"if",
"self",
".",
"ground_motion_correlation_model",
":",
"for",
"imt",
"in",
"self",
".",
"imtls",
":",
"if",
"not",
"(",
"imt",
".",
"startswith",
"(",
"'SA'",
")",
"or",
"imt",
"==",
"'P... | 47.7 | 0.002055 |
def replace(text, old, new, count=None, strip=False):
'''
Replace an ``old`` subset of ``text`` with ``new``.
``old`` type may be either a string or regular expression.
If ``strip``, remove all leading/trailing whitespace.
If ``count``, replace the specified number of occurence, other... | [
"def",
"replace",
"(",
"text",
",",
"old",
",",
"new",
",",
"count",
"=",
"None",
",",
"strip",
"=",
"False",
")",
":",
"if",
"is_string",
"(",
"old",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"old",
",",
"new",
",",
"-",
"1",
"if",
... | 31.315789 | 0.013051 |
def get_stats_str(list_=None, newlines=False, keys=None, exclude_keys=[], lbl=None,
precision=None, axis=0, stat_dict=None, use_nan=False,
align=False, use_median=False, **kwargs):
"""
Returns the string version of get_stats
DEPRICATE in favor of ut.repr3(ut.get_stats(..... | [
"def",
"get_stats_str",
"(",
"list_",
"=",
"None",
",",
"newlines",
"=",
"False",
",",
"keys",
"=",
"None",
",",
"exclude_keys",
"=",
"[",
"]",
",",
"lbl",
"=",
"None",
",",
"precision",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"stat_dict",
"=",
"N... | 35.813187 | 0.00209 |
def equals(self, data):
"""Adds new `IN` or `=` condition depending on if a list or string was provided
:param data: string or list of values
:raise:
- QueryTypeError: if `data` is of an unexpected type
"""
if isinstance(data, six.string_types):
return s... | [
"def",
"equals",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
":",
"return",
"self",
".",
"_add_condition",
"(",
"'='",
",",
"data",
",",
"types",
"=",
"[",
"int",
",",
"str",
"]",
")",
... | 40.571429 | 0.008606 |
def seq_len(self,L):
"""set the length of the uncompressed sequence. its inverse 'one_mutation'
is frequently used as a general length scale. This can't be changed once
it is set.
Parameters
----------
L : int
length of the sequence alignment
"""
... | [
"def",
"seq_len",
"(",
"self",
",",
"L",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"self",
",",
"'_seq_len'",
")",
")",
"or",
"self",
".",
"_seq_len",
"is",
"None",
":",
"if",
"L",
":",
"self",
".",
"_seq_len",
"=",
"int",
"(",
"L",
")",
"els... | 35.133333 | 0.012939 |
def get_variable(self, variable_name, client=None):
"""API call: get a variable via a ``GET`` request.
This will return None if the variable doesn't exist::
>>> from google.cloud import runtimeconfig
>>> client = runtimeconfig.Client()
>>> config = client.config('my-conf... | [
"def",
"get_variable",
"(",
"self",
",",
"variable_name",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"variable",
"=",
"Variable",
"(",
"config",
"=",
"self",
",",
"name",
"=",
"variable_name",
... | 38.709677 | 0.001626 |
def getRepositories(self):
"""Returns a list of repositories for this directory.
"""
if self.srcdir and not self.duplicate:
return self.srcdir.get_all_rdirs() + self.repositories
return self.repositories | [
"def",
"getRepositories",
"(",
"self",
")",
":",
"if",
"self",
".",
"srcdir",
"and",
"not",
"self",
".",
"duplicate",
":",
"return",
"self",
".",
"srcdir",
".",
"get_all_rdirs",
"(",
")",
"+",
"self",
".",
"repositories",
"return",
"self",
".",
"reposito... | 40.333333 | 0.008097 |
def replace(self, html):
"""Perform replacements on given HTML fragment."""
self.html = html
text = html.text()
positions = []
def perform_replacement(match):
offset = sum(positions)
start, stop = match.start() + offset, match.end() + offset
... | [
"def",
"replace",
"(",
"self",
",",
"html",
")",
":",
"self",
".",
"html",
"=",
"html",
"text",
"=",
"html",
".",
"text",
"(",
")",
"positions",
"=",
"[",
"]",
"def",
"perform_replacement",
"(",
"match",
")",
":",
"offset",
"=",
"sum",
"(",
"positi... | 31.740741 | 0.002265 |
def new_thing(self, name, **stats):
"""Create a new thing, located here, and return it."""
return self.character.new_thing(
name, self.name, **stats
) | [
"def",
"new_thing",
"(",
"self",
",",
"name",
",",
"*",
"*",
"stats",
")",
":",
"return",
"self",
".",
"character",
".",
"new_thing",
"(",
"name",
",",
"self",
".",
"name",
",",
"*",
"*",
"stats",
")"
] | 36.4 | 0.010753 |
def audio(self, audio, sample_rate, name=None, subdir=''):
"""Summary audio to listen on web browser.
Args:
audio (:class:`numpy.ndarray` or :class:`cupy.ndarray` or \
:class:`chainer.Variable`): sampled wave array.
sample_rate (int): sampling rate.
n... | [
"def",
"audio",
"(",
"self",
",",
"audio",
",",
"sample_rate",
",",
"name",
"=",
"None",
",",
"subdir",
"=",
"''",
")",
":",
"from",
"chainerui",
".",
"report",
".",
"audio_report",
"import",
"check_available",
"if",
"not",
"check_available",
"(",
")",
"... | 41 | 0.002073 |
def _extend_str(class_node, rvalue):
"""function to extend builtin str/unicode class"""
code = dedent(
"""
class whatever(object):
def join(self, iterable):
return {rvalue}
def replace(self, old, new, count=None):
return {rvalue}
def format(self, *args... | [
"def",
"_extend_str",
"(",
"class_node",
",",
"rvalue",
")",
":",
"code",
"=",
"dedent",
"(",
"\"\"\"\n class whatever(object):\n def join(self, iterable):\n return {rvalue}\n def replace(self, old, new, count=None):\n return {rvalue}\n def forma... | 32.909091 | 0.000536 |
def cleaned_date(day, keep_datetime=False):
"""
Return a "clean" date type.
* keep a `date` unchanged
* convert a datetime into a date,
* convert any "duck date" type into a date using its `date()` method.
"""
if not isinstance(day, (date, datetime)):
raise UnsupportedDateType(
... | [
"def",
"cleaned_date",
"(",
"day",
",",
"keep_datetime",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"day",
",",
"(",
"date",
",",
"datetime",
")",
")",
":",
"raise",
"UnsupportedDateType",
"(",
"\"`{}` is of unsupported type ({})\"",
".",
"format"... | 33.2 | 0.001953 |
def parse_cmd_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('file', type=str,
help='Filename to be staticfied')
parser.add_argument('--static-endpoint',
help='Static endpoint which is "static" by de... | [
"def",
"parse_cmd_arguments",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'Filename to be staticfied'",
")",
"parser",
".",
"add_argument",... | 47.368421 | 0.001089 |
def add_aggregated_lv_components(network, components):
"""
Aggregates LV load and generation at LV stations
Use this function if you aim for MV calculation only. The according
DataFrames of `components` are extended by load and generators representing
these aggregated respecting the technology type... | [
"def",
"add_aggregated_lv_components",
"(",
"network",
",",
"components",
")",
":",
"generators",
"=",
"{",
"}",
"loads",
"=",
"{",
"}",
"# collect aggregated generation capacity by type and subtype",
"# collect aggregated load grouped by sector",
"for",
"lv_grid",
"in",
"n... | 38.851852 | 0.00031 |
def slice(self, who):
"return the slice entry (in a bed6 format), AS IS in the chain header"
assert who in ('t', 'q'), "who should be 't' or 'q'"
if who == 't':
return (self.tName, self.tStart, self.tEnd, self.id, self.score, self.tStrand)
else:
return (self.qNa... | [
"def",
"slice",
"(",
"self",
",",
"who",
")",
":",
"assert",
"who",
"in",
"(",
"'t'",
",",
"'q'",
")",
",",
"\"who should be 't' or 'q'\"",
"if",
"who",
"==",
"'t'",
":",
"return",
"(",
"self",
".",
"tName",
",",
"self",
".",
"tStart",
",",
"self",
... | 41.555556 | 0.010471 |
def skewvT(self,R,romberg=False,nsigma=None,phi=0.):
"""
NAME:
skewvT
PURPOSE:
calculate skew in vT at R by marginalizing over velocity
INPUT:
R - radius at which to calculate <vR> (can be Quantity)
OPTIONAL INPUT:
nsigma - numbe... | [
"def",
"skewvT",
"(",
"self",
",",
"R",
",",
"romberg",
"=",
"False",
",",
"nsigma",
"=",
"None",
",",
"phi",
"=",
"0.",
")",
":",
"surfmass",
"=",
"self",
".",
"surfacemass",
"(",
"R",
",",
"romberg",
"=",
"romberg",
",",
"nsigma",
"=",
"nsigma",
... | 24.853659 | 0.02644 |
def get_id_for_extra_dim_type(type_str):
""" Returns the index of the type as defined in the LAS Specification
Parameters
----------
type_str: str
Returns
-------
int
index of the type
"""
try:
return _type_to_extra_dim_id_style_1[type_str]
except KeyError:
... | [
"def",
"get_id_for_extra_dim_type",
"(",
"type_str",
")",
":",
"try",
":",
"return",
"_type_to_extra_dim_id_style_1",
"[",
"type_str",
"]",
"except",
"KeyError",
":",
"try",
":",
"return",
"_type_to_extra_dim_id_style_2",
"[",
"type_str",
"]",
"except",
"KeyError",
... | 22.3 | 0.002151 |
def from_scene_coords(self, x=0, y=0):
"""Converts x, y given in the scene coordinates to sprite's local ones
coordinates"""
matrix = self.get_matrix()
matrix.invert()
return matrix.transform_point(x, y) | [
"def",
"from_scene_coords",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"matrix",
"=",
"self",
".",
"get_matrix",
"(",
")",
"matrix",
".",
"invert",
"(",
")",
"return",
"matrix",
".",
"transform_point",
"(",
"x",
",",
"y",
")"
] | 39.666667 | 0.00823 |
def is_obtuse(p1, v, p2):
'''Determine whether the angle, p1 - v - p2 is obtuse
p1 - N x 2 array of coordinates of first point on edge
v - N x 2 array of vertex coordinates
p2 - N x 2 array of coordinates of second point on edge
returns vector of booleans
'''
p1x = p1[:,1]
p1y ... | [
"def",
"is_obtuse",
"(",
"p1",
",",
"v",
",",
"p2",
")",
":",
"p1x",
"=",
"p1",
"[",
":",
",",
"1",
"]",
"p1y",
"=",
"p1",
"[",
":",
",",
"0",
"]",
"p2x",
"=",
"p2",
"[",
":",
",",
"1",
"]",
"p2y",
"=",
"p2",
"[",
":",
",",
"0",
"]",
... | 24.75 | 0.01751 |
def _format_output(selected_number, raw_data):
"""Format data to get a readable output"""
tmp_data = {}
data = collections.defaultdict(lambda: 0)
balance = raw_data.pop('balance')
for number in raw_data.keys():
tmp_data = dict([(k, int(v) if v is not None else "No limit")
... | [
"def",
"_format_output",
"(",
"selected_number",
",",
"raw_data",
")",
":",
"tmp_data",
"=",
"{",
"}",
"data",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"balance",
"=",
"raw_data",
".",
"pop",
"(",
"'balance'",
")",
"for",
"nu... | 33 | 0.001473 |
def to_html(self):
"""Render a Table MessageElement as html.
:returns: The html representation of the Table MessageElement
:rtype: basestring
"""
table = '<table%s>\n' % self.html_attributes()
if self.caption is not None:
if isinstance(self.caption, MessageEl... | [
"def",
"to_html",
"(",
"self",
")",
":",
"table",
"=",
"'<table%s>\\n'",
"%",
"self",
".",
"html_attributes",
"(",
")",
"if",
"self",
".",
"caption",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"caption",
",",
"MessageElement",
")",
... | 34.16 | 0.002278 |
def parse_package(package_string, arch_included=True):
"""Parse an RPM version string to get name, version, and arch
Splits most (all tested) RPM version strings into name, epoch,
version, release, and architecture. Epoch (also called serial) is
an optional component of RPM versioning and is also optio... | [
"def",
"parse_package",
"(",
"package_string",
",",
"arch_included",
"=",
"True",
")",
":",
"# Yum sets epoch values to 0 if they are not specified",
"logger",
".",
"debug",
"(",
"'parse_package(%s, %s)'",
",",
"package_string",
",",
"arch_included",
")",
"default_epoch",
... | 41.390244 | 0.000576 |
def _convert(self, args):
'''convert '(1,1)' to 'B2' and 'B2' to '(1,1)' auto-recongnize'''
if args.find(",") > -1:
b, a = args.replace("(", "").replace(")", "").split(",")
a = chr(int(a)+65)#chr(65) is "A" and ord("A") is 65
b = str(int(b)+1)
return a+b
... | [
"def",
"_convert",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"find",
"(",
"\",\"",
")",
">",
"-",
"1",
":",
"b",
",",
"a",
"=",
"args",
".",
"replace",
"(",
"\"(\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\")\"",
",",
"\"\"",
")... | 47.636364 | 0.009363 |
def scroll_to(self, line):
"""
Scroll the abstract canvas to make a specific line.
:param line: The line to scroll to.
"""
self._buffer.scroll(line - self._start_line)
self._start_line = line | [
"def",
"scroll_to",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"_buffer",
".",
"scroll",
"(",
"line",
"-",
"self",
".",
"_start_line",
")",
"self",
".",
"_start_line",
"=",
"line"
] | 29.125 | 0.008333 |
def create_folder(self, name, parent_folder_id=0):
"""Create a folder
If the folder exists, a BoxError will be raised.
Args:
folder_id (int): Name of the folder.
parent_folder_id (int): ID of the folder where to create the new one.
Returns:
dict. R... | [
"def",
"create_folder",
"(",
"self",
",",
"name",
",",
"parent_folder_id",
"=",
"0",
")",
":",
"return",
"self",
".",
"__request",
"(",
"\"POST\"",
",",
"\"folders\"",
",",
"data",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"parent\"",
":",
"{",
"\"id\"",... | 31.913043 | 0.009259 |
def condense_otus(otuF, nuniqueF):
"""
Traverse the input otu-sequence file, collect the non-unique OTU IDs and
file the sequences associated with then under the unique OTU ID as defined
by the input matrix.
:@type otuF: file
:@param otuF: The output file from QIIME's pick_otus.py
:@type nu... | [
"def",
"condense_otus",
"(",
"otuF",
",",
"nuniqueF",
")",
":",
"uniqueOTUs",
"=",
"set",
"(",
")",
"nuOTUs",
"=",
"{",
"}",
"# parse non-unique otu matrix",
"for",
"line",
"in",
"nuniqueF",
":",
"line",
"=",
"line",
".",
"split",
"(",
")",
"uOTU",
"=",
... | 30.236842 | 0.000843 |
def get_distribution(cls, ctx, name=None, recipes=[],
ndk_api=None,
force_build=False,
extra_dist_dirs=[],
require_perfect_match=False,
allow_replace_dist=True):
'''Takes information abou... | [
"def",
"get_distribution",
"(",
"cls",
",",
"ctx",
",",
"name",
"=",
"None",
",",
"recipes",
"=",
"[",
"]",
",",
"ndk_api",
"=",
"None",
",",
"force_build",
"=",
"False",
",",
"extra_dist_dirs",
"=",
"[",
"]",
",",
"require_perfect_match",
"=",
"False",
... | 38.426087 | 0.001985 |
def remove_other_cflags(self, flags, target_name=None, configuration_name=None):
"""
Removes the given flags from the OTHER_CFLAGS section of the target on the configurations
:param flags: A string or array of strings. If none, removes all values from the flag.
:param target_name: Target... | [
"def",
"remove_other_cflags",
"(",
"self",
",",
"flags",
",",
"target_name",
"=",
"None",
",",
"configuration_name",
"=",
"None",
")",
":",
"self",
".",
"remove_flags",
"(",
"XCBuildConfigurationFlags",
".",
"OTHER_CFLAGS",
",",
"flags",
",",
"target_name",
",",... | 70.555556 | 0.012442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.