text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def update_opdocs(self, checksum, opdocs, revision=None):
"""
Modifies the internal state based a change to the content and returns
the sets of words added and removed.
:Parameters:
checksum : `hashable`
A checksum generated from the text of a revision
... | [
"def",
"update_opdocs",
"(",
"self",
",",
"checksum",
",",
"opdocs",
",",
"revision",
"=",
"None",
")",
":",
"return",
"self",
".",
"_update",
"(",
"checksum",
"=",
"checksum",
",",
"opdocs",
"=",
"opdocs",
",",
"revision",
"=",
"revision",
")"
] | 40.925926 | 0.001768 |
def get_default_mapping(self, z, cmapper):
"""Create dictionary containing default ColumnDataSource glyph to data
mappings.
"""
map_annular = dict(x=self.max_radius, y=self.max_radius,
inner_radius="inner_radius",
outer_radius="oute... | [
"def",
"get_default_mapping",
"(",
"self",
",",
"z",
",",
"cmapper",
")",
":",
"map_annular",
"=",
"dict",
"(",
"x",
"=",
"self",
".",
"max_radius",
",",
"y",
"=",
"self",
".",
"max_radius",
",",
"inner_radius",
"=",
"\"inner_radius\"",
",",
"outer_radius"... | 39.2 | 0.00249 |
def _route(self, attr, args, kwargs, **fkwargs):
"""
Perform routing and return db_nums
"""
return self.cluster.hosts.keys() | [
"def",
"_route",
"(",
"self",
",",
"attr",
",",
"args",
",",
"kwargs",
",",
"*",
"*",
"fkwargs",
")",
":",
"return",
"self",
".",
"cluster",
".",
"hosts",
".",
"keys",
"(",
")"
] | 30.4 | 0.012821 |
def _make_policies(self):
"""
Convert the 'scalingPolicies' dictionary into AutoScalePolicy objects.
"""
self.policies = [AutoScalePolicy(self.manager, dct, self)
for dct in self.scalingPolicies] | [
"def",
"_make_policies",
"(",
"self",
")",
":",
"self",
".",
"policies",
"=",
"[",
"AutoScalePolicy",
"(",
"self",
".",
"manager",
",",
"dct",
",",
"self",
")",
"for",
"dct",
"in",
"self",
".",
"scalingPolicies",
"]"
] | 39.666667 | 0.012346 |
def _roots_to_targets(self, build_graph, target_roots):
"""Populate the BuildGraph and target list from a set of input TargetRoots."""
with self._run_tracker.new_workunit(name='parse', labels=[WorkUnitLabel.SETUP]):
return [
build_graph.get_target(address)
for address
in build_grap... | [
"def",
"_roots_to_targets",
"(",
"self",
",",
"build_graph",
",",
"target_roots",
")",
":",
"with",
"self",
".",
"_run_tracker",
".",
"new_workunit",
"(",
"name",
"=",
"'parse'",
",",
"labels",
"=",
"[",
"WorkUnitLabel",
".",
"SETUP",
"]",
")",
":",
"retur... | 46.75 | 0.010499 |
def getipmacarp(self):
"""
Function operates on the IMCDev object and updates the ipmacarp attribute
:return:
"""
self.ipmacarp = get_ip_mac_arp_list(self.auth, self.url, devid = self.devid) | [
"def",
"getipmacarp",
"(",
"self",
")",
":",
"self",
".",
"ipmacarp",
"=",
"get_ip_mac_arp_list",
"(",
"self",
".",
"auth",
",",
"self",
".",
"url",
",",
"devid",
"=",
"self",
".",
"devid",
")"
] | 37.5 | 0.026087 |
def check_class(self, id_, class_, lineno, scope=None, show_error=True):
""" Check the id is either undefined or defined with
the given class.
- If the identifier (e.g. variable) does not exists means
it's undeclared, and returns True (OK).
- If the identifier exists, but its cl... | [
"def",
"check_class",
"(",
"self",
",",
"id_",
",",
"class_",
",",
"lineno",
",",
"scope",
"=",
"None",
",",
"show_error",
"=",
"True",
")",
":",
"assert",
"CLASS",
".",
"is_valid",
"(",
"class_",
")",
"entry",
"=",
"self",
".",
"get_entry",
"(",
"id... | 36.8125 | 0.001654 |
def can_run_c_extension(name=None):
"""
Determine whether the given Python C extension loads correctly.
If ``name`` is ``None``, tests all Python C extensions,
and return ``True`` if and only if all load correctly.
:param string name: the name of the Python C extension to test
:rtype: bool
... | [
"def",
"can_run_c_extension",
"(",
"name",
"=",
"None",
")",
":",
"def",
"can_run_cdtw",
"(",
")",
":",
"\"\"\" Python C extension for computing DTW \"\"\"",
"try",
":",
"import",
"aeneas",
".",
"cdtw",
".",
"cdtw",
"return",
"True",
"except",
"ImportError",
":",
... | 27.283019 | 0.000668 |
def create_oqhazardlib_source(self, tom, mesh_spacing, use_defaults=False):
"""
Returns an instance of the :class:
`openquake.hazardlib.source.simple_fault.SimpleFaultSource`
:param tom:
Temporal occurrance model
:param float mesh_spacing:
Mesh spacing
... | [
"def",
"create_oqhazardlib_source",
"(",
"self",
",",
"tom",
",",
"mesh_spacing",
",",
"use_defaults",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"mfd",
":",
"raise",
"ValueError",
"(",
"\"Cannot write to hazardlib without MFD\"",
")",
"return",
"SimpleFaul... | 32.923077 | 0.00227 |
def add_to_hash(self, filename, hasher):
"""Contribute `filename`'s data to the Md5Hash `hasher`."""
hasher.update(self.executed_lines(filename))
hasher.update(self.executed_arcs(filename)) | [
"def",
"add_to_hash",
"(",
"self",
",",
"filename",
",",
"hasher",
")",
":",
"hasher",
".",
"update",
"(",
"self",
".",
"executed_lines",
"(",
"filename",
")",
")",
"hasher",
".",
"update",
"(",
"self",
".",
"executed_arcs",
"(",
"filename",
")",
")"
] | 52.5 | 0.00939 |
def template(page=None, layout=None, **kwargs):
"""
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:fi... | [
"def",
"template",
"(",
"page",
"=",
"None",
",",
"layout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pkey",
"=",
"\"_template_extends__\"",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"f",
")",
":",
"layout_"... | 33.09375 | 0.000459 |
def filter_create(self, phrase, context, irreversible = False, whole_word = True, expires_in = None):
"""
Creates a new keyword filter. `phrase` is the phrase that should be
filtered out, `context` specifies from where to filter the keywords.
Valid contexts are 'home', 'notifications', '... | [
"def",
"filter_create",
"(",
"self",
",",
"phrase",
",",
"context",
",",
"irreversible",
"=",
"False",
",",
"whole_word",
"=",
"True",
",",
"expires_in",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")"... | 48.5 | 0.016849 |
def get_dual_rmetric( self, invert_h = False, mode_inv = 'svd' ):
"""
Compute the dual Riemannian Metric
This is not satisfactory, because if mdimG<mdimY the shape of H
will not be the same as the shape of G. TODO(maybe): return a (copied)
smaller H with only the rows and columns... | [
"def",
"get_dual_rmetric",
"(",
"self",
",",
"invert_h",
"=",
"False",
",",
"mode_inv",
"=",
"'svd'",
")",
":",
"if",
"self",
".",
"H",
"is",
"None",
":",
"self",
".",
"H",
",",
"self",
".",
"G",
",",
"self",
".",
"Hvv",
",",
"self",
".",
"Hsvals... | 46 | 0.021311 |
def _load(db_data, db):
"""
Load :class:`mongomock.database.Database` from dict data.
"""
if db.name != db_data["name"]:
raise ValueError("dbname doesn't matches! Maybe wrong database data.")
db.__init__(client=db._client, name=db.name)
for col_name, col_data in iteritems(db_data["_coll... | [
"def",
"_load",
"(",
"db_data",
",",
"db",
")",
":",
"if",
"db",
".",
"name",
"!=",
"db_data",
"[",
"\"name\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"dbname doesn't matches! Maybe wrong database data.\"",
")",
"db",
".",
"__init__",
"(",
"client",
"=",
"d... | 35.6 | 0.001825 |
def _upload_resumable_all(self, upload_info, bitmap,
number_of_units, unit_size):
"""Prepare and upload all resumable units and return upload_key
upload_info -- UploadInfo object
bitmap -- bitmap node of upload/check
number_of_units -- number of units reque... | [
"def",
"_upload_resumable_all",
"(",
"self",
",",
"upload_info",
",",
"bitmap",
",",
"number_of_units",
",",
"unit_size",
")",
":",
"fd",
"=",
"upload_info",
".",
"fd",
"upload_key",
"=",
"None",
"for",
"unit_id",
"in",
"range",
"(",
"number_of_units",
")",
... | 33.44186 | 0.002027 |
def debug_inspect_node(self, node_msindex):
"""
Get info about the node. See pycut.inspect_node() for details.
Processing is done in temporary shape.
:param node_seed:
:return: node_unariesalt, node_neighboor_edges_and_weights, node_neighboor_seeds
"""
return ins... | [
"def",
"debug_inspect_node",
"(",
"self",
",",
"node_msindex",
")",
":",
"return",
"inspect_node",
"(",
"self",
".",
"nlinks",
",",
"self",
".",
"unariesalt2",
",",
"self",
".",
"msinds",
",",
"node_msindex",
")"
] | 42.111111 | 0.010336 |
def point_in_prism(tri1, tri2, pt):
'''
point_in_prism(tri1, tri2, pt) yields True if the given point is inside the prism that stretches
between triangle 1 and triangle 2. Will automatically thread over extended dimensions. If
multiple triangles are given, then the vertices must be an earlier dimens... | [
"def",
"point_in_prism",
"(",
"tri1",
",",
"tri2",
",",
"pt",
")",
":",
"bcs",
"=",
"prism_barycentric_coordinates",
"(",
"tri1",
",",
"tri2",
",",
"pt",
")",
"return",
"np",
".",
"logical_not",
"(",
"np",
".",
"isclose",
"(",
"np",
".",
"sum",
"(",
... | 61.5 | 0.008013 |
def smeft_toarray(wc_name, wc_dict):
"""Construct a numpy array with Wilson coefficient values from a
dictionary of label-value pairs corresponding to the non-redundant
elements."""
shape = smeftutil.C_keys_shape[wc_name]
C = np.zeros(shape, dtype=complex)
for k, v in wc_dict.items():
if... | [
"def",
"smeft_toarray",
"(",
"wc_name",
",",
"wc_dict",
")",
":",
"shape",
"=",
"smeftutil",
".",
"C_keys_shape",
"[",
"wc_name",
"]",
"C",
"=",
"np",
".",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"complex",
")",
"for",
"k",
",",
"v",
"in",
"wc_dict... | 40.571429 | 0.001721 |
def validate(bbllines:iter, *, profiling=False):
"""Yield lines of warnings and errors about input bbl lines.
profiling -- yield also info lines about input bbl file.
If bbllines is a valid file name, it will be read.
Else, it should be an iterable of bubble file lines.
"""
if isinstance(bbll... | [
"def",
"validate",
"(",
"bbllines",
":",
"iter",
",",
"*",
",",
"profiling",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"bbllines",
",",
"str",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"bbllines",
")",
":",
"# filename containing bu... | 43.466667 | 0.0015 |
def get_total_ram():
"""The total amount of system RAM in bytes.
This is what is reported by the OS, and may be overcommitted when
there are multiple containers hosted on the same machine.
"""
with open('/proc/meminfo', 'r') as f:
for line in f.readlines():
if line:
... | [
"def",
"get_total_ram",
"(",
")",
":",
"with",
"open",
"(",
"'/proc/meminfo'",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"line",
":",
"key",
",",
"value",
",",
"unit",
"=",
"line",
".",
"spl... | 38.5 | 0.001812 |
def _to_point(dims):
"""Convert (width, height) or size -> point.Point."""
assert dims
if isinstance(dims, (tuple, list)):
if len(dims) != 2:
raise ValueError(
"A two element tuple or list is expected here, got {}.".format(dims))
else:
width = int(dims[0])
height = int(dims[1]... | [
"def",
"_to_point",
"(",
"dims",
")",
":",
"assert",
"dims",
"if",
"isinstance",
"(",
"dims",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"len",
"(",
"dims",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"A two element tuple or list is expe... | 29.5 | 0.01791 |
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_Rforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"r",
"=",
"nu",
".",
"sqrt",
"(",
"R",
"*",
"R",
"+",
"z",
"*",
"z",
")",
"return",
"-",
"self",
".",
"_mass",
"(",
"r",
")",
"*",
... | 25.5 | 0.014706 |
def FixmatFactory(fixmatfile, categories = None, var_name = 'fixmat', field_name='x'):
"""
Loads a single fixmat (fixmatfile).
Parameters:
fixmatfile : string
The matlab fixmat that should be loaded.
categories : instance of stimuli.Categories, optional
Links dat... | [
"def",
"FixmatFactory",
"(",
"fixmatfile",
",",
"categories",
"=",
"None",
",",
"var_name",
"=",
"'fixmat'",
",",
"field_name",
"=",
"'x'",
")",
":",
"try",
":",
"data",
"=",
"loadmat",
"(",
"fixmatfile",
",",
"struct_as_record",
"=",
"False",
")",
"keys",... | 35.465116 | 0.012125 |
def ignore_path(path, ignore_list=None, whitelist=None):
"""
Returns a boolean indicating if a path should be ignored given an
ignore_list and a whitelist of glob patterns.
"""
if ignore_list is None:
return True
should_ignore = matches_glob_list(path, ignore_list)
if whitelist is N... | [
"def",
"ignore_path",
"(",
"path",
",",
"ignore_list",
"=",
"None",
",",
"whitelist",
"=",
"None",
")",
":",
"if",
"ignore_list",
"is",
"None",
":",
"return",
"True",
"should_ignore",
"=",
"matches_glob_list",
"(",
"path",
",",
"ignore_list",
")",
"if",
"w... | 31.538462 | 0.00237 |
def trigger(self, source):
"""
Triggers all actions meant to trigger on the board state from `source`.
"""
actions = self.evaluate(source)
if actions:
if not hasattr(actions, "__iter__"):
actions = (actions, )
source.game.trigger_actions(source, actions) | [
"def",
"trigger",
"(",
"self",
",",
"source",
")",
":",
"actions",
"=",
"self",
".",
"evaluate",
"(",
"source",
")",
"if",
"actions",
":",
"if",
"not",
"hasattr",
"(",
"actions",
",",
"\"__iter__\"",
")",
":",
"actions",
"=",
"(",
"actions",
",",
")"... | 29.555556 | 0.036496 |
def plot_vectors(self, arrows=True):
"""
Plot vectors of positional transition of LISA values
within quadrant in scatterplot in a polar plot.
Parameters
----------
ax : Matplotlib Axes instance, optional
If given, the figure will be created inside this axis.
... | [
"def",
"plot_vectors",
"(",
"self",
",",
"arrows",
"=",
"True",
")",
":",
"from",
"splot",
".",
"giddy",
"import",
"dynamic_lisa_vectors",
"fig",
",",
"ax",
"=",
"dynamic_lisa_vectors",
"(",
"self",
",",
"arrows",
"=",
"arrows",
")",
"return",
"fig",
",",
... | 32.793103 | 0.002043 |
def get_settings_from_client(client):
"""Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance
"""
settings = {
'username': '',
'api_key': '',
'timeout': '',
'endpoint_url': '',
}
try:
settings['username'] = ... | [
"def",
"get_settings_from_client",
"(",
"client",
")",
":",
"settings",
"=",
"{",
"'username'",
":",
"''",
",",
"'api_key'",
":",
"''",
",",
"'timeout'",
":",
"''",
",",
"'endpoint_url'",
":",
"''",
",",
"}",
"try",
":",
"settings",
"[",
"'username'",
"]... | 25.44 | 0.001515 |
def _init():
"""Dynamically import engines that initialize successfully."""
import importlib
import os
import re
filenames = os.listdir(os.path.dirname(__file__))
module_names = set()
for filename in filenames:
match = re.match(r'^(?P<name>[A-Z_a-z]\w*)\.py[co]?$', filename)
... | [
"def",
"_init",
"(",
")",
":",
"import",
"importlib",
"import",
"os",
"import",
"re",
"filenames",
"=",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"module_names",
"=",
"set",
"(",
")",
"for",
"filename",
... | 28.864865 | 0.000906 |
def displayEmptyInputWarningBox(display=True, parent=None):
""" Displays a warning box for the 'input' parameter.
"""
if sys.version_info[0] >= 3:
from tkinter.messagebox import showwarning
else:
from tkMessageBox import showwarning
if display:
msg = 'No valid input files fo... | [
"def",
"displayEmptyInputWarningBox",
"(",
"display",
"=",
"True",
",",
"parent",
"=",
"None",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">=",
"3",
":",
"from",
"tkinter",
".",
"messagebox",
"import",
"showwarning",
"else",
":",
"from",
... | 35.846154 | 0.008368 |
def _check_directory_arguments(self):
"""
Validates arguments for loading from directories, including static image and time series directories.
"""
if not os.path.isdir(self.datapath):
raise (NotADirectoryError('Directory does not exist: %s' % self.datapath))
if self.... | [
"def",
"_check_directory_arguments",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"datapath",
")",
":",
"raise",
"(",
"NotADirectoryError",
"(",
"'Directory does not exist: %s'",
"%",
"self",
".",
"datapath",
")",
")... | 57.363636 | 0.00936 |
def remove_invalid_fields(self, queryset, fields, view):
"""Remove invalid fields from an ordering.
Overwrites the DRF default remove_invalid_fields method to return
both the valid orderings and any invalid orderings.
"""
valid_orderings = []
invalid_orderings = []
... | [
"def",
"remove_invalid_fields",
"(",
"self",
",",
"queryset",
",",
"fields",
",",
"view",
")",
":",
"valid_orderings",
"=",
"[",
"]",
"invalid_orderings",
"=",
"[",
"]",
"# for each field sent down from the query param,",
"# determine if its valid or invalid",
"for",
"t... | 36.458333 | 0.002227 |
def is_null(*symbols):
""" True if no nodes or all the given nodes are either
None, NOP or empty blocks. For blocks this applies recursively
"""
from symbols.symbol_ import Symbol
for sym in symbols:
if sym is None:
continue
if not isinstance(sym, Symbol):
re... | [
"def",
"is_null",
"(",
"*",
"symbols",
")",
":",
"from",
"symbols",
".",
"symbol_",
"import",
"Symbol",
"for",
"sym",
"in",
"symbols",
":",
"if",
"sym",
"is",
"None",
":",
"continue",
"if",
"not",
"isinstance",
"(",
"sym",
",",
"Symbol",
")",
":",
"r... | 27.736842 | 0.001835 |
def get_renderer(app, id):
"""Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up
"""
renderer = app.extensions.get('nav_renderers', {})[id]
if isinstance(renderer, tuple):
mod_name, cls_name = render... | [
"def",
"get_renderer",
"(",
"app",
",",
"id",
")",
":",
"renderer",
"=",
"app",
".",
"extensions",
".",
"get",
"(",
"'nav_renderers'",
",",
"{",
"}",
")",
"[",
"id",
"]",
"if",
"isinstance",
"(",
"renderer",
",",
"tuple",
")",
":",
"mod_name",
",",
... | 25.263158 | 0.002008 |
def append_if_local_or_in_imports(self, definition):
"""Add definition to list.
Handles local definitions and adds to project_definitions.
"""
if isinstance(definition, LocalModuleDefinition):
self.definitions.append(definition)
elif self.import_names == ["*"]:
... | [
"def",
"append_if_local_or_in_imports",
"(",
"self",
",",
"definition",
")",
":",
"if",
"isinstance",
"(",
"definition",
",",
"LocalModuleDefinition",
")",
":",
"self",
".",
"definitions",
".",
"append",
"(",
"definition",
")",
"elif",
"self",
".",
"import_names... | 41.75 | 0.002342 |
def deepupdate(
mapping: abc.MutableMapping, other: abc.Mapping, listextend=False
):
"""update one dictionary from another recursively. Only individual
values will be overwritten--not entire branches of nested
dictionaries.
"""
def inner(other, previouskeys):
"""previouskeys is a tuple ... | [
"def",
"deepupdate",
"(",
"mapping",
":",
"abc",
".",
"MutableMapping",
",",
"other",
":",
"abc",
".",
"Mapping",
",",
"listextend",
"=",
"False",
")",
":",
"def",
"inner",
"(",
"other",
",",
"previouskeys",
")",
":",
"\"\"\"previouskeys is a tuple that stores... | 35.125 | 0.000866 |
def main():
"""Start the bot."""
# Bale Bot Authorization Token
updater = Updater("TOKEN")
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Bale
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", hel... | [
"def",
"main",
"(",
")",
":",
"# Bale Bot Authorization Token",
"updater",
"=",
"Updater",
"(",
"\"TOKEN\"",
")",
"# Get the dispatcher to register handlers",
"dp",
"=",
"updater",
".",
"dispatcher",
"# on different commands - answer in Bale",
"dp",
".",
"add_handler",
"(... | 25.75 | 0.001873 |
def setParts( self, parts ):
"""
Sets the path for this edit widget by providing the parts to the path.
:param parts | [<str>, ..]
"""
self.setText(self.separator().join(map(str, parts))) | [
"def",
"setParts",
"(",
"self",
",",
"parts",
")",
":",
"self",
".",
"setText",
"(",
"self",
".",
"separator",
"(",
")",
".",
"join",
"(",
"map",
"(",
"str",
",",
"parts",
")",
")",
")"
] | 33.571429 | 0.020747 |
def printDeadCells(self):
"""
Print statistics for the dead cells
"""
columnCasualties = numpy.zeros(self.numberOfColumns())
for cell in self.deadCells:
col = self.columnForCell(cell)
columnCasualties[col] += 1
for col in range(self.numberOfColumns()):
print col, columnCasualti... | [
"def",
"printDeadCells",
"(",
"self",
")",
":",
"columnCasualties",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"numberOfColumns",
"(",
")",
")",
"for",
"cell",
"in",
"self",
".",
"deadCells",
":",
"col",
"=",
"self",
".",
"columnForCell",
"(",
"cell",... | 31.8 | 0.012232 |
def scan_file(fullpath, relpath, assign_id):
""" scan a file and put it into the index """
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
# Since a file has changed, the lrucache is invalid.
load_message.cache_clear()
try:
entry = load_message(fullpath)
except ... | [
"def",
"scan_file",
"(",
"fullpath",
",",
"relpath",
",",
"assign_id",
")",
":",
"# pylint: disable=too-many-branches,too-many-statements,too-many-locals",
"# Since a file has changed, the lrucache is invalid.",
"load_message",
".",
"cache_clear",
"(",
")",
"try",
":",
"entry",... | 32.088496 | 0.000535 |
def get_route_to(self, destination="", protocol=""):
"""
Only IPv4 supported, vrf aware, longer_prefixes parameter ready
"""
longer_pref = "" # longer_prefixes support, for future use
vrf = ""
ip_version = None
try:
ip_version = IPNetwork(destination... | [
"def",
"get_route_to",
"(",
"self",
",",
"destination",
"=",
"\"\"",
",",
"protocol",
"=",
"\"\"",
")",
":",
"longer_pref",
"=",
"\"\"",
"# longer_prefixes support, for future use",
"vrf",
"=",
"\"\"",
"ip_version",
"=",
"None",
"try",
":",
"ip_version",
"=",
... | 50.841121 | 0.001803 |
def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
"""
Load the schedulers state.
Parameters
----------
state_dict : ``Dict[str, Any]``
Scheduler state. Should be an object returned from a call to ``state_dict``.
"""
self.__dict__.update(s... | [
"def",
"load_state_dict",
"(",
"self",
",",
"state_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"state_dict",
")"
] | 32.1 | 0.009091 |
def _read_from_paths():
"""
Try to read data from configuration paths ($HOME/_SETTINGS_PATH,
/etc/_SETTINGS_PATH).
"""
home = os.environ.get("HOME", "")
home_path = os.path.join(home, _SETTINGS_PATH)
etc_path = os.path.join("/etc", _SETTINGS_PATH)
env_path = os.environ.get("SETTINGS_PATH... | [
"def",
"_read_from_paths",
"(",
")",
":",
"home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"HOME\"",
",",
"\"\"",
")",
"home_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"_SETTINGS_PATH",
")",
"etc_path",
"=",
"os",
".",
"path",... | 27.782609 | 0.001513 |
def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | [
"def",
"A",
"(",
"*",
"a",
")",
":",
"return",
"np",
".",
"array",
"(",
"a",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"a",
")",
"==",
"1",
"else",
"[",
"np",
".",
"array",
"(",
"o",
")",
"for",
"o",
"in",
"a",
"]"
] | 42.666667 | 0.015385 |
def _gl_look_at(self, pos, target, up):
"""
The standard lookAt method
:param pos: current position
:param target: target position to look at
:param up: direction up
"""
z = vector.normalise(pos - target)
x = vector.normalise(vector3.cross(vector.normalis... | [
"def",
"_gl_look_at",
"(",
"self",
",",
"pos",
",",
"target",
",",
"up",
")",
":",
"z",
"=",
"vector",
".",
"normalise",
"(",
"pos",
"-",
"target",
")",
"x",
"=",
"vector",
".",
"normalise",
"(",
"vector3",
".",
"cross",
"(",
"vector",
".",
"normal... | 29.482759 | 0.002265 |
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Digest object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
... | [
"def",
"write",
"(",
"self",
",",
"ostream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"tstream",
"=",
"BytearrayStream",
"(",
")",
"self",
".",
"hashing_algorithm",
".",
"write",
"(",
"tstream",
",",
"kmip_version",
... | 44.15 | 0.002217 |
def get_key(raw=False):
""" Gets a single key from stdin
"""
file_descriptor = stdin.fileno()
state = tcgetattr(file_descriptor)
chars = []
try:
setraw(stdin.fileno())
for i in range(3):
char = stdin.read(1)
ordinal = ord(char)
chars.append(cha... | [
"def",
"get_key",
"(",
"raw",
"=",
"False",
")",
":",
"file_descriptor",
"=",
"stdin",
".",
"fileno",
"(",
")",
"state",
"=",
"tcgetattr",
"(",
"file_descriptor",
")",
"chars",
"=",
"[",
"]",
"try",
":",
"setraw",
"(",
"stdin",
".",
"fileno",
"(",
")... | 29.863636 | 0.001475 |
def make_view(robot):
"""
为一个 BaseRoBot 生成 Bottle view。
Usage ::
from werobot import WeRoBot
robot = WeRoBot(token='token')
@robot.handler
def hello(message):
return 'Hello World!'
from bottle import Bottle
from werobot.contrib.bottle import ... | [
"def",
"make_view",
"(",
"robot",
")",
":",
"def",
"werobot_view",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"robot",
".",
"check_signature",
"(",
"request",
".",
"query",
".",
"timestamp",
",",
"request",
".",
"query",
".",
"... | 24.403846 | 0.000758 |
def delete(self, **context):
"""
Removes this record from the database. If the dryRun \
flag is specified then the command will be logged and \
not executed.
:note From version 0.6.0 on, this method now accepts a mutable
keyword dictionary of values. ... | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"context",
")",
":",
"if",
"not",
"self",
".",
"isRecord",
"(",
")",
":",
"return",
"0",
"event",
"=",
"orb",
".",
"events",
".",
"DeleteEvent",
"(",
"record",
"=",
"self",
",",
"context",
"=",
"self",
... | 32.813953 | 0.002065 |
def find_common_root(elements):
"""
Find root which is common for all `elements`.
Args:
elements (list): List of double-linked HTMLElement objects.
Returns:
list: Vector of HTMLElement containing path to common root.
"""
if not elements:
raise UserWarning("Can't find co... | [
"def",
"find_common_root",
"(",
"elements",
")",
":",
"if",
"not",
"elements",
":",
"raise",
"UserWarning",
"(",
"\"Can't find common root - no elements suplied.\"",
")",
"root_path",
"=",
"el_to_path_vector",
"(",
"elements",
".",
"pop",
"(",
")",
")",
"for",
"el... | 25.576923 | 0.001449 |
def dependency_to_rpm(dep, runtime):
"""Converts a dependency got by pkg_resources.Requirement.parse()
to RPM format.
Args:
dep - a dependency retrieved by pkg_resources.Requirement.parse()
runtime - whether the returned dependency should be runtime (True)
or build time (False)
R... | [
"def",
"dependency_to_rpm",
"(",
"dep",
",",
"runtime",
")",
":",
"logger",
".",
"debug",
"(",
"'Dependencies provided: {0} runtime: {1}.'",
".",
"format",
"(",
"dep",
",",
"runtime",
")",
")",
"converted",
"=",
"[",
"]",
"if",
"not",
"len",
"(",
"dep",
".... | 37.194444 | 0.000728 |
def execute_nonstop_tasks(self, tasks_cls):
"""
Just a wrapper to the execute_batch_tasks method
"""
self.execute_batch_tasks(tasks_cls,
self.conf['sortinghat']['sleep_for'],
self.conf['general']['min_update_delay'], F... | [
"def",
"execute_nonstop_tasks",
"(",
"self",
",",
"tasks_cls",
")",
":",
"self",
".",
"execute_batch_tasks",
"(",
"tasks_cls",
",",
"self",
".",
"conf",
"[",
"'sortinghat'",
"]",
"[",
"'sleep_for'",
"]",
",",
"self",
".",
"conf",
"[",
"'general'",
"]",
"["... | 45.571429 | 0.009231 |
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
return self.get_json(self.USER_INFO_URL, method="POST", headers=self._get_headers(access_token)) | [
"def",
"user_data",
"(",
"self",
",",
"access_token",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_json",
"(",
"self",
".",
"USER_INFO_URL",
",",
"method",
"=",
"\"POST\"",
",",
"headers",
"=",
"self",
".",
"_get_hea... | 49.25 | 0.015 |
def run_initialization_experiment(seed,
num_neurons = 50,
dim = 40,
num_bins = 10,
num_samples = 50*600,
neuron_size = 10000,
... | [
"def",
"run_initialization_experiment",
"(",
"seed",
",",
"num_neurons",
"=",
"50",
",",
"dim",
"=",
"40",
",",
"num_bins",
"=",
"10",
",",
"num_samples",
"=",
"50",
"*",
"600",
",",
"neuron_size",
"=",
"10000",
",",
"num_dendrites",
"=",
"400",
",",
"de... | 51.195122 | 0.020332 |
def poisson(grid, spacing=None, dtype=float, format=None, type='FD'):
"""Return a sparse matrix for the N-dimensional Poisson problem.
The matrix represents a finite Difference approximation to the
Poisson problem on a regular n-dimensional grid with unit grid
spacing and Dirichlet boundary conditions.... | [
"def",
"poisson",
"(",
"grid",
",",
"spacing",
"=",
"None",
",",
"dtype",
"=",
"float",
",",
"format",
"=",
"None",
",",
"type",
"=",
"'FD'",
")",
":",
"grid",
"=",
"tuple",
"(",
"grid",
")",
"N",
"=",
"len",
"(",
"grid",
")",
"# grid dimension",
... | 29.803571 | 0.00058 |
def summarize_video_metrics(hook_args):
"""Computes video metrics summaries using the decoder output."""
problem_name = hook_args.problem.name
current_problem = hook_args.problem
hparams = hook_args.hparams
output_dirs = hook_args.output_dirs
predictions = hook_args.predictions
frame_shape = [
curre... | [
"def",
"summarize_video_metrics",
"(",
"hook_args",
")",
":",
"problem_name",
"=",
"hook_args",
".",
"problem",
".",
"name",
"current_problem",
"=",
"hook_args",
".",
"problem",
"hparams",
"=",
"hook_args",
".",
"hparams",
"output_dirs",
"=",
"hook_args",
".",
"... | 39 | 0.016682 |
def parallel_runners(name, runners, **kwargs): # pylint: disable=unused-argument
'''
Executes multiple runner modules on the master in parallel.
.. versionadded:: 2017.x.0 (Nitrogen)
A separate thread is spawned for each runner. This state is intended to be
used with the orchestrate runner in pla... | [
"def",
"parallel_runners",
"(",
"name",
",",
"runners",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"# For the sake of consistency, we treat a single string in the same way as",
"# a key without a value. This allows something like",
"# salt.parallel_runn... | 39.494505 | 0.000271 |
def save(sources, targets, masked=False):
"""
Save the numeric results of each source into its corresponding target.
Parameters
----------
sources: list
The list of source arrays for saving from; limited to length 1.
targets: list
The list of target arrays for saving to; limited... | [
"def",
"save",
"(",
"sources",
",",
"targets",
",",
"masked",
"=",
"False",
")",
":",
"# TODO: Remove restriction",
"assert",
"len",
"(",
"sources",
")",
"==",
"1",
"and",
"len",
"(",
"targets",
")",
"==",
"1",
"array",
"=",
"sources",
"[",
"0",
"]",
... | 36.970588 | 0.000775 |
def get_season_code_from_name(self, season_name) -> int:
"""
Args:
season_name: season name
Returns: season code
"""
self.validator_season_name.validate(season_name, 'get_season_code_from_name')
return self.seasons_enum[season_name] | [
"def",
"get_season_code_from_name",
"(",
"self",
",",
"season_name",
")",
"->",
"int",
":",
"self",
".",
"validator_season_name",
".",
"validate",
"(",
"season_name",
",",
"'get_season_code_from_name'",
")",
"return",
"self",
".",
"seasons_enum",
"[",
"season_name",... | 31.666667 | 0.010239 |
def check_arguments(c: typing.Callable,
hints: typing.Mapping[str, typing.Optional[type]],
*args, **kwargs) -> None:
"""Check arguments type, raise :class:`TypeError` if argument type is not
expected type.
:param c: callable object want to check types
:param hint... | [
"def",
"check_arguments",
"(",
"c",
":",
"typing",
".",
"Callable",
",",
"hints",
":",
"typing",
".",
"Mapping",
"[",
"str",
",",
"typing",
".",
"Optional",
"[",
"type",
"]",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
... | 36.32 | 0.001073 |
def _reconnect(self, errorState):
"""
Attempt to reconnect.
If the current back-off delay is 0, L{connect} is called. Otherwise,
it will cause a transition to the C{'waiting'} state, ultimately
causing a call to L{connect} when the delay expires.
"""
def connect(... | [
"def",
"_reconnect",
"(",
"self",
",",
"errorState",
")",
":",
"def",
"connect",
"(",
")",
":",
"if",
"self",
".",
"noisy",
":",
"log",
".",
"msg",
"(",
"\"Reconnecting now.\"",
")",
"self",
".",
"connect",
"(",
")",
"backOff",
"=",
"self",
".",
"bac... | 34.814815 | 0.00207 |
def read_dictionary_file(dictionary_path):
"""Return all words in dictionary file as set."""
try:
return _user_dictionary_cache[dictionary_path]
except KeyError:
if dictionary_path and os.path.exists(dictionary_path):
with open(dictionary_path, "rt") as dict_f:
wo... | [
"def",
"read_dictionary_file",
"(",
"dictionary_path",
")",
":",
"try",
":",
"return",
"_user_dictionary_cache",
"[",
"dictionary_path",
"]",
"except",
"KeyError",
":",
"if",
"dictionary_path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"dictionary_path",
")",
... | 39.833333 | 0.002045 |
def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB',
resample=None):
"""Return an image resized."""
if x <= 0:
raise ValueError('x must be greater than zero')
if y <= 0:
raise ValueError('y must be greater than zero')
from PIL import Image
resample = I... | [
"def",
"resize",
"(",
"image",
",",
"x",
",",
"y",
",",
"stretch",
"=",
"False",
",",
"top",
"=",
"None",
",",
"left",
"=",
"None",
",",
"mode",
"=",
"'RGB'",
",",
"resample",
"=",
"None",
")",
":",
"if",
"x",
"<=",
"0",
":",
"raise",
"ValueErr... | 29.808511 | 0.001382 |
def p_expr_shl_expr(p):
""" expr : expr SHL expr
"""
if p[1] is None or p[3] is None:
p[0] = None
return
if p[1].type_ in (TYPE.float_, TYPE.fixed):
p[1] = make_typecast(TYPE.ulong, p[1], p.lineno(2))
p[0] = make_binary(p.lineno(2), 'SHL', p[1],
make_... | [
"def",
"p_expr_shl_expr",
"(",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
"is",
"None",
"or",
"p",
"[",
"3",
"]",
"is",
"None",
":",
"p",
"[",
"0",
"]",
"=",
"None",
"return",
"if",
"p",
"[",
"1",
"]",
".",
"type_",
"in",
"(",
"TYPE",
".",
... | 30.153846 | 0.002475 |
def render(self):
"""Render this page and return the rendition.
Converts the markdown content to html, and then renders the
(mako) template specified in the config, using that html.
The task of writing of the rendition to a real file is
responsibility of the generate method.
... | [
"def",
"render",
"(",
"self",
")",
":",
"(",
"pthemedir",
",",
"ptemplatefname",
")",
"=",
"self",
".",
"_theme_and_template_fp",
"(",
")",
"mylookup",
"=",
"TemplateLookup",
"(",
"directories",
"=",
"[",
"self",
".",
"site",
".",
"dirs",
"[",
"'s2'",
"]... | 49.753623 | 0.010568 |
def voronoi_neighbors_from_pixels_and_ridge_points(pixels, ridge_points):
"""Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with.
The ridge points of the Voronoi grid are used to derive this.
Parameters
----------
ridge_points : scipy.spatial.Voronoi... | [
"def",
"voronoi_neighbors_from_pixels_and_ridge_points",
"(",
"pixels",
",",
"ridge_points",
")",
":",
"pixel_neighbors_size",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"pixels",
")",
")",
"for",
"ridge_index",
"in",
"range",
"(",
"ridge_points",
".",
"sh... | 39.806452 | 0.002373 |
def format_hyperlink( val, hlx, hxl, xhl ):
"""
Formats an html hyperlink into other forms.
@hlx, hxl, xhl: values returned by set_output_format
"""
if '<a href="' in str(val) and hlx != '<a href="':
val = val.replace('<a href="', hlx).replace('">', hxl, 1).replace('</a>', xhl)
return... | [
"def",
"format_hyperlink",
"(",
"val",
",",
"hlx",
",",
"hxl",
",",
"xhl",
")",
":",
"if",
"'<a href=\"'",
"in",
"str",
"(",
"val",
")",
"and",
"hlx",
"!=",
"'<a href=\"'",
":",
"val",
"=",
"val",
".",
"replace",
"(",
"'<a href=\"'",
",",
"hlx",
")",... | 31.5 | 0.015432 |
def fit_apply(fit_result,vec_array):
'''fit_apply(fir_result,vec_array) -> vec_array
Applies a fit result to an array of vectors
'''
return map( lambda x,t1=fit_result[0],mt2=negate(fit_result[1]),
m=fit_result[2]: add(t1,transform(m,add(mt2,x))),vec_array) | [
"def",
"fit_apply",
"(",
"fit_result",
",",
"vec_array",
")",
":",
"return",
"map",
"(",
"lambda",
"x",
",",
"t1",
"=",
"fit_result",
"[",
"0",
"]",
",",
"mt2",
"=",
"negate",
"(",
"fit_result",
"[",
"1",
"]",
")",
",",
"m",
"=",
"fit_result",
"[",... | 35 | 0.038328 |
def visualRect(self, index):
"""The rectangle for the bounds of the item at *index*. :qtdoc:`Re-implemented<QAbstractItemView.visualRect>`
:param index: index for the rect you want
:type index: :qtdoc:`QModelIndex`
:returns: :qtdoc:`QRect` -- rectangle of the borders of the item
... | [
"def",
"visualRect",
"(",
"self",
",",
"index",
")",
":",
"if",
"len",
"(",
"self",
".",
"_rects",
"[",
"index",
".",
"row",
"(",
")",
"]",
")",
"-",
"1",
"<",
"index",
".",
"column",
"(",
")",
"or",
"index",
".",
"row",
"(",
")",
"==",
"-",
... | 47.583333 | 0.013746 |
def graph_impl(self, run, tag, is_conceptual, limit_attr_size=None, large_attrs_key=None):
"""Result of the form `(body, mime_type)`, or `None` if no graph exists."""
if is_conceptual:
tensor_events = self._multiplexer.Tensors(run, tag)
# Take the first event if there are multiple events written fro... | [
"def",
"graph_impl",
"(",
"self",
",",
"run",
",",
"tag",
",",
"is_conceptual",
",",
"limit_attr_size",
"=",
"None",
",",
"large_attrs_key",
"=",
"None",
")",
":",
"if",
"is_conceptual",
":",
"tensor_events",
"=",
"self",
".",
"_multiplexer",
".",
"Tensors",... | 49.76 | 0.013407 |
def readin_rho(filename, rhofile=True, aniso=False):
"""Read in the values of the resistivity in Ohmm.
The format is variable: rho-file or mag-file.
"""
if aniso:
a = [[0, 1, 2], [2, 3, 4]]
else:
a = [0, 2]
if rhofile:
if filename is None:
filename = 'rho/rho.... | [
"def",
"readin_rho",
"(",
"filename",
",",
"rhofile",
"=",
"True",
",",
"aniso",
"=",
"False",
")",
":",
"if",
"aniso",
":",
"a",
"=",
"[",
"[",
"0",
",",
"1",
",",
"2",
"]",
",",
"[",
"2",
",",
"3",
",",
"4",
"]",
"]",
"else",
":",
"a",
... | 29.285714 | 0.001575 |
def plot_world(world, **kwargs):
"""
Addes a heat-map representing the data in world (an EnvironmentFile object)
to the current plot.
kwargs:
palette - a seaborn palette (list of RGB values) indicating
how to color values. Will be converted to a continuous
... | [
"def",
"plot_world",
"(",
"world",
",",
"*",
"*",
"kwargs",
")",
":",
"denom",
",",
"palette",
"=",
"get_kwargs",
"(",
"world",
",",
"kwargs",
",",
"False",
")",
"world",
"=",
"color_grid",
"(",
"world",
",",
"palette",
",",
"denom",
",",
"True",
")"... | 45.043478 | 0.000945 |
def list_chunks(l, n):
"""
Return a list of chunks
:param l: List
:param n: int The number of items per chunk
:return: List
"""
if n < 1:
n = 1
return [l[i:i + n] for i in range(0, len(l), n)] | [
"def",
"list_chunks",
"(",
"l",
",",
"n",
")",
":",
"if",
"n",
"<",
"1",
":",
"n",
"=",
"1",
"return",
"[",
"l",
"[",
"i",
":",
"i",
"+",
"n",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"l",
")",
",",
"n",
")",
"]"
] | 22.3 | 0.008621 |
def update(self, a, b, c, d):
"""
Update contingency table with new values without creating a new object.
"""
self.table.ravel()[:] = [a, b, c, d]
self.N = self.table.sum() | [
"def",
"update",
"(",
"self",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
")",
":",
"self",
".",
"table",
".",
"ravel",
"(",
")",
"[",
":",
"]",
"=",
"[",
"a",
",",
"b",
",",
"c",
",",
"d",
"]",
"self",
".",
"N",
"=",
"self",
".",
"table",
... | 34.5 | 0.009434 |
def check_auth(self, all_credentials):
"""Update this socket's authentication.
Log in or out to bring this socket's credentials up to date with
those provided. Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `all_credentials`: dict, maps auth source to MongoCr... | [
"def",
"check_auth",
"(",
"self",
",",
"all_credentials",
")",
":",
"if",
"all_credentials",
"or",
"self",
".",
"authset",
":",
"cached",
"=",
"set",
"(",
"itervalues",
"(",
"all_credentials",
")",
")",
"authset",
"=",
"self",
".",
"authset",
".",
"copy",
... | 39.809524 | 0.002336 |
def from_semiaxes(cls,axes):
"""
Get axis-aligned elliptical conic from axis lenths
This can be converted into a hyperbola by getting the dual conic
"""
ax = list(1/N.array(axes)**2)
#ax[-1] *= -1 # Not sure what is going on here...
arr = N.diag(ax + [-1])
... | [
"def",
"from_semiaxes",
"(",
"cls",
",",
"axes",
")",
":",
"ax",
"=",
"list",
"(",
"1",
"/",
"N",
".",
"array",
"(",
"axes",
")",
"**",
"2",
")",
"#ax[-1] *= -1 # Not sure what is going on here...",
"arr",
"=",
"N",
".",
"diag",
"(",
"ax",
"+",
"[",
... | 37.111111 | 0.011696 |
def validate(ref_time, ref_freqs, est_time, est_freqs):
"""Checks that the time and frequency inputs are well-formed.
Parameters
----------
ref_time : np.ndarray
reference time stamps in seconds
ref_freqs : list of np.ndarray
reference frequencies in Hz
est_time : np.ndarray
... | [
"def",
"validate",
"(",
"ref_time",
",",
"ref_freqs",
",",
"est_time",
",",
"est_freqs",
")",
":",
"util",
".",
"validate_events",
"(",
"ref_time",
",",
"max_time",
"=",
"MAX_TIME",
")",
"util",
".",
"validate_events",
"(",
"est_time",
",",
"max_time",
"=",
... | 36.555556 | 0.000592 |
def generate_value_processor(type_, collectionFormat=None, items=None, **kwargs):
"""
Create a callable that will take the string value of a header and cast it
to the appropriate type. This can involve:
- splitting a header of type 'array' by its delimeters.
- type casting the internal elements of... | [
"def",
"generate_value_processor",
"(",
"type_",
",",
"collectionFormat",
"=",
"None",
",",
"items",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"processors",
"=",
"[",
"]",
"if",
"is_non_string_iterable",
"(",
"type_",
")",
":",
"assert",
"False",
","... | 43.403226 | 0.001453 |
def gettext(*args, **kwargs):
"""
Return the localized translation of message, based on the language, and
locale directory of the domain specified in the translation key (or the
current global domain). This function is usually aliased as ``_``.
"""
key = args[0]
key_match = TRANSLATION_KEY_R... | [
"def",
"gettext",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"args",
"[",
"0",
"]",
"key_match",
"=",
"TRANSLATION_KEY_RE",
".",
"match",
"(",
"key",
")",
"translation",
"=",
"_gettext",
"(",
"*",
"args",
",",
"*",
"*",
"kwarg... | 38.076923 | 0.001972 |
def rl_marks(x):
"""
Replace +-, (c), (tm), (r), (p), etc by its typographic eqivalents
"""
# простые замены, можно без регулярок
replacements = (
(u'(r)', u'\u00ae'), # ®
(u'(R)', u'\u00ae'), # ®
(u'(p)', u'\u00a7'), # §
(u'(P)', u'\u00a7'), # §
(u'(tm)', u'\... | [
"def",
"rl_marks",
"(",
"x",
")",
":",
"# простые замены, можно без регулярок",
"replacements",
"=",
"(",
"(",
"u'(r)'",
",",
"u'\\u00ae'",
")",
",",
"# ®",
"(",
"u'(R)'",
",",
"u'\\u00ae'",
")",
",",
"# ®",
"(",
"u'(p)'",
",",
"u'\\u00a7'",
")",
",",
"# §... | 38.533333 | 0.011814 |
def _activate_stream(self, idx):
'''Randomly select and create a stream.
StochasticMux adds mode handling to _activate_stream, making it so that
if we're not sampling "with_replacement", the distribution for this
chosen streamer is set to 0, causing the streamer not to be available
... | [
"def",
"_activate_stream",
"(",
"self",
",",
"idx",
")",
":",
"# Get the number of samples for this streamer.",
"n_samples_to_stream",
"=",
"None",
"if",
"self",
".",
"rate",
"is",
"not",
"None",
":",
"n_samples_to_stream",
"=",
"1",
"+",
"self",
".",
"rng",
"."... | 38.558824 | 0.001488 |
def expand_entries(entries, ignore_xs=None):
"""Turn all Xs which are not ignored in all entries into ``0`` s and
``1`` s.
For example::
>>> from rig.routing_table import RoutingTableEntry
>>> entries = [
... RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100), # 01XX
... | [
"def",
"expand_entries",
"(",
"entries",
",",
"ignore_xs",
"=",
"None",
")",
":",
"# Find the common Xs for the entries",
"if",
"ignore_xs",
"is",
"None",
":",
"ignore_xs",
"=",
"get_common_xs",
"(",
"entries",
")",
"# Keep a track of keys that we've seen",
"seen_keys",... | 39.914634 | 0.000298 |
def gts7(Input, flags, output):
'''
/* Thermospheric portion of NRLMSISE-00
* See GTD7 for more extensive comments
* alt > 72.5 km!
*/
'''
zn1 = [120.0, 110.0, 100.0, 90.0, 72.5]
mn1 = 5
dgtr=1.74533E-2;
dr=1.72142E-2;
alpha = [-0.38, 0.0, 0.0, 0.0, 0.17, 0.0, -0.38, 0.0, 0.0]
... | [
"def",
"gts7",
"(",
"Input",
",",
"flags",
",",
"output",
")",
":",
"zn1",
"=",
"[",
"120.0",
",",
"110.0",
",",
"100.0",
",",
"90.0",
",",
"72.5",
"]",
"mn1",
"=",
"5",
"dgtr",
"=",
"1.74533E-2",
"dr",
"=",
"1.72142E-2",
"alpha",
"=",
"[",
"-",
... | 37.477401 | 0.055213 |
def creation_ordered(class_to_decorate):
"""
Class decorator that ensures that instances will be ordered after creation order when sorted.
:type class_to_decorate: class
:rtype: class
"""
next_index = functools.partial(next, itertools.count())
__init__orig = class_to_decorate.... | [
"def",
"creation_ordered",
"(",
"class_to_decorate",
")",
":",
"next_index",
"=",
"functools",
".",
"partial",
"(",
"next",
",",
"itertools",
".",
"count",
"(",
")",
")",
"__init__orig",
"=",
"class_to_decorate",
".",
"__init__",
"@",
"functools",
".",
"wraps"... | 29.785714 | 0.002323 |
def radar_xsect(scatterer, h_pol=True):
"""Radar cross section for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The radar cross section.
"""
Z = sca... | [
"def",
"radar_xsect",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"if",
"h_pol",
":",
"return",
"2",
"*",
"np",
".",
"pi",
"*",
"(",
"Z",
"[",
"0",
",",
"0",
"]",
"-",
"Z",
"[",
"0",
... | 27.5 | 0.019531 |
def list(self, per_page=None, page=None, status=None, service='facebook'):
""" Get a list of Pylon tasks
:param per_page: How many tasks to display per page
:type per_page: int
:param page: Which page of tasks to display
:type page: int
:param status:... | [
"def",
"list",
"(",
"self",
",",
"per_page",
"=",
"None",
",",
"page",
"=",
"None",
",",
"status",
"=",
"None",
",",
"service",
"=",
"'facebook'",
")",
":",
"params",
"=",
"{",
"}",
"if",
"per_page",
"is",
"not",
"None",
":",
"params",
"[",
"'per_p... | 36.62963 | 0.00197 |
def incrby(self, fmt, offset, increment, overflow=None):
"""
Increment a bitfield by a given amount.
:param fmt: format-string for the bitfield being updated, e.g. u8 for
an unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:param int increment: ... | [
"def",
"incrby",
"(",
"self",
",",
"fmt",
",",
"offset",
",",
"increment",
",",
"overflow",
"=",
"None",
")",
":",
"if",
"overflow",
"is",
"not",
"None",
"and",
"overflow",
"!=",
"self",
".",
"_last_overflow",
":",
"self",
".",
"_last_overflow",
"=",
"... | 45.368421 | 0.002273 |
def run(
project: 'projects.Project',
step: 'projects.ProjectStep'
) -> dict:
"""
Runs the markdown file and renders the contents to the notebook display
:param project:
:param step:
:return:
A run response dictionary containing
"""
with open(step.source_path, 'r') ... | [
"def",
"run",
"(",
"project",
":",
"'projects.Project'",
",",
"step",
":",
"'projects.ProjectStep'",
")",
"->",
"dict",
":",
"with",
"open",
"(",
"step",
".",
"source_path",
",",
"'r'",
")",
"as",
"f",
":",
"code",
"=",
"f",
".",
"read",
"(",
")",
"t... | 24.259259 | 0.001468 |
def append_dynamics(self, t, dynamics, canvas=0, separate=False, color='blue'):
"""!
@brief Append several dynamics to canvas or canvases (defined by 'canvas' and 'separate' arguments).
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
... | [
"def",
"append_dynamics",
"(",
"self",
",",
"t",
",",
"dynamics",
",",
"canvas",
"=",
"0",
",",
"separate",
"=",
"False",
",",
"color",
"=",
"'blue'",
")",
":",
"description",
"=",
"dynamic_descr",
"(",
"canvas",
",",
"t",
",",
"dynamics",
",",
"separa... | 72.111111 | 0.010646 |
def resize(att_mat, max_length=None):
"""Normalize attention matrices and reshape as necessary."""
for i, att in enumerate(att_mat):
# Add extra batch dim for viz code to work.
if att.ndim == 3:
att = np.expand_dims(att, axis=0)
if max_length is not None:
# Sum across different attention val... | [
"def",
"resize",
"(",
"att_mat",
",",
"max_length",
"=",
"None",
")",
":",
"for",
"i",
",",
"att",
"in",
"enumerate",
"(",
"att_mat",
")",
":",
"# Add extra batch dim for viz code to work.",
"if",
"att",
".",
"ndim",
"==",
"3",
":",
"att",
"=",
"np",
"."... | 36.214286 | 0.019231 |
def dvcircdR(self,R,phi=None):
"""
NAME:
dvcircdR
PURPOSE:
calculate the derivative of the circular velocity at R wrt R
in this potential
INPUT:
R - Galactocentric radius (can be Quantity)
... | [
"def",
"dvcircdR",
"(",
"self",
",",
"R",
",",
"phi",
"=",
"None",
")",
":",
"return",
"0.5",
"*",
"(",
"-",
"self",
".",
"Rforce",
"(",
"R",
",",
"0.",
",",
"phi",
"=",
"phi",
",",
"use_physical",
"=",
"False",
")",
"+",
"R",
"*",
"self",
".... | 26.6875 | 0.031638 |
def make_router():
"""Return a WSGI application that searches requests to controllers """
global router
routings = [
('GET', '^/$', index),
('GET', '^/api/?$', index),
('POST', '^/api/1/calculate/?$', calculate.api1_calculate),
('GET', '^/api/2/entities/?$', entities.api2_ent... | [
"def",
"make_router",
"(",
")",
":",
"global",
"router",
"routings",
"=",
"[",
"(",
"'GET'",
",",
"'^/$'",
",",
"index",
")",
",",
"(",
"'GET'",
",",
"'^/api/?$'",
",",
"index",
")",
",",
"(",
"'POST'",
",",
"'^/api/1/calculate/?$'",
",",
"calculate",
... | 50.105263 | 0.002062 |
def pretty_print(d, ind='', verbosity=0):
"""Pretty print a data dictionary from the bridge client
"""
assert isinstance(d, dict)
for k, v in sorted(d.items()):
str_base = '{} - [{}] {}'.format(ind, type(v).__name__, k)
if isinstance(v, dict):
print(str_base.replace('-', '+'... | [
"def",
"pretty_print",
"(",
"d",
",",
"ind",
"=",
"''",
",",
"verbosity",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"d",
",",
"dict",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"d",
".",
"items",
"(",
")",
")",
":",
"str_base",
"=",... | 39.961538 | 0.00094 |
def cmd_hasher(f, algorithm):
"""Compute various hashes for the input data, that can be a file or a stream.
Example:
\b
$ habu.hasher README.rst
md5 992a833cd162047daaa6a236b8ac15ae README.rst
ripemd160 0566f9141e65e57cae93e0e3b70d1d8c2ccb0623 README.rst
sha1 d7dbfd2c5e... | [
"def",
"cmd_hasher",
"(",
"f",
",",
"algorithm",
")",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"if",
"not",
"data",
":",
"print",
"(",
"\"Empty file or string!\"",
")",
"return",
"1",
"if",
"algorithm",
":",
"print",
"(",
"hasher",
"(",
"data",
... | 31.878788 | 0.001845 |
def get_identities(self, identity=None, attrs=None):
""" Get identities matching name and attrs
of the user, as a list
:param: zobjects.Identity or identity name (string)
:param: attrs dict of attributes to return only identities matching
:returns: list of zobjects.Identity
... | [
"def",
"get_identities",
"(",
"self",
",",
"identity",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"resp",
"=",
"self",
".",
"request",
"(",
"'GetIdentities'",
")",
"if",
"'identity'",
"in",
"resp",
":",
"identities",
"=",
"resp",
"[",
"'identity'"... | 39.631579 | 0.001296 |
def add_operator(self, operator):
"""Add an ``Operator`` to the ``Expression``.
The ``Operator`` may result in a new ``Expression`` if an ``Operator``
already exists and is of a different precedence.
There are three possibilities when adding an ``Operator`` to an
``Expression``... | [
"def",
"add_operator",
"(",
"self",
",",
"operator",
")",
":",
"if",
"not",
"isinstance",
"(",
"operator",
",",
"Operator",
")",
":",
"raise",
"FiqlObjectException",
"(",
"\"%s is not a valid element type\"",
"%",
"(",
"operator",
".",
"__class__",
")",
")",
"... | 44.795918 | 0.001337 |
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.... | [
"def",
"get_git_changeset",
"(",
")",
":",
"repo_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"git_log",
"=",
"subprocess",
".",
"Popen",
"(",
"'git log --pretty=format:%ct --quiet -1 HEAD'",
... | 48.411765 | 0.002384 |
def post_event(api_key=None,
app_key=None,
title=None,
text=None,
date_happened=None,
priority=None,
host=None,
tags=None,
alert_type=None,
aggregation_key=None,
source_t... | [
"def",
"post_event",
"(",
"api_key",
"=",
"None",
",",
"app_key",
"=",
"None",
",",
"title",
"=",
"None",
",",
"text",
"=",
"None",
",",
"date_happened",
"=",
"None",
",",
"priority",
"=",
"None",
",",
"host",
"=",
"None",
",",
"tags",
"=",
"None",
... | 40.195122 | 0.000888 |
def __init(self):
""" initializes the service """
params = {
"f" : "json",
}
json_dict = self._get(self._url, params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
... | [
"def",
"__init",
"(",
"self",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"}",
"json_dict",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_url",
",",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_po... | 39.333333 | 0.012422 |
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs) | [
"def",
"info",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_log",
"(",
"logging",
".",
"INFO",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 42.25 | 0.011628 |
def haversine_distance(origin, destination):
"""
Calculate the Haversine distance.
Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)
Returns
-------
distance_in_km : float
Examples
--------
>>> munich = (... | [
"def",
"haversine_distance",
"(",
"origin",
",",
"destination",
")",
":",
"lat1",
",",
"lon1",
"=",
"origin",
"lat2",
",",
"lon2",
"=",
"destination",
"if",
"not",
"(",
"-",
"90.0",
"<=",
"lat1",
"<=",
"90",
")",
":",
"raise",
"ValueError",
"(",
"'lat1... | 30.46 | 0.000636 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.