text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def help_center_category_translation_create(self, category_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#create-translation"
api_path = "/api/v2/help_center/categories/{category_id}/translations.json"
api_path = api_path.format(category_id=category_id... | [
"def",
"help_center_category_translation_create",
"(",
"self",
",",
"category_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/categories/{category_id}/translations.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"ca... | 77.6 | 0.010204 |
def func_globals_inject(func, **overrides):
'''
Override specific variables within a function's global context.
'''
# recognize methods
if hasattr(func, 'im_func'):
func = func.__func__
# Get a reference to the function globals dictionary
func_globals = func.__globals__
# Save t... | [
"def",
"func_globals_inject",
"(",
"func",
",",
"*",
"*",
"overrides",
")",
":",
"# recognize methods",
"if",
"hasattr",
"(",
"func",
",",
"'im_func'",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"# Get a reference to the function globals dictionary",
"func_glob... | 31.676471 | 0.000901 |
def _plot2d(plotfunc):
"""
Decorator for common 2d plotting logic
Also adds the 2d plot method to class _PlotMethods
"""
commondoc = """
Parameters
----------
darray : DataArray
Must be 2 dimensional, unless creating faceted plots
x : string, optional
Coordinate for ... | [
"def",
"_plot2d",
"(",
"plotfunc",
")",
":",
"commondoc",
"=",
"\"\"\"\n Parameters\n ----------\n darray : DataArray\n Must be 2 dimensional, unless creating faceted plots\n x : string, optional\n Coordinate for x axis. If None use darray.dims[1]\n y : string, optional\... | 46.003509 | 0.000075 |
def call(self, tokens, *args, **kwargs):
"""Add args and kwargs to the tokens.
"""
tokens.append([evaluate, [args, kwargs], {}])
return tokens | [
"def",
"call",
"(",
"self",
",",
"tokens",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tokens",
".",
"append",
"(",
"[",
"evaluate",
",",
"[",
"args",
",",
"kwargs",
"]",
",",
"{",
"}",
"]",
")",
"return",
"tokens"
] | 34 | 0.011494 |
def cltext(fname):
"""
Internal undocumented command for closing a text file opened by RDTEXT.
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, rdtext.f::
C$Procedure CLTEXT ( Close a text file opened by RDTEXT)
ENTRY CLTEXT ( FILE )
CHARACTER*(... | [
"def",
"cltext",
"(",
"fname",
")",
":",
"fnameP",
"=",
"stypes",
".",
"stringToCharP",
"(",
"fname",
")",
"fname_len",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"fname",
")",
")",
"libspice",
".",
"cltext_",
"(",
"fnameP",
",",
"fname_len",
")"
] | 31.148148 | 0.002307 |
def set_data(self, xs=None, ys=None, zs=None, colors=None):
'''Update the mesh data.
Parameters
----------
xs : ndarray | None
A 2d array of x coordinates for the vertices of the mesh.
ys : ndarray | None
A 2d array of y coordinates for the vertices of th... | [
"def",
"set_data",
"(",
"self",
",",
"xs",
"=",
"None",
",",
"ys",
"=",
"None",
",",
"zs",
"=",
"None",
",",
"colors",
"=",
"None",
")",
":",
"if",
"xs",
"is",
"None",
":",
"xs",
"=",
"self",
".",
"_xs",
"self",
".",
"__vertices",
"=",
"None",
... | 32.711111 | 0.001319 |
def get_scores(self, *args):
'''
In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores
'''
if self.tdf_ is None:
raise Exception("Use set_category_name('category name', ['not category name', ...]) " +
... | [
"def",
"get_scores",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"tdf_",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Use set_category_name('category name', ['not category name', ...]) \"",
"+",
"\"to set the category of interest\"",
")",
"avgdl",
... | 26.96875 | 0.033557 |
def getDownloadUrls(self):
"""Return a list of the urls to download from"""
data = self.searchIndex(False)
fileUrls = []
for datum in data:
fileUrl = self.formatDownloadUrl(datum[0])
fileUrls.append(fileUrl)
return fileUrls | [
"def",
"getDownloadUrls",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"searchIndex",
"(",
"False",
")",
"fileUrls",
"=",
"[",
"]",
"for",
"datum",
"in",
"data",
":",
"fileUrl",
"=",
"self",
".",
"formatDownloadUrl",
"(",
"datum",
"[",
"0",
"]",
... | 29 | 0.037657 |
def print_boggle(board):
"Print the board in a 2-d array."
n2 = len(board); n = exact_sqrt(n2)
for i in range(n2):
if i % n == 0 and i > 0: print
if board[i] == 'Q': print 'Qu',
else: print str(board[i]) + ' ',
print | [
"def",
"print_boggle",
"(",
"board",
")",
":",
"n2",
"=",
"len",
"(",
"board",
")",
"n",
"=",
"exact_sqrt",
"(",
"n2",
")",
"for",
"i",
"in",
"range",
"(",
"n2",
")",
":",
"if",
"i",
"%",
"n",
"==",
"0",
"and",
"i",
">",
"0",
":",
"print",
... | 31.125 | 0.019531 |
def breslauer_corrections(seq, pars_error):
'''Sum corrections for Breslauer '84 method.
:param seq: sequence for which to calculate corrections.
:type seq: str
:param pars_error: dictionary of error corrections
:type pars_error: dict
:returns: Corrected delta_H and delta_S parameters
:rtyp... | [
"def",
"breslauer_corrections",
"(",
"seq",
",",
"pars_error",
")",
":",
"deltas_corr",
"=",
"[",
"0",
",",
"0",
"]",
"contains_gc",
"=",
"'G'",
"in",
"str",
"(",
"seq",
")",
"or",
"'C'",
"in",
"str",
"(",
"seq",
")",
"only_at",
"=",
"str",
"(",
"s... | 37.481481 | 0.000963 |
def get_worker(*queue_names, **kwargs):
"""
Returns a RQ worker for all queues or specified ones.
"""
job_class = get_job_class(kwargs.pop('job_class', None))
queue_class = kwargs.pop('queue_class', None)
queues = get_queues(*queue_names, **{'job_class': job_class,
... | [
"def",
"get_worker",
"(",
"*",
"queue_names",
",",
"*",
"*",
"kwargs",
")",
":",
"job_class",
"=",
"get_job_class",
"(",
"kwargs",
".",
"pop",
"(",
"'job_class'",
",",
"None",
")",
")",
"queue_class",
"=",
"kwargs",
".",
"pop",
"(",
"'queue_class'",
",",... | 47.058824 | 0.001225 |
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1'):
""" Signs `s' with passphrase `passphrase' """
if isinstance(s, six.text_type):
raise ValueError("Encode `s` to a bytestring yourself to" +
" prevent problems with different default encodings")
curve = Curve... | [
"def",
"sign",
"(",
"s",
",",
"passphrase",
",",
"sig_format",
"=",
"SER_COMPACT",
",",
"curve",
"=",
"'secp160r1'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"ValueError",
"(",
"\"Encode `s` to a bytestring you... | 55.75 | 0.002208 |
def has_known_servers(self):
"""Whether there are any Servers of types besides Unknown."""
return any(s for s in self._server_descriptions.values()
if s.is_server_type_known) | [
"def",
"has_known_servers",
"(",
"self",
")",
":",
"return",
"any",
"(",
"s",
"for",
"s",
"in",
"self",
".",
"_server_descriptions",
".",
"values",
"(",
")",
"if",
"s",
".",
"is_server_type_known",
")"
] | 51.5 | 0.009569 |
def _apply_theme(self):
"""
Apply theme attributes to Matplotlib objects
"""
self.theme.apply_axs(self.axs)
self.theme.apply_figure(self.figure) | [
"def",
"_apply_theme",
"(",
"self",
")",
":",
"self",
".",
"theme",
".",
"apply_axs",
"(",
"self",
".",
"axs",
")",
"self",
".",
"theme",
".",
"apply_figure",
"(",
"self",
".",
"figure",
")"
] | 29.833333 | 0.01087 |
def show(self):
"""Publish HTML."""
IPython.display.display(IPython.display.HTML(self.as_html())) | [
"def",
"show",
"(",
"self",
")",
":",
"IPython",
".",
"display",
".",
"display",
"(",
"IPython",
".",
"display",
".",
"HTML",
"(",
"self",
".",
"as_html",
"(",
")",
")",
")"
] | 37 | 0.017699 |
def plot_alpha_returns(alpha_returns, ax=None):
"""
Plot histogram of daily multi-factor alpha returns (specific returns).
Parameters
----------
alpha_returns : pd.Series
series of daily alpha returns indexed by datetime
ax : matplotlib.axes.Axes
axes on which plots are made. ... | [
"def",
"plot_alpha_returns",
"(",
"alpha_returns",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"ax",
".",
"hist",
"(",
"alpha_returns",
",",
"color",
"=",
"'g'",
",",
"label",
"=",
"'Mult... | 26.392857 | 0.001305 |
def fetchChildren(self):
""" Fetches children.
The actual work is done by _fetchAllChildren. Descendant classes should typically
override that method instead of this one.
"""
assert self._canFetchChildren, "canFetchChildren must be True"
try:
childIte... | [
"def",
"fetchChildren",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_canFetchChildren",
",",
"\"canFetchChildren must be True\"",
"try",
":",
"childItems",
"=",
"self",
".",
"_fetchAllChildren",
"(",
")",
"finally",
":",
"self",
".",
"_canFetchChildren",
"=",
... | 35.769231 | 0.010482 |
def untar_file(filename, location):
"""Untar the file (tar file located at filename) to the destination location"""
if not os.path.exists(location):
os.makedirs(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswit... | [
"def",
"untar_file",
"(",
"filename",
",",
"location",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"os",
".",
"makedirs",
"(",
"location",
")",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
... | 39.156863 | 0.001466 |
def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Ignore the template inputs when initially reading the job template.
Look up each TemplateInput entity separately
and afterwords add them to the JobTemplate entity."""
if attrs is None:
attrs = self.... | [
"def",
"read",
"(",
"self",
",",
"entity",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"self",
".",
"read_json",
"(",
"params",
"=",
"pa... | 48.75 | 0.002012 |
def store(self, name, data, version, size=0,
compressed=False, digest=None, logical_size=None):
"""Adds a new file to the storage.
If the file with the same name existed before, it's not
guaranteed that the link for the old version will exist until
the operation co... | [
"def",
"store",
"(",
"self",
",",
"name",
",",
"data",
",",
"version",
",",
"size",
"=",
"0",
",",
"compressed",
"=",
"False",
",",
"digest",
"=",
"None",
",",
"logical_size",
"=",
"None",
")",
":",
"with",
"_exclusive_lock",
"(",
"self",
".",
"_lock... | 49.243478 | 0.001212 |
def tsne(
adata,
n_pcs=None,
use_rep=None,
perplexity=30,
early_exaggeration=12,
learning_rate=1000,
random_state=0,
use_fast_tsne=True,
n_jobs=None,
copy=False,
):
"""\
t-SNE [Maaten08]_ [Amir13]_ [Pedregosa11]_.
t-distributed stochastic neighborhood embedding (tSNE... | [
"def",
"tsne",
"(",
"adata",
",",
"n_pcs",
"=",
"None",
",",
"use_rep",
"=",
"None",
",",
"perplexity",
"=",
"30",
",",
"early_exaggeration",
"=",
"12",
",",
"learning_rate",
"=",
"1000",
",",
"random_state",
"=",
"0",
",",
"use_fast_tsne",
"=",
"True",
... | 46.169811 | 0.0014 |
def cmd_tuneopt(self, args):
'''Select option for Tune Pot on Channel 6 (quadcopter only)'''
usage = "usage: tuneopt <set|show|reset|list>"
if self.mpstate.vehicle_type != 'copter':
print("This command is only available for copter")
return
if len(args) < 1:
... | [
"def",
"cmd_tuneopt",
"(",
"self",
",",
"args",
")",
":",
"usage",
"=",
"\"usage: tuneopt <set|show|reset|list>\"",
"if",
"self",
".",
"mpstate",
".",
"vehicle_type",
"!=",
"'copter'",
":",
"print",
"(",
"\"This command is only available for copter\"",
")",
"return",
... | 38.0625 | 0.001601 |
def _check_raising_stopiteration_in_generator_next_call(self, node):
"""Check if a StopIteration exception is raised by the call to next function
If the next value has a default value, then do not add message.
:param node: Check to see if this Call node is a next function
:type node: :... | [
"def",
"_check_raising_stopiteration_in_generator_next_call",
"(",
"self",
",",
"node",
")",
":",
"def",
"_looks_like_infinite_iterator",
"(",
"param",
")",
":",
"inferred",
"=",
"utils",
".",
"safe_infer",
"(",
"param",
")",
"if",
"inferred",
":",
"return",
"infe... | 41.272727 | 0.002152 |
def get(msg_or_dict, key, default=_SENTINEL):
"""Retrieve a key's value from a protobuf Message or dictionary.
Args:
mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
object.
key (str): The key to retrieve from the object.
default (Any): If the key is not p... | [
"def",
"get",
"(",
"msg_or_dict",
",",
"key",
",",
"default",
"=",
"_SENTINEL",
")",
":",
"# We may need to get a nested key. Resolve this.",
"key",
",",
"subkey",
"=",
"_resolve_subkeys",
"(",
"key",
")",
"# Attempt to get the value from the two types of objects we know ab... | 40.755102 | 0.000489 |
def cliconfig(fp, env=None):
""" Load configuration data.
Given pointer is closed internally.
If ``None`` is given, force to exit.
More detailed information is available on underlying feature,
:mod:`clitool.config`.
:param fp: opened file pointer of configuration
:type fp: FileType
:pa... | [
"def",
"cliconfig",
"(",
"fp",
",",
"env",
"=",
"None",
")",
":",
"if",
"fp",
"is",
"None",
":",
"raise",
"SystemExit",
"(",
"'No configuration file is given.'",
")",
"from",
"clitool",
".",
"config",
"import",
"ConfigLoader",
"loader",
"=",
"ConfigLoader",
... | 28.041667 | 0.001437 |
def _index_idiom(el_name, index, alt=None):
"""
Generate string where `el_name` is indexed by `index` if there are enough
items or `alt` is returned.
Args:
el_name (str): Name of the `container` which is indexed.
index (int): Index of the item you want to obtain from container.
... | [
"def",
"_index_idiom",
"(",
"el_name",
",",
"index",
",",
"alt",
"=",
"None",
")",
":",
"el_index",
"=",
"\"%s[%d]\"",
"%",
"(",
"el_name",
",",
"index",
")",
"if",
"index",
"==",
"0",
":",
"cond",
"=",
"\"%s\"",
"%",
"el_name",
"else",
":",
"cond",
... | 28.162162 | 0.000928 |
def cmd_export_doc(*args):
"""
Arguments:
<document id> <output PDF file path>
[-- [--quality <0-100>] [--page_format <page_format>]]
Export one document as a PDF file.
Default quality is 50.
Default page format is A4.
Possible JSON replies:
--
{
"s... | [
"def",
"cmd_export_doc",
"(",
"*",
"args",
")",
":",
"(",
"docid",
",",
"output_pdf",
",",
"quality",
",",
"page_format",
")",
"=",
"_get_export_params",
"(",
"args",
")",
"dsearch",
"=",
"get_docsearch",
"(",
")",
"doc",
"=",
"dsearch",
".",
"get",
"(",... | 26.55102 | 0.000741 |
def has_c_library(library, extension=".c"):
"""Check whether a C/C++ library is available on the system to the compiler.
Parameters
----------
library: str
The library we want to check for e.g. if we are interested in FFTW3, we
want to check for `fftw3.h`, so this parameter will be `fft... | [
"def",
"has_c_library",
"(",
"library",
",",
"extension",
"=",
"\".c\"",
")",
":",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
"dir",
"=",
"\".\"",
")",
"as",
"directory",
":",
"name",
"=",
"join",
"(",
"directory",
",",
"\"%s%s\"",
"%",
"(",
"li... | 33.529412 | 0.001705 |
def _find_position_of_minute(self, minute_dt):
"""
Internal method that returns the position of the given minute in the
list of every trading minute since market open of the first trading
day. Adjusts non market minutes to the last close.
ex. this method would return 1 for 2002-... | [
"def",
"_find_position_of_minute",
"(",
"self",
",",
"minute_dt",
")",
":",
"return",
"find_position_of_minute",
"(",
"self",
".",
"_market_open_values",
",",
"self",
".",
"_market_close_values",
",",
"minute_dt",
".",
"value",
"/",
"NANOS_IN_MINUTE",
",",
"self",
... | 35.269231 | 0.002123 |
def getUniqueFilename(dir=None, base=None):
"""
DESCRP: Generate a filename in the directory <dir> which is
unique (i.e. not in use at the moment)
PARAMS: dir -- the directory to look in. If None, use CWD
base -- use this as the base name for the filename
RETURN: string -- the fil... | [
"def",
"getUniqueFilename",
"(",
"dir",
"=",
"None",
",",
"base",
"=",
"None",
")",
":",
"while",
"True",
":",
"fn",
"=",
"str",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"100000",
")",
")",
"+",
"\".tmp\"",
"if",
"not",
"os",
".",
"path",
".... | 34.384615 | 0.010893 |
def _decode_fname(self):
"""Extracts the actual string from the available bytes."""
self.fname = self.fname[:self.fname.find('\0')]
self.fname = self.fname.replace('\\', '/') | [
"def",
"_decode_fname",
"(",
"self",
")",
":",
"self",
".",
"fname",
"=",
"self",
".",
"fname",
"[",
":",
"self",
".",
"fname",
".",
"find",
"(",
"'\\0'",
")",
"]",
"self",
".",
"fname",
"=",
"self",
".",
"fname",
".",
"replace",
"(",
"'\\\\'",
"... | 48.75 | 0.010101 |
def time_correlations_direct(P, pi, obs1, obs2=None, times=[1]):
r"""Compute time-correlations of obs1, or time-cross-correlation with obs2.
The time-correlation at time=k is computed by the matrix-vector expression:
cor(k) = obs1' diag(pi) P^k obs2
Parameters
----------
P : ndarray, shape=(n... | [
"def",
"time_correlations_direct",
"(",
"P",
",",
"pi",
",",
"obs1",
",",
"obs2",
"=",
"None",
",",
"times",
"=",
"[",
"1",
"]",
")",
":",
"n_t",
"=",
"len",
"(",
"times",
")",
"times",
"=",
"np",
".",
"sort",
"(",
"times",
")",
"# sort it to use c... | 34.480769 | 0.002169 |
def _format_name(self, name, surname, snake_case=False):
"""Format a first name and a surname into a cohesive string.
Note that either name or surname can be empty strings, and
formatting will still succeed.
:param str name: A first name.
:param str surname: A surname.
... | [
"def",
"_format_name",
"(",
"self",
",",
"name",
",",
"surname",
",",
"snake_case",
"=",
"False",
")",
":",
"if",
"not",
"name",
"or",
"not",
"surname",
":",
"sep",
"=",
"''",
"elif",
"snake_case",
":",
"sep",
"=",
"'_'",
"else",
":",
"sep",
"=",
"... | 30.666667 | 0.002342 |
def one_cycle_scheduler(lr_max:float, **kwargs:Any)->OneCycleScheduler:
"Instantiate a `OneCycleScheduler` with `lr_max`."
return partial(OneCycleScheduler, lr_max=lr_max, **kwargs) | [
"def",
"one_cycle_scheduler",
"(",
"lr_max",
":",
"float",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"OneCycleScheduler",
":",
"return",
"partial",
"(",
"OneCycleScheduler",
",",
"lr_max",
"=",
"lr_max",
",",
"*",
"*",
"kwargs",
")"
] | 62.333333 | 0.021164 |
def cf_string_to_unicode(value):
"""
Creates a python unicode string from a CFString object
:param value:
The CFString to convert
:return:
A python unicode string
"""
string_ptr = CoreFoundation.CFStringGetCStringPtr(
value,
... | [
"def",
"cf_string_to_unicode",
"(",
"value",
")",
":",
"string_ptr",
"=",
"CoreFoundation",
".",
"CFStringGetCStringPtr",
"(",
"value",
",",
"kCFStringEncodingUTF8",
")",
"string",
"=",
"None",
"if",
"is_null",
"(",
"string_ptr",
")",
"else",
"ffi",
".",
"string... | 29.933333 | 0.002157 |
def statistical_inefficiency(X, truncate_acf=True):
""" Estimates the statistical inefficiency from univariate time series X
The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal.
Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I... | [
"def",
"statistical_inefficiency",
"(",
"X",
",",
"truncate_acf",
"=",
"True",
")",
":",
"# check input",
"assert",
"np",
".",
"ndim",
"(",
"X",
"[",
"0",
"]",
")",
"==",
"1",
",",
"'Data must be 1-dimensional'",
"N",
"=",
"_maxlength",
"(",
"X",
")",
"#... | 42.184615 | 0.008553 |
def load(self, _=None):
"""
Add formulas to layer.
"""
for k, v in self.layer.iteritems():
self.add(k, v['module'], v.get('package')) | [
"def",
"load",
"(",
"self",
",",
"_",
"=",
"None",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"layer",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"add",
"(",
"k",
",",
"v",
"[",
"'module'",
"]",
",",
"v",
".",
"get",
"(",
"'packa... | 28.666667 | 0.011299 |
def urlsplit(name):
"""
Parse :param:`name` into (netloc, port, ssl)
"""
if not (isinstance(name, string_types)):
name = str(name)
if not name.startswith(('http://', 'https://')):
name = 'http://' + name
rv = urlparse(name)
if rv.scheme == 'https' and rv.port is None:
... | [
"def",
"urlsplit",
"(",
"name",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"name",
",",
"string_types",
")",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"not",
"name",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
... | 27.333333 | 0.002358 |
def append(self, element):
"""
Append a new element to the result.
:param element: The element to append
:type element: overpy.Element
"""
if is_valid_type(element, Element):
self._class_collection_map[element.__class__].setdefault(element.id, element) | [
"def",
"append",
"(",
"self",
",",
"element",
")",
":",
"if",
"is_valid_type",
"(",
"element",
",",
"Element",
")",
":",
"self",
".",
"_class_collection_map",
"[",
"element",
".",
"__class__",
"]",
".",
"setdefault",
"(",
"element",
".",
"id",
",",
"elem... | 33.888889 | 0.009585 |
def onset_strength_multi(y=None, sr=22050, S=None, lag=1, max_size=1,
ref=None, detrend=False, center=True, feature=None,
aggregate=None, channels=None, **kwargs):
"""Compute a spectral flux onset strength envelope across multiple channels.
Onset strength for c... | [
"def",
"onset_strength_multi",
"(",
"y",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"S",
"=",
"None",
",",
"lag",
"=",
"1",
",",
"max_size",
"=",
"1",
",",
"ref",
"=",
"None",
",",
"detrend",
"=",
"False",
",",
"center",
"=",
"True",
",",
"featur... | 29.755556 | 0.000903 |
def get_google_playlist(self, playlist):
"""Get playlist information of a user-generated Google Music playlist.
Parameters:
playlist (str): Name or ID of Google Music playlist. Names are case-sensitive.
Google allows multiple playlists with the same name.
If multiple playlists have the same name, the fi... | [
"def",
"get_google_playlist",
"(",
"self",
",",
"playlist",
")",
":",
"logger",
".",
"info",
"(",
"\"Loading playlist {0}\"",
".",
"format",
"(",
"playlist",
")",
")",
"for",
"google_playlist",
"in",
"self",
".",
"api",
".",
"get_all_user_playlist_contents",
"("... | 37.7 | 0.025873 |
def add_prioritized(self, command_obj, priority):
""" Add command with the specified priority
:param command_obj: command to add
:param priority: command priority
:return: None
"""
if priority not in self.__priorities.keys():
self.__priorities[priority] = []
self.__priorities[priority].append(command... | [
"def",
"add_prioritized",
"(",
"self",
",",
"command_obj",
",",
"priority",
")",
":",
"if",
"priority",
"not",
"in",
"self",
".",
"__priorities",
".",
"keys",
"(",
")",
":",
"self",
".",
"__priorities",
"[",
"priority",
"]",
"=",
"[",
"]",
"self",
".",... | 28.636364 | 0.030769 |
def _is_out_of_order(segmentation):
"""
Check if a given segmentation is out of order.
Examples
--------
>>> _is_out_of_order([[0, 1, 2, 3]])
False
>>> _is_out_of_order([[0, 1], [2, 3]])
False
>>> _is_out_of_order([[0, 1, 3], [2]])
True
"""
last_stroke = -1
for symbo... | [
"def",
"_is_out_of_order",
"(",
"segmentation",
")",
":",
"last_stroke",
"=",
"-",
"1",
"for",
"symbol",
"in",
"segmentation",
":",
"for",
"stroke",
"in",
"symbol",
":",
"if",
"last_stroke",
">",
"stroke",
":",
"return",
"True",
"last_stroke",
"=",
"stroke",... | 23.2 | 0.00207 |
def subscribe_user(self, user):
""" method to subscribe a user to a service
"""
url = self.root_url + "subscribe_user"
values = {}
values["username"] = user
return self._query(url, values) | [
"def",
"subscribe_user",
"(",
"self",
",",
"user",
")",
":",
"url",
"=",
"self",
".",
"root_url",
"+",
"\"subscribe_user\"",
"values",
"=",
"{",
"}",
"values",
"[",
"\"username\"",
"]",
"=",
"user",
"return",
"self",
".",
"_query",
"(",
"url",
",",
"va... | 32.857143 | 0.008475 |
def migrate_1to2(store):
"""Migrate array metadata in `store` from Zarr format version 1 to
version 2.
Parameters
----------
store : MutableMapping
Store to be migrated.
Notes
-----
Version 1 did not support hierarchies, so this migration function will
look for a single arr... | [
"def",
"migrate_1to2",
"(",
"store",
")",
":",
"# migrate metadata",
"from",
"zarr",
"import",
"meta_v1",
"meta",
"=",
"meta_v1",
".",
"decode_metadata",
"(",
"store",
"[",
"'meta'",
"]",
")",
"del",
"store",
"[",
"'meta'",
"]",
"# add empty filters",
"meta",
... | 27.617021 | 0.000744 |
def broadcast_dimension_size(
variables: List[Variable],
) -> 'OrderedDict[Any, int]':
"""Extract dimension sizes from a dictionary of variables.
Raises ValueError if any dimensions have different sizes.
"""
dims = OrderedDict() # type: OrderedDict[Any, int]
for var in variables:
for d... | [
"def",
"broadcast_dimension_size",
"(",
"variables",
":",
"List",
"[",
"Variable",
"]",
",",
")",
"->",
"'OrderedDict[Any, int]'",
":",
"dims",
"=",
"OrderedDict",
"(",
")",
"# type: OrderedDict[Any, int]",
"for",
"var",
"in",
"variables",
":",
"for",
"dim",
","... | 35.857143 | 0.001942 |
def marshal(self) :
"serializes this Message into the wire protocol format and returns a bytes object."
buf = ct.POINTER(ct.c_ubyte)()
nr_bytes = ct.c_int()
if not dbus.dbus_message_marshal(self._dbobj, ct.byref(buf), ct.byref(nr_bytes)) :
raise CallFailed("dbus_message_marsh... | [
"def",
"marshal",
"(",
"self",
")",
":",
"buf",
"=",
"ct",
".",
"POINTER",
"(",
"ct",
".",
"c_ubyte",
")",
"(",
")",
"nr_bytes",
"=",
"ct",
".",
"c_int",
"(",
")",
"if",
"not",
"dbus",
".",
"dbus_message_marshal",
"(",
"self",
".",
"_dbobj",
",",
... | 35.117647 | 0.014682 |
def chars(self, font, block):
"""
Analyses characters in single font or all fonts.
"""
if font:
font_files = self._getFont(font)
else:
font_files = fc.query()
code_points = self._getFontChars(font_files)
if not block:
blocks = ... | [
"def",
"chars",
"(",
"self",
",",
"font",
",",
"block",
")",
":",
"if",
"font",
":",
"font_files",
"=",
"self",
".",
"_getFont",
"(",
"font",
")",
"else",
":",
"font_files",
"=",
"fc",
".",
"query",
"(",
")",
"code_points",
"=",
"self",
".",
"_getF... | 39.5 | 0.002059 |
def cli(ctx, packages, all, list, force, platform):
"""Install packages."""
if packages:
for package in packages:
Installer(package, platform, force).install()
elif all: # pragma: no cover
packages = Resources(platform).packages
for package in packages:
Inst... | [
"def",
"cli",
"(",
"ctx",
",",
"packages",
",",
"all",
",",
"list",
",",
"force",
",",
"platform",
")",
":",
"if",
"packages",
":",
"for",
"package",
"in",
"packages",
":",
"Installer",
"(",
"package",
",",
"platform",
",",
"force",
")",
".",
"instal... | 34.714286 | 0.002004 |
def _process_transform(self, data, transform, step_size):
'''
Process transforms on the data.
'''
if isinstance(transform, (list,tuple,set)):
return { t : self._transform(data,t,step_size) for t in transform }
elif isinstance(transform, dict):
return { tn : self._transform(data,tf,step_s... | [
"def",
"_process_transform",
"(",
"self",
",",
"data",
",",
"transform",
",",
"step_size",
")",
":",
"if",
"isinstance",
"(",
"transform",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"{",
"t",
":",
"self",
".",
"_transform",
... | 44.666667 | 0.046341 |
def earth_accel_df(IMU,ATT):
'''return earth frame acceleration vector from df log'''
r = rotation_df(ATT)
accel = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ)
return r * accel | [
"def",
"earth_accel_df",
"(",
"IMU",
",",
"ATT",
")",
":",
"r",
"=",
"rotation_df",
"(",
"ATT",
")",
"accel",
"=",
"Vector3",
"(",
"IMU",
".",
"AccX",
",",
"IMU",
".",
"AccY",
",",
"IMU",
".",
"AccZ",
")",
"return",
"r",
"*",
"accel"
] | 36.2 | 0.010811 |
def is_valid_mpls_label(label):
"""Validates `label` according to MPLS label rules
RFC says:
This 20-bit field.
A value of 0 represents the "IPv4 Explicit NULL Label".
A value of 1 represents the "Router Alert Label".
A value of 2 represents the "IPv6 Explicit NULL Label".
A value of 3 repr... | [
"def",
"is_valid_mpls_label",
"(",
"label",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"label",
",",
"numbers",
".",
"Integral",
")",
"or",
"(",
"4",
"<=",
"label",
"<=",
"15",
")",
"or",
"(",
"label",
"<",
"0",
"or",
"label",
">",
"2",
"**",
... | 31.941176 | 0.001789 |
def subnet_create_or_update(name, address_prefix, virtual_network, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a subnet.
:param name: The name assigned to the subnet being created or updated.
:param address_prefix: A valid CIDR block within the virtual network.
... | [
"def",
"subnet_create_or_update",
"(",
"name",
",",
"address_prefix",
",",
"virtual_network",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
"... | 31.933333 | 0.00162 |
def error(self, instance, value, error_class=None, extra=''):
"""Generate a :code:`ValueError` for invalid value assignment
The instance is the containing HasProperties instance, but it may
be None if the error is raised outside a HasProperties class.
"""
error_class = error_cla... | [
"def",
"error",
"(",
"self",
",",
"instance",
",",
"value",
",",
"error_class",
"=",
"None",
",",
"extra",
"=",
"''",
")",
":",
"error_class",
"=",
"error_class",
"or",
"ValidationError",
"prefix",
"=",
"'The {} property'",
".",
"format",
"(",
"self",
".",... | 41.5 | 0.001472 |
def declare_example(self, source):
"""Execute the given code, adding it to the runner's namespace."""
with patch_modules():
code = compile(source, "<docs>", "exec")
exec(code, self.namespace) | [
"def",
"declare_example",
"(",
"self",
",",
"source",
")",
":",
"with",
"patch_modules",
"(",
")",
":",
"code",
"=",
"compile",
"(",
"source",
",",
"\"<docs>\"",
",",
"\"exec\"",
")",
"exec",
"(",
"code",
",",
"self",
".",
"namespace",
")"
] | 45.4 | 0.008658 |
def stream(repo_uri, stream_uri, verbose, assume, sort, before=None, after=None):
"""Stream git history policy changes to destination.
Default stream destination is a summary of the policy changes to stdout, one
per line. Also supported for stdout streaming is `jsonline`.
AWS Kinesis and SQS destinat... | [
"def",
"stream",
"(",
"repo_uri",
",",
"stream_uri",
",",
"verbose",
",",
"assume",
",",
"sort",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(messag... | 39.244898 | 0.001522 |
def get_message(self):
"""Process the accumulated buffer and return the first message.
If the buffer starts with FIX fields other than BeginString
(8), these are discarded until the start of a message is
found.
If no BeginString (8) field is found, this function returns
... | [
"def",
"get_message",
"(",
"self",
")",
":",
"# Break buffer into tag=value pairs.",
"start",
"=",
"0",
"point",
"=",
"0",
"in_tag",
"=",
"True",
"tag",
"=",
"0",
"while",
"point",
"<",
"len",
"(",
"self",
".",
"buf",
")",
":",
"if",
"in_tag",
"and",
"... | 31.060976 | 0.000761 |
def hurst_compare_nvals(data, nvals=None):
"""
Creates a plot that compares the results of different choices for nvals
for the function hurst_rs.
Args:
data (array-like of float):
the input data from which the hurst exponent should be estimated
Kwargs:
nvals (array of int):
a manually se... | [
"def",
"hurst_compare_nvals",
"(",
"data",
",",
"nvals",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"n_all",
"=",
"np",
".",
"arange",
"(",
"2",
",",
"len",
"(",
"... | 36.673913 | 0.016166 |
def ttl(self, value):
"""Change self ttl with input value.
:param float value: new ttl in seconds.
"""
# get timer
timer = getattr(self, Annotation.__TIMER, None)
# if timer is running, stop the timer
if timer is not None:
timer.cancel()
# ... | [
"def",
"ttl",
"(",
"self",
",",
"value",
")",
":",
"# get timer",
"timer",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"None",
")",
"# if timer is running, stop the timer",
"if",
"timer",
"is",
"not",
"None",
":",
"timer",
".",
"ca... | 25.387097 | 0.002448 |
def _inject_closure_values_fix_code(c, injected, **kwargs):
"""
Fix code objects, recursively fixing any closures
"""
# Add more closure variables
c.freevars += injected
# Replace LOAD_GLOBAL with LOAD_DEREF (fetch from closure cells)
# for named variables
for i, (opcode, value) in enum... | [
"def",
"_inject_closure_values_fix_code",
"(",
"c",
",",
"injected",
",",
"*",
"*",
"kwargs",
")",
":",
"# Add more closure variables",
"c",
".",
"freevars",
"+=",
"injected",
"# Replace LOAD_GLOBAL with LOAD_DEREF (fetch from closure cells)",
"# for named variables",
"for",
... | 31.9375 | 0.001901 |
def repo_present(
name,
description=None,
homepage=None,
private=None,
has_issues=None,
has_wiki=None,
has_downloads=None,
auto_init=False,
gitignore_template=None,
license_template=None,
teams=None,
profile="github",
... | [
"def",
"repo_present",
"(",
"name",
",",
"description",
"=",
"None",
",",
"homepage",
"=",
"None",
",",
"private",
"=",
"None",
",",
"has_issues",
"=",
"None",
",",
"has_wiki",
"=",
"None",
",",
"has_downloads",
"=",
"None",
",",
"auto_init",
"=",
"False... | 38.316206 | 0.002312 |
def argsort(self, *args, **kwargs):
"""
Return the integer indices that would sort the index.
Parameters
----------
*args
Passed to `numpy.ndarray.argsort`.
**kwargs
Passed to `numpy.ndarray.argsort`.
Returns
-------
numpy... | [
"def",
"argsort",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"asi8",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"np",
".",
"array",
"(",
"self",
")",
"return",
"result",
".",
"argsort",
"(... | 25.282051 | 0.001953 |
def inasafe_place_value_coefficient(number, feature, parent):
"""Given a number, it will return the coefficient of the place value name.
For instance:
* inasafe_place_value_coefficient(10) -> 1
* inasafe_place_value_coefficient(1700) -> 1.7
It needs to be used with inasafe_number_denomination_un... | [
"def",
"inasafe_place_value_coefficient",
"(",
"number",
",",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"if",
"number",
">=",
"0",
":",
"rounded_number",
"=",
"round_affected_number",
"(",
"number",
",",
"use_rounding",
... | 30.923077 | 0.001206 |
def count(self):
"""Return a count of instances."""
if self._primary_keys is None:
return self.queryset.count()
else:
return len(self.pks) | [
"def",
"count",
"(",
"self",
")",
":",
"if",
"self",
".",
"_primary_keys",
"is",
"None",
":",
"return",
"self",
".",
"queryset",
".",
"count",
"(",
")",
"else",
":",
"return",
"len",
"(",
"self",
".",
"pks",
")"
] | 30.166667 | 0.010753 |
def lease(queue_name, owner, count=1, timeout_seconds=60):
"""Leases a work item from a queue, usually the oldest task available.
Args:
queue_name: Name of the queue to lease work from.
owner: Who or what is leasing the task.
count: Lease up to this many tasks. Return value will never h... | [
"def",
"lease",
"(",
"queue_name",
",",
"owner",
",",
"count",
"=",
"1",
",",
"timeout_seconds",
"=",
"60",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"query",
"=",
"(",
"WorkQueue",
".",
"query",
".",
"filter_by",
"(... | 32.725 | 0.000742 |
def example():
"""creates example data set"""
J,v = multidict({1:16, 2:19, 3:23, 4:28})
a = {(1,1):2, (1,2):3, (1,3):4, (1,4):5,
(2,1):3000, (2,2):3500, (2,3):5100, (2,4):7200,
}
I,b = multidict({1:7, 2:10000})
return I,J,v,a,b | [
"def",
"example",
"(",
")",
":",
"J",
",",
"v",
"=",
"multidict",
"(",
"{",
"1",
":",
"16",
",",
"2",
":",
"19",
",",
"3",
":",
"23",
",",
"4",
":",
"28",
"}",
")",
"a",
"=",
"{",
"(",
"1",
",",
"1",
")",
":",
"2",
",",
"(",
"1",
",... | 33.375 | 0.105839 |
def status(self):
"""Get the status of the daemon."""
if self.pidfile is None:
raise DaemonError('Cannot get status of daemon without PID file')
pid = self._read_pidfile()
if pid is None:
self._emit_message(
'{prog} -- not running\n'.format(prog=s... | [
"def",
"status",
"(",
"self",
")",
":",
"if",
"self",
".",
"pidfile",
"is",
"None",
":",
"raise",
"DaemonError",
"(",
"'Cannot get status of daemon without PID file'",
")",
"pid",
"=",
"self",
".",
"_read_pidfile",
"(",
")",
"if",
"pid",
"is",
"None",
":",
... | 37.18 | 0.001048 |
def queryMany(self, query, args):
"""
Executes a series of the same Insert Statments
Each tuple in the args list will be applied to the query and executed.
This is the equivilant of MySQLDB.cursor.executemany()
@author: Nick Verbeck
@since: 9/7/2008
"""
self.lastError = None
self.affectedRows = ... | [
"def",
"queryMany",
"(",
"self",
",",
"query",
",",
"args",
")",
":",
"self",
".",
"lastError",
"=",
"None",
"self",
".",
"affectedRows",
"=",
"None",
"self",
".",
"rowcount",
"=",
"None",
"self",
".",
"record",
"=",
"None",
"cursor",
"=",
"None",
"t... | 23.852941 | 0.046209 |
def double_tab_complete(self):
"""If several options available a double tab displays options."""
opts = self._complete_options()
if len(opts) > 1:
self.completer().complete() | [
"def",
"double_tab_complete",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"_complete_options",
"(",
")",
"if",
"len",
"(",
"opts",
")",
">",
"1",
":",
"self",
".",
"completer",
"(",
")",
".",
"complete",
"(",
")"
] | 42 | 0.009346 |
def _setup(self):
"""Performs the RFXtrx initialisation protocol in a Future.
Currently this is the rough workflow of the interactions with the
RFXtrx. We also do a few extra things - flush the buffer, and attach
readers/writers to the asyncio loop.
1. Write a RESET packet (wri... | [
"def",
"_setup",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Adding reader to prepare to receive.\"",
")",
"self",
".",
"loop",
".",
"add_reader",
"(",
"self",
".",
"dev",
".",
"fd",
",",
"self",
".",
"read",
")",
"self",
".",
"log"... | 39.060606 | 0.001514 |
def map_template(category, template_list):
"""
Given a file path and an acceptable list of templates, return the
best-matching template's path relative to the configured template
directory.
Arguments:
category -- The path to map
template_list -- A template to look up (as a string), or a li... | [
"def",
"map_template",
"(",
"category",
",",
"template_list",
")",
":",
"if",
"isinstance",
"(",
"template_list",
",",
"str",
")",
":",
"template_list",
"=",
"[",
"template_list",
"]",
"for",
"template",
"in",
"template_list",
":",
"path",
"=",
"os",
".",
... | 35.178571 | 0.001976 |
def p_param_args(self, p):
'param_args : param_args COMMA param_arg'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_param_args",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"3",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 35 | 0.013986 |
def rotate(self, alpha, beta, gamma, degrees=True, convention='y',
body=False, dj_matrix=None):
"""
Rotate either the coordinate system used to express the spherical
harmonic coefficients or the physical body, and return a new class
instance.
Usage
-----
... | [
"def",
"rotate",
"(",
"self",
",",
"alpha",
",",
"beta",
",",
"gamma",
",",
"degrees",
"=",
"True",
",",
"convention",
"=",
"'y'",
",",
"body",
"=",
"False",
",",
"dj_matrix",
"=",
"None",
")",
":",
"if",
"type",
"(",
"convention",
")",
"!=",
"str"... | 40.944444 | 0.000662 |
def _extract_from_sans(self):
"""Looks for different TLDs as well as different sub-domains in SAN list"""
self.logger.info("{} Trying to find Subdomains in SANs list".format(COLORED_COMBOS.NOTIFY))
if self.host.naked:
domain = self.host.naked
tld_less = domain.split(".")[... | [
"def",
"_extract_from_sans",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"{} Trying to find Subdomains in SANs list\"",
".",
"format",
"(",
"COLORED_COMBOS",
".",
"NOTIFY",
")",
")",
"if",
"self",
".",
"host",
".",
"naked",
":",
"domain",... | 48.214286 | 0.008721 |
def save_block_to_crt(filename, group, norrec='all', store_errors=False):
"""Save a dataset to a CRTomo-compatible .crt file
Parameters
----------
filename : string
Output filename
group : pandas.group
Data group
norrec : string
Which data to export Possible values: all|... | [
"def",
"save_block_to_crt",
"(",
"filename",
",",
"group",
",",
"norrec",
"=",
"'all'",
",",
"store_errors",
"=",
"False",
")",
":",
"if",
"norrec",
"!=",
"'all'",
":",
"group",
"=",
"group",
".",
"query",
"(",
"'norrec == \"{0}\"'",
".",
"format",
"(",
... | 27.425532 | 0.000749 |
def translate_array(trans_vec,vec_array):
'''translate_array(trans_vec,vec_array) -> vec_array
Adds 'mult'*'trans_vec' to each element in vec_array, and returns
the translated vector.
'''
return map ( lambda x,m=trans_vec:add(m,x),vec_array ) | [
"def",
"translate_array",
"(",
"trans_vec",
",",
"vec_array",
")",
":",
"return",
"map",
"(",
"lambda",
"x",
",",
"m",
"=",
"trans_vec",
":",
"add",
"(",
"m",
",",
"x",
")",
",",
"vec_array",
")"
] | 28.555556 | 0.033962 |
def send_mail(self, to, cc=[], bcc=[], attachfiles=[], embeddedimages_tag="graphic_embedded", embeddedimages=[]):
"""
Envoi d'un email à un ou plusieurs correspondants
:param to: liste des correspondants en adresse directe
:param cc: liste des correspondants en copie du mail
:param bcc: liste des corresponda... | [
"def",
"send_mail",
"(",
"self",
",",
"to",
",",
"cc",
"=",
"[",
"]",
",",
"bcc",
"=",
"[",
"]",
",",
"attachfiles",
"=",
"[",
"]",
",",
"embeddedimages_tag",
"=",
"\"graphic_embedded\"",
",",
"embeddedimages",
"=",
"[",
"]",
")",
":",
"# vérifications... | 31.548387 | 0.027014 |
def get_interface_detail_output_interface_ifHCOutMulticastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "o... | [
"def",
"get_interface_detail_output_interface_ifHCOutMulticastPkts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\"",
")",... | 51.647059 | 0.002237 |
def sync(self, userId, groupInfo):
"""
同步用户所属群组方法(当第一次连接融云服务器时,需要向融云服务器提交 userId 对应的用户当前所加入的所有群组,此接口主要为防止应用中用户群信息同融云已知的用户所属群信息不同步。) 方法
@param userId:被同步群信息的用户 Id。(必传)
@param groupInfo:该用户的群信息,如群 Id 已经存在,则不会刷新对应群组名称,如果想刷新群组名称请调用刷新群组信息方法。
@return code:返回码,200 为正常。
@ret... | [
"def",
"sync",
"(",
"self",
",",
"userId",
",",
"groupInfo",
")",
":",
"desc",
"=",
"{",
"\"name\"",
":",
"\"CodeSuccessReslut\"",
",",
"\"desc\"",
":",
"\" http 成功返回结果\",",
"",
"\"fields\"",
":",
"[",
"{",
"\"name\"",
":",
"\"code\"",
",",
"\"type\"",
":"... | 33.466667 | 0.008712 |
def merge(self, po_file, source_files):
"""从源码中获取所有条目,合并到 po_file 中。
:param string po_file: 待写入的 po 文件路径。
:param list source_files : 所有待处理的原文件路径 list。
"""
# Create a temporary file to write pot file
pot_file = tempfile.NamedTemporaryFile(mode='wb', prefix='rookout_', d... | [
"def",
"merge",
"(",
"self",
",",
"po_file",
",",
"source_files",
")",
":",
"# Create a temporary file to write pot file",
"pot_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'wb'",
",",
"prefix",
"=",
"'rookout_'",
",",
"delete",
"=",
"Fa... | 39.724138 | 0.011017 |
def add_plugin(self, plugin):
"""Append `plugin` to model
Arguments:
plugin (dict): Serialised plug-in from pyblish-rpc
Schema:
plugin.json
"""
item = {}
item.update(defaults["common"])
item.update(defaults["plugin"])
for membe... | [
"def",
"add_plugin",
"(",
"self",
",",
"plugin",
")",
":",
"item",
"=",
"{",
"}",
"item",
".",
"update",
"(",
"defaults",
"[",
"\"common\"",
"]",
")",
"item",
".",
"update",
"(",
"defaults",
"[",
"\"plugin\"",
"]",
")",
"for",
"member",
"in",
"[",
... | 30.712121 | 0.000956 |
def fit(self, X, y=None):
"""Compute the Deterministic Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
y : not used
"""
logger.... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'Starting Deterministic SRM'",
")",
"# Check the number of subjects",
"if",
"len",
"(",
"X",
")",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"\"There are no... | 33.916667 | 0.001592 |
def copy(self):
"""
Return a new :class:`~pywbem.CIMClass` object that is a copy
of this CIM class.
This is a middle-deep copy; any mutable types in attributes except the
following are copied, so besides these exceptions, modifications of the
original object will not aff... | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"CIMClass",
"(",
"self",
".",
"classname",
",",
"properties",
"=",
"self",
".",
"properties",
",",
"# setter copies",
"methods",
"=",
"self",
".",
"methods",
",",
"# setter copies",
"superclass",
"=",
"self",
... | 44.5 | 0.001375 |
def disambiguate_unit(unit, text):
"""
Resolve ambiguity.
Distinguish between units that have same names, symbols or abbreviations.
"""
new_unit = l.UNITS[unit]
if not new_unit:
new_unit = l.LOWER_UNITS[unit.lower()]
if not new_unit:
raise KeyError('Could not find un... | [
"def",
"disambiguate_unit",
"(",
"unit",
",",
"text",
")",
":",
"new_unit",
"=",
"l",
".",
"UNITS",
"[",
"unit",
"]",
"if",
"not",
"new_unit",
":",
"new_unit",
"=",
"l",
".",
"LOWER_UNITS",
"[",
"unit",
".",
"lower",
"(",
")",
"]",
"if",
"not",
"ne... | 33.965517 | 0.000987 |
def move_particles(self):
"""
Move each particle by it's velocity, adjusting brightness as we go.
Particles that have moved beyond their range (steps to live), and
those that move off the ends and are not wrapped get sacked.
Particles can stay between _end and up to but not inclu... | [
"def",
"move_particles",
"(",
"self",
")",
":",
"moved_particles",
"=",
"[",
"]",
"for",
"vel",
",",
"pos",
",",
"stl",
",",
"color",
",",
"bright",
"in",
"self",
".",
"particles",
":",
"stl",
"-=",
"1",
"# steps to live",
"if",
"stl",
">",
"0",
":",... | 38.536585 | 0.001235 |
def groups_archive(self, room_id, **kwargs):
"""Archives a private group, only if you’re part of the group."""
return self.__call_api_post('groups.archive', roomId=room_id, kwargs=kwargs) | [
"def",
"groups_archive",
"(",
"self",
",",
"room_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'groups.archive'",
",",
"roomId",
"=",
"room_id",
",",
"kwargs",
"=",
"kwargs",
")"
] | 67 | 0.014778 |
def createEditor(self, delegate, parent, _option):
""" Creates a hidden widget so that only the reset button is visible during editing.
:type option: QStyleOptionViewItem
"""
return GroupCtiEditor(self, delegate, parent=parent) | [
"def",
"createEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
",",
"_option",
")",
":",
"return",
"GroupCtiEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
"=",
"parent",
")"
] | 51.8 | 0.011407 |
def add_fs(self, name, fs, write=False, priority=0):
# type: (Text, FS, bool, int) -> None
"""Add a filesystem to the MultiFS.
Arguments:
name (str): A unique name to refer to the filesystem being
added.
fs (FS or str): The filesystem (instance or URL) to... | [
"def",
"add_fs",
"(",
"self",
",",
"name",
",",
"fs",
",",
"write",
"=",
"False",
",",
"priority",
"=",
"0",
")",
":",
"# type: (Text, FS, bool, int) -> None",
"if",
"isinstance",
"(",
"fs",
",",
"text_type",
")",
":",
"fs",
"=",
"open_fs",
"(",
"fs",
... | 38.15625 | 0.002396 |
def get_mesh_name_from_web(mesh_id):
"""Get the MESH label for the given MESH ID using the NLM REST API.
Parameters
----------
mesh_id : str
MESH Identifier, e.g. 'D003094'.
Returns
-------
str
Label for the MESH ID, or None if the query failed or no label was
found... | [
"def",
"get_mesh_name_from_web",
"(",
"mesh_id",
")",
":",
"url",
"=",
"MESH_URL",
"+",
"mesh_id",
"+",
"'.json'",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"resp",
".",
"status_code",
"!=",
"200",
":",
"return",
"None",
"mesh_json",
"=... | 24.916667 | 0.00161 |
def _expectation(X, centers, weights, concentrations, posterior_type="soft"):
"""Compute the log-likelihood of each datapoint being in each cluster.
Parameters
----------
centers (mu) : array, [n_centers x n_features]
weights (alpha) : array, [n_centers, ] (alpha)
concentrations (kappa) : array... | [
"def",
"_expectation",
"(",
"X",
",",
"centers",
",",
"weights",
",",
"concentrations",
",",
"posterior_type",
"=",
"\"soft\"",
")",
":",
"n_examples",
",",
"n_features",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"n_clusters",
",",
"_",
"=",
"centers",
"."... | 34.410256 | 0.001449 |
def delete_view(self, request, object_id, extra_context=None):
"""
Overrides the default to enable redirecting to the directory view after
deletion of a image.
we need to fetch the object and find out who the parent is
before super, because super will delete the object and make ... | [
"def",
"delete_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"extra_context",
"=",
"None",
")",
":",
"try",
":",
"obj",
"=",
"self",
".",
"get_queryset",
"(",
"request",
")",
".",
"get",
"(",
"pk",
"=",
"unquote",
"(",
"object_id",
")",
... | 40.647059 | 0.001413 |
def print_http_nfc_lease_info(info):
""" Prints information about the lease,
such as the entity covered by the lease,
and HTTP URLs for up/downloading file backings.
:param info:
:type info: vim.HttpNfcLease.Info
:return:
"""
print 'Lease timeout: {0.leaseTimeout}\n' \
'Disk Ca... | [
"def",
"print_http_nfc_lease_info",
"(",
"info",
")",
":",
"print",
"'Lease timeout: {0.leaseTimeout}\\n'",
"'Disk Capacity KB: {0.totalDiskCapacityInKB}'",
".",
"format",
"(",
"info",
")",
"device_number",
"=",
"1",
"if",
"info",
".",
"deviceUrl",
":",
"for",
"device_u... | 42.107143 | 0.001658 |
def make_counts(
n_samples=1000,
n_features=100,
n_informative=2,
scale=1.0,
chunks=100,
random_state=None,
):
"""
Generate a dummy dataset for modeling count data.
Parameters
----------
n_samples : int
number of rows in the output array
n_features : int
... | [
"def",
"make_counts",
"(",
"n_samples",
"=",
"1000",
",",
"n_features",
"=",
"100",
",",
"n_informative",
"=",
"2",
",",
"scale",
"=",
"1.0",
",",
"chunks",
"=",
"100",
",",
"random_state",
"=",
"None",
",",
")",
":",
"rng",
"=",
"dask_ml",
".",
"uti... | 30.5 | 0.001906 |
def _store_path(self, filepath, fprogress):
"""Store file at filepath in the database and return the base index entry
Needs the git_working_dir decorator active ! This must be assured in the calling code"""
st = os.lstat(filepath) # handles non-symlinks as well
if S_ISLNK(st.st_mode)... | [
"def",
"_store_path",
"(",
"self",
",",
"filepath",
",",
"fprogress",
")",
":",
"st",
"=",
"os",
".",
"lstat",
"(",
"filepath",
")",
"# handles non-symlinks as well",
"if",
"S_ISLNK",
"(",
"st",
".",
"st_mode",
")",
":",
"# in PY3, readlink is string, but we nee... | 63.466667 | 0.010352 |
def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'tes... | [
"def",
"reference_cluster",
"(",
"envs",
",",
"name",
")",
":",
"edges",
"=",
"[",
"set",
"(",
"[",
"env",
"[",
"'name'",
"]",
",",
"ref",
"]",
")",
"for",
"env",
"in",
"envs",
"for",
"ref",
"in",
"env",
"[",
"'refs'",
"]",
"]",
"prev",
",",
"c... | 28.242424 | 0.001037 |
def rename(name, source, force=False, makedirs=False, **kwargs):
'''
If the source file exists on the system, rename it to the named file. The
named file will not be overwritten if it already exists unless the force
option is set to True.
name
The location of the file to rename to
sour... | [
"def",
"rename",
"(",
"name",
",",
"source",
",",
"force",
"=",
"False",
",",
"makedirs",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"source",
"=",
"os",
".",
"path",
".",... | 31.384615 | 0.000679 |
def install():
"""Install Fleaker.
In a function so we can protect this file so it's only run when we
explicitly invoke it and not, say, when py.test collects all Python
modules.
"""
_version_re = re.compile(r"__version__\s+=\s+(.*)") # pylint: disable=invalid-name
with open('./fleaker/__... | [
"def",
"install",
"(",
")",
":",
"_version_re",
"=",
"re",
".",
"compile",
"(",
"r\"__version__\\s+=\\s+(.*)\"",
")",
"# pylint: disable=invalid-name",
"with",
"open",
"(",
"'./fleaker/__init__.py'",
",",
"'rb'",
")",
"as",
"file_",
":",
"version",
"=",
"ast",
"... | 35.464789 | 0.001932 |
def ParseSudoersEntry(self, entry, sudoers_config):
"""Parse an entry and add it to the given SudoersConfig rdfvalue."""
key = entry[0]
if key in SudoersFieldParser.ALIAS_TYPES:
# Alias.
alias_entry = rdf_config_file.SudoersAlias(
type=SudoersFieldParser.ALIAS_TYPES.get(key), name=ent... | [
"def",
"ParseSudoersEntry",
"(",
"self",
",",
"entry",
",",
"sudoers_config",
")",
":",
"key",
"=",
"entry",
"[",
"0",
"]",
"if",
"key",
"in",
"SudoersFieldParser",
".",
"ALIAS_TYPES",
":",
"# Alias.",
"alias_entry",
"=",
"rdf_config_file",
".",
"SudoersAlias"... | 36.571429 | 0.01379 |
def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Override Qt method"""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant(int(Qt.AlignRight | Qt.AlignVC... | [
"def",
"headerData",
"(",
"self",
",",
"section",
",",
"orientation",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"role",
"==",
"Qt",
".",
"TextAlignmentRole",
":",
"if",
"orientation",
"==",
"Qt",
".",
"Horizontal",
":",
"return",
"to_qv... | 44.45 | 0.002203 |
def set_value(dictionary, keys, value):
"""
Similar to Python's built in `dictionary[key] = value`,
but takes a list of nested keys instead of a single key.
set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
set_value({'a': 1}, ['x', 'y'], 2)... | [
"def",
"set_value",
"(",
"dictionary",
",",
"keys",
",",
"value",
")",
":",
"if",
"not",
"keys",
":",
"dictionary",
".",
"update",
"(",
"value",
")",
"return",
"for",
"key",
"in",
"keys",
"[",
":",
"-",
"1",
"]",
":",
"if",
"key",
"not",
"in",
"d... | 29.842105 | 0.001709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.