text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def query_keywords_empty(kind='1'):
'''
Query keywords, empty.
'''
return TabPost.select().where((TabPost.kind == kind) & (TabPost.keywords == '')) | [
"def",
"query_keywords_empty",
"(",
"kind",
"=",
"'1'",
")",
":",
"return",
"TabPost",
".",
"select",
"(",
")",
".",
"where",
"(",
"(",
"TabPost",
".",
"kind",
"==",
"kind",
")",
"&",
"(",
"TabPost",
".",
"keywords",
"==",
"''",
")",
")"
] | 35 | 0.01676 |
def sync(data, idx, aggregate=None, pad=True, axis=-1):
"""Synchronous aggregation of a multi-dimensional array between boundaries
.. note::
In order to ensure total coverage, boundary points may be added
to `idx`.
If synchronizing a feature matrix against beat tracker output, ensure
... | [
"def",
"sync",
"(",
"data",
",",
"idx",
",",
"aggregate",
"=",
"None",
",",
"pad",
"=",
"True",
",",
"axis",
"=",
"-",
"1",
")",
":",
"if",
"aggregate",
"is",
"None",
":",
"aggregate",
"=",
"np",
".",
"mean",
"shape",
"=",
"list",
"(",
"data",
... | 32.047619 | 0.001201 |
def load(self):
""" Load each path in order. Remember paths already loaded and only load new ones. """
data = self.dict_class()
for path in self.paths:
if path in self.paths_loaded: continue
try:
with open(path, 'r') as file:
... | [
"def",
"load",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"dict_class",
"(",
")",
"for",
"path",
"in",
"self",
".",
"paths",
":",
"if",
"path",
"in",
"self",
".",
"paths_loaded",
":",
"continue",
"try",
":",
"with",
"open",
"(",
"path",
",",
... | 37.944444 | 0.008571 |
def clacks_overhead(fn):
"""
A Django view decorator that will add the `X-Clacks-Overhead` header.
Usage:
@clacks_overhead
def my_view(request):
return my_response
"""
@wraps(fn)
def _wrapped(*args, **kw):
response = fn(*args, **kw)
response['X-Clac... | [
"def",
"clacks_overhead",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"_wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"response",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"response",
"[",
"'X-Clacks-Overhe... | 21.388889 | 0.002488 |
def onAuthenticate(self, signature, extra):
"""
Callback fired when a client responds to an authentication challenge.
"""
log.msg("onAuthenticate: {} {}".format(signature, extra))
## if there is a pending auth, and the signature provided by client matches ..
if self._pen... | [
"def",
"onAuthenticate",
"(",
"self",
",",
"signature",
",",
"extra",
")",
":",
"log",
".",
"msg",
"(",
"\"onAuthenticate: {} {}\"",
".",
"format",
"(",
"signature",
",",
"extra",
")",
")",
"## if there is a pending auth, and the signature provided by client matches .."... | 37.333333 | 0.023939 |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep
"""
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
if layer_purpose != layer_purpose_aggregation:
subcat... | [
"def",
"get_next_step",
"(",
"self",
")",
":",
"layer_purpose",
"=",
"self",
".",
"parent",
".",
"step_kw_purpose",
".",
"selected_purpose",
"(",
")",
"if",
"layer_purpose",
"!=",
"layer_purpose_aggregation",
":",
"subcategory",
"=",
"self",
".",
"parent",
".",
... | 40.470588 | 0.000946 |
def _get_dependency_order(g, node_list):
"""Return list of nodes as close as possible to the ordering in node_list,
but with child nodes earlier in the list than parents."""
access_ = accessibility(g)
deps = dict((k, set(v) - set([k])) for k, v in access_.iteritems())
nodes = node_list + list(set(g.... | [
"def",
"_get_dependency_order",
"(",
"g",
",",
"node_list",
")",
":",
"access_",
"=",
"accessibility",
"(",
"g",
")",
"deps",
"=",
"dict",
"(",
"(",
"k",
",",
"set",
"(",
"v",
")",
"-",
"set",
"(",
"[",
"k",
"]",
")",
")",
"for",
"k",
",",
"v",... | 31.444444 | 0.001143 |
def examples(self):
"""Return example functions in the space.
Example functions include:
Zero
One
Heaviside function
Hypercube characteristic function
Hypersphere characteristic function
Gaussian
Linear gradients
"""
# TODO: adapt... | [
"def",
"examples",
"(",
"self",
")",
":",
"# TODO: adapt for tensor-valued functions",
"# Get the points and calculate some statistics on them",
"mins",
"=",
"self",
".",
"domain",
".",
"min",
"(",
")",
"maxs",
"=",
"self",
".",
"domain",
".",
"max",
"(",
")",
"me... | 31.726027 | 0.000838 |
def render(self, *args, **kwargs):
"""Override so each html page served have a doctype"""
return self.doctype.render() + super().render(*args, **kwargs) | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"doctype",
".",
"render",
"(",
")",
"+",
"super",
"(",
")",
".",
"render",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 55.333333 | 0.011905 |
def start_receive(self, fd, data=None):
"""
Cause :meth:`poll` to yield `data` when `fd` is readable.
"""
self._rfds[fd] = (data or fd, self._generation)
self._update(fd) | [
"def",
"start_receive",
"(",
"self",
",",
"fd",
",",
"data",
"=",
"None",
")",
":",
"self",
".",
"_rfds",
"[",
"fd",
"]",
"=",
"(",
"data",
"or",
"fd",
",",
"self",
".",
"_generation",
")",
"self",
".",
"_update",
"(",
"fd",
")"
] | 34.166667 | 0.009524 |
def observer(names_or_instance, names=None, func=None, change_only=False):
"""Specify a callback function that will fire on Property value change
Observer functions on a HasProperties class fire after the observed
Property or Properties have been changed (unlike validator functions
that fire on set bef... | [
"def",
"observer",
"(",
"names_or_instance",
",",
"names",
"=",
"None",
",",
"func",
"=",
"None",
",",
"change_only",
"=",
"False",
")",
":",
"mode",
"=",
"'observe_change'",
"if",
"change_only",
"else",
"'observe_set'",
"if",
"names",
"is",
"None",
"and",
... | 41.290909 | 0.00043 |
def do_POST(self):
"""
This method will be called for each POST request to one of the
listener ports.
It parses the CIM-XML export message and delivers the contained
CIM indication to the stored listener object.
"""
# Accept header check described in DSP0200
... | [
"def",
"do_POST",
"(",
"self",
")",
":",
"# Accept header check described in DSP0200",
"accept",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'Accept'",
",",
"'text/xml'",
")",
"if",
"accept",
"not",
"in",
"(",
"'text/xml'",
",",
"'application/xml'",
",",
"'... | 42.228395 | 0.000286 |
def add_shot(self, shot):
"""Add a Shot to :attr:`shots`, applying our survey's :attr:`declination` to it."""
shot.declination = self.declination
if shot.is_splay:
self.splays[shot['FROM']].append(shot)
self.shots.append(shot) | [
"def",
"add_shot",
"(",
"self",
",",
"shot",
")",
":",
"shot",
".",
"declination",
"=",
"self",
".",
"declination",
"if",
"shot",
".",
"is_splay",
":",
"self",
".",
"splays",
"[",
"shot",
"[",
"'FROM'",
"]",
"]",
".",
"append",
"(",
"shot",
")",
"s... | 44.166667 | 0.011111 |
def help_center_category_translation_update(self, category_id, locale, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#update-translation"
api_path = "/api/v2/help_center/categories/{category_id}/translations/{locale}.json"
api_path = api_path.format(catego... | [
"def",
"help_center_category_translation_update",
"(",
"self",
",",
"category_id",
",",
"locale",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/categories/{category_id}/translations/{locale}.json\"",
"api_path",
"=",
"api_path",
"... | 83.8 | 0.01182 |
def _user_input() -> str:
"""
A helper function which waits for user multi-line input.
:return: A string input by user, separated by ``'\\n'``.
"""
lines = []
try:
while True:
line = input()
if line != '':
lines.append(line)
else:
... | [
"def",
"_user_input",
"(",
")",
"->",
"str",
":",
"lines",
"=",
"[",
"]",
"try",
":",
"while",
"True",
":",
"line",
"=",
"input",
"(",
")",
"if",
"line",
"!=",
"''",
":",
"lines",
".",
"append",
"(",
"line",
")",
"else",
":",
"break",
"except",
... | 23.294118 | 0.002427 |
def specialInterpretValue(value,index,*args,**kwargs):
"""Interprets a passed value. In this order:
- If it's callable, call it with the parameters provided
- If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict
- Else, just return it
"""
if callable(valu... | [
"def",
"specialInterpretValue",
"(",
"value",
",",
"index",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"value",
")",
":",
"return",
"value",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"index",
"is",
"not"... | 54.333333 | 0.024145 |
def safe_execfile(self, fname, *where, **kw):
"""A safe version of the builtin execfile().
This version will never throw an exception, but instead print
helpful error messages to the screen. This only works on pure
Python files with the .py extension.
Parameters
------... | [
"def",
"safe_execfile",
"(",
"self",
",",
"fname",
",",
"*",
"where",
",",
"*",
"*",
"kw",
")",
":",
"kw",
".",
"setdefault",
"(",
"'exit_ignore'",
",",
"False",
")",
"kw",
".",
"setdefault",
"(",
"'raise_exceptions'",
",",
"False",
")",
"fname",
"=",
... | 40.183333 | 0.002024 |
def from_dict(cls, ctx):
'Instance a new structure from a Python dictionary.'
ctx = Context(ctx)
s = cls()
ContextFlags = ctx['ContextFlags']
setattr(s, 'ContextFlags', ContextFlags)
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for k... | [
"def",
"from_dict",
"(",
"cls",
",",
"ctx",
")",
":",
"ctx",
"=",
"Context",
"(",
"ctx",
")",
"s",
"=",
"cls",
"(",
")",
"ContextFlags",
"=",
"ctx",
"[",
"'ContextFlags'",
"]",
"setattr",
"(",
"s",
",",
"'ContextFlags'",
",",
"ContextFlags",
")",
"if... | 47.230769 | 0.002394 |
def interpolate_with(self, other_tf, t):
"""Interpolate with another rigid transformation.
Parameters
----------
other_tf : :obj:`RigidTransform`
The transform to interpolate with.
t : float
The interpolation step in [0,1], where 0 favors this RigidTrans... | [
"def",
"interpolate_with",
"(",
"self",
",",
"other_tf",
",",
"t",
")",
":",
"if",
"t",
"<",
"0",
"or",
"t",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Must interpolate between 0 and 1'",
")",
"interp_translation",
"=",
"(",
"1.0",
"-",
"t",
")",
"*",
... | 34 | 0.011834 |
def catch_nb_assignment(func):
"""
Wrapper to catch `nb` keyword arguments
This helps catch `nb` keyword arguments and assign onto self when passed to
the wrapped function.
Used for callback methods when the caller may optionally have a new copy
of the originally wrapped `nb` object.
"""
... | [
"def",
"catch_nb_assignment",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nb",
"=",
"kwargs",
".",
"get",
"(",
"'nb'",
")",
"if",
"nb",
":",
"# Reassi... | 27.75 | 0.001742 |
def num_tasks(self, work_spec_name):
'''Get the total number of work units for some work spec.'''
return self.num_finished(work_spec_name) + \
self.num_failed(work_spec_name) + \
self.registry.len(WORK_UNITS_ + work_spec_name) | [
"def",
"num_tasks",
"(",
"self",
",",
"work_spec_name",
")",
":",
"return",
"self",
".",
"num_finished",
"(",
"work_spec_name",
")",
"+",
"self",
".",
"num_failed",
"(",
"work_spec_name",
")",
"+",
"self",
".",
"registry",
".",
"len",
"(",
"WORK_UNITS_",
"... | 53.6 | 0.014706 |
def _get_github(self):
"""Creates an instance of github.Github to interact with the repos via the
API interface in pygithub.
"""
from github import Github
vms("Querying github with user '{}'.".format(self.username))
g = Github(self.username, self.apikey)
self._us... | [
"def",
"_get_github",
"(",
"self",
")",
":",
"from",
"github",
"import",
"Github",
"vms",
"(",
"\"Querying github with user '{}'.\"",
".",
"format",
"(",
"self",
".",
"username",
")",
")",
"g",
"=",
"Github",
"(",
"self",
".",
"username",
",",
"self",
".",... | 51.322581 | 0.010487 |
def NaiveBayesLearner(dataset):
"""Just count how many times each value of each input attribute
occurs, conditional on the target value. Count the different
target values too."""
targetvals = dataset.values[dataset.target]
target_dist = CountingProbDist(targetvals)
attr_dists = dict(((gv, attr)... | [
"def",
"NaiveBayesLearner",
"(",
"dataset",
")",
":",
"targetvals",
"=",
"dataset",
".",
"values",
"[",
"dataset",
".",
"target",
"]",
"target_dist",
"=",
"CountingProbDist",
"(",
"targetvals",
")",
"attr_dists",
"=",
"dict",
"(",
"(",
"(",
"gv",
",",
"att... | 42.923077 | 0.000876 |
def get(self):
'''taobao.time.get 获取前台展示的店铺类目
获取淘宝系统当前时间'''
request = TOPRequest('taobao.time.get')
self.create(self.execute(request))
return self.time | [
"def",
"get",
"(",
"self",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.time.get'",
")",
"self",
".",
"create",
"(",
"self",
".",
"execute",
"(",
"request",
")",
")",
"return",
"self",
".",
"time"
] | 27.714286 | 0.015 |
def wait_for_build(self, interval=5, path=None):
"""
A convenience method designed to inform you when a project build has
completed. It polls the API every `interval` seconds until there is
not a build running. At that point, it returns the "last_build_info"
field of the projec... | [
"def",
"wait_for_build",
"(",
"self",
",",
"interval",
"=",
"5",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"''",
"start",
"=",
"time",
".",
"time",
"(",
")",
"next_log",
"=",
"0",
"while",
"True",
":",
"response",
"=",
"self",
... | 44.206897 | 0.001527 |
def get(self, key):
"""Get data for given store key. Raise hug.exceptions.StoreKeyNotFound if key does not exist."""
try:
data = self._data[key]
except KeyError:
raise StoreKeyNotFound(key)
return data | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"_data",
"[",
"key",
"]",
"except",
"KeyError",
":",
"raise",
"StoreKeyNotFound",
"(",
"key",
")",
"return",
"data"
] | 35.857143 | 0.011673 |
def validate_settings(settings):
"""
Raise an error in prod if we see any insecure settings.
This used to warn during development but that was changed in
71718bec324c2561da6cc3990c927ee87362f0f7
"""
from django.core.exceptions import ImproperlyConfigured
if settings.SECRET_KEY == '':
... | [
"def",
"validate_settings",
"(",
"settings",
")",
":",
"from",
"django",
".",
"core",
".",
"exceptions",
"import",
"ImproperlyConfigured",
"if",
"settings",
".",
"SECRET_KEY",
"==",
"''",
":",
"msg",
"=",
"'settings.SECRET_KEY cannot be blank! Check your local settings'... | 40.083333 | 0.001015 |
def parse_requirements(filename, finder=None, comes_from=None, options=None,
session=None, wheel_cache=None):
"""
Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.Pack... | [
"def",
"parse_requirements",
"(",
"filename",
",",
"finder",
"=",
"None",
",",
"comes_from",
"=",
"None",
",",
"options",
"=",
"None",
",",
"session",
"=",
"None",
",",
"wheel_cache",
"=",
"None",
")",
":",
"if",
"session",
"is",
"None",
":",
"raise",
... | 36.375 | 0.000837 |
def bitwise_xor(self, t):
"""
Operation xor
:param t: The other operand.
"""
# Using same variables as in paper
s = self
new_interval = (s.bitwise_not().bitwise_or(t)).bitwise_not().bitwise_or(s.bitwise_or(t.bitwise_not()).bitwise_not())
return new_int... | [
"def",
"bitwise_xor",
"(",
"self",
",",
"t",
")",
":",
"# Using same variables as in paper",
"s",
"=",
"self",
"new_interval",
"=",
"(",
"s",
".",
"bitwise_not",
"(",
")",
".",
"bitwise_or",
"(",
"t",
")",
")",
".",
"bitwise_not",
"(",
")",
".",
"bitwise... | 29.727273 | 0.008902 |
def Overlay_highlightFrame(self, frameId, **kwargs):
"""
Function path: Overlay.highlightFrame
Domain: Overlay
Method name: highlightFrame
Parameters:
Required arguments:
'frameId' (type: Page.FrameId) -> Identifier of the frame to highlight.
Optional arguments:
'contentColor' (type: D... | [
"def",
"Overlay_highlightFrame",
"(",
"self",
",",
"frameId",
",",
"*",
"*",
"kwargs",
")",
":",
"expected",
"=",
"[",
"'contentColor'",
",",
"'contentOutlineColor'",
"]",
"passed_keys",
"=",
"list",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"assert",
"al... | 41.347826 | 0.034943 |
def affected_files(self):
"""
Get's a fast accessible file changes for given changeset
"""
added, modified, deleted = self._changes_cache
return list(added.union(modified).union(deleted)) | [
"def",
"affected_files",
"(",
"self",
")",
":",
"added",
",",
"modified",
",",
"deleted",
"=",
"self",
".",
"_changes_cache",
"return",
"list",
"(",
"added",
".",
"union",
"(",
"modified",
")",
".",
"union",
"(",
"deleted",
")",
")"
] | 37 | 0.008811 |
def update_app(id, config):
'''
Update the specified app with the given configuration.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.update_app my-app '<config yaml>'
'''
if 'id' not in config:
config['id'] = id
config.pop('version', None)
# mirror... | [
"def",
"update_app",
"(",
"id",
",",
"config",
")",
":",
"if",
"'id'",
"not",
"in",
"config",
":",
"config",
"[",
"'id'",
"]",
"=",
"id",
"config",
".",
"pop",
"(",
"'version'",
",",
"None",
")",
"# mirror marathon-ui handling for uris deprecation (see",
"# ... | 29.763158 | 0.000856 |
def gpio_set(self, pins, states):
"""Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
state... | [
"def",
"gpio_set",
"(",
"self",
",",
"pins",
",",
"states",
")",
":",
"if",
"len",
"(",
"pins",
")",
"!=",
"len",
"(",
"states",
")",
":",
"raise",
"ValueError",
"(",
"'Length mismatch between pins and states.'",
")",
"size",
"=",
"len",
"(",
"pins",
")"... | 35.393939 | 0.001667 |
def check_output_format(fmt, nfiles):
"""Validate file format string.
Parameters
----------
fmt : `str`
File format string.
nfiles : `int`
Number of files.
Raises
------
ValueError
If nfiles < 0 or format string is invalid.
"""
if nfiles < 0:
rai... | [
"def",
"check_output_format",
"(",
"fmt",
",",
"nfiles",
")",
":",
"if",
"nfiles",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid file count: '",
"+",
"str",
"(",
"nfiles",
")",
")",
"if",
"nfiles",
"==",
"1",
":",
"return",
"try",
":",
"fmt",
"%... | 22.08 | 0.001736 |
def offset_to_skydir(skydir, offset_lon, offset_lat,
coordsys='CEL', projection='AIT'):
"""Convert a cartesian offset (X,Y) in the given projection into
a SkyCoord."""
offset_lon = np.array(offset_lon, ndmin=1)
offset_lat = np.array(offset_lat, ndmin=1)
w = create_wcs(skydir, ... | [
"def",
"offset_to_skydir",
"(",
"skydir",
",",
"offset_lon",
",",
"offset_lat",
",",
"coordsys",
"=",
"'CEL'",
",",
"projection",
"=",
"'AIT'",
")",
":",
"offset_lon",
"=",
"np",
".",
"array",
"(",
"offset_lon",
",",
"ndmin",
"=",
"1",
")",
"offset_lat",
... | 39.3 | 0.002488 |
def is_estimator(model):
"""
Determines if a model is an estimator using issubclass and isinstance.
Parameters
----------
estimator : class or instance
The object to test if it is a Scikit-Learn clusterer, especially a
Scikit-Learn estimator or Yellowbrick visualizer
"""
if ... | [
"def",
"is_estimator",
"(",
"model",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"model",
")",
":",
"return",
"issubclass",
"(",
"model",
",",
"BaseEstimator",
")",
"return",
"isinstance",
"(",
"model",
",",
"BaseEstimator",
")"
] | 30.214286 | 0.002294 |
def package_repositories(self):
"""
Property for accessing :class:`PackageRepositoryManager` instance, which is used to manage package repos.
:rtype: yagocd.resources.package_repository.PackageRepositoryManager
"""
if self._package_repository_manager is None:
self._p... | [
"def",
"package_repositories",
"(",
"self",
")",
":",
"if",
"self",
".",
"_package_repository_manager",
"is",
"None",
":",
"self",
".",
"_package_repository_manager",
"=",
"PackageRepositoryManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
"se... | 48.333333 | 0.009029 |
def nucnorm(x, rho, penalty, newshape=None):
"""
Nuclear norm
Parameters
----------
penalty : float
nuclear norm penalty hyperparameter
newshape : tuple, optional
Desired shape of the parameters to apply the nuclear norm to. The given
parameters are reshaped to an array... | [
"def",
"nucnorm",
"(",
"x",
",",
"rho",
",",
"penalty",
",",
"newshape",
"=",
"None",
")",
":",
"orig_shape",
"=",
"x",
".",
"shape",
"if",
"newshape",
"is",
"not",
"None",
":",
"x",
"=",
"x",
".",
"reshape",
"(",
"newshape",
")",
"u",
",",
"s",
... | 27.416667 | 0.001468 |
def validateDocumentFinal(self, doc):
"""Does the final step for the document validation once all
the incremental validation steps have been completed
basically it does the following checks described by the XML
Rec Check all the IDREF/IDREFS attributes definition for
va... | [
"def",
"validateDocumentFinal",
"(",
"self",
",",
"doc",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateDocumentFinal",
"(",
"self",
".",
"_o",
"... | 47.5 | 0.008264 |
def run(self):
'''
Execute the salt call logic
'''
profiling_enabled = self.opts.get('profiling_enabled', False)
try:
pr = salt.utils.profile.activate_profile(profiling_enabled)
try:
ret = self.call()
finally:
sa... | [
"def",
"run",
"(",
"self",
")",
":",
"profiling_enabled",
"=",
"self",
".",
"opts",
".",
"get",
"(",
"'profiling_enabled'",
",",
"False",
")",
"try",
":",
"pr",
"=",
"salt",
".",
"utils",
".",
"profile",
".",
"activate_profile",
"(",
"profiling_enabled",
... | 39.28125 | 0.002329 |
def check_collision_state( cls, collision_state, history_id_key, history_id, block_id, checked_ops, affected_opcodes ):
"""
Given a history ID, see if it already exists
at the given block ID (i.e. it's not expired),
using the given collision state.
Return True if so; False if not... | [
"def",
"check_collision_state",
"(",
"cls",
",",
"collision_state",
",",
"history_id_key",
",",
"history_id",
",",
"block_id",
",",
"checked_ops",
",",
"affected_opcodes",
")",
":",
"# seen before in this block?",
"if",
"collision_state",
".",
"has_key",
"(",
"block_i... | 34.367347 | 0.013279 |
def products(self):
"""List of output files produces by self."""
_products = []
for ext in self.exts:
prod = Product(ext, self.node.opath_from_ext(ext))
_products.append(prod)
return _products | [
"def",
"products",
"(",
"self",
")",
":",
"_products",
"=",
"[",
"]",
"for",
"ext",
"in",
"self",
".",
"exts",
":",
"prod",
"=",
"Product",
"(",
"ext",
",",
"self",
".",
"node",
".",
"opath_from_ext",
"(",
"ext",
")",
")",
"_products",
".",
"append... | 30.25 | 0.008032 |
def failure_message(description, options):
"""
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
"""... | [
"def",
"failure_message",
"(",
"description",
",",
"options",
")",
":",
"message",
"=",
"\"expected to find {}\"",
".",
"format",
"(",
"description",
")",
"if",
"options",
"[",
"\"count\"",
"]",
"is",
"not",
"None",
":",
"message",
"+=",
"\" {count} {times}\"",
... | 33.289474 | 0.000768 |
def ExpandWindowsUserEnvironmentVariables(data_string,
knowledge_base,
sid=None,
username=None):
r"""Take a string and expand windows user environment variables based.
Args:
data_string... | [
"def",
"ExpandWindowsUserEnvironmentVariables",
"(",
"data_string",
",",
"knowledge_base",
",",
"sid",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"win_environ_regex",
"=",
"re",
".",
"compile",
"(",
"r\"%([^%]+?)%\"",
")",
"components",
"=",
"[",
"]",
... | 36.75 | 0.009114 |
def push_object(self, channel_id, obj):
"""Push ``obj`` for ``channel_id``. ``obj`` will be encoded as JSON in
the request.
"""
return self.push(channel_id, json.dumps(obj).replace('"', '\\"')) | [
"def",
"push_object",
"(",
"self",
",",
"channel_id",
",",
"obj",
")",
":",
"return",
"self",
".",
"push",
"(",
"channel_id",
",",
"json",
".",
"dumps",
"(",
"obj",
")",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
")"
] | 36.833333 | 0.00885 |
def delete_dev_vlans(devid, vlanid, auth, url):
"""
function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the
specified VLAN from the target device.
:param devid: int or str value of the target device
:param vlanid:
:return:HTTP Status code of... | [
"def",
"delete_dev_vlans",
"(",
"devid",
",",
"vlanid",
",",
"auth",
",",
"url",
")",
":",
"remove_dev_vlan_url",
"=",
"\"/imcrs/vlan/delvlan?devId=\"",
"+",
"str",
"(",
"devid",
")",
"+",
"\"&vlanId=\"",
"+",
"str",
"(",
"vlanid",
")",
"f_url",
"=",
"url",
... | 47.454545 | 0.008451 |
def get_cache_subnet_group(name, region=None, key=None, keyid=None,
profile=None):
'''
Get information about a cache subnet group.
CLI example::
salt myminion boto_elasticache.get_cache_subnet_group mycache_subnet_group
'''
conn = _get_conn(region=region, key=key... | [
"def",
"get_cache_subnet_group",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
... | 36.534884 | 0.00124 |
def same_pyname(expected, pyname):
"""Check whether `expected` and `pyname` are the same"""
if expected is None or pyname is None:
return False
if expected == pyname:
return True
if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) \
and type(pyname) not in \
... | [
"def",
"same_pyname",
"(",
"expected",
",",
"pyname",
")",
":",
"if",
"expected",
"is",
"None",
"or",
"pyname",
"is",
"None",
":",
"return",
"False",
"if",
"expected",
"==",
"pyname",
":",
"return",
"True",
"if",
"type",
"(",
"expected",
")",
"not",
"i... | 41.384615 | 0.001818 |
def compar(self, x, y):
'''
simple comparator method
'''
indX=0
indY=0
a= int(x[0].split('-')[1])
b= int(y[0].split('-')[1])
if a>b:
return 1
if a==b:
return 0
if a<b:
return -1 | [
"def",
"compar",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"indX",
"=",
"0",
"indY",
"=",
"0",
"a",
"=",
"int",
"(",
"x",
"[",
"0",
"]",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
")",
"b",
"=",
"int",
"(",
"y",
"[",
"0",
"]",
"."... | 14 | 0.033445 |
def _load_network(self):
""" Building the predictor out of the model."""
self.embeddings = load_embeddings(self.lang, type='cw')
self.model = load_pos_model(lang=self.lang, version=2)
def predict_proba(input_):
hidden = np.tanh(np.dot(input_, self.model["W1"]) + self.model["b1"])
output = ... | [
"def",
"_load_network",
"(",
"self",
")",
":",
"self",
".",
"embeddings",
"=",
"load_embeddings",
"(",
"self",
".",
"lang",
",",
"type",
"=",
"'cw'",
")",
"self",
".",
"model",
"=",
"load_pos_model",
"(",
"lang",
"=",
"self",
".",
"lang",
",",
"version... | 39 | 0.014614 |
def print_memory(function):
'''
Decorator that prints memory information at each call of the function
'''
import memory_profiler
def wrapper(*args,**kwargs):
m = StringIO()
temp_func = memory_profiler.profile(func = function,stream=m,precision=4)
output = temp_func(*args,**kw... | [
"def",
"print_memory",
"(",
"function",
")",
":",
"import",
"memory_profiler",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"m",
"=",
"StringIO",
"(",
")",
"temp_func",
"=",
"memory_profiler",
".",
"profile",
"(",
"func",
"=",
... | 30.769231 | 0.021845 |
def verifymenucheck(self, window_name, object_name):
"""
Verify a menu item is checked
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either ful... | [
"def",
"verifymenucheck",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"try",
":",
"menu_handle",
"=",
"self",
".",
"_get_menu_handle",
"(",
"window_name",
",",
"object_name",
",",
"False",
")",
"try",
":",
"if",
"menu_handle",
".",
"AXMenu... | 33.423077 | 0.002237 |
def create(self, workflow_id, email_id, data):
"""
Manually add a subscriber to a workflow, bypassing the default trigger
settings. You can also use this endpoint to trigger a series of
automated emails in an API 3.0 workflow type or add subscribers to an
automated email queue th... | [
"def",
"create",
"(",
"self",
",",
"workflow_id",
",",
"email_id",
",",
"data",
")",
":",
"self",
".",
"workflow_id",
"=",
"workflow_id",
"self",
".",
"email_id",
"=",
"email_id",
"if",
"'email_address'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",... | 40.83871 | 0.002315 |
def refresh(self):
'''
Refresh the list and the screen
'''
self._screen.force_update()
self._screen.refresh()
self._update(1) | [
"def",
"refresh",
"(",
"self",
")",
":",
"self",
".",
"_screen",
".",
"force_update",
"(",
")",
"self",
".",
"_screen",
".",
"refresh",
"(",
")",
"self",
".",
"_update",
"(",
"1",
")"
] | 23.857143 | 0.011561 |
def get_deviations(self):
"""get the deviations of the ensemble value from the mean vector
Returns
-------
en : pyemu.Ensemble
Ensemble of deviations from the mean
"""
bt = False
if not self.istransformed:
bt = True
sel... | [
"def",
"get_deviations",
"(",
"self",
")",
":",
"bt",
"=",
"False",
"if",
"not",
"self",
".",
"istransformed",
":",
"bt",
"=",
"True",
"self",
".",
"_transform",
"(",
")",
"mean_vec",
"=",
"self",
".",
"mean",
"(",
")",
"df",
"=",
"self",
".",
"loc... | 28.3 | 0.008547 |
def add(self, *args):
""" Add integers
args:
args (list): target
returns:
str
"""
if (len(args) <= 1):
return 0
return sum([int(v) for v in args]) | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"(",
"len",
"(",
"args",
")",
"<=",
"1",
")",
":",
"return",
"0",
"return",
"sum",
"(",
"[",
"int",
"(",
"v",
")",
"for",
"v",
"in",
"args",
"]",
")"
] | 22.1 | 0.008696 |
def filter_time_frame(start, delta):
"""Filter :class:`.Line` objects by their connection time.
:param start: a time expression (see -s argument on --help for its format)
to filter log lines that are before this time.
:type start: string
:param delta: a relative time expression (see -s argument o... | [
"def",
"filter_time_frame",
"(",
"start",
",",
"delta",
")",
":",
"start_value",
"=",
"start",
"delta_value",
"=",
"delta",
"end_value",
"=",
"None",
"if",
"start_value",
"is",
"not",
"''",
":",
"start_value",
"=",
"_date_str_to_datetime",
"(",
"start_value",
... | 30.102564 | 0.000825 |
def optimisation_plot(d, overlay_alpha=0.5, **kwargs):
"""
Plot the result of signal_optimise.
`signal_optimiser` must be run first, and the output
stored in the `opt` attribute of the latools.D object.
Parameters
----------
d : latools.D object
A latools data object.
overlay_a... | [
"def",
"optimisation_plot",
"(",
"d",
",",
"overlay_alpha",
"=",
"0.5",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"d",
",",
"'opt'",
")",
":",
"raise",
"ValueError",
"(",
"'Please run `signal_optimiser` before trying to plot its results.'",
... | 38.452991 | 0.010618 |
def index():
"""
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with result.show_result directly and are instead
dynamically generated through javas... | [
"def",
"index",
"(",
")",
":",
"if",
"current_app",
".",
"config",
"[",
"'ARA_PLAYBOOK_OVERRIDE'",
"]",
"is",
"not",
"None",
":",
"override",
"=",
"current_app",
".",
"config",
"[",
"'ARA_PLAYBOOK_OVERRIDE'",
"]",
"results",
"=",
"(",
"models",
".",
"TaskRes... | 43.941176 | 0.001311 |
def get_brokendate_fx_forward_rate(self, asset_manager_id, asset_id, price_date, value_date):
"""
This method takes calculates broken date forward FX rate based on the passed in parameters
"""
self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s ... | [
"def",
"get_brokendate_fx_forward_rate",
"(",
"self",
",",
"asset_manager_id",
",",
"asset_id",
",",
"price_date",
",",
"value_date",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s - Price Date:... | 62.4 | 0.010526 |
def yiq_to_rgb(y, i=None, q=None):
"""Convert the color from YIQ coordinates to RGB.
Parameters:
:y:
Tte Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...... | [
"def",
"yiq_to_rgb",
"(",
"y",
",",
"i",
"=",
"None",
",",
"q",
"=",
"None",
")",
":",
"if",
"type",
"(",
"y",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"y",
",",
"i",
",",
"q",
"=",
"y",
"r",
"=",
"y",
"+",
"(",
"i",
"*",
"0.9562... | 22.777778 | 0.014041 |
def _load_manifest_interpret_source(manifest, source, username=None, password=None, verify_certificate=True, do_inherit=True):
""" Interpret the <source>, and load the results into <manifest> """
try:
if isinstance(source, string_types):
if source.startswith("http"):
# if man... | [
"def",
"_load_manifest_interpret_source",
"(",
"manifest",
",",
"source",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"verify_certificate",
"=",
"True",
",",
"do_inherit",
"=",
"True",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"sour... | 53 | 0.002316 |
def _create_producer(self, settings):
"""Tries to establish a Kafka consumer connection"""
try:
brokers = settings['KAFKA_HOSTS']
self.logger.debug("Creating new kafka producer using brokers: " +
str(brokers))
return KafkaProducer(boots... | [
"def",
"_create_producer",
"(",
"self",
",",
"settings",
")",
":",
"try",
":",
"brokers",
"=",
"settings",
"[",
"'KAFKA_HOSTS'",
"]",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Creating new kafka producer using brokers: \"",
"+",
"str",
"(",
"brokers",
")",
... | 50.052632 | 0.008256 |
def normalize_datum(self, datum):
"""
Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is called by :meth:... | [
"def",
"normalize_datum",
"(",
"self",
",",
"datum",
")",
":",
"if",
"datum",
"is",
"None",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
",",
"self",
".",
"PACKABLE_TYPES",
")",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
",",
... | 50.347368 | 0.00041 |
def get_my_choices_tasks(current_proj):
""" Retrieves all tasks in the system
for the task management page
"""
task_list = []
tasks = Task.objects.all()
for task in tasks:
if task.project == current_proj:
task_list.append(task)
task_tuple = []
counter = 1
fo... | [
"def",
"get_my_choices_tasks",
"(",
"current_proj",
")",
":",
"task_list",
"=",
"[",
"]",
"tasks",
"=",
"Task",
".",
"objects",
".",
"all",
"(",
")",
"for",
"task",
"in",
"tasks",
":",
"if",
"task",
".",
"project",
"==",
"current_proj",
":",
"task_list",... | 24.647059 | 0.002299 |
def convert_month(date, shorten=True, cable=True):
"""Replace month by shortening or lengthening it.
:param shorten: Set to True to shorten month name.
:param cable: Set to True if category is Cable.
"""
month = date.split()[0].lower()
if 'sept' in month:
shorten = False if cable else T... | [
"def",
"convert_month",
"(",
"date",
",",
"shorten",
"=",
"True",
",",
"cable",
"=",
"True",
")",
":",
"month",
"=",
"date",
".",
"split",
"(",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"'sept'",
"in",
"month",
":",
"shorten",
"=",
"False... | 30.210526 | 0.001689 |
def _canceling_task(self, backend):
"""
Used internally to decrement `backend`s current and total task counts
when `backend` could not be reached.
"""
with self.backend_mutex:
self.backends[backend] -= 1
self.task_counter[backend] -= 1 | [
"def",
"_canceling_task",
"(",
"self",
",",
"backend",
")",
":",
"with",
"self",
".",
"backend_mutex",
":",
"self",
".",
"backends",
"[",
"backend",
"]",
"-=",
"1",
"self",
".",
"task_counter",
"[",
"backend",
"]",
"-=",
"1"
] | 36.625 | 0.01 |
def register_filter_builder(self, function, **kwargs):
"""Register a filter function with this :class:`~.Filters` instance.
This function is curried with :class:`~okcupyd.util.currying.curry`
-- that is, it can be invoked partially before it is fully evaluated.
This allows us to pass kwa... | [
"def",
"register_filter_builder",
"(",
"self",
",",
"function",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'transform'",
"]",
"=",
"function",
"if",
"kwargs",
".",
"get",
"(",
"'decider'",
")",
":",
"kwargs",
"[",
"'decide'",
"]",
"=",
"kwargs",
... | 55.225 | 0.001335 |
def AgregarContingencias(self, tipo=None, observacion=None, **kwargs):
"Agrega la información referente a los opcionales de la liq. seq."
contingencia = dict(tipoContingencia=tipo, observacion=observacion)
self.remito['arrayContingencias'].append(dict(contingencia=contingencia))
return T... | [
"def",
"AgregarContingencias",
"(",
"self",
",",
"tipo",
"=",
"None",
",",
"observacion",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"contingencia",
"=",
"dict",
"(",
"tipoContingencia",
"=",
"tipo",
",",
"observacion",
"=",
"observacion",
")",
"self"... | 63.8 | 0.009288 |
def _raise_disambiguation_error(self, page, pageid):
""" parse and throw a disambiguation error """
query_params = {
"prop": "revisions",
"rvprop": "content",
"rvparse": "",
"rvlimit": 1,
}
query_params.update(self.__title_query_param())
... | [
"def",
"_raise_disambiguation_error",
"(",
"self",
",",
"page",
",",
"pageid",
")",
":",
"query_params",
"=",
"{",
"\"prop\"",
":",
"\"revisions\"",
",",
"\"rvprop\"",
":",
"\"content\"",
",",
"\"rvparse\"",
":",
"\"\"",
",",
"\"rvlimit\"",
":",
"1",
",",
"}... | 39.4 | 0.002123 |
def get_host_usage(self):
"""
get details of CPU, RAM usage of this PC
"""
import psutil
process_names = [proc.name for proc in psutil.process_iter()]
cpu_pct = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory()
return str(cpu_pct), str(len(pro... | [
"def",
"get_host_usage",
"(",
"self",
")",
":",
"import",
"psutil",
"process_names",
"=",
"[",
"proc",
".",
"name",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
"]",
"cpu_pct",
"=",
"psutil",
".",
"cpu_percent",
"(",
"interval",
"=",
"1"... | 40 | 0.013587 |
def validate(
self, schema_id, validation_function=None,
validation_error_handler=None):
"""
A decorator that is used to validate incoming requests data
against a schema
swagger = Swagger(app)
@app.route('/pets', methods=['POST'])
@sw... | [
"def",
"validate",
"(",
"self",
",",
"schema_id",
",",
"validation_function",
"=",
"None",
",",
"validation_error_handler",
"=",
"None",
")",
":",
"if",
"validation_function",
"is",
"None",
":",
"validation_function",
"=",
"self",
".",
"validation_function",
"if",... | 36.981481 | 0.000976 |
def parse_options_header(value, multiple=False):
"""Parse a ``Content-Type`` like header into a tuple with the content
type and the options:
>>> parse_options_header('text/html; charset=utf8')
('text/html', {'charset': 'utf8'})
This should not be used to parse ``Cache-Control`` like headers that u... | [
"def",
"parse_options_header",
"(",
"value",
",",
"multiple",
"=",
"False",
")",
":",
"if",
"not",
"value",
":",
"return",
"\"\"",
",",
"{",
"}",
"result",
"=",
"[",
"]",
"value",
"=",
"\",\"",
"+",
"value",
".",
"replace",
"(",
"\"\\n\"",
",",
"\",\... | 37.228571 | 0.001121 |
def compile_file(self, filename, ns):
"""
Compile a MOF file into a namespace of the associated CIM repository.
Parameters:
filename (:term:`string`):
The path name of the MOF file containing the MOF statements to be
compiled.
ns (:term:`string`):
... | [
"def",
"compile_file",
"(",
"self",
",",
"filename",
",",
"ns",
")",
":",
"if",
"self",
".",
"parser",
".",
"verbose",
":",
"self",
".",
"parser",
".",
"log",
"(",
"_format",
"(",
"\"Compiling file {0!A}\"",
",",
"filename",
")",
")",
"if",
"not",
"os"... | 33.026316 | 0.001548 |
def export_gpg_key(key):
"""Exports a GPG key and returns it"""
cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),
"--export", key])
handle, gpg_stderr = stderr_handle()
try:
gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # nosec
... | [
"def",
"export_gpg_key",
"(",
"key",
")",
":",
"cmd",
"=",
"flatten",
"(",
"[",
"gnupg_bin",
"(",
")",
",",
"gnupg_verbose",
"(",
")",
",",
"gnupg_home",
"(",
")",
",",
"\"--export\"",
",",
"key",
"]",
")",
"handle",
",",
"gpg_stderr",
"=",
"stderr_han... | 40.823529 | 0.001408 |
def point_plane_distance(points,
plane_normal,
plane_origin=[0.0, 0.0, 0.0]):
"""
The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vecto... | [
"def",
"point_plane_distance",
"(",
"points",
",",
"plane_normal",
",",
"plane_origin",
"=",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
")",
":",
"points",
"=",
"np",
".",
"asanyarray",
"(",
"points",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"w",
... | 31.45 | 0.001543 |
def send(self, signal, **kwargs):
"""
Sends a signal for the given plugin.
:param signal: Name of the signal
:type signal: str
"""
return self.__app.signals.send(signal, plugin=self._plugin, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"signal",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__app",
".",
"signals",
".",
"send",
"(",
"signal",
",",
"plugin",
"=",
"self",
".",
"_plugin",
",",
"*",
"*",
"kwargs",
")"
] | 30.25 | 0.008032 |
def create_gzip_cache(pelican):
'''Create a gzip cache file for every file that a webserver would
reasonably want to cache (e.g., text type files).
:param pelican: The Pelican instance
'''
for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
for name in filenames:
... | [
"def",
"create_gzip_cache",
"(",
"pelican",
")",
":",
"for",
"dirpath",
",",
"_",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"pelican",
".",
"settings",
"[",
"'OUTPUT_PATH'",
"]",
")",
":",
"for",
"name",
"in",
"filenames",
":",
"if",
"should_compre... | 43 | 0.00207 |
def close(self):
"""close an open connection"""
if not self.connected: return True
self._close()
self.connected = False
self.log("Closed Connection {}", self.connection_config.interface_name)
return True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"return",
"True",
"self",
".",
"_close",
"(",
")",
"self",
".",
"connected",
"=",
"False",
"self",
".",
"log",
"(",
"\"Closed Connection {}\"",
",",
"self",
".",
"connec... | 30.625 | 0.011905 |
def delete_differ_record(old_image, durable_model):
"""Handles a DynamoDB DELETE event type -- For the Differ."""
data = {}
for item in old_image:
data[item] = DESER.deserialize(old_image[item])
data['configuration'] = {}
# we give our own timestamps for TTL deletions
del data['eventTim... | [
"def",
"delete_differ_record",
"(",
"old_image",
",",
"durable_model",
")",
":",
"data",
"=",
"{",
"}",
"for",
"item",
"in",
"old_image",
":",
"data",
"[",
"item",
"]",
"=",
"DESER",
".",
"deserialize",
"(",
"old_image",
"[",
"item",
"]",
")",
"data",
... | 35.545455 | 0.002494 |
def writelines(self, lines):
"""Write a list of strings to file."""
self.make_dir()
with open(self.path, "w") as f:
return f.writelines(lines) | [
"def",
"writelines",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"make_dir",
"(",
")",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"return",
"f",
".",
"writelines",
"(",
"lines",
")"
] | 34.8 | 0.011236 |
def mix(color1, color2, weight=Number(50, "%")):
"""
Mixes together two colors. Specifically, takes the average of each of the
RGB components, optionally weighted by the given percentage.
The opacity of the colors is also considered when weighting the components.
Specifically, takes the average of ... | [
"def",
"mix",
"(",
"color1",
",",
"color2",
",",
"weight",
"=",
"Number",
"(",
"50",
",",
"\"%\"",
")",
")",
":",
"# This algorithm factors in both the user-provided weight",
"# and the difference between the alpha values of the two colors",
"# to decide how to perform the weig... | 39.069444 | 0.000347 |
def _default_static_lib(self, obj_files):
"""Create a static library (i.e. a ``.a`` / ``.lib`` file).
Args:
obj_files (List[str]): List of paths of compiled object files.
"""
c_compiler = self.F90_COMPILER.c_compiler
static_lib_dir = os.path.join(self.build_lib, "bez... | [
"def",
"_default_static_lib",
"(",
"self",
",",
"obj_files",
")",
":",
"c_compiler",
"=",
"self",
".",
"F90_COMPILER",
".",
"c_compiler",
"static_lib_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"build_lib",
",",
"\"bezier\"",
",",
"\"lib\"",... | 42.761905 | 0.002179 |
def abu_chart(self, cycle, mass_range=None ,ilabel=True,
imlabel=True, imlabel_fontsize=8, imagic=False,
boxstable=True, lbound=(-12, 0),
plotaxis=[0, 0, 0, 0], show=True, color_map='jet',
ifig=None,data_provided=False,thedata=None,
... | [
"def",
"abu_chart",
"(",
"self",
",",
"cycle",
",",
"mass_range",
"=",
"None",
",",
"ilabel",
"=",
"True",
",",
"imlabel",
"=",
"True",
",",
"imlabel_fontsize",
"=",
"8",
",",
"imagic",
"=",
"False",
",",
"boxstable",
"=",
"True",
",",
"lbound",
"=",
... | 34.767677 | 0.016098 |
def name(self):
"""Give back tab name if is set else generate name by code"""
if self._name:
return self._name
return self.code.replace('_', ' ').capitalize() | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
":",
"return",
"self",
".",
"_name",
"return",
"self",
".",
"code",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"capitalize",
"(",
")"
] | 38 | 0.010309 |
def _add_eap_args(eap_args: Dict[str, str]) -> List[str]:
""" Add configuration options suitable for an nmcli con add command
for WPA-EAP configuration. These options are mostly in the
802-1x group.
The eap_args dict should be a flat structure of arguments. They
must contain at least 'eapType', spe... | [
"def",
"_add_eap_args",
"(",
"eap_args",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"args",
"=",
"[",
"'wifi-sec.key-mgmt'",
",",
"'wpa-eap'",
"]",
"eap_type",
"=",
"EAP_TYPES",
".",
"by_qualified_name",
"(",
"eap_... | 44.714286 | 0.000782 |
def calculate_z2pt5_ngaw2(vs30):
'''
Reads an array of vs30 values (in m/s) and
returns the depth to the 2.5 km/s velocity horizon (in km)
Ref: Campbell, K.W. & Bozorgnia, Y., 2014.
'NGA-West2 ground motion model for the average horizontal components of
PGA, PGV, and 5pct damped linear accelerat... | [
"def",
"calculate_z2pt5_ngaw2",
"(",
"vs30",
")",
":",
"c1",
"=",
"7.089",
"c2",
"=",
"-",
"1.144",
"z2pt5",
"=",
"numpy",
".",
"exp",
"(",
"c1",
"+",
"numpy",
".",
"log",
"(",
"vs30",
")",
"*",
"c2",
")",
"return",
"z2pt5"
] | 36.533333 | 0.001779 |
def check_vector_template(self):
"""Determines if features are defined as vector source based on MapViz arguments."""
if self.vector_url is not None and self.vector_layer_name is not None:
self.template = 'vector_' + self.template
self.vector_source = True
else:
... | [
"def",
"check_vector_template",
"(",
"self",
")",
":",
"if",
"self",
".",
"vector_url",
"is",
"not",
"None",
"and",
"self",
".",
"vector_layer_name",
"is",
"not",
"None",
":",
"self",
".",
"template",
"=",
"'vector_'",
"+",
"self",
".",
"template",
"self",... | 42.875 | 0.008571 |
def centroid_sources(data, xpos, ypos, box_size=11, footprint=None,
error=None, mask=None, centroid_func=centroid_com):
"""
Calculate the centroid of sources at the defined positions.
A cutout image centered on each input position will be used to
calculate the centroid position. T... | [
"def",
"centroid_sources",
"(",
"data",
",",
"xpos",
",",
"ypos",
",",
"box_size",
"=",
"11",
",",
"footprint",
"=",
"None",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"centroid_func",
"=",
"centroid_com",
")",
":",
"xpos",
"=",
"np",
... | 39.290323 | 0.0002 |
def AddEventData(self, event_data):
"""Adds event data.
Args:
event_data (EventData): event data.
Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.
"""
self._RaiseIfNotWritable()
event_data = self._PrepareAttributeContainer(event... | [
"def",
"AddEventData",
"(",
"self",
",",
"event_data",
")",
":",
"self",
".",
"_RaiseIfNotWritable",
"(",
")",
"event_data",
"=",
"self",
".",
"_PrepareAttributeContainer",
"(",
"event_data",
")",
"identifier",
"=",
"event_data",
".",
"GetIdentifier",
"(",
")",
... | 26.117647 | 0.002174 |
def continuous_eval(self):
"""Evaluate until checkpoints stop being produced."""
for ckpt_path in next_checkpoint(self._hparams.model_dir,
self._hparams.eval_timeout_mins):
# Skip zero'th step.
train_step = decoding.get_step_from_ckpt_path(ckpt_path)
if tra... | [
"def",
"continuous_eval",
"(",
"self",
")",
":",
"for",
"ckpt_path",
"in",
"next_checkpoint",
"(",
"self",
".",
"_hparams",
".",
"model_dir",
",",
"self",
".",
"_hparams",
".",
"eval_timeout_mins",
")",
":",
"# Skip zero'th step.",
"train_step",
"=",
"decoding",... | 42 | 0.011655 |
def kurt(self):
"""
Kurtosis coefficient value as a result of an uncertainty calculation,
defined as::
m4
beta2 = ------
std**4
where m4 is the fourth central moment and std is the standard deviation
"""
... | [
"def",
"kurt",
"(",
"self",
")",
":",
"mn",
"=",
"self",
".",
"mean",
"sd",
"=",
"self",
".",
"std",
"kt",
"=",
"0.0",
"if",
"abs",
"(",
"sd",
")",
"<=",
"1e-8",
"else",
"np",
".",
"mean",
"(",
"(",
"self",
".",
"_mcpts",
"-",
"mn",
")",
"*... | 29.6 | 0.008734 |
def update(self, role_sid=values.unset, attributes=values.unset,
friendly_name=values.unset):
"""
Update the UserInstance
:param unicode role_sid: The SID id of the Role assigned to this user
:param unicode attributes: A valid JSON string that contains application-specifi... | [
"def",
"update",
"(",
"self",
",",
"role_sid",
"=",
"values",
".",
"unset",
",",
"attributes",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"role_sid",
"=... | 46.692308 | 0.008078 |
def visit_class(rec, cls, op):
# type: (Any, Iterable, Union[Callable[..., Any], partial[Any]]) -> None
"""Apply a function to with "class" in cls."""
if isinstance(rec, MutableMapping):
if "class" in rec and rec.get("class") in cls:
op(rec)
for d in rec:
visit_class... | [
"def",
"visit_class",
"(",
"rec",
",",
"cls",
",",
"op",
")",
":",
"# type: (Any, Iterable, Union[Callable[..., Any], partial[Any]]) -> None",
"if",
"isinstance",
"(",
"rec",
",",
"MutableMapping",
")",
":",
"if",
"\"class\"",
"in",
"rec",
"and",
"rec",
".",
"get"... | 35.416667 | 0.002294 |
def _should_retry(self, context):
'''
A function which determines whether or not to retry.
:param ~azure.storage.models.RetryContext context:
The retry context. This contains the request, response, and other data
which can be used to determine whether or not to retry.
... | [
"def",
"_should_retry",
"(",
"self",
",",
"context",
")",
":",
"# If max attempts are reached, do not retry.",
"if",
"context",
".",
"count",
">=",
"self",
".",
"max_attempts",
":",
"return",
"False",
"status",
"=",
"None",
"if",
"context",
".",
"response",
"and... | 38.672727 | 0.008253 |
def crypto_hash_sha512(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = ffi.new("unsigned char[]", crypto_hash_sha512_BYTES)
rc = lib.crypto_hash_sha512(digest, message, len(message))
ensure(rc == 0,
'Unexpected librar... | [
"def",
"crypto_hash_sha512",
"(",
"message",
")",
":",
"digest",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_hash_sha512_BYTES",
")",
"rc",
"=",
"lib",
".",
"crypto_hash_sha512",
"(",
"digest",
",",
"message",
",",
"len",
"(",
"message",
... | 31.769231 | 0.002353 |
def fit_df(self, dfs, pstate_col=PSTATE_COL):
"""
Convenience function to fit a model from a list of dataframes
"""
obs_cols = list(self.emission_name)
obs = [df[df.columns.difference([pstate_col])][obs_cols].values for df in dfs]
pstates = [df[pstate_col].values for df i... | [
"def",
"fit_df",
"(",
"self",
",",
"dfs",
",",
"pstate_col",
"=",
"PSTATE_COL",
")",
":",
"obs_cols",
"=",
"list",
"(",
"self",
".",
"emission_name",
")",
"obs",
"=",
"[",
"df",
"[",
"df",
".",
"columns",
".",
"difference",
"(",
"[",
"pstate_col",
"]... | 44.625 | 0.008242 |
def write_rtt(jlink):
"""Writes kayboard input to JLink RTT buffer #0.
This method is a loop that blocks waiting on stdin. When enter is pressed,
LF and NUL bytes are added to the input and transmitted as a byte list.
If the JLink is disconnected, it will exit gracefully. If any other
exceptions ar... | [
"def",
"write_rtt",
"(",
"jlink",
")",
":",
"try",
":",
"while",
"jlink",
".",
"connected",
"(",
")",
":",
"bytes",
"=",
"list",
"(",
"bytearray",
"(",
"input",
"(",
")",
",",
"\"utf-8\"",
")",
"+",
"b\"\\x0A\\x00\"",
")",
"bytes_written",
"=",
"jlink"... | 33.782609 | 0.001252 |
def join(*paths):
# type: (*Text) -> Text
"""Join any number of paths together.
Arguments:
*paths (str): Paths to join, given as positional arguments.
Returns:
str: The joined path.
Example:
>>> join('foo', 'bar', 'baz')
'foo/bar/baz'
>>> join('foo/bar', '.... | [
"def",
"join",
"(",
"*",
"paths",
")",
":",
"# type: (*Text) -> Text",
"absolute",
"=",
"False",
"relpaths",
"=",
"[",
"]",
"# type: List[Text]",
"for",
"p",
"in",
"paths",
":",
"if",
"p",
":",
"if",
"p",
"[",
"0",
"]",
"==",
"\"/\"",
":",
"del",
"re... | 21.65625 | 0.001381 |
def plot(self):
"""
Returns a hvPlot object to provide a high-level plotting API.
To display in a notebook, be sure to run ``intake.output_notebook()``
first.
"""
try:
from hvplot import hvPlot
except ImportError:
raise ImportError("The in... | [
"def",
"plot",
"(",
"self",
")",
":",
"try",
":",
"from",
"hvplot",
"import",
"hvPlot",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"The intake plotting API requires hvplot.\"",
"\"hvplot may be installed with:\\n\\n\"",
"\"`conda install -c pyviz hvplot` or ... | 40.454545 | 0.002195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.