text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def serialize_operator_equal(self, op):
"""
Serializer for :meth:`SpiffWorkflow.operators.Equal`.
Example::
<equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
</equ... | [
"def",
"serialize_operator_equal",
"(",
"self",
",",
"op",
")",
":",
"elem",
"=",
"etree",
".",
"Element",
"(",
"'equals'",
")",
"return",
"self",
".",
"serialize_value_list",
"(",
"elem",
",",
"op",
".",
"args",
")"
] | 29.857143 | 15.428571 |
def get_resources_chunk(self, resource_iter, first=None):
"""Return next chunk of resources from resource_iter, and next item.
If first parameter is specified then this will be prepended to
the list.
The chunk will contain self.max_sitemap_entries if the iterator
returns that m... | [
"def",
"get_resources_chunk",
"(",
"self",
",",
"resource_iter",
",",
"first",
"=",
"None",
")",
":",
"chunk",
"=",
"ListBase",
"(",
"md",
"=",
"self",
".",
"md",
".",
"copy",
"(",
")",
",",
"ln",
"=",
"list",
"(",
"self",
".",
"ln",
")",
")",
"c... | 39.692308 | 18.5 |
def competition_submissions(self, competition):
""" get the list of Submission for a particular competition
Parameters
==========
competition: the name of the competition
"""
submissions_result = self.process_response(
self.competitions_submission... | [
"def",
"competition_submissions",
"(",
"self",
",",
"competition",
")",
":",
"submissions_result",
"=",
"self",
".",
"process_response",
"(",
"self",
".",
"competitions_submissions_list_with_http_info",
"(",
"id",
"=",
"competition",
")",
")",
"return",
"[",
"Submis... | 40.8 | 16.2 |
def profile_device_get(name, device_name, remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Get a profile device.
name :
The name of the profile to get the device from.
device_name :
The name of the device to retrieve.
remote_addr... | [
"def",
"profile_device_get",
"(",
"name",
",",
"device_name",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"profile",
"=",
"profile_get",
"(",
"name",
",",
"remote_addr",
"... | 25.098039 | 23.764706 |
def _ParseFiletime(self, byte_stream):
"""Parses a FILETIME date and time value from a byte stream.
Args:
byte_stream (bytes): byte stream.
Returns:
dfdatetime.Filetime: FILETIME date and time value or None if no
value is set.
Raises:
ParseError: if the FILETIME could not ... | [
"def",
"_ParseFiletime",
"(",
"self",
",",
"byte_stream",
")",
":",
"filetime_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'filetime'",
")",
"try",
":",
"filetime",
"=",
"self",
".",
"_ReadStructureFromByteStream",
"(",
"byte_stream",
",",
"0",
",",
"filet... | 28.258065 | 21.322581 |
def add(self, other_op):
"""Combines `other_op` with the operation held by this aggregator.
N.B. It merges the operations log entries and metric values, but makes
the assumption the operation is consistent. It's the callers
responsibility to ensure consistency
Args:
... | [
"def",
"add",
"(",
"self",
",",
"other_op",
")",
":",
"self",
".",
"_op",
".",
"logEntries",
".",
"extend",
"(",
"other_op",
".",
"logEntries",
")",
"self",
".",
"_merge_timestamps",
"(",
"other_op",
")",
"self",
".",
"_merge_metric_values",
"(",
"other_op... | 37.5625 | 20 |
def main():
"""
NAME
dmag_magic2.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag_magic -h [command line options]
INPUT
takes magic formatted magic_measurements.txt files
OPTIONS
-h prints help message and quits
... | [
"def",
"main",
"(",
")",
":",
"FIG",
"=",
"{",
"}",
"# plot dictionary",
"FIG",
"[",
"'demag'",
"]",
"=",
"1",
"# demag is figure 1",
"in_file",
",",
"plot_key",
",",
"LT",
"=",
"'magic_measurements.txt'",
",",
"'er_location_name'",
",",
"\"LT-AF-Z\"",
"XLP",
... | 37.649351 | 16.272727 |
def _calcCTRBUF(self):
"""Calculates one block of CTR keystream"""
self.ctr_cks = self.encrypt(struct.pack("Q", self.ctr_iv)) # keystream block
self.ctr_iv += 1
self.ctr_pos = 0 | [
"def",
"_calcCTRBUF",
"(",
"self",
")",
":",
"self",
".",
"ctr_cks",
"=",
"self",
".",
"encrypt",
"(",
"struct",
".",
"pack",
"(",
"\"Q\"",
",",
"self",
".",
"ctr_iv",
")",
")",
"# keystream block",
"self",
".",
"ctr_iv",
"+=",
"1",
"self",
".",
"ctr... | 41 | 18.8 |
def add_material(self, x_min, x_max, n, angle=0):
'''
Add a refractive index between two x-points.
Args:
x_min (float): The start x-point.
x_max (float): The stop x-point.
n (float, function): Refractive index between
`x_min` and `x_max`. E... | [
"def",
"add_material",
"(",
"self",
",",
"x_min",
",",
"x_max",
",",
"n",
",",
"angle",
"=",
"0",
")",
":",
"self",
".",
"_mat_params",
".",
"append",
"(",
"[",
"x_min",
",",
"x_max",
",",
"n",
",",
"angle",
"]",
")",
"if",
"not",
"callable",
"("... | 41.703704 | 23.259259 |
def getExpInfo(expnum):
"""Return a dictionary of information about a particular exposure"""
col_names=['object',
'e.expnum',
'mjdate',
'uttime',
'filter',
'elongation',
'obs_iq_refccd',
'triple', 'qso_stat... | [
"def",
"getExpInfo",
"(",
"expnum",
")",
":",
"col_names",
"=",
"[",
"'object'",
",",
"'e.expnum'",
",",
"'mjdate'",
",",
"'uttime'",
",",
"'filter'",
",",
"'elongation'",
",",
"'obs_iq_refccd'",
",",
"'triple'",
",",
"'qso_status'",
"]",
"sql",
"=",
"\"SELE... | 27.354839 | 17.290323 |
def resume_scan(self, scan_id, options):
""" Reset the scan status in the scan_table to INIT.
Also, overwrite the options, because a resume task cmd
can add some new option. E.g. exclude hosts list.
Parameters:
scan_id (uuid): Scan ID to identify the scan process to be resume... | [
"def",
"resume_scan",
"(",
"self",
",",
"scan_id",
",",
"options",
")",
":",
"self",
".",
"scans_table",
"[",
"scan_id",
"]",
"[",
"'status'",
"]",
"=",
"ScanStatus",
".",
"INIT",
"if",
"options",
":",
"self",
".",
"scans_table",
"[",
"scan_id",
"]",
"... | 40.35 | 21.3 |
def TODO(message, prefix=True, traceflag=True):
"""
prints an TODO message
:param message: the message
:param prefix: if set to true it prints TODO: as prefix
:param traceflag: if true the stack trace is retrieved and printed
:return:
"""
message = messag... | [
"def",
"TODO",
"(",
"message",
",",
"prefix",
"=",
"True",
",",
"traceflag",
"=",
"True",
")",
":",
"message",
"=",
"message",
"or",
"\"\"",
"if",
"prefix",
":",
"text",
"=",
"\"TODO: \"",
"else",
":",
"text",
"=",
"\"\"",
"if",
"Console",
".",
"colo... | 29.958333 | 16.708333 |
def run_baton_query(self, baton_binary: BatonBinary, program_arguments: List[str]=None, input_data: Any=None) \
-> List[Dict]:
"""
Runs a baton query.
:param baton_binary: the baton binary to use
:param program_arguments: arguments to give to the baton binary
:param i... | [
"def",
"run_baton_query",
"(",
"self",
",",
"baton_binary",
":",
"BatonBinary",
",",
"program_arguments",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"input_data",
":",
"Any",
"=",
"None",
")",
"->",
"List",
"[",
"Dict",
"]",
":",
"if",
"program_argu... | 48.9375 | 28.0625 |
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
... | [
"def",
"wipe",
"(",
"device",
")",
":",
"cmd",
"=",
"'wipefs -a {0}'",
".",
"format",
"(",
"device",
")",
"try",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"except",
"subprocess",
".",
"C... | 22.238095 | 23.47619 |
def filter_table(table, filter_series, ignore=None):
"""
Filter a table based on a set of restrictions given in
Series of column name / filter parameter pairs. The column
names can have suffixes `_min` and `_max` to indicate
"less than" and "greater than" constraints.
Parameters
----------
... | [
"def",
"filter_table",
"(",
"table",
",",
"filter_series",
",",
"ignore",
"=",
"None",
")",
":",
"with",
"log_start_finish",
"(",
"'filter table'",
",",
"logger",
")",
":",
"ignore",
"=",
"ignore",
"if",
"ignore",
"else",
"set",
"(",
")",
"filters",
"=",
... | 36.6 | 18.828571 |
def resampling_scheme(func):
"""Decorator for resampling schemes."""
@functools.wraps(func)
def modif_func(W, M=None):
M = W.shape[0] if M is None else M
return func(W, M)
rs_funcs[func.__name__] = modif_func
modif_func.__doc__ = rs_doc % func.__name__.capitalize()
return modif... | [
"def",
"resampling_scheme",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"modif_func",
"(",
"W",
",",
"M",
"=",
"None",
")",
":",
"M",
"=",
"W",
".",
"shape",
"[",
"0",
"]",
"if",
"M",
"is",
"None",
"else",
"M... | 28.636364 | 15.636364 |
def interlink_removed_content(generator):
'''For all contents removed from generation queue update interlinks
link to the native location
'''
current_lang = generator.settings['DEFAULT_LANG']
for content in _GENERATOR_DB[generator]:
url = _NATIVE_CONTENT_URL_DB[content.source_path]
... | [
"def",
"interlink_removed_content",
"(",
"generator",
")",
":",
"current_lang",
"=",
"generator",
".",
"settings",
"[",
"'DEFAULT_LANG'",
"]",
"for",
"content",
"in",
"_GENERATOR_DB",
"[",
"generator",
"]",
":",
"url",
"=",
"_NATIVE_CONTENT_URL_DB",
"[",
"content"... | 42.4 | 18.8 |
def post(self, uri, data, **kwargs):
"""POST the provided data to the specified path
See :meth:`request` for additional details. The `data` parameter here is
expected to be a string type.
"""
return self.request("POST", uri, data=data, **kwargs) | [
"def",
"post",
"(",
"self",
",",
"uri",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"POST\"",
",",
"uri",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 40.142857 | 15.571429 |
def search(self, ** args):
"""
Checks email inbox every 15 seconds that match the criteria
up until timeout.
Search criteria should be keyword args eg
TO="selenium@gmail.com". See __imap_search docstring for list
of valid criteria. If content_type is not defined, will r... | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"if",
"\"content_type\"",
"not",
"in",
"args",
".",
"keys",
"(",
")",
":",
"content_type",
"=",
"None",
"elif",
"\"HTML\"",
"in",
"args",
"[",
"\"content_type\"",
"]",
":",
"content_type",
... | 35.985294 | 16.161765 |
def array_size(x, axis):
"""Calculate the size of `x` along `axis` dimensions only."""
axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)
return max(numpy.prod(axis_shape), 1) | [
"def",
"array_size",
"(",
"x",
",",
"axis",
")",
":",
"axis_shape",
"=",
"x",
".",
"shape",
"if",
"axis",
"is",
"None",
"else",
"tuple",
"(",
"x",
".",
"shape",
"[",
"a",
"]",
"for",
"a",
"in",
"axis",
")",
"return",
"max",
"(",
"numpy",
".",
"... | 50.25 | 13 |
def predict(self, X, lengths=None):
"""Predict labels/tags for samples X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Feature matrix.
lengths : array-like of integer, shape (n_sequences,), optional
Lengths of sequ... | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"lengths",
"=",
"None",
")",
":",
"X",
"=",
"atleast2d_or_csr",
"(",
"X",
")",
"scores",
"=",
"safe_sparse_dot",
"(",
"X",
",",
"self",
".",
"coef_",
".",
"T",
")",
"if",
"hasattr",
"(",
"self",
",",
... | 35.595238 | 20.452381 |
def get_asset_ids(self):
"""Gets the Ids of any assets associated with this activity.
return: (osid.id.IdList) - list of asset Ids
raise: IllegalState - is_asset_based_activity() is false
compliance: mandatory - This method must be implemented.
"""
if not self.is_asset... | [
"def",
"get_asset_ids",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_asset_based_activity",
"(",
")",
":",
"raise",
"IllegalState",
"(",
")",
"else",
":",
"ids",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"_my_map",
"[",
"'assetIds'",
"]",
... | 33.6 | 16.066667 |
def update_bookmark(self, old, new, *, max_retries=3):
"""
Update a bookmark and check it was successful.
The bookmark matches an existing bookmark `old` according to
bookmark equalitiy and replaces it by `new`. The bookmark
`new` is added if no bookmark matching `old` exists.
... | [
"def",
"update_bookmark",
"(",
"self",
",",
"old",
",",
"new",
",",
"*",
",",
"max_retries",
"=",
"3",
")",
":",
"def",
"replace_bookmark",
"(",
"bookmarks",
",",
"old",
",",
"new",
")",
":",
"modified_bookmarks",
"=",
"list",
"(",
"bookmarks",
")",
"t... | 41 | 19.625 |
def get_offset():
'''
Get current numeric timezone offset from UTC (i.e. -0700)
Returns:
str: Offset from UTC
CLI Example:
.. code-block:: bash
salt '*' timezone.get_offset
'''
# http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and... | [
"def",
"get_offset",
"(",
")",
":",
"# http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/",
"tz_object",
"=",
"pytz",
".",
"timezone",
"(",
"get_zone",
"(",
")",
")",
"utc_time",
"=",
"pytz",
".",
"utc",
... | 29.052632 | 24.631579 |
def static_fit_result(fit_result, v_residual=None,
v_label='Unit-cell volume $(\mathrm{\AA}^3)$',
figsize=(5, 5), height_ratios=(3, 1), ms_data=8,
p_err=None, v_err=None, pdf_filen=None,
title='Fit result'):
"""
plot static ... | [
"def",
"static_fit_result",
"(",
"fit_result",
",",
"v_residual",
"=",
"None",
",",
"v_label",
"=",
"'Unit-cell volume $(\\mathrm{\\AA}^3)$'",
",",
"figsize",
"=",
"(",
"5",
",",
"5",
")",
",",
"height_ratios",
"=",
"(",
"3",
",",
"1",
")",
",",
"ms_data",
... | 44.075949 | 14.607595 |
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, p... | [
"def",
"exists",
"(",
"name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"group_id",
"=",
"None",
")",
"... | 32.055556 | 26.388889 |
def state_blank(self, flag_page=None, **kwargs):
"""
:param flag_page: Flag page content, either a string or a list of BV8s
"""
s = super(SimCGC, self).state_blank(**kwargs) # pylint:disable=invalid-name
# Special stack base for CGC binaries to work with Shellphish CRS
... | [
"def",
"state_blank",
"(",
"self",
",",
"flag_page",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"super",
"(",
"SimCGC",
",",
"self",
")",
".",
"state_blank",
"(",
"*",
"*",
"kwargs",
")",
"# pylint:disable=invalid-name",
"# Special stack bas... | 37.85 | 23.35 |
def try_choice(self, other):
'''(^) Choice with backtrack. This combinator is used whenever arbitrary
look ahead is needed. The parser p || q first applies p, if it success,
the value of p is returned. If p fails, it pretends that it hasn't consumed
any input, and then parser q is tried.... | [
"def",
"try_choice",
"(",
"self",
",",
"other",
")",
":",
"@",
"Parser",
"def",
"try_choice_parser",
"(",
"text",
",",
"index",
")",
":",
"res",
"=",
"self",
"(",
"text",
",",
"index",
")",
"return",
"res",
"if",
"res",
".",
"status",
"else",
"other"... | 46.545455 | 20.909091 |
def setup_GitHub_push(deploy_repo, *, auth_type='deploy_key',
full_key_path='github_deploy_key.enc', require_master=None,
branch_whitelist=None, deploy_branch='gh-pages',
env_name='DOCTR_DEPLOY_ENCRYPTION_KEY', build_tags=False):
"""
Setup the remote to push to GitHub (to be run on Travis).
``a... | [
"def",
"setup_GitHub_push",
"(",
"deploy_repo",
",",
"*",
",",
"auth_type",
"=",
"'deploy_key'",
",",
"full_key_path",
"=",
"'github_deploy_key.enc'",
",",
"require_master",
"=",
"None",
",",
"branch_whitelist",
"=",
"None",
",",
"deploy_branch",
"=",
"'gh-pages'",
... | 43.046512 | 26.139535 |
def msg(message):
"""
Log a regular message
:param message: the message to be logged
"""
to_stdout(" --- {message}".format(message=message))
if _logger:
_logger.info(message) | [
"def",
"msg",
"(",
"message",
")",
":",
"to_stdout",
"(",
"\" --- {message}\"",
".",
"format",
"(",
"message",
"=",
"message",
")",
")",
"if",
"_logger",
":",
"_logger",
".",
"info",
"(",
"message",
")"
] | 22.111111 | 14.777778 |
def _consume_add_and_get_tag(self, consume_rpc_result):
"""Add the tag to the channel and return it.
:param dict consume_rpc_result:
:rtype: str
"""
consumer_tag = consume_rpc_result['consumer_tag']
self._channel.add_consumer_tag(consumer_tag)
return consumer_ta... | [
"def",
"_consume_add_and_get_tag",
"(",
"self",
",",
"consume_rpc_result",
")",
":",
"consumer_tag",
"=",
"consume_rpc_result",
"[",
"'consumer_tag'",
"]",
"self",
".",
"_channel",
".",
"add_consumer_tag",
"(",
"consumer_tag",
")",
"return",
"consumer_tag"
] | 31.2 | 15.9 |
def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned):
"""
Helper method for generic forward checking
Currently, this method acts only when there's a single
unassigned variable.
@param variables: Variables affected by that constraint, in the
... | [
"def",
"forwardCheck",
"(",
"self",
",",
"variables",
",",
"domains",
",",
"assignments",
",",
"_unassigned",
"=",
"Unassigned",
")",
":",
"unassignedvariable",
"=",
"_unassigned",
"for",
"variable",
"in",
"variables",
":",
"if",
"variable",
"not",
"in",
"assi... | 41.925 | 16.775 |
def start_linear_address(eip):
"""Return Start Linear Address Record.
@param eip 32-bit linear address for the EIP register.
@return String representation of Intel Hex SLA record.
"""
b = [4, 0, 0, 0x05, (eip>>24)&0x0FF, (eip>>16)&0x0FF,
(eip>>8)&0x0FF,... | [
"def",
"start_linear_address",
"(",
"eip",
")",
":",
"b",
"=",
"[",
"4",
",",
"0",
",",
"0",
",",
"0x05",
",",
"(",
"eip",
">>",
"24",
")",
"&",
"0x0FF",
",",
"(",
"eip",
">>",
"16",
")",
"&",
"0x0FF",
",",
"(",
"eip",
">>",
"8",
")",
"&",
... | 40 | 14.777778 |
def register_device(ctx, device, model, nickname, client_type):
"""Registers a device instance under an existing device model.
Device instance fields must start with a letter or number. The device ID
can only contain letters, numbers, and the following symbols: period (.),
hyphen (-), underscore (_), a... | [
"def",
"register_device",
"(",
"ctx",
",",
"device",
",",
"model",
",",
"nickname",
",",
"client_type",
")",
":",
"session",
",",
"api_url",
",",
"project_id",
"=",
"build_client_from_context",
"(",
"ctx",
")",
"device_base_url",
"=",
"'/'",
".",
"join",
"("... | 41.828571 | 19.571429 |
def post_event_discounts(self, id, **data):
"""
POST /events/:id/discounts/
Creates a new discount; returns the result as a :format:`discount` as the key ``discount``.
"""
return self.post("/events/{0}/discounts/".format(id), data=data) | [
"def",
"post_event_discounts",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"post",
"(",
"\"/events/{0}/discounts/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | 39.857143 | 18.714286 |
def get_dataset(self, dataset_id, ds_info, out=None):
"""Load a dataset."""
var_path = ds_info.get('file_key', '{}'.format(dataset_id.name))
dtype = ds_info.get('dtype', np.float32)
if var_path + '/shape' not in self:
# loading a scalar value
shape = 1
els... | [
"def",
"get_dataset",
"(",
"self",
",",
"dataset_id",
",",
"ds_info",
",",
"out",
"=",
"None",
")",
":",
"var_path",
"=",
"ds_info",
".",
"get",
"(",
"'file_key'",
",",
"'{}'",
".",
"format",
"(",
"dataset_id",
".",
"name",
")",
")",
"dtype",
"=",
"d... | 39.207547 | 17.415094 |
def teal(theTask, parent=None, loadOnly=False, returnAs="dict",
canExecute=True, strict=False, errorsToTerm=False,
autoClose=True, defaults=False):
# overrides=None):
""" Start the GUI session, or simply load a task's ConfigObj. """
if loadOnly: # this forces returnAs="dict"
obj... | [
"def",
"teal",
"(",
"theTask",
",",
"parent",
"=",
"None",
",",
"loadOnly",
"=",
"False",
",",
"returnAs",
"=",
"\"dict\"",
",",
"canExecute",
"=",
"True",
",",
"strict",
"=",
"False",
",",
"errorsToTerm",
"=",
"False",
",",
"autoClose",
"=",
"True",
"... | 39.491803 | 19.344262 |
def token_chain(text, filters):
"""
Chain several filters after each other, applying filters only on non special class tokens as detected by
{@link ClassifierOptions#isSpecialClassWord(String)}
:param text: String to format
:param filters: Sequence of filters to apply to tokens
... | [
"def",
"token_chain",
"(",
"text",
",",
"filters",
")",
":",
"if",
"filters",
"is",
"None",
":",
"return",
"text",
"sb",
"=",
"\"\"",
"for",
"token",
"in",
"RegexFilters",
".",
"WHITESPACE",
".",
"split",
"(",
"text",
")",
":",
"if",
"not",
"classifier... | 32.8 | 22.1 |
def create_experiment(self, workflow_type, microscope_type, plate_format,
plate_acquisition_mode):
'''Creates the experiment.
Parameters
----------
workflow_type: str
workflow type
microscope_type: str
microscope type
plate_format: int... | [
"def",
"create_experiment",
"(",
"self",
",",
"workflow_type",
",",
"microscope_type",
",",
"plate_format",
",",
"plate_acquisition_mode",
")",
":",
"logger",
".",
"info",
"(",
"'create experiment \"%s\"'",
",",
"self",
".",
"experiment_name",
")",
"content",
"=",
... | 35.069767 | 18.837209 |
def _set_designated_forwarder_hold_time(self, v, load=False):
"""
Setter method for designated_forwarder_hold_time, mapped from YANG variable /cluster/designated_forwarder_hold_time (uint16)
If this variable is read-only (config: false) in the
source YANG file, then _set_designated_forwarder_hold_time i... | [
"def",
"_set_designated_forwarder_hold_time",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
... | 103.409091 | 49.772727 |
def apriori(transactions, **kwargs):
"""
Executes Apriori algorithm and returns a RelationRecord generator.
Arguments:
transactions -- A transaction iterable object
(eg. [['A', 'B'], ['B', 'C']]).
Keyword arguments:
min_support -- The minimum support of relation... | [
"def",
"apriori",
"(",
"transactions",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse the arguments.",
"min_support",
"=",
"kwargs",
".",
"get",
"(",
"'min_support'",
",",
"0.1",
")",
"min_confidence",
"=",
"kwargs",
".",
"get",
"(",
"'min_confidence'",
",",
"0... | 36.74 | 17.78 |
def _parse_signature(stream):
"""See https://tools.ietf.org/html/rfc4880#section-5.2 for details."""
p = {'type': 'signature'}
to_hash = io.BytesIO()
with stream.capture(to_hash):
p['version'] = stream.readfmt('B')
p['sig_type'] = stream.readfmt('B')
p['pubkey_alg'] = stream.rea... | [
"def",
"_parse_signature",
"(",
"stream",
")",
":",
"p",
"=",
"{",
"'type'",
":",
"'signature'",
"}",
"to_hash",
"=",
"io",
".",
"BytesIO",
"(",
")",
"with",
"stream",
".",
"capture",
"(",
"to_hash",
")",
":",
"p",
"[",
"'version'",
"]",
"=",
"stream... | 36.057143 | 17.2 |
def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []):
""" Declares a subfeature.
feature_name: Root feature that is not a subfeature.
value_string: An optional value-string specifying which feature or
subfeature values this subfeature is spe... | [
"def",
"subfeature",
"(",
"feature_name",
",",
"value_string",
",",
"subfeature",
",",
"subvalues",
",",
"attributes",
"=",
"[",
"]",
")",
":",
"parent_feature",
"=",
"validate_feature",
"(",
"feature_name",
")",
"# Add grist to the subfeature name if a value-string was... | 48.392857 | 25.357143 |
def t_DOUBLECOLON(self, t):
r"::"
t.endlexpos = t.lexpos + len(t.value)
return t | [
"def",
"t_DOUBLECOLON",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"endlexpos",
"=",
"t",
".",
"lexpos",
"+",
"len",
"(",
"t",
".",
"value",
")",
"return",
"t"
] | 25.25 | 17.25 |
def add_url_rule(
self,
path: str,
endpoint: Optional[str]=None,
view_func: Optional[Callable]=None,
methods: Optional[Iterable[str]]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=No... | [
"def",
"add_url_rule",
"(",
"self",
",",
"path",
":",
"str",
",",
"endpoint",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"view_func",
":",
"Optional",
"[",
"Callable",
"]",
"=",
"None",
",",
"methods",
":",
"Optional",
"[",
"Iterable",
"[",
... | 34.842105 | 17.894737 |
def derive_key(self,
derivation_method,
derivation_length,
derivation_data=None,
key_material=None,
hash_algorithm=None,
salt=None,
iteration_count=None,
encryption_alg... | [
"def",
"derive_key",
"(",
"self",
",",
"derivation_method",
",",
"derivation_length",
",",
"derivation_data",
"=",
"None",
",",
"key_material",
"=",
"None",
",",
"hash_algorithm",
"=",
"None",
",",
"salt",
"=",
"None",
",",
"iteration_count",
"=",
"None",
",",... | 47 | 18.707865 |
def set_eng_float_format(accuracy=3, use_eng_prefix=False):
"""
Alter default behavior on how float is formatted in DataFrame.
Format float in engineering format. By accuracy, we mean the number of
decimal digits after the floating point.
See also EngFormatter.
"""
set_option("display.floa... | [
"def",
"set_eng_float_format",
"(",
"accuracy",
"=",
"3",
",",
"use_eng_prefix",
"=",
"False",
")",
":",
"set_option",
"(",
"\"display.float_format\"",
",",
"EngFormatter",
"(",
"accuracy",
",",
"use_eng_prefix",
")",
")",
"set_option",
"(",
"\"display.column_space\... | 38.363636 | 21.454545 |
def _prepare_uri(self, service_name, **parameters):
"""Prepare the URI for a request
:param service_name: The target service
:type service_name: str
:param kwargs: query parameters
:return: The uri of the request
"""
query_parameters = []
for key, value i... | [
"def",
"_prepare_uri",
"(",
"self",
",",
"service_name",
",",
"*",
"*",
"parameters",
")",
":",
"query_parameters",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"parameters",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
... | 38.409091 | 14.636364 |
def make_fasta_dna_url(
ensembl_release,
species,
contig,
server=ENSEMBL_FTP_SERVER):
"""
Construct URL to FASTA file with full sequence of a particular chromosome.
Returns server_url/subdir and filename as tuple result.
"""
ensembl_release, species, _ = \
nor... | [
"def",
"make_fasta_dna_url",
"(",
"ensembl_release",
",",
"species",
",",
"contig",
",",
"server",
"=",
"ENSEMBL_FTP_SERVER",
")",
":",
"ensembl_release",
",",
"species",
",",
"_",
"=",
"normalize_release_properties",
"(",
"ensembl_release",
",",
"species",
")",
"... | 33.521739 | 13.956522 |
def createRect(self, x, y, width, height, rx=None, ry=None, strokewidth=1, stroke='black', fill='none'):
"""
Creates a Rectangle
@type x: string or int
@param x: starting x-coordinate
@type y: string or int
@param y: starting y-coordinate
@type width: stri... | [
"def",
"createRect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"rx",
"=",
"None",
",",
"ry",
"=",
"None",
",",
"strokewidth",
"=",
"1",
",",
"stroke",
"=",
"'black'",
",",
"fill",
"=",
"'none'",
")",
":",
"style_dict",
"=... | 52.535714 | 21.035714 |
def get_all_values(self):
"""Returns a list of lists containing all cells' values as strings.
.. note::
Empty trailing rows and columns will not be included.
"""
data = self.spreadsheet.values_get(self.title)
try:
return fill_gaps(data['values'])
... | [
"def",
"get_all_values",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"spreadsheet",
".",
"values_get",
"(",
"self",
".",
"title",
")",
"try",
":",
"return",
"fill_gaps",
"(",
"data",
"[",
"'values'",
"]",
")",
"except",
"KeyError",
":",
"return",
... | 24.857143 | 21.714286 |
def verify(self, tool):
"""
check that the tool exists
"""
if os.path.isfile(tool['file']):
print('Toolbox: program exists = TOK :: ' + tool['file'])
return True
else:
print('Toolbox: program exists = FAIL :: ' + tool['file'])
retu... | [
"def",
"verify",
"(",
"self",
",",
"tool",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"tool",
"[",
"'file'",
"]",
")",
":",
"print",
"(",
"'Toolbox: program exists = TOK :: '",
"+",
"tool",
"[",
"'file'",
"]",
")",
"return",
"True",
"else"... | 31.9 | 14.3 |
def p_cellarray(p):
"""
cellarray : LBRACE RBRACE
| LBRACE expr_list RBRACE
| LBRACE concat_list RBRACE
| LBRACE concat_list SEMI RBRACE
"""
if len(p) == 3:
p[0] = node.cellarray(op="{}", args=node.expr_list())
else:
p[0] = node.cellarray(op=... | [
"def",
"p_cellarray",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"node",
".",
"cellarray",
"(",
"op",
"=",
"\"{}\"",
",",
"args",
"=",
"node",
".",
"expr_list",
"(",
")",
")",
"else",
":",
"p",
... | 29.636364 | 11.090909 |
def delete(self, name):
'''
Delete all the data in a named timeseries.
'''
keys = self._client.keys('%s%s:*'%(self._prefix,name))
pipe = self._client.pipeline(transaction=False)
for key in keys:
pipe.delete( key )
pipe.execute()
# Could be not technically the exact number of keys... | [
"def",
"delete",
"(",
"self",
",",
"name",
")",
":",
"keys",
"=",
"self",
".",
"_client",
".",
"keys",
"(",
"'%s%s:*'",
"%",
"(",
"self",
".",
"_prefix",
",",
"name",
")",
")",
"pipe",
"=",
"self",
".",
"_client",
".",
"pipeline",
"(",
"transaction... | 27.071429 | 23.5 |
def crude_tokenizer(line):
"""This is a very crude tokenizer from pynlpl"""
tokens = []
buffer = ''
for c in line.strip():
if c == ' ' or c in string.punctuation:
if buffer:
tokens.append(buffer)
buffer = ''
else:
buffer += c
if... | [
"def",
"crude_tokenizer",
"(",
"line",
")",
":",
"tokens",
"=",
"[",
"]",
"buffer",
"=",
"''",
"for",
"c",
"in",
"line",
".",
"strip",
"(",
")",
":",
"if",
"c",
"==",
"' '",
"or",
"c",
"in",
"string",
".",
"punctuation",
":",
"if",
"buffer",
":",... | 27.384615 | 14.615385 |
def EnumerateConfig(self, service, path, cache, filter_type=None):
"""Return PamConfigEntries it finds as it recursively follows PAM configs.
Args:
service: A string containing the service name we are processing.
path: A string containing the file path name we want.
cache: A dictionary keyed ... | [
"def",
"EnumerateConfig",
"(",
"self",
",",
"service",
",",
"path",
",",
"cache",
",",
"filter_type",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"external",
"=",
"[",
"]",
"path",
"=",
"self",
".",
"_FixPath",
"(",
"path",
")",
"# Make sure we onl... | 41.575758 | 21.141414 |
def check_status_code(response, verbose):
"""
Shouldn't happen, thanks to the UploadToDeprecatedPyPIDetected
exception, but this is in case that breaks and it does.
"""
if (response.status_code == 410 and
response.url.startswith(("https://pypi.python.org",
... | [
"def",
"check_status_code",
"(",
"response",
",",
"verbose",
")",
":",
"if",
"(",
"response",
".",
"status_code",
"==",
"410",
"and",
"response",
".",
"url",
".",
"startswith",
"(",
"(",
"\"https://pypi.python.org\"",
",",
"\"https://testpypi.python.org\"",
")",
... | 46.884615 | 19.653846 |
def _check_boolean(parameter_name, value, parameter_config):
"""Checks if a boolean value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This checks that the string value passed in can be converted to a valid
boolean value.
Args:
parameter_name: A... | [
"def",
"_check_boolean",
"(",
"parameter_name",
",",
"value",
",",
"parameter_config",
")",
":",
"if",
"parameter_config",
".",
"get",
"(",
"'type'",
")",
"!=",
"'boolean'",
":",
"return",
"if",
"value",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'1'",
"... | 36.740741 | 27.074074 |
def add_output_file(self, filename):
"""
Add filename as a output file for this DAG node.
@param filename: output filename to add
"""
if filename not in self.__output_files:
self.__output_files.append(filename) | [
"def",
"add_output_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"__output_files",
":",
"self",
".",
"__output_files",
".",
"append",
"(",
"filename",
")"
] | 28.75 | 8 |
def treeWidgetChanged(self):
"""Called when this item is added or removed from a tree."""
ParameterItem.treeWidgetChanged(self)
# add all widgets for this item into the tree
if self.widget is not None:
tree = self.treeWidget()
if tree is None:
ret... | [
"def",
"treeWidgetChanged",
"(",
"self",
")",
":",
"ParameterItem",
".",
"treeWidgetChanged",
"(",
"self",
")",
"# add all widgets for this item into the tree",
"if",
"self",
".",
"widget",
"is",
"not",
"None",
":",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
"... | 36.75 | 11.583333 |
def _connect_websocket(self, url, headers, engineio_path):
"""Establish or upgrade to a WebSocket connection with the server."""
if websocket is None: # pragma: no cover
# not installed
self.logger.warning('websocket-client package not installed, only '
... | [
"def",
"_connect_websocket",
"(",
"self",
",",
"url",
",",
"headers",
",",
"engineio_path",
")",
":",
"if",
"websocket",
"is",
"None",
":",
"# pragma: no cover",
"# not installed",
"self",
".",
"logger",
".",
"warning",
"(",
"'websocket-client package not installed,... | 43.510417 | 18.520833 |
def replace_subscription(self, subscription, subscription_id=None):
"""ReplaceSubscription.
Update a subscription. <param name="subscriptionId">ID for a subscription that you wish to update.</param>
:param :class:`<Subscription> <azure.devops.v5_0.service_hooks.models.Subscription>` subscription... | [
"def",
"replace_subscription",
"(",
"self",
",",
"subscription",
",",
"subscription_id",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"subscription_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'subscriptionId'",
"]",
"=",
"self",
".",
... | 60.529412 | 25.235294 |
def row_col_maker(app, fromdocname, all_needs, need_info, need_key, make_ref=False, ref_lookup=False, prefix=''):
"""
Creates and returns a column.
:param app: current sphinx app
:param fromdocname: current document
:param all_needs: Dictionary of all need objects
:param need_info: need_info ob... | [
"def",
"row_col_maker",
"(",
"app",
",",
"fromdocname",
",",
"all_needs",
",",
"need_info",
",",
"need_key",
",",
"make_ref",
"=",
"False",
",",
"ref_lookup",
"=",
"False",
",",
"prefix",
"=",
"''",
")",
":",
"row_col",
"=",
"nodes",
".",
"entry",
"(",
... | 39.819672 | 20.344262 |
def unpickle(pickled_string):
"""Unpickles a string, but raises a unified UnpickleError in case anything
fails.
This is a helper method to not have to deal with the fact that `loads()`
potentially raises many types of exceptions (e.g. AttributeError,
IndexError, TypeError, KeyError, etc.)
"""
... | [
"def",
"unpickle",
"(",
"pickled_string",
")",
":",
"try",
":",
"obj",
"=",
"loads",
"(",
"pickled_string",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"UnpickleError",
"(",
"'Could not unpickle'",
",",
"pickled_string",
",",
"e",
")",
"return",
"ob... | 38.5 | 17.75 |
def cdn_url(request):
"""
A context processor that exposes the full CDN URL in templates.
"""
cdn_url, ssl_url = _get_container_urls(CumulusStorage())
static_url = settings.STATIC_URL
return {
"CDN_URL": cdn_url + static_url,
"CDN_SSL_URL": ssl_url + static_url,
} | [
"def",
"cdn_url",
"(",
"request",
")",
":",
"cdn_url",
",",
"ssl_url",
"=",
"_get_container_urls",
"(",
"CumulusStorage",
"(",
")",
")",
"static_url",
"=",
"settings",
".",
"STATIC_URL",
"return",
"{",
"\"CDN_URL\"",
":",
"cdn_url",
"+",
"static_url",
",",
"... | 27.181818 | 16.090909 |
def get_event_logs(self, request_filter=None, log_limit=20, iterator=True):
"""Returns a list of event logs
Example::
event_mgr = SoftLayer.EventLogManager(env.client)
request_filter = event_mgr.build_filter(date_min="01/01/2019", date_max="02/01/2019")
logs = event... | [
"def",
"get_event_logs",
"(",
"self",
",",
"request_filter",
"=",
"None",
",",
"log_limit",
"=",
"20",
",",
"iterator",
"=",
"True",
")",
":",
"if",
"iterator",
":",
"# Call iter_call directly as this returns the actual generator",
"return",
"self",
".",
"client",
... | 53.136364 | 34.045455 |
def avail_images():
'''
Available images
'''
response = _query('grid', 'image/list')
ret = {}
for item in response['list']:
name = item['friendlyName']
ret[name] = item
return ret | [
"def",
"avail_images",
"(",
")",
":",
"response",
"=",
"_query",
"(",
"'grid'",
",",
"'image/list'",
")",
"ret",
"=",
"{",
"}",
"for",
"item",
"in",
"response",
"[",
"'list'",
"]",
":",
"name",
"=",
"item",
"[",
"'friendlyName'",
"]",
"ret",
"[",
"na... | 17.833333 | 22.666667 |
def is_client(self):
"""Return True if Glances is running in client mode."""
return (self.args.client or self.args.browser) and not self.args.server | [
"def",
"is_client",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"args",
".",
"client",
"or",
"self",
".",
"args",
".",
"browser",
")",
"and",
"not",
"self",
".",
"args",
".",
"server"
] | 54 | 19.666667 |
def yang_modules(self):
"""
Return a list of advertised YANG module names with revisions.
Avoid repeated modules.
"""
res = {}
for c in self.capabilities:
m = c.parameters.get("module")
if m is None or m in res: continue
res[m] = c.par... | [
"def",
"yang_modules",
"(",
"self",
")",
":",
"res",
"=",
"{",
"}",
"for",
"c",
"in",
"self",
".",
"capabilities",
":",
"m",
"=",
"c",
".",
"parameters",
".",
"get",
"(",
"\"module\"",
")",
"if",
"m",
"is",
"None",
"or",
"m",
"in",
"res",
":",
... | 29.916667 | 12.916667 |
def lookup_samecode(self, local, state):
"""Given County, State return the SAME code for specified location. Return False if not found"""
for location in self.samecodes:
if state.lower() == self.samecodes[location]['state'].lower():
if local.lower() == self.samecodes[location... | [
"def",
"lookup_samecode",
"(",
"self",
",",
"local",
",",
"state",
")",
":",
"for",
"location",
"in",
"self",
".",
"samecodes",
":",
"if",
"state",
".",
"lower",
"(",
")",
"==",
"self",
".",
"samecodes",
"[",
"location",
"]",
"[",
"'state'",
"]",
"."... | 58 | 14.857143 |
def create_failover_dns(self, primary_region='us-east-1'):
"""Create dns entries in route53 for multiregion failover setups.
Args:
primary_region (str): primary AWS region for failover
Returns:
Auto-generated DNS name.
"""
dns_record = self.generated.dns(... | [
"def",
"create_failover_dns",
"(",
"self",
",",
"primary_region",
"=",
"'us-east-1'",
")",
":",
"dns_record",
"=",
"self",
".",
"generated",
".",
"dns",
"(",
")",
"[",
"'global'",
"]",
"zone_ids",
"=",
"get_dns_zone_ids",
"(",
"env",
"=",
"self",
".",
"env... | 36.285714 | 21.657143 |
def getTypeByPosition(self, idx):
"""Return ASN.1 type object by its position in fields set.
Parameters
----------
idx: :py:class:`int`
Field index
Returns
-------
:
ASN.1 type
Raises
------
: :class:`~pyasn1.erro... | [
"def",
"getTypeByPosition",
"(",
"self",
",",
"idx",
")",
":",
"try",
":",
"return",
"self",
".",
"__namedTypes",
"[",
"idx",
"]",
".",
"asn1Object",
"except",
"IndexError",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Type position out of range'",
")"
] | 23.347826 | 21.130435 |
def set_string(self, string):
"""Set the working string and its length then reset positions."""
self.string = string
self.length = len(string)
self.reset_position() | [
"def",
"set_string",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"string",
"=",
"string",
"self",
".",
"length",
"=",
"len",
"(",
"string",
")",
"self",
".",
"reset_position",
"(",
")"
] | 38.4 | 8.2 |
def params_to_dict(params, dct):
"""
Updates the 'dct' dictionary with the 'params' dictionary, filtering out
all those whose param value is None.
"""
for param, val in params.items():
if val is None:
continue
dct[param] = val
return dct | [
"def",
"params_to_dict",
"(",
"params",
",",
"dct",
")",
":",
"for",
"param",
",",
"val",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"val",
"is",
"None",
":",
"continue",
"dct",
"[",
"param",
"]",
"=",
"val",
"return",
"dct"
] | 28 | 12.6 |
def default_attributes(self):
"""List of default attributes for the dataset."""
if self._default_attributes is None:
self._default_attributes = {
name: attr
for name, attr in self.attributes.items()
if attr.default is True
}
... | [
"def",
"default_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_default_attributes",
"is",
"None",
":",
"self",
".",
"_default_attributes",
"=",
"{",
"name",
":",
"attr",
"for",
"name",
",",
"attr",
"in",
"self",
".",
"attributes",
".",
"items",
... | 38.222222 | 8.333333 |
def _parse_field_text(field, conf, creds):
"""
Return form field value from 3 options:
1. If value key is present, render it as a Jinja2 template.
The template has access to ``conf`` and ``creds`` dictionaries.
2. If creds key is present, use it as a dot-delimited path
... | [
"def",
"_parse_field_text",
"(",
"field",
",",
"conf",
",",
"creds",
")",
":",
"value",
"=",
"field",
".",
"get",
"(",
"'value'",
")",
"if",
"value",
":",
"template",
"=",
"Template",
"(",
"value",
")",
"return",
"template",
".",
"render",
"(",
"conf",... | 35.166667 | 12.416667 |
def close(self):
"""
Same as disconnect, but not a coroutine, i.e. it does not wait
for disconnect to finish.
"""
if self._state == ConnectionState.DISCONNECTED:
return
self._set_state(ConnectionState.DISCONNECTING)
logger.info('%s Disconnect... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"ConnectionState",
".",
"DISCONNECTED",
":",
"return",
"self",
".",
"_set_state",
"(",
"ConnectionState",
".",
"DISCONNECTING",
")",
"logger",
".",
"info",
"(",
"'%s Disconnecting...'",
... | 30.428571 | 17.714286 |
def split(self, spike_ids=None, spike_clusters_rel=0):
"""Split the selected spikes."""
if spike_ids is None:
spike_ids = self.emit('request_split', single=True)
spike_ids = np.asarray(spike_ids, dtype=np.int64)
assert spike_ids.dtype == np.int64
assert sp... | [
"def",
"split",
"(",
"self",
",",
"spike_ids",
"=",
"None",
",",
"spike_clusters_rel",
"=",
"0",
")",
":",
"if",
"spike_ids",
"is",
"None",
":",
"spike_ids",
"=",
"self",
".",
"emit",
"(",
"'request_split'",
",",
"single",
"=",
"True",
")",
"spike_ids",
... | 47.125 | 13.25 |
def use_tsig(self, keyring, keyname=None, fudge=300,
original_id=None, tsig_error=0, other_data='',
algorithm=dns.tsig.default_algorithm):
"""When sending, a TSIG signature using the specified keyring
and keyname should be added.
@param keyring: The TSIG keyrin... | [
"def",
"use_tsig",
"(",
"self",
",",
"keyring",
",",
"keyname",
"=",
"None",
",",
"fudge",
"=",
"300",
",",
"original_id",
"=",
"None",
",",
"tsig_error",
"=",
"0",
",",
"other_data",
"=",
"''",
",",
"algorithm",
"=",
"dns",
".",
"tsig",
".",
"defaul... | 43.357143 | 16.071429 |
def get(self):
"""Returns the Mlag configuration as a resource dict
Returns:
dict: A dict ojbect containing the Mlag resource attributes.
"""
resource = dict()
resource.update(self._parse_config())
resource.update(self._parse_interfaces())
return res... | [
"def",
"get",
"(",
"self",
")",
":",
"resource",
"=",
"dict",
"(",
")",
"resource",
".",
"update",
"(",
"self",
".",
"_parse_config",
"(",
")",
")",
"resource",
".",
"update",
"(",
"self",
".",
"_parse_interfaces",
"(",
")",
")",
"return",
"resource"
] | 28.636364 | 18.909091 |
def get_public_url(self, doc_id, branch='master'):
"""Returns a GitHub URL for the doc in question (study, collection, ...)
"""
name, path_frag = self.get_repo_and_path_fragment(doc_id)
return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag | [
"def",
"get_public_url",
"(",
"self",
",",
"doc_id",
",",
"branch",
"=",
"'master'",
")",
":",
"name",
",",
"path_frag",
"=",
"self",
".",
"get_repo_and_path_fragment",
"(",
"doc_id",
")",
"return",
"'https://raw.githubusercontent.com/OpenTreeOfLife/'",
"+",
"name",... | 62.4 | 20.2 |
def init_defaults(self):
"""Initializes important headers to default values, if not already specified.
The WARC-Record-ID header is set to a newly generated UUID.
The WARC-Date header is set to the current datetime.
The Content-Type is set based on the WARC-Type header.
... | [
"def",
"init_defaults",
"(",
"self",
")",
":",
"if",
"\"WARC-Record-ID\"",
"not",
"in",
"self",
":",
"self",
"[",
"'WARC-Record-ID'",
"]",
"=",
"\"<urn:uuid:%s>\"",
"%",
"uuid",
".",
"uuid1",
"(",
")",
"if",
"\"WARC-Date\"",
"not",
"in",
"self",
":",
"self... | 52.5 | 19.214286 |
async def handle_post_request(self, environ):
"""Handle a long-polling POST request from the client."""
length = int(environ.get('CONTENT_LENGTH', '0'))
if length > self.server.max_http_buffer_size:
raise exceptions.ContentTooLongError()
else:
body = await environ... | [
"async",
"def",
"handle_post_request",
"(",
"self",
",",
"environ",
")",
":",
"length",
"=",
"int",
"(",
"environ",
".",
"get",
"(",
"'CONTENT_LENGTH'",
",",
"'0'",
")",
")",
"if",
"length",
">",
"self",
".",
"server",
".",
"max_http_buffer_size",
":",
"... | 46.6 | 11.1 |
def _timestamp_regulator(self):
"""
Makes a dictionary whose keys are audio file basenames and whose
values are a list of word blocks from unregulated timestamps and
updates the main timestamp attribute. After all done, purges
unregulated ones.
In case the audio file was ... | [
"def",
"_timestamp_regulator",
"(",
"self",
")",
":",
"unified_timestamps",
"=",
"_PrettyDefaultDict",
"(",
"list",
")",
"staged_files",
"=",
"self",
".",
"_list_audio_files",
"(",
"sub_dir",
"=",
"\"staging\"",
")",
"for",
"timestamp_basename",
"in",
"self",
".",... | 53.186441 | 19.830508 |
def brotli(f, *args, **kwargs):
"""Brotli Flask Response Decorator"""
data = f(*args, **kwargs)
if isinstance(data, Response):
content = data.data
else:
content = data
deflated_data = _brotli.compress(content)
if isinstance(data, Response):
data.data = deflated_data
... | [
"def",
"brotli",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"data",
",",
"Response",
")",
":",
"content",
"=",
"data",
".",
"data",
... | 22.75 | 20.5 |
def length(self):
"""
Calculate total length of the polyline
:return: total length in meters
:rtype: float
"""
total_length = 0
for location_a, location_b in zip(
self.locations[:-1], self.locations[1:]):
total_length += Line(location_... | [
"def",
"length",
"(",
"self",
")",
":",
"total_length",
"=",
"0",
"for",
"location_a",
",",
"location_b",
"in",
"zip",
"(",
"self",
".",
"locations",
"[",
":",
"-",
"1",
"]",
",",
"self",
".",
"locations",
"[",
"1",
":",
"]",
")",
":",
"total_lengt... | 29.833333 | 13.333333 |
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
... | [
"def",
"addBinding",
"(",
"self",
",",
"node",
",",
"value",
")",
":",
"# assert value.source in (node, node.parent):",
"for",
"scope",
"in",
"self",
".",
"scopeStack",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"value",
".",
"name",
"in",
"scope",
":",
"b... | 45.560976 | 22.536585 |
def hasChildren(self, index):
'''Return if *index* has children.'''
sourceModel = self.sourceModel()
if not sourceModel:
return False
return sourceModel.hasChildren(self.mapToSource(index)) | [
"def",
"hasChildren",
"(",
"self",
",",
"index",
")",
":",
"sourceModel",
"=",
"self",
".",
"sourceModel",
"(",
")",
"if",
"not",
"sourceModel",
":",
"return",
"False",
"return",
"sourceModel",
".",
"hasChildren",
"(",
"self",
".",
"mapToSource",
"(",
"ind... | 28.5 | 18.5 |
def set_placeholder_dropdown(cls, input_el):
"""
Set the element to show the multiple choice text.
"""
text = cls.get_placeholder_text(input_el)
cls.set_placeholder_text(
input_el=input_el,
text=text + cls._dropdown_text
) | [
"def",
"set_placeholder_dropdown",
"(",
"cls",
",",
"input_el",
")",
":",
"text",
"=",
"cls",
".",
"get_placeholder_text",
"(",
"input_el",
")",
"cls",
".",
"set_placeholder_text",
"(",
"input_el",
"=",
"input_el",
",",
"text",
"=",
"text",
"+",
"cls",
".",
... | 31.777778 | 8.888889 |
def get_template_dirs(self):
"""
Get templates directory from apps, but in reversed order, so the same named template
file will be overrided by latter defined app
"""
def if_not_empty(dir):
if not os.path.exists(dir):
return
for root, dirs,... | [
"def",
"get_template_dirs",
"(",
"self",
")",
":",
"def",
"if_not_empty",
"(",
"dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir",
")",
":",
"return",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
... | 36.931034 | 13.62069 |
def match_criterion(self, tag):
'''Override. Determine if a tag has the desired name and kind attribute
value.
Args:
tag: A BeautifulSoup Tag.
Returns:
True if tag has the desired name and kind, otherwise False.
'''
return tag.name == self.refere... | [
"def",
"match_criterion",
"(",
"self",
",",
"tag",
")",
":",
"return",
"tag",
".",
"name",
"==",
"self",
".",
"reference_tag_name",
"and",
"tag",
".",
"attrs",
".",
"get",
"(",
"'kind'",
",",
"''",
")",
"==",
"self",
".",
"reference_tag_kind"
] | 32.666667 | 25.666667 |
def get_cached_zone_variable(self, zone_id, variable, default=None):
""" Retrieve the current value of a zone variable from the cache or
return the default value if the variable is not present. """
try:
return self._retrieve_cached_zone_variable(zone_id, variable)
except Unc... | [
"def",
"get_cached_zone_variable",
"(",
"self",
",",
"zone_id",
",",
"variable",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_retrieve_cached_zone_variable",
"(",
"zone_id",
",",
"variable",
")",
"except",
"UncachedVariable",
":",
... | 44.25 | 18.875 |
def get_encoder_component(name,
input_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
... | [
"def",
"get_encoder_component",
"(",
"name",
",",
"input_layer",
",",
"head_num",
",",
"hidden_dim",
",",
"attention_activation",
"=",
"None",
",",
"feed_forward_activation",
"=",
"'relu'",
",",
"dropout_rate",
"=",
"0.0",
",",
"trainable",
"=",
"True",
")",
":"... | 36.5625 | 11.708333 |
def essl(lw):
"""ESS (Effective sample size) computed from log-weights.
Parameters
----------
lw: (N,) ndarray
log-weights
Returns
-------
float
the ESS of weights w = exp(lw), i.e. the quantity
sum(w**2) / (sum(w))**2
Note
----
The ESS is a popula... | [
"def",
"essl",
"(",
"lw",
")",
":",
"w",
"=",
"np",
".",
"exp",
"(",
"lw",
"-",
"lw",
".",
"max",
"(",
")",
")",
"return",
"(",
"w",
".",
"sum",
"(",
")",
")",
"**",
"2",
"/",
"np",
".",
"sum",
"(",
"w",
"**",
"2",
")"
] | 24 | 23.826087 |
def save_object(self, obj):
"""Save an object with Discipline
Only argument is a Django object. This function saves the object
(regardless of whether it already exists or not) and registers with
Discipline, creating a new Action object. Do not use obj.save()!
"""
obj.sav... | [
"def",
"save_object",
"(",
"self",
",",
"obj",
")",
":",
"obj",
".",
"save",
"(",
")",
"try",
":",
"save_object",
"(",
"obj",
",",
"editor",
"=",
"self",
")",
"except",
"DisciplineException",
":",
"pass"
] | 35 | 19.333333 |
def rotate_bitmap_to_root(bitmap, chord_root):
"""Circularly shift a relative bitmap to its asbolute pitch classes.
For clarity, the best explanation is an example. Given 'G:Maj', the root
and quality map are as follows::
root=5
quality=[1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0] # Relative chor... | [
"def",
"rotate_bitmap_to_root",
"(",
"bitmap",
",",
"chord_root",
")",
":",
"bitmap",
"=",
"np",
".",
"asarray",
"(",
"bitmap",
")",
"assert",
"bitmap",
".",
"ndim",
"==",
"1",
",",
"\"Currently only 1D bitmaps are supported.\"",
"idxs",
"=",
"list",
"(",
"np"... | 30.818182 | 20.909091 |
def GetEvents(self):
"""Retrieves the events.
Yield:
EventObject: event.
"""
for event in self._GetAttributeContainers('event'):
if hasattr(event, 'event_data_row_identifier'):
event_data_identifier = identifiers.SQLTableIdentifier(
'event_data', event.event_data_row_ide... | [
"def",
"GetEvents",
"(",
"self",
")",
":",
"for",
"event",
"in",
"self",
".",
"_GetAttributeContainers",
"(",
"'event'",
")",
":",
"if",
"hasattr",
"(",
"event",
",",
"'event_data_row_identifier'",
")",
":",
"event_data_identifier",
"=",
"identifiers",
".",
"S... | 29.2 | 19.933333 |
def get_text(self, position_from, position_to):
"""
Return text between *position_from* and *position_to*
Positions may be positions or 'sol', 'eol', 'sof', 'eof' or 'cursor'
"""
cursor = self.__select_text(position_from, position_to)
text = to_text_string(cursor.se... | [
"def",
"get_text",
"(",
"self",
",",
"position_from",
",",
"position_to",
")",
":",
"cursor",
"=",
"self",
".",
"__select_text",
"(",
"position_from",
",",
"position_to",
")",
"text",
"=",
"to_text_string",
"(",
"cursor",
".",
"selectedText",
"(",
")",
")",
... | 42.642857 | 12.642857 |
def _wrap_layer(name, input_layer, build_func, dropout_rate=0.0, trainable=True):
"""Wrap layers with residual, normalization and dropout.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param build_func: A callable that takes the input tensor and generates the outpu... | [
"def",
"_wrap_layer",
"(",
"name",
",",
"input_layer",
",",
"build_func",
",",
"dropout_rate",
"=",
"0.0",
",",
"trainable",
"=",
"True",
")",
":",
"build_output",
"=",
"build_func",
"(",
"input_layer",
")",
"if",
"dropout_rate",
">",
"0.0",
":",
"dropout_la... | 38.076923 | 14.807692 |
def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> fro... | [
"def",
"docx_extraction",
"(",
"docx",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"docx",
"=",
"docx_preprocess",
"(",
"docx",
",",
"batch",
"=",... | 37.1 | 23.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.