text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def create_debit():
"""
Create a new debit, sending tokens out of your User's account.
---
parameters:
- name: debit
in: body
description: The debit you would like to create.
required: true
schema:
$ref: '#/definitions/Debit'
responses:
'200':
... | [
"def",
"create_debit",
"(",
")",
":",
"currency",
"=",
"request",
".",
"jws_payload",
"[",
"'data'",
"]",
".",
"get",
"(",
"'currency'",
")",
"amount",
"=",
"Amount",
"(",
"\"%s %s\"",
"%",
"(",
"request",
".",
"jws_payload",
"[",
"'data'",
"]",
".",
"... | 33.176471 | 0.001148 |
def drop_slot(self, slot=None, drop_stack=False):
"""
Drop one or all items of the slot.
Does not wait for confirmation from the server. If you want that,
use a ``Task`` and ``yield inventory.async.drop_slot()`` instead.
If ``slot`` is None, drops the ``cursor_slot`` or, if tha... | [
"def",
"drop_slot",
"(",
"self",
",",
"slot",
"=",
"None",
",",
"drop_stack",
"=",
"False",
")",
":",
"if",
"slot",
"is",
"None",
":",
"if",
"self",
".",
"cursor_slot",
".",
"is_empty",
":",
"slot",
"=",
"self",
".",
"active_slot",
"else",
":",
"slot... | 38.607143 | 0.001805 |
def import_spydercustomize():
"""Import our customizations into the kernel."""
here = osp.dirname(__file__)
parent = osp.dirname(here)
customize_dir = osp.join(parent, 'customize')
# Remove current directory from sys.path to prevent kernel
# crashes when people name Python files or modules with... | [
"def",
"import_spydercustomize",
"(",
")",
":",
"here",
"=",
"osp",
".",
"dirname",
"(",
"__file__",
")",
"parent",
"=",
"osp",
".",
"dirname",
"(",
"here",
")",
"customize_dir",
"=",
"osp",
".",
"join",
"(",
"parent",
",",
"'customize'",
")",
"# Remove ... | 30.045455 | 0.001466 |
def post_processor_population_displacement_function(
hazard=None, classification=None, hazard_class=None, population=None):
"""Private function used in the displacement postprocessor.
:param hazard: The hazard to use.
:type hazard: str
:param classification: The hazard classification to use.
... | [
"def",
"post_processor_population_displacement_function",
"(",
"hazard",
"=",
"None",
",",
"classification",
"=",
"None",
",",
"hazard_class",
"=",
"None",
",",
"population",
"=",
"None",
")",
":",
"_",
"=",
"population",
"# NOQA",
"return",
"get_displacement_rate",... | 32.826087 | 0.001287 |
def zeroize_crypto_domain(self, crypto_adapter, crypto_domain_index):
"""
Zeroize a single crypto domain on a crypto adapter.
Zeroizing a crypto domain clears the cryptographic keys and
non-compliance mode settings in the crypto domain.
The crypto domain must be attached to thi... | [
"def",
"zeroize_crypto_domain",
"(",
"self",
",",
"crypto_adapter",
",",
"crypto_domain_index",
")",
":",
"body",
"=",
"{",
"'crypto-adapter-uri'",
":",
"crypto_adapter",
".",
"uri",
",",
"'domain-index'",
":",
"crypto_domain_index",
"}",
"self",
".",
"manager",
"... | 33.179487 | 0.001502 |
def setup_for_bottle(
auth, app, send_email=None, render=None,
session=None, request=None, urloptions=None):
import bottle
auth.request = request or bottle.request
if session is not None:
auth.session = session
if send_email:
auth.send_email = send_email
auth.render... | [
"def",
"setup_for_bottle",
"(",
"auth",
",",
"app",
",",
"send_email",
"=",
"None",
",",
"render",
"=",
"None",
",",
"session",
"=",
"None",
",",
"request",
"=",
"None",
",",
"urloptions",
"=",
"None",
")",
":",
"import",
"bottle",
"auth",
".",
"reques... | 33.388889 | 0.000808 |
def ranseed(seed=None):
""" Seed random number generators with tuple ``seed``.
Argument ``seed`` is an integer or
a :class:`tuple` of integers that is used to seed
the random number generators used by :mod:`numpy` and
:mod:`random` (and therefore by :mod:`gvar`). Reusing
the same ``seed`` resul... | [
"def",
"ranseed",
"(",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"numpy",
".",
"random",
".",
"randint",
"(",
"1",
",",
"int",
"(",
"2e9",
")",
",",
"size",
"=",
"3",
")",
"try",
":",
"seed",
"=",
"tuple",
"... | 34.344828 | 0.000977 |
def ffmpeg_version():
"""Returns the available ffmpeg version
Returns
----------
version : str
version number as string
"""
cmd = [
'ffmpeg',
'-version'
]
output = sp.check_output(cmd)
aac_codecs = [
x for x in
output.splitlines() if "ffmpeg... | [
"def",
"ffmpeg_version",
"(",
")",
":",
"cmd",
"=",
"[",
"'ffmpeg'",
",",
"'-version'",
"]",
"output",
"=",
"sp",
".",
"check_output",
"(",
"cmd",
")",
"aac_codecs",
"=",
"[",
"x",
"for",
"x",
"in",
"output",
".",
"splitlines",
"(",
")",
"if",
"\"ffm... | 20.44 | 0.001869 |
def _download_libraries(self, libname):
""" download enrichr libraries."""
self._logger.info("Downloading and generating Enrichr library gene sets......")
s = retry(5)
# queery string
ENRICHR_URL = 'http://amp.pharm.mssm.edu/Enrichr/geneSetLibrary'
query_string = '?mode=t... | [
"def",
"_download_libraries",
"(",
"self",
",",
"libname",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Downloading and generating Enrichr library gene sets......\"",
")",
"s",
"=",
"retry",
"(",
"5",
")",
"# queery string",
"ENRICHR_URL",
"=",
"'http://am... | 44.5 | 0.00846 |
def deseq2_size_factors(counts, meta, design):
"""
Get size factors for counts using DESeq2.
Parameters
----------
counts : pandas.DataFrame
Counts to pass to DESeq2.
meta : pandas.DataFrame
Pandas dataframe whose index matches the columns of counts. This is
passed to D... | [
"def",
"deseq2_size_factors",
"(",
"counts",
",",
"meta",
",",
"design",
")",
":",
"import",
"rpy2",
".",
"robjects",
"as",
"r",
"from",
"rpy2",
".",
"robjects",
"import",
"pandas2ri",
"pandas2ri",
".",
"activate",
"(",
")",
"r",
".",
"r",
"(",
"'suppres... | 31.135135 | 0.000842 |
def _pop_letters(char_list):
"""Pop consecutive letters from the front of a list and return them
Pops any and all consecutive letters from the start of the provided
character list and returns them as a list of characters. Operates
on (and possibly alters) the passed list
:param list char_list: a l... | [
"def",
"_pop_letters",
"(",
"char_list",
")",
":",
"logger",
".",
"debug",
"(",
"'_pop_letters(%s)'",
",",
"char_list",
")",
"letters",
"=",
"[",
"]",
"while",
"len",
"(",
"char_list",
")",
"!=",
"0",
"and",
"char_list",
"[",
"0",
"]",
".",
"isalpha",
... | 36.666667 | 0.001477 |
def update_pool(self, pool, body=None):
"""Updates a load balancer pool."""
return self.put(self.pool_path % (pool), body=body) | [
"def",
"update_pool",
"(",
"self",
",",
"pool",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"pool_path",
"%",
"(",
"pool",
")",
",",
"body",
"=",
"body",
")"
] | 47 | 0.013986 |
def step(self):
"""Perform a single step of the morphological Chan-Vese evolution."""
# Assign attributes to local variables for convenience.
u = self._u
if u is None:
raise ValueError("the levelset function is not set "
"(use set_levelse... | [
"def",
"step",
"(",
"self",
")",
":",
"# Assign attributes to local variables for convenience.",
"u",
"=",
"self",
".",
"_u",
"if",
"u",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"the levelset function is not set \"",
"\"(use set_levelset)\"",
")",
"data",
"=",... | 31.242424 | 0.009407 |
def render(raw_config, environment=None):
"""Renders a config, using it as a template with the environment.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
st... | [
"def",
"render",
"(",
"raw_config",
",",
"environment",
"=",
"None",
")",
":",
"t",
"=",
"Template",
"(",
"raw_config",
")",
"buff",
"=",
"StringIO",
"(",
")",
"if",
"not",
"environment",
":",
"environment",
"=",
"{",
"}",
"try",
":",
"substituted",
"=... | 29.1875 | 0.001036 |
def archive(cwd, output, rev='tip', fmt=None, prefix=None, user=None):
'''
Export a tarball from the repository
cwd
The path to the Mercurial repository
output
The path to the archive tarball
rev: tip
The revision to create an archive from
fmt: None
Format of ... | [
"def",
"archive",
"(",
"cwd",
",",
"output",
",",
"rev",
"=",
"'tip'",
",",
"fmt",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'archive'",
",",
"'{0}'",
".",
"format",
"(",
"output",... | 24.826087 | 0.000842 |
def scatter2d(data, **kwargs):
"""Create a 2D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, shape=[n_samples, n_features]
Input data. Only the first two components will b... | [
"def",
"scatter2d",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`phate.plot.scatter2d` is deprecated. \"",
"\"Use `scprep.plot.scatter2d` instead.\"",
",",
"FutureWarning",
")",
"data",
"=",
"_get_plot_data",
"(",
"data",
",",
"n... | 47.087302 | 0.00033 |
def get_consensus(block):
"""Calculate a simple consensus sequence for the block."""
from collections import Counter
# Take aligned (non-insert) chars from all rows; transpose
columns = zip(*[[c for c in row['seq'] if not c.islower()]
for row in block['sequences']])
cons_chars =... | [
"def",
"get_consensus",
"(",
"block",
")",
":",
"from",
"collections",
"import",
"Counter",
"# Take aligned (non-insert) chars from all rows; transpose",
"columns",
"=",
"zip",
"(",
"*",
"[",
"[",
"c",
"for",
"c",
"in",
"row",
"[",
"'seq'",
"]",
"if",
"not",
"... | 33.44 | 0.001163 |
def get_modname_from_modpath(module_fpath):
"""
returns importable name from file path
get_modname_from_modpath
Args:
module_fpath (str): module filepath
Returns:
str: modname
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> ... | [
"def",
"get_modname_from_modpath",
"(",
"module_fpath",
")",
":",
"modsubdir_list",
"=",
"get_module_subdir_list",
"(",
"module_fpath",
")",
"modname",
"=",
"'.'",
".",
"join",
"(",
"modsubdir_list",
")",
"modname",
"=",
"modname",
".",
"replace",
"(",
"'.__init__... | 27.333333 | 0.001309 |
def _run_yum_command(cmd, fatal=False):
"""Run an YUM command.
Checks the output and retry if the fatal flag is set to True.
:param: cmd: str: The yum command to run.
:param: fatal: bool: Whether the command's output should be checked and
retried.
"""
env = os.environ.copy()
if fa... | [
"def",
"_run_yum_command",
"(",
"cmd",
",",
"fatal",
"=",
"False",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"fatal",
":",
"retry_count",
"=",
"0",
"result",
"=",
"None",
"# If the command is considered \"fatal\", we need to retr... | 32.4375 | 0.000935 |
def enter_node(self, ir_node):
"""
Enter the given element; keeps track of `cdata`;
subclasses may extend by overriding
"""
this_is_cdata = (isinstance(ir_node, Element)
and ir_node.name in self.cdata_elements)
self.state['is_cdata'] = bool(self.s... | [
"def",
"enter_node",
"(",
"self",
",",
"ir_node",
")",
":",
"this_is_cdata",
"=",
"(",
"isinstance",
"(",
"ir_node",
",",
"Element",
")",
"and",
"ir_node",
".",
"name",
"in",
"self",
".",
"cdata_elements",
")",
"self",
".",
"state",
"[",
"'is_cdata'",
"]... | 43.875 | 0.00838 |
def merge_opt_params(self, method, kargs):
'''Combine existing parameters with extra options supplied from command line
options. Carefully merge special type of parameter if needed.
'''
for key in self.legal_params[method]:
if not hasattr(self.opt, key) or getattr(self.opt, key) is None:
... | [
"def",
"merge_opt_params",
"(",
"self",
",",
"method",
",",
"kargs",
")",
":",
"for",
"key",
"in",
"self",
".",
"legal_params",
"[",
"method",
"]",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"opt",
",",
"key",
")",
"or",
"getattr",
"(",
"self",
... | 37.588235 | 0.00916 |
def alias_tags(tags_list, alias_map):
"""
update tags to new values
Args:
tags_list (list):
alias_map (list): list of 2-tuples with regex, value
Returns:
list: updated tags
CommandLine:
python -m utool.util_tags alias_tags --show
Example:
>>> # DISABLE... | [
"def",
"alias_tags",
"(",
"tags_list",
",",
"alias_map",
")",
":",
"def",
"_alias_dict",
"(",
"tags",
")",
":",
"tags_",
"=",
"[",
"alias_map",
".",
"get",
"(",
"t",
",",
"t",
")",
"for",
"t",
"in",
"tags",
"]",
"return",
"list",
"(",
"set",
"(",
... | 28.214286 | 0.001224 |
def recipe_tree(self, kitchen, recipe):
"""
gets the status of a recipe
:param self: DKCloudAPI
:param kitchen: string
:param recipe: string
:rtype: dict
"""
rc = DKReturnCode()
if kitchen is None or isinstance(kitchen, basestring) is False:
... | [
"def",
"recipe_tree",
"(",
"self",
",",
"kitchen",
",",
"recipe",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"isinstance",
"(",
"kitchen",
",",
"basestring",
")",
"is",
"False",
":",
"rc",
".",
"set",
"(",
"rc... | 39.625 | 0.00154 |
def overlay_mask(self, image, predictions):
"""
Adds the instances contours for each predicted object.
Each label has a different color.
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by the mode... | [
"def",
"overlay_mask",
"(",
"self",
",",
"image",
",",
"predictions",
")",
":",
"masks",
"=",
"predictions",
".",
"get_field",
"(",
"\"mask\"",
")",
".",
"numpy",
"(",
")",
"labels",
"=",
"predictions",
".",
"get_field",
"(",
"\"labels\"",
")",
"colors",
... | 35.52 | 0.002193 |
def getBestTranslation(basedir, lang=None):
"""
Find inside basedir the best translation available.
lang, if defined, should be a list of prefered languages.
It will look for file in the form:
- en-US.qm
- en_US.qm
- en.qm
"""
if not lang:
lang = QtCore.QLocale.system().uiL... | [
"def",
"getBestTranslation",
"(",
"basedir",
",",
"lang",
"=",
"None",
")",
":",
"if",
"not",
"lang",
":",
"lang",
"=",
"QtCore",
".",
"QLocale",
".",
"system",
"(",
")",
".",
"uiLanguages",
"(",
")",
"for",
"l",
"in",
"lang",
":",
"l",
"=",
"l",
... | 23 | 0.009816 |
def make_cell(table, span, widths, heights, use_headers):
"""
Convert the contents of a span of the table to a grid table cell
Parameters
----------
table : list of lists of str
The table of rows containg strings to convert to a grid table
span : list of lists of int
list of [ro... | [
"def",
"make_cell",
"(",
"table",
",",
"span",
",",
"widths",
",",
"heights",
",",
"use_headers",
")",
":",
"width",
"=",
"get_span_char_width",
"(",
"span",
",",
"widths",
")",
"height",
"=",
"get_span_char_height",
"(",
"span",
",",
"heights",
")",
"text... | 26.693548 | 0.000583 |
def build_journals_kb(knowledgebase):
"""Given the path to a knowledge base file, read in the contents
of that file into a dictionary of search->replace word phrases.
The search phrases are compiled into a regex pattern object.
The knowledge base file should consist only of lines that take
... | [
"def",
"build_journals_kb",
"(",
"knowledgebase",
")",
":",
"# Initialise vars:",
"# dictionary of search and replace phrases from KB:",
"kb",
"=",
"{",
"}",
"standardised_titles",
"=",
"{",
"}",
"seek_phrases",
"=",
"[",
"]",
"# A dictionary of \"replacement terms\" (RHS) to... | 44.151899 | 0.001122 |
def _ces_distance_emd(unique_C1, unique_C2):
"""Return the distance between two cause-effect structures.
Uses the generalized EMD.
"""
# Get the pairwise distances between the concepts in the unpartitioned and
# partitioned CESs.
distances = np.array([
[concept_distance(i, j) for j in u... | [
"def",
"_ces_distance_emd",
"(",
"unique_C1",
",",
"unique_C2",
")",
":",
"# Get the pairwise distances between the concepts in the unpartitioned and",
"# partitioned CESs.",
"distances",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"concept_distance",
"(",
"i",
",",
"j",
")... | 46.895522 | 0.000312 |
def dockerCall(*args, **kwargs):
"""
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_call()'. This has since been supplanted and
apiDockerCall() is recommended.
"""
l... | [
"def",
"dockerCall",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"warn",
"(",
"\"WARNING: dockerCall() using subprocess.check_output() \"",
"\"is deprecated, please switch to apiDockerCall().\"",
")",
"return",
"subprocessDockerCall",
"(",
"*",
"ar... | 46.636364 | 0.001912 |
def chebyshev(h1, h2): # 12 us @array, 36 us @list \w 100 bins
r"""
Chebyshev distance.
Also Tchebychev distance, Maximum or :math:`L_{\infty}` metric; equal to Minowski
distance with :math:`p=+\infty`. For the case of :math:`p=-\infty`, use `chebyshev_neg`.
The Chebyshev distance between ... | [
"def",
"chebyshev",
"(",
"h1",
",",
"h2",
")",
":",
"# 12 us @array, 36 us @list \\w 100 bins",
"h1",
",",
"h2",
"=",
"__prepare_histogram",
"(",
"h1",
",",
"h2",
")",
"return",
"max",
"(",
"scipy",
".",
"absolute",
"(",
"h1",
"-",
"h2",
")",
")"
] | 23.615385 | 0.015637 |
def _start_loop(self, websocket, event_handler):
"""
We will listen for websockets events, sending a heartbeat/pong everytime
we react a TimeoutError. If we don't the webserver would close the idle connection,
forcing us to reconnect.
"""
log.debug('Starting websocket loop')
while True:
try:
yield ... | [
"def",
"_start_loop",
"(",
"self",
",",
"websocket",
",",
"event_handler",
")",
":",
"log",
".",
"debug",
"(",
"'Starting websocket loop'",
")",
"while",
"True",
":",
"try",
":",
"yield",
"from",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"_wait_for_messa... | 31.705882 | 0.034234 |
def fill_in_textfield(self, field_name, value):
"""
Fill in the HTML input with given label (recommended), name or id with
the given text.
Supported input types are text, textarea, password, month, time, week,
number, range, email, url, tel and color.
"""
date_field = find_any_field(world.... | [
"def",
"fill_in_textfield",
"(",
"self",
",",
"field_name",
",",
"value",
")",
":",
"date_field",
"=",
"find_any_field",
"(",
"world",
".",
"browser",
",",
"DATE_FIELDS",
",",
"field_name",
")",
"if",
"date_field",
":",
"field",
"=",
"date_field",
"else",
":... | 27.931034 | 0.001193 |
def create_switch(apps, schema_editor):
"""Create the `role_based_access_control` switch if it does not already exist."""
Switch = apps.get_model('waffle', 'Switch')
Switch.objects.update_or_create(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH, defaults={'active': False}) | [
"def",
"create_switch",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Switch",
"=",
"apps",
".",
"get_model",
"(",
"'waffle'",
",",
"'Switch'",
")",
"Switch",
".",
"objects",
".",
"update_or_create",
"(",
"name",
"=",
"ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH",... | 71 | 0.010453 |
def StartRun(self, wait_for_start_event, signal_event, wait_for_write_event):
"""Starts a new run for the given cron job."""
# Signal that the cron thread has started. This way the cron scheduler
# will know that the task is not sitting in a threadpool queue, but is
# actually executing.
wait_for_st... | [
"def",
"StartRun",
"(",
"self",
",",
"wait_for_start_event",
",",
"signal_event",
",",
"wait_for_write_event",
")",
":",
"# Signal that the cron thread has started. This way the cron scheduler",
"# will know that the task is not sitting in a threadpool queue, but is",
"# actually executi... | 44.584615 | 0.008778 |
def post_save_update_cache(sender, instance, created, raw, **kwargs):
"""Update the cache when an instance is created or modified."""
if raw:
return
name = sender.__name__
if name in cached_model_names:
delay_cache = getattr(instance, '_delay_cache', False)
if not delay_cache:
... | [
"def",
"post_save_update_cache",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"raw",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"raw",
":",
"return",
"name",
"=",
"sender",
".",
"__name__",
"if",
"name",
"in",
"cached_model_names",
":",
"delay_cache"... | 43.2 | 0.002268 |
def compare_names(first, second):
"""
Compare two names in complicated, but more error prone way.
Algorithm is using vector comparison.
Example:
>>> compare_names("Franta Putšálek", "ing. Franta Putšálek")
100.0
>>> compare_names("F. Putšálek", "ing. Franta Putšálek")
5... | [
"def",
"compare_names",
"(",
"first",
",",
"second",
")",
":",
"first",
"=",
"name_to_vector",
"(",
"first",
")",
"second",
"=",
"name_to_vector",
"(",
"second",
")",
"zipped",
"=",
"zip",
"(",
"first",
",",
"second",
")",
"if",
"not",
"zipped",
":",
"... | 23.454545 | 0.001241 |
def removeCMSPadding(str, blocksize=AES_blocksize):
'''CMS padding: Remove padding with bytes containing the number of padding bytes '''
try:
pad_len = ord(str[-1]) # last byte contains number of padding bytes
except TypeError:
pad_len = str[-1]
assert pad_len <= blocksize, 'padding error'
assert pad... | [
"def",
"removeCMSPadding",
"(",
"str",
",",
"blocksize",
"=",
"AES_blocksize",
")",
":",
"try",
":",
"pad_len",
"=",
"ord",
"(",
"str",
"[",
"-",
"1",
"]",
")",
"# last byte contains number of padding bytes",
"except",
"TypeError",
":",
"pad_len",
"=",
"str",
... | 37.3 | 0.028796 |
def barrier_layer_thickness(SA, CT):
"""
Compute the thickness of water separating the mixed surface layer from the
thermocline. A more precise definition would be the difference between
mixed layer depth (MLD) calculated from temperature minus the mixed layer
depth calculated using density.
"... | [
"def",
"barrier_layer_thickness",
"(",
"SA",
",",
"CT",
")",
":",
"import",
"gsw",
"sigma_theta",
"=",
"gsw",
".",
"sigma0",
"(",
"SA",
",",
"CT",
")",
"mask",
"=",
"mixed_layer_depth",
"(",
"CT",
")",
"mld",
"=",
"np",
".",
"where",
"(",
"mask",
")"... | 36 | 0.001425 |
def put(self, source, rel_path, metadata=None):
"""Puts to only the first upstream. This is to be symmetric with put_stream."""
return self.upstreams[0].put(source, rel_path, metadata) | [
"def",
"put",
"(",
"self",
",",
"source",
",",
"rel_path",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"self",
".",
"upstreams",
"[",
"0",
"]",
".",
"put",
"(",
"source",
",",
"rel_path",
",",
"metadata",
")"
] | 66 | 0.015 |
def _compute_threshold(self,z=2.0):
"""
m._compute_threshold(z=2.0) -- For Motif objects assembled from a set of sequence,
compute a self.threshold with a z-score based on the distribution
of scores in among the original input... | [
"def",
"_compute_threshold",
"(",
"self",
",",
"z",
"=",
"2.0",
")",
":",
"scoretally",
"=",
"[",
"]",
"for",
"seq",
"in",
"self",
".",
"seqs",
":",
"matches",
",",
"endpoints",
",",
"scores",
"=",
"self",
".",
"scan",
"(",
"seq",
",",
"-",
"100",
... | 46.75 | 0.019231 |
def make_call(id_, lineno, args):
""" This will return an AST node for a function call/array access.
A "call" is just an ID followed by a list of arguments.
E.g. a(4)
- a(4) can be a function call if 'a' is a function
- a(4) can be a string slice if a is a string variable: a$(4)
- a(4) can be a... | [
"def",
"make_call",
"(",
"id_",
",",
"lineno",
",",
"args",
")",
":",
"assert",
"isinstance",
"(",
"args",
",",
"symbols",
".",
"ARGLIST",
")",
"entry",
"=",
"SYMBOL_TABLE",
".",
"access_call",
"(",
"id_",
",",
"lineno",
")",
"if",
"entry",
"is",
"None... | 34.612245 | 0.00172 |
def do_command(self, words):
"""Parse and act upon the command in the list of strings `words`."""
self.output = ''
self._do_command(words)
return self.output | [
"def",
"do_command",
"(",
"self",
",",
"words",
")",
":",
"self",
".",
"output",
"=",
"''",
"self",
".",
"_do_command",
"(",
"words",
")",
"return",
"self",
".",
"output"
] | 37 | 0.010582 |
def return_hdr(self):
"""Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
... | [
"def",
"return_hdr",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"i_annot",
"=",
"self",
".",
"hdr",
"[",
"'label'",
"]",
".",
"index",
"(",
"ANNOT_NAME",
")",
"except",
"ValueError",
":",
"self",
".",
"i_annot",
"=",
"None",
"self",
".",
"smp_in... | 40.196429 | 0.002168 |
def eval_mus_track(
track,
user_estimates,
output_dir=None,
mode='v4',
win=1.0,
hop=1.0
):
"""Compute all bss_eval metrics for the musdb track and estimated signals,
given by a `user_estimates` dict.
Parameters
----------
track : Track
musdb track object loaded using... | [
"def",
"eval_mus_track",
"(",
"track",
",",
"user_estimates",
",",
"output_dir",
"=",
"None",
",",
"mode",
"=",
"'v4'",
",",
"win",
"=",
"1.0",
",",
"hop",
"=",
"1.0",
")",
":",
"audio_estimates",
"=",
"[",
"]",
"audio_reference",
"=",
"[",
"]",
"# mak... | 28.0625 | 0.000239 |
def sql(self, sql, *params):
"""Execure raw SQL."""
self.ops.append(self.migrator.sql(sql, *params)) | [
"def",
"sql",
"(",
"self",
",",
"sql",
",",
"*",
"params",
")",
":",
"self",
".",
"ops",
".",
"append",
"(",
"self",
".",
"migrator",
".",
"sql",
"(",
"sql",
",",
"*",
"params",
")",
")"
] | 38 | 0.017241 |
def get_posts(self, count=10, offset=0, recent=True, tag=None,
user_id=None, include_draft=False):
"""TODO: implement cursors support, if it will be needed.
But for the regular blog, it is overhead and
cost savings are minimal.
"""
query = self._client.que... | [
"def",
"get_posts",
"(",
"self",
",",
"count",
"=",
"10",
",",
"offset",
"=",
"0",
",",
"recent",
"=",
"True",
",",
"tag",
"=",
"None",
",",
"user_id",
"=",
"None",
",",
"include_draft",
"=",
"False",
")",
":",
"query",
"=",
"self",
".",
"_client",... | 31.488372 | 0.002149 |
def datapoint_indices_for_tensor(self, tensor_index):
""" Returns the indices for all datapoints in the given tensor. """
if tensor_index >= self._num_tensors:
raise ValueError('Tensor index %d is greater than the number of tensors (%d)' %(tensor_index, self._num_tensors))
return sel... | [
"def",
"datapoint_indices_for_tensor",
"(",
"self",
",",
"tensor_index",
")",
":",
"if",
"tensor_index",
">=",
"self",
".",
"_num_tensors",
":",
"raise",
"ValueError",
"(",
"'Tensor index %d is greater than the number of tensors (%d)'",
"%",
"(",
"tensor_index",
",",
"s... | 70.4 | 0.011236 |
def parse_socket_info(cls, info):
""" Parse string that is formed like '[address]<:port>' and return corresponding
:class:`.WIPV4ScketInfo` object
:param info: string to parse
:return: WIPV4ScketInfo
"""
info = info.split(':')
if len(info) > 2:
raise ValueError('Incorrect socket info specified')
ad... | [
"def",
"parse_socket_info",
"(",
"cls",
",",
"info",
")",
":",
"info",
"=",
"info",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"info",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Incorrect socket info specified'",
")",
"address",
"=",
"info",... | 31.5 | 0.030837 |
def import_complex_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN complex gateway.
In addition to attributes inherited from Gateway type, complex gateway
has additional attribute default flow (default value... | [
"def",
"import_complex_gateway_to_graph",
"(",
"diagram_graph",
",",
"process_id",
",",
"process_attributes",
",",
"element",
")",
":",
"element_id",
"=",
"element",
".",
"getAttribute",
"(",
"consts",
".",
"Consts",
".",
"id",
")",
"BpmnDiagramGraphImport",
".",
... | 66.75 | 0.00831 |
def set_freq(self, fout, freq):
"""
Sets new output frequency, required parameters are real current frequency at output and new required frequency.
"""
hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers
n1div_tuple = (1,) + tuple(range(2,129,2)) #
fdco_min =... | [
"def",
"set_freq",
"(",
"self",
",",
"fout",
",",
"freq",
")",
":",
"hsdiv_tuple",
"=",
"(",
"4",
",",
"5",
",",
"6",
",",
"7",
",",
"9",
",",
"11",
")",
"# possible dividers",
"n1div_tuple",
"=",
"(",
"1",
",",
")",
"+",
"tuple",
"(",
"range",
... | 43.763158 | 0.009412 |
def _format_list_objects(result):
"""Format list of objects into a table."""
all_keys = set()
for item in result:
all_keys = all_keys.union(item.keys())
all_keys = sorted(all_keys)
table = Table(all_keys)
for item in result:
values = []
for key in all_keys:
... | [
"def",
"_format_list_objects",
"(",
"result",
")",
":",
"all_keys",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"result",
":",
"all_keys",
"=",
"all_keys",
".",
"union",
"(",
"item",
".",
"keys",
"(",
")",
")",
"all_keys",
"=",
"sorted",
"(",
"all_keys"... | 22.157895 | 0.002278 |
def rating_score(obj, user):
"""
Returns the score a user has given an object
"""
if not user.is_authenticated() or not hasattr(obj, '_ratings_field'):
return False
ratings_descriptor = getattr(obj, obj._ratings_field)
try:
rating = ratings_descriptor.get(user=user).score
ex... | [
"def",
"rating_score",
"(",
"obj",
",",
"user",
")",
":",
"if",
"not",
"user",
".",
"is_authenticated",
"(",
")",
"or",
"not",
"hasattr",
"(",
"obj",
",",
"'_ratings_field'",
")",
":",
"return",
"False",
"ratings_descriptor",
"=",
"getattr",
"(",
"obj",
... | 27.928571 | 0.002475 |
def upload_file(self, metadata, filename, signer=None, sign_password=None,
filetype='sdist', pyversion='source', keystore=None):
"""
Upload a release file to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and versio... | [
"def",
"upload_file",
"(",
"self",
",",
"metadata",
",",
"filename",
",",
"signer",
"=",
"None",
",",
"sign_password",
"=",
"None",
",",
"filetype",
"=",
"'sdist'",
",",
"pyversion",
"=",
"'source'",
",",
"keystore",
"=",
"None",
")",
":",
"self",
".",
... | 47.767857 | 0.001099 |
def update_rtc_as_set(self):
"""Syncs RT NLRIs for new and removed RTC_ASes.
This method should be called when a neighbor is added or removed.
"""
# Compute the diffs in RTC_ASes
curr_rtc_as_set = self._neighbors_conf.rtc_as_set
# Always add local AS to RTC AS set
... | [
"def",
"update_rtc_as_set",
"(",
"self",
")",
":",
"# Compute the diffs in RTC_ASes",
"curr_rtc_as_set",
"=",
"self",
".",
"_neighbors_conf",
".",
"rtc_as_set",
"# Always add local AS to RTC AS set",
"curr_rtc_as_set",
".",
"add",
"(",
"self",
".",
"_core_service",
".",
... | 44.434783 | 0.001916 |
def fetch_rrlyrae_fitdata(**kwargs):
"""Fetch data from table 3 of Sesar 2010
This table includes parameters derived from template fits to all the
Sesar 2010 lightcurves.
"""
save_loc = _get_download_or_cache('table3.dat.gz', **kwargs)
dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', ... | [
"def",
"fetch_rrlyrae_fitdata",
"(",
"*",
"*",
"kwargs",
")",
":",
"save_loc",
"=",
"_get_download_or_cache",
"(",
"'table3.dat.gz'",
",",
"*",
"*",
"kwargs",
")",
"dtype",
"=",
"[",
"(",
"'id'",
",",
"'i'",
")",
",",
"(",
"'RA'",
",",
"'f'",
")",
",",... | 36.9375 | 0.00165 |
def pairwise(reference_intervals, reference_labels,
estimated_intervals, estimated_labels,
frame_size=0.1, beta=1.0):
"""Frame-clustering segmentation evaluation by pair-wise agreement.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_inter... | [
"def",
"pairwise",
"(",
"reference_intervals",
",",
"reference_labels",
",",
"estimated_intervals",
",",
"estimated_labels",
",",
"frame_size",
"=",
"0.1",
",",
"beta",
"=",
"1.0",
")",
":",
"validate_structure",
"(",
"reference_intervals",
",",
"reference_labels",
... | 39.210526 | 0.000262 |
def subblocks(a, *ranges):
"""
This function produces a distributed array from a subset of the blocks in
the `a`. The result and `a` will have the same number of dimensions. For
example,
subblocks(a, [0, 1], [2, 4])
will produce a DistArray whose objectids are
[[a.objectids[0, 2], a.... | [
"def",
"subblocks",
"(",
"a",
",",
"*",
"ranges",
")",
":",
"ranges",
"=",
"list",
"(",
"ranges",
")",
"if",
"len",
"(",
"ranges",
")",
"!=",
"a",
".",
"ndim",
":",
"raise",
"Exception",
"(",
"\"sub_blocks expects to receive a number of ranges \"",
"\"equal ... | 50.47619 | 0.000463 |
def append(self, value):
"""Appends an item to the list. Similar to list.append()."""
self._values.append(self._type_checker.CheckValue(value))
if not self._message_listener.dirty:
self._message_listener.Modified() | [
"def",
"append",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_values",
".",
"append",
"(",
"self",
".",
"_type_checker",
".",
"CheckValue",
"(",
"value",
")",
")",
"if",
"not",
"self",
".",
"_message_listener",
".",
"dirty",
":",
"self",
".",
... | 45.6 | 0.008621 |
def rewind(self, count):
"""Rewind index."""
if count > self._index: # pragma: no cover
raise ValueError("Can't rewind past beginning!")
self._index -= count | [
"def",
"rewind",
"(",
"self",
",",
"count",
")",
":",
"if",
"count",
">",
"self",
".",
"_index",
":",
"# pragma: no cover",
"raise",
"ValueError",
"(",
"\"Can't rewind past beginning!\"",
")",
"self",
".",
"_index",
"-=",
"count"
] | 27.142857 | 0.010204 |
def direction_neuron(layer_name, vec, batch=None, x=None, y=None, cossim_pow=0):
"""Visualize a single (x, y) position along the given direction"""
def inner(T):
layer = T(layer_name)
shape = tf.shape(layer)
x_ = shape[1] // 2 if x is None else x
y_ = shape[2] // 2 if y is None else y
if batch i... | [
"def",
"direction_neuron",
"(",
"layer_name",
",",
"vec",
",",
"batch",
"=",
"None",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"cossim_pow",
"=",
"0",
")",
":",
"def",
"inner",
"(",
"T",
")",
":",
"layer",
"=",
"T",
"(",
"layer_name",
")... | 41.083333 | 0.013889 |
def wda(X, y, p=2, reg=1, k=10, solver=None, maxiter=100, verbose=0, P0=None):
"""
Wasserstein Discriminant Analysis [11]_
The function solves the following optimization problem:
.. math::
P = \\text{arg}\min_P \\frac{\\sum_i W(PX^i,PX^i)}{\\sum_{i,j\\neq i} W(PX^i,PX^j)}
where :
- :... | [
"def",
"wda",
"(",
"X",
",",
"y",
",",
"p",
"=",
"2",
",",
"reg",
"=",
"1",
",",
"k",
"=",
"10",
",",
"solver",
"=",
"None",
",",
"maxiter",
"=",
"100",
",",
"verbose",
"=",
"0",
",",
"P0",
"=",
"None",
")",
":",
"# noqa",
"mx",
"=",
"np"... | 28.117021 | 0.000365 |
def source_absent(name):
'''
Ensure an image source is absent on the computenode
name : string
source url
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if name not in __salt__['imgadm.sources']():
# source is absent
... | [
"def",
"source_absent",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"if",
"name",
"not",
"in",
"__salt__",
"[",
"'imgadm.sources'",
"]... | 28.470588 | 0.001998 |
def run(self, data_x):
"""
Run the model with validation data and return costs.
"""
output_vars = self.compute(*data_x)
return self._extract_costs(output_vars) | [
"def",
"run",
"(",
"self",
",",
"data_x",
")",
":",
"output_vars",
"=",
"self",
".",
"compute",
"(",
"*",
"data_x",
")",
"return",
"self",
".",
"_extract_costs",
"(",
"output_vars",
")"
] | 32.333333 | 0.01005 |
def delete_keys(self, fingerprints, secret=False, subkeys=False):
"""Delete a key, or list of keys, from the current keyring.
The keys must be referred to by their full fingerprints for GnuPG to
delete them. If ``secret=True``, the corresponding secret keyring will
be deleted from :obj:... | [
"def",
"delete_keys",
"(",
"self",
",",
"fingerprints",
",",
"secret",
"=",
"False",
",",
"subkeys",
"=",
"False",
")",
":",
"which",
"=",
"'keys'",
"if",
"secret",
":",
"which",
"=",
"'secret-keys'",
"if",
"subkeys",
":",
"which",
"=",
"'secret-and-public... | 40.742857 | 0.002055 |
def get_instance(cls, device):
"""
This is only a slot to store and get already initialized poco instance rather than initializing again. You can
simply pass the ``current device instance`` provided by ``airtest`` to get the AndroidUiautomationPoco instance.
If no such AndroidUiautomatio... | [
"def",
"get_instance",
"(",
"cls",
",",
"device",
")",
":",
"if",
"cls",
".",
"_nuis",
".",
"get",
"(",
"device",
")",
"is",
"None",
":",
"cls",
".",
"_nuis",
"[",
"device",
"]",
"=",
"AndroidUiautomationPoco",
"(",
"device",
")",
"return",
"cls",
".... | 42 | 0.010189 |
def overlay_gateway_name(self, **kwargs):
"""Configure Name of Overlay Gateway on vdx switches
Args:
gw_name: Name of Overlay Gateway
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the overlay gateway config.
... | [
"def",
"overlay_gateway_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"self",
".",
"_callback",
")",
"get_config",
"=",
"kwargs",
".",
"pop",
"(",
"'get'",
",",
"False",
")",
"if",... | 40.1 | 0.000974 |
def get_annotation_entries_by_names(self, url: str, names: Iterable[str]) -> List[NamespaceEntry]:
"""Get annotation entries by URL and names.
:param url: The url of the annotation source
:param names: The names of the annotation entries from the given url's document
"""
annotat... | [
"def",
"get_annotation_entries_by_names",
"(",
"self",
",",
"url",
":",
"str",
",",
"names",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"NamespaceEntry",
"]",
":",
"annotation_filter",
"=",
"and_",
"(",
"Namespace",
".",
"url",
"==",
"url",
... | 60.25 | 0.01227 |
def location_autosuggest(self, **params):
"""
Location Autosuggest Services
Doc URLs:
http://business.skyscanner.net/portal/en-GB/
Documentation/Autosuggest
http://business.skyscanner.net/portal/en-GB/
Documentation/CarHireAutoSuggest
... | [
"def",
"location_autosuggest",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"service_url",
"=",
"\"{url}/{params_path}\"",
".",
"format",
"(",
"url",
"=",
"self",
".",
"LOCATION_AUTOSUGGEST_URL",
",",
"params_path",
"=",
"self",
".",
"_construct_params",
"(",... | 33.451613 | 0.001874 |
def compute_theta(self):
"""Compute theta parameter using Kendall's tau.
On Clayton copula this is :math:`τ = θ/(θ + 2) \\implies θ = 2τ/(1-τ)` with
:math:`θ ∈ (0, ∞)`.
On the corner case of :math:`τ = 1`, a big enough number is returned instead of infinity.
"""
if self... | [
"def",
"compute_theta",
"(",
"self",
")",
":",
"if",
"self",
".",
"tau",
"==",
"1",
":",
"theta",
"=",
"10000",
"else",
":",
"theta",
"=",
"2",
"*",
"self",
".",
"tau",
"/",
"(",
"1",
"-",
"self",
".",
"tau",
")",
"return",
"theta"
] | 28.6 | 0.009029 |
def create_branches(self, left_nodes, right_nodes, threshold,
value, features, node, depth, init=False):
"""
Parse and port a single tree estimator.
Parameters
----------
:param left_nodes : object
The left children node.
:param right_... | [
"def",
"create_branches",
"(",
"self",
",",
"left_nodes",
",",
"right_nodes",
",",
"threshold",
",",
"value",
",",
"features",
",",
"node",
",",
"depth",
",",
"init",
"=",
"False",
")",
":",
"out",
"=",
"''",
"if",
"threshold",
"[",
"node",
"]",
"!=",
... | 36.392857 | 0.001911 |
def to_serialized_field(tensor_info):
"""Convert a `TensorInfo` object into a feature proto object."""
# Select the type
dtype = tensor_info.dtype
# TODO(b/119937875): TF Examples proto only support int64, float32 and string
# This create limitation like float64 downsampled to float32, bool converted
# to ... | [
"def",
"to_serialized_field",
"(",
"tensor_info",
")",
":",
"# Select the type",
"dtype",
"=",
"tensor_info",
".",
"dtype",
"# TODO(b/119937875): TF Examples proto only support int64, float32 and string",
"# This create limitation like float64 downsampled to float32, bool converted",
"# ... | 38.486486 | 0.013014 |
def get_user(user, driver): # noqa: E501
"""Retrieve a user
Retrieve a user # noqa: E501
:param user: Get user with this name
:type user: str
:param driver: The driver to use for the request. ie. github
:type driver: str
:rtype: Response
"""
response = ApitaxResponse()
driv... | [
"def",
"get_user",
"(",
"user",
",",
"driver",
")",
":",
"# noqa: E501",
"response",
"=",
"ApitaxResponse",
"(",
")",
"driver",
":",
"Driver",
"=",
"LoadedDrivers",
".",
"getDriver",
"(",
"driver",
")",
"user",
":",
"User",
"=",
"driver",
".",
"getApitaxUs... | 27.5 | 0.001757 |
def remove_option(file_name, section, option, separator='='):
'''
Remove a key/value pair from a section in an ini file. Returns the value of
the removed key, or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
... | [
"def",
"remove_option",
"(",
"file_name",
",",
"section",
",",
"option",
",",
"separator",
"=",
"'='",
")",
":",
"inifile",
"=",
"_Ini",
".",
"get_ini_file",
"(",
"file_name",
",",
"separator",
"=",
"separator",
")",
"if",
"isinstance",
"(",
"inifile",
"."... | 28.964286 | 0.001193 |
def get_absolute_path(some_path):
"""
This function will return an appropriate absolute path for the path it is
given. If the input is absolute, it will return unmodified; if the input is
relative, it will be rendered as relative to the current working directory.
"""
if os.path.isabs(some_path):... | [
"def",
"get_absolute_path",
"(",
"some_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"some_path",
")",
":",
"return",
"some_path",
"else",
":",
"return",
"evaluate_relative_path",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"some_path",
")"
] | 40.8 | 0.002398 |
def initialize_plot(self, ranges=None):
"""
Plot all the views contained in the AdjointLayout Object using axes
appropriate to the layout configuration. All the axes are
supplied by LayoutPlot - the purpose of the call is to
invoke subplots with correct options and styles and hid... | [
"def",
"initialize_plot",
"(",
"self",
",",
"ranges",
"=",
"None",
")",
":",
"for",
"pos",
"in",
"self",
".",
"view_positions",
":",
"# Pos will be one of 'main', 'top' or 'right' or None",
"view",
"=",
"self",
".",
"layout",
".",
"get",
"(",
"pos",
",",
"None... | 41.904762 | 0.002222 |
def screen_text(
self, text_content_type, text_content, language=None, autocorrect=False, pii=False, list_id=None, classify=False, custom_headers=None, raw=False, callback=None, **operation_config):
"""Detect profanity and match against custom and shared blacklists.
Detects profanity in mor... | [
"def",
"screen_text",
"(",
"self",
",",
"text_content_type",
",",
"text_content",
",",
"language",
"=",
"None",
",",
"autocorrect",
"=",
"False",
",",
"pii",
"=",
"False",
",",
"list_id",
"=",
"None",
",",
"classify",
"=",
"False",
",",
"custom_headers",
"... | 46.162791 | 0.002466 |
def _write_new_messages(po_file_path, trans_writer, meta_writer,
msgids, msgstrs, languages):
"""
Write new msgids which appeared in po files with empty msgstrs values
and metadata. Look for all new msgids which are diffed with msgids list
provided as an argument.
"""
po_... | [
"def",
"_write_new_messages",
"(",
"po_file_path",
",",
"trans_writer",
",",
"meta_writer",
",",
"msgids",
",",
"msgstrs",
",",
"languages",
")",
":",
"po_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"po_file_path",
")",
"po_file",
"=",
"polib",
... | 34.444444 | 0.001046 |
def _write_local_data_files(self, cursor):
"""
Takes a cursor, and writes results to a local file.
:return: A dictionary where keys are filenames to be used as object
names in GCS, and values are file handles to local files that
contain the data for the GCS objects.
... | [
"def",
"_write_local_data_files",
"(",
"self",
",",
"cursor",
")",
":",
"schema",
"=",
"list",
"(",
"map",
"(",
"lambda",
"schema_tuple",
":",
"schema_tuple",
"[",
"0",
"]",
",",
"cursor",
".",
"description",
")",
")",
"col_type_dict",
"=",
"self",
".",
... | 40.517857 | 0.002151 |
def _init_harness(self):
"""Restart harness backend service.
Please start the harness controller before running the cases, otherwise, nothing happens
"""
self._hc = HarnessController(self.result_dir)
self._hc.stop()
time.sleep(1)
self._hc.start()
time.sle... | [
"def",
"_init_harness",
"(",
"self",
")",
":",
"self",
".",
"_hc",
"=",
"HarnessController",
"(",
"self",
".",
"result_dir",
")",
"self",
".",
"_hc",
".",
"stop",
"(",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"self",
".",
"_hc",
".",
"start",
"(",... | 55.363636 | 0.009685 |
def local_batch_predict(model_dir, csv_file_pattern, output_dir, output_format, batch_size=100):
""" Batch Predict with a specified model.
It does batch prediction, saves results to output files and also creates an output
schema file. The output file names are input file names prepended by 'predict_results_'.
... | [
"def",
"local_batch_predict",
"(",
"model_dir",
",",
"csv_file_pattern",
",",
"output_dir",
",",
"output_format",
",",
"batch_size",
"=",
"100",
")",
":",
"file_io",
".",
"recursive_create_dir",
"(",
"output_dir",
")",
"csv_files",
"=",
"file_io",
".",
"get_matchi... | 48.25641 | 0.011458 |
def angles(self, zfill = 3):
"""
Returns the internal angles of all elements and the associated statistics
"""
elements = self.elements.sort_index(axis = 1)
etypes = elements[("type", "argiope")].unique()
out = []
for etype in etypes:
etype_info = ELEMENTS[etype]
angles_info = e... | [
"def",
"angles",
"(",
"self",
",",
"zfill",
"=",
"3",
")",
":",
"elements",
"=",
"self",
".",
"elements",
".",
"sort_index",
"(",
"axis",
"=",
"1",
")",
"etypes",
"=",
"elements",
"[",
"(",
"\"type\"",
",",
"\"argiope\"",
")",
"]",
".",
"unique",
"... | 45.166667 | 0.044695 |
def grade(grader_data,submission):
"""
Grades a specified submission using specified models
grader_data - A dictionary:
{
'model' : trained model,
'extractor' : trained feature extractor,
'prompt' : prompt for the question,
'algorithm' : algorithm for the question,
}
... | [
"def",
"grade",
"(",
"grader_data",
",",
"submission",
")",
":",
"#Initialize result dictionary",
"results",
"=",
"{",
"'errors'",
":",
"[",
"]",
",",
"'tests'",
":",
"[",
"]",
",",
"'score'",
":",
"0",
",",
"'feedback'",
":",
"\"\"",
",",
"'success'",
"... | 34.744186 | 0.013667 |
def display(self, tool):
"""Displays the given tool above the current layer, and sets the
title to its name.
"""
self._tools.append(tool)
self._justDisplay(tool) | [
"def",
"display",
"(",
"self",
",",
"tool",
")",
":",
"self",
".",
"_tools",
".",
"append",
"(",
"tool",
")",
"self",
".",
"_justDisplay",
"(",
"tool",
")"
] | 28 | 0.009901 |
def setFont(self, font):
"""
Sets the font for this widget and propogates down to the buttons.
:param font | <QFont>
"""
super(XSplitButton, self).setFont(font)
self.rebuild() | [
"def",
"setFont",
"(",
"self",
",",
"font",
")",
":",
"super",
"(",
"XSplitButton",
",",
"self",
")",
".",
"setFont",
"(",
"font",
")",
"self",
".",
"rebuild",
"(",
")"
] | 29.625 | 0.012295 |
def _get_keycodes():
"""Read keypress giving a tuple of key codes
A 'key code' is the ordinal value of characters read
For example, pressing 'A' will give (65,)
"""
try:
return _key_cache.pop()
except IndexError:
pass
result = []
terminators = 'ABCDFHPQRS~'
with Ter... | [
"def",
"_get_keycodes",
"(",
")",
":",
"try",
":",
"return",
"_key_cache",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"pass",
"result",
"=",
"[",
"]",
"terminators",
"=",
"'ABCDFHPQRS~'",
"with",
"TerminalContext",
"(",
")",
":",
"code",
"=",
"ge... | 29.193548 | 0.00107 |
def pubticker(self, symbol='btcusd'):
"""Send a request for latest ticker info, return the response."""
url = self.base_url + '/v1/pubticker/' + symbol
return requests.get(url) | [
"def",
"pubticker",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/pubticker/'",
"+",
"symbol",
"return",
"requests",
".",
"get",
"(",
"url",
")"
] | 39.4 | 0.00995 |
def _StartProfiling(self, configuration):
"""Starts profiling.
Args:
configuration (ProfilingConfiguration): profiling configuration.
"""
if not configuration:
return
if configuration.HaveProfileMemoryGuppy():
self._guppy_memory_profiler = profilers.GuppyMemoryProfiler(
... | [
"def",
"_StartProfiling",
"(",
"self",
",",
"configuration",
")",
":",
"if",
"not",
"configuration",
":",
"return",
"if",
"configuration",
".",
"HaveProfileMemoryGuppy",
"(",
")",
":",
"self",
".",
"_guppy_memory_profiler",
"=",
"profilers",
".",
"GuppyMemoryProfi... | 34.641026 | 0.011519 |
def _process_wave_param(self, pval):
"""Process individual model parameter representing wavelength."""
return self._process_generic_param(
pval, self._internal_wave_unit, equivalencies=u.spectral()) | [
"def",
"_process_wave_param",
"(",
"self",
",",
"pval",
")",
":",
"return",
"self",
".",
"_process_generic_param",
"(",
"pval",
",",
"self",
".",
"_internal_wave_unit",
",",
"equivalencies",
"=",
"u",
".",
"spectral",
"(",
")",
")"
] | 55.75 | 0.00885 |
def sub(self, quantity):
"""
Subtracts an angle from the value
"""
newvalue = self._value - quantity
self.set(newvalue.deg) | [
"def",
"sub",
"(",
"self",
",",
"quantity",
")",
":",
"newvalue",
"=",
"self",
".",
"_value",
"-",
"quantity",
"self",
".",
"set",
"(",
"newvalue",
".",
"deg",
")"
] | 26.333333 | 0.01227 |
def to_node(self, exp, schema):
"""
Return a Node that is the root of the parse tree for the the specified
expression.
:param exp: A list that represents a relational algebra expression.
Assumes that this list was generated by pyparsing.
:param schema: A dictionary of re... | [
"def",
"to_node",
"(",
"self",
",",
"exp",
",",
"schema",
")",
":",
"# A relation node.",
"if",
"len",
"(",
"exp",
")",
"==",
"1",
"and",
"isinstance",
"(",
"exp",
"[",
"0",
"]",
",",
"str",
")",
":",
"node",
"=",
"RelationNode",
"(",
"name",
"=",
... | 39.709091 | 0.00134 |
def basic_fc_small():
"""Small fully connected model."""
hparams = common_hparams.basic_params1()
hparams.learning_rate = 0.1
hparams.batch_size = 128
hparams.hidden_size = 256
hparams.num_hidden_layers = 2
hparams.initializer = "uniform_unit_scaling"
hparams.initializer_gain = 1.0
hparams.weight_deca... | [
"def",
"basic_fc_small",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"learning_rate",
"=",
"0.1",
"hparams",
".",
"batch_size",
"=",
"128",
"hparams",
".",
"hidden_size",
"=",
"256",
"hparams",
".",
"num_h... | 29.75 | 0.032609 |
def _check_old_config_root():
"""
Prior versions of keyring would search for the config
in XDG_DATA_HOME, but should probably have been
searching for config in XDG_CONFIG_HOME. If the
config exists in the former but not in the latter,
raise a RuntimeError to force the change.
"""
# disab... | [
"def",
"_check_old_config_root",
"(",
")",
":",
"# disable the check - once is enough and avoids infinite loop",
"globals",
"(",
")",
"[",
"'_check_old_config_root'",
"]",
"=",
"lambda",
":",
"None",
"config_file_new",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_confi... | 52.235294 | 0.001106 |
def trigger(self, source, actions, event_args):
"""
Perform actions as a result of an event listener (TRIGGER)
"""
type = BlockType.TRIGGER
return self.action_block(source, actions, type, event_args=event_args) | [
"def",
"trigger",
"(",
"self",
",",
"source",
",",
"actions",
",",
"event_args",
")",
":",
"type",
"=",
"BlockType",
".",
"TRIGGER",
"return",
"self",
".",
"action_block",
"(",
"source",
",",
"actions",
",",
"type",
",",
"event_args",
"=",
"event_args",
... | 35.833333 | 0.031818 |
def load_recipe(self, recipe):
"""Populates the internal module pool with modules declared in a recipe.
Args:
recipe: Dict, recipe declaring modules to load.
"""
self.recipe = recipe
for module_description in recipe['modules']:
# Combine CLI args with args from the recipe description
... | [
"def",
"load_recipe",
"(",
"self",
",",
"recipe",
")",
":",
"self",
".",
"recipe",
"=",
"recipe",
"for",
"module_description",
"in",
"recipe",
"[",
"'modules'",
"]",
":",
"# Combine CLI args with args from the recipe description",
"module_name",
"=",
"module_descripti... | 38 | 0.010707 |
def get_default_for(prop, value):
""" Ensures complex property types have the correct default values """
prop = prop.strip('_') # Handle alternate props (leading underscores)
val = reduce_value(value) # Filtering of value happens here
if prop in _COMPLEX_LISTS:
return wrap_value(val)
... | [
"def",
"get_default_for",
"(",
"prop",
",",
"value",
")",
":",
"prop",
"=",
"prop",
".",
"strip",
"(",
"'_'",
")",
"# Handle alternate props (leading underscores)",
"val",
"=",
"reduce_value",
"(",
"value",
")",
"# Filtering of value happens here",
"if",
"prop",
"... | 34.75 | 0.002336 |
def set_cookie_if_ok(self, cookie, request):
"""Set a cookie if policy says it's OK to do so."""
self._cookies_lock.acquire()
try:
self._policy._now = self._now = int(time.time())
if self._policy.set_ok(cookie, request):
self.set_cookie(cookie)
... | [
"def",
"set_cookie_if_ok",
"(",
"self",
",",
"cookie",
",",
"request",
")",
":",
"self",
".",
"_cookies_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_policy",
".",
"_now",
"=",
"self",
".",
"_now",
"=",
"int",
"(",
"time",
".",
"time",
... | 29.833333 | 0.00813 |
def _set_id(infos):
'''
ID compatibility hack
return: dict
'''
if infos:
cid = None
if infos.get("Id"): cid = infos["Id"]
elif infos.get("ID"): cid = infos["ID"]
elif infos.get("id"): cid = infos["id"]
if "Id" not in infos:
infos["Id"] = cid
... | [
"def",
"_set_id",
"(",
"infos",
")",
":",
"if",
"infos",
":",
"cid",
"=",
"None",
"if",
"infos",
".",
"get",
"(",
"\"Id\"",
")",
":",
"cid",
"=",
"infos",
"[",
"\"Id\"",
"]",
"elif",
"infos",
".",
"get",
"(",
"\"ID\"",
")",
":",
"cid",
"=",
"in... | 23.375 | 0.015424 |
def _register_file_server(self, app):
"""
File server
Only local files can be served
It's recommended to serve static files through NGINX instead of Python
Use this for development only
:param app: Flask app instance
"""
if isinstance(self.driver, local.L... | [
"def",
"_register_file_server",
"(",
"self",
",",
"app",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"driver",
",",
"local",
".",
"LocalStorageDriver",
")",
"and",
"self",
".",
"config",
"[",
"\"serve_files\"",
"]",
":",
"server_url",
"=",
"self",
".",... | 42.735294 | 0.002019 |
def reorder_levels(self, dim_order=None, inplace=None,
**dim_order_kwargs):
"""Rearrange index levels using input order.
Parameters
----------
dim_order : optional
Mapping from names matching dimensions and values given
by lists representin... | [
"def",
"reorder_levels",
"(",
"self",
",",
"dim_order",
"=",
"None",
",",
"inplace",
"=",
"None",
",",
"*",
"*",
"dim_order_kwargs",
")",
":",
"inplace",
"=",
"_check_inplace",
"(",
"inplace",
")",
"dim_order",
"=",
"either_dict_or_kwargs",
"(",
"dim_order",
... | 42.540541 | 0.001863 |
def enable_vmm_statistics(self, enable):
"""Enables or disables collection of VMM RAM statistics.
in enable of type bool
True enables statistics collection.
raises :class:`VBoxErrorInvalidVmState`
Machine session is not open.
raises :class:`VBoxErrorInv... | [
"def",
"enable_vmm_statistics",
"(",
"self",
",",
"enable",
")",
":",
"if",
"not",
"isinstance",
"(",
"enable",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"enable can only be an instance of type bool\"",
")",
"self",
".",
"_call",
"(",
"\"enableVMMStatist... | 33.823529 | 0.00846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.