text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def sanitize_dataframe(df):
"""Sanitize a DataFrame to prepare it for serialization.
* Make a copy
* Raise ValueError if it has a hierarchical index.
* Convert categoricals to strings.
* Convert np.bool_ dtypes to Python bool objects
* Convert np.int dtypes to Python int objects
* Convert f... | [
"def",
"sanitize_dataframe",
"(",
"df",
")",
":",
"import",
"pandas",
"as",
"pd",
"import",
"numpy",
"as",
"np",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"if",
"isinstance",
"(",
"df",
".",
"index",
",",
"pd",
".",
"core",
".",
"index",
".",
"MultiI... | 43.388889 | 0.001252 |
def put_files(self, files, content_type=None, compress=None, cache_control=None, block=True):
"""
Put lots of files at once and get a nice progress bar. It'll also wait
for the upload to complete, just like get_files.
Required:
files: [ (filepath, content), .... ]
"""
for path, content in... | [
"def",
"put_files",
"(",
"self",
",",
"files",
",",
"content_type",
"=",
"None",
",",
"compress",
"=",
"None",
",",
"cache_control",
"=",
"None",
",",
"block",
"=",
"True",
")",
":",
"for",
"path",
",",
"content",
"in",
"tqdm",
"(",
"files",
",",
"di... | 45.583333 | 0.010753 |
def _reaction_cartesion_expansion_unqualified_helper(
graph: BELGraph,
u: BaseEntity,
v: BaseEntity,
d: dict,
) -> None:
"""Helper to deal with cartension expansion in unqualified edges."""
if isinstance(u, Reaction) and isinstance(v, Reaction):
enzymes = _get_catalysts_i... | [
"def",
"_reaction_cartesion_expansion_unqualified_helper",
"(",
"graph",
":",
"BELGraph",
",",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
",",
"d",
":",
"dict",
",",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"u",
",",
"Reaction",
")",
"and... | 34.073529 | 0.001258 |
def setAll(self, pairs):
"""
Set multiple parameters, passed as a list of key-value pairs.
:param pairs: list of key-value pairs to set
"""
for (k, v) in pairs:
self.set(k, v)
return self | [
"def",
"setAll",
"(",
"self",
",",
"pairs",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"pairs",
":",
"self",
".",
"set",
"(",
"k",
",",
"v",
")",
"return",
"self"
] | 26.666667 | 0.008065 |
def make_nn_descent(dist, dist_args):
"""Create a numba accelerated version of nearest neighbor descent
specialised for the given distance metric and metric arguments. Numba
doesn't support higher order functions directly, but we can instead JIT
compile the version of NN-descent for any given metric.
... | [
"def",
"make_nn_descent",
"(",
"dist",
",",
"dist_args",
")",
":",
"@",
"numba",
".",
"njit",
"(",
"parallel",
"=",
"True",
")",
"def",
"nn_descent",
"(",
"data",
",",
"n_neighbors",
",",
"rng_state",
",",
"max_candidates",
"=",
"50",
",",
"n_iters",
"="... | 35.447917 | 0.001429 |
def _validate_inputs(self, inputdict):
""" Validate input links.
"""
# Check inputdict
try:
parameters = inputdict.pop(self.get_linkname('parameters'))
except KeyError:
raise InputValidationError("No parameters specified for this "
... | [
"def",
"_validate_inputs",
"(",
"self",
",",
"inputdict",
")",
":",
"# Check inputdict",
"try",
":",
"parameters",
"=",
"inputdict",
".",
"pop",
"(",
"self",
".",
"get_linkname",
"(",
"'parameters'",
")",
")",
"except",
"KeyError",
":",
"raise",
"InputValidati... | 40.209302 | 0.001129 |
def parse_config(self, config):
"""
Override this, making sure to chain up first, if your extension adds
its own custom command line arguments, or you want to do any further
processing on the automatically added arguments.
The default implementation will set attributes on the ex... | [
"def",
"parse_config",
"(",
"self",
",",
"config",
")",
":",
"prefix",
"=",
"self",
".",
"argument_prefix",
"self",
".",
"sources",
"=",
"config",
".",
"get_sources",
"(",
"prefix",
")",
"self",
".",
"smart_sources",
"=",
"[",
"self",
".",
"_get_smart_file... | 40.571429 | 0.001376 |
def resolve_class(operation):
"""For the given `tx` based on the `operation` key return its implementation class"""
create_txn_class = Transaction.type_registry.get(Transaction.CREATE)
return Transaction.type_registry.get(operation, create_txn_class) | [
"def",
"resolve_class",
"(",
"operation",
")",
":",
"create_txn_class",
"=",
"Transaction",
".",
"type_registry",
".",
"get",
"(",
"Transaction",
".",
"CREATE",
")",
"return",
"Transaction",
".",
"type_registry",
".",
"get",
"(",
"operation",
",",
"create_txn_cl... | 54.2 | 0.010909 |
def clean_deleted_sessions(cls):
"""remove old :class:`FederateSLO` object for which the session do not exists anymore"""
for federate_slo in cls.objects.all():
if not SessionStore(session_key=federate_slo.session_key).get('authenticated'):
federate_slo.delete() | [
"def",
"clean_deleted_sessions",
"(",
"cls",
")",
":",
"for",
"federate_slo",
"in",
"cls",
".",
"objects",
".",
"all",
"(",
")",
":",
"if",
"not",
"SessionStore",
"(",
"session_key",
"=",
"federate_slo",
".",
"session_key",
")",
".",
"get",
"(",
"'authenti... | 60.4 | 0.013072 |
def _to_original_callable(obj):
"""
Find the Python object that contains the source code of the object.
This is useful to find the place in the source code (file and line
number) where a docstring is defined. It does not currently work for
all cases, but it should help find some... | [
"def",
"_to_original_callable",
"(",
"obj",
")",
":",
"while",
"True",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"f",
"=",
"inspect",
".",
"getfile",
"(",
"obj",
")",
"if",
"f",
... | 38.545455 | 0.002301 |
def get_family(families):
"""Return the first installed font family in family list"""
if not isinstance(families, list):
families = [ families ]
for family in families:
if font_is_installed(family):
return family
else:
print("Warning: None of the following fonts is in... | [
"def",
"get_family",
"(",
"families",
")",
":",
"if",
"not",
"isinstance",
"(",
"families",
",",
"list",
")",
":",
"families",
"=",
"[",
"families",
"]",
"for",
"family",
"in",
"families",
":",
"if",
"font_is_installed",
"(",
"family",
")",
":",
"return"... | 38.8 | 0.010076 |
def acknowledge(self, project, subscription, ack_ids):
"""Pulls up to ``max_messages`` messages from Pub/Sub subscription.
:param project: the GCP project name or ID in which to create
the topic
:type project: str
:param subscription: the Pub/Sub subscription name to delete;... | [
"def",
"acknowledge",
"(",
"self",
",",
"project",
",",
"subscription",
",",
"ack_ids",
")",
":",
"service",
"=",
"self",
".",
"get_conn",
"(",
")",
"full_subscription",
"=",
"_format_subscription",
"(",
"project",
",",
"subscription",
")",
"try",
":",
"serv... | 45.391304 | 0.001876 |
def get_Tuple_params(tpl):
"""Python version independent function to obtain the parameters
of a typing.Tuple object.
Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
"""
try:
return tpl.__tuple_params__
except... | [
"def",
"get_Tuple_params",
"(",
"tpl",
")",
":",
"try",
":",
"return",
"tpl",
".",
"__tuple_params__",
"except",
"AttributeError",
":",
"try",
":",
"if",
"tpl",
".",
"__args__",
"is",
"None",
":",
"return",
"None",
"# Python 3.6",
"if",
"tpl",
".",
"__args... | 33.909091 | 0.001304 |
def content_type(self, data):
"""The Content-Type header value for this request."""
self._content_type = str(data)
self.add_header('Content-Type', str(data)) | [
"def",
"content_type",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_content_type",
"=",
"str",
"(",
"data",
")",
"self",
".",
"add_header",
"(",
"'Content-Type'",
",",
"str",
"(",
"data",
")",
")"
] | 44.5 | 0.01105 |
def insert_short(self, index, value):
"""Inserts an unsigned short in a certain position in the packet"""
format = '!H'
self.data.insert(index, struct.pack(format, value))
self.size += 2 | [
"def",
"insert_short",
"(",
"self",
",",
"index",
",",
"value",
")",
":",
"format",
"=",
"'!H'",
"self",
".",
"data",
".",
"insert",
"(",
"index",
",",
"struct",
".",
"pack",
"(",
"format",
",",
"value",
")",
")",
"self",
".",
"size",
"+=",
"2"
] | 42.8 | 0.009174 |
def backtrace_root(node):
"""
Example:
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> self = EulerTourTree(range(10))
>>> self._assert_nodes()
>>> root = self.root
>>> node = self.get_node(5)
>>> self.print_tree()
>>> print('node = %r... | [
"def",
"backtrace_root",
"(",
"node",
")",
":",
"# Trace path to the root",
"rpath",
"=",
"[",
"]",
"prev",
"=",
"node",
"now",
"=",
"node",
".",
"parent",
"while",
"now",
"is",
"not",
"None",
":",
"if",
"now",
".",
"left",
"is",
"prev",
":",
"rpath",
... | 28.37037 | 0.001263 |
def cmd_print(self):
"""Returns the raw lines to be printed."""
if not self._valid_lines:
return ''
return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n' | [
"def",
"cmd_print",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_valid_lines",
":",
"return",
"''",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"line",
".",
"raw_line",
"for",
"line",
"in",
"self",
".",
"_valid_lines",
"]",
")",
"+",
"'\\n'"
] | 40.4 | 0.009709 |
def write_xlsx_catalog(catalog, path, xlsx_fields=None):
"""Escribe el catálogo en Excel.
Args:
catalog (DataJson): Catálogo de datos.
path (str): Directorio absoluto donde se crea el archivo XLSX.
xlsx_fields (dict): Orden en que los campos del perfil de metadatos
se escrib... | [
"def",
"write_xlsx_catalog",
"(",
"catalog",
",",
"path",
",",
"xlsx_fields",
"=",
"None",
")",
":",
"xlsx_fields",
"=",
"xlsx_fields",
"or",
"XLSX_FIELDS",
"catalog_dict",
"=",
"{",
"}",
"catalog_dict",
"[",
"\"catalog\"",
"]",
"=",
"[",
"_tabulate_nested_dict"... | 36.37037 | 0.000992 |
def merge_includes(code):
"""Merge all includes recursively."""
pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"'
regex = re.compile(pattern)
includes = []
def replace(match):
filename = match.group("filename")
if filename not in includes:
includes.append... | [
"def",
"merge_includes",
"(",
"code",
")",
":",
"pattern",
"=",
"'\\#\\s*include\\s*\"(?P<filename>[a-zA-Z0-9\\_\\-\\.\\/]+)\"'",
"regex",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"includes",
"=",
"[",
"]",
"def",
"replace",
"(",
"match",
")",
":",
"filen... | 29.322581 | 0.00852 |
def x_is_greater_than(self, test_ordinate):
""" Comparison for x coordinate"""
self._is_coordinate(test_ordinate)
if self.x > test_ordinate.x:
return True
else:
return False | [
"def",
"x_is_greater_than",
"(",
"self",
",",
"test_ordinate",
")",
":",
"self",
".",
"_is_coordinate",
"(",
"test_ordinate",
")",
"if",
"self",
".",
"x",
">",
"test_ordinate",
".",
"x",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | 32.714286 | 0.008511 |
def autocorrelation(self, x, lag):
"""
As in tsfresh `autocorrelation <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1457>`_
Calculates the autocorrelation of the specified lag, according to the `formula <https://en.wikipedia.org... | [
"def",
"autocorrelation",
"(",
"self",
",",
"x",
",",
"lag",
")",
":",
"# This is important: If a series is passed, the product below is calculated",
"# based on the index, which corresponds to squaring the series.",
"if",
"lag",
"is",
"None",
":",
"lag",
"=",
"0",
"_autoc",
... | 41.172414 | 0.010638 |
def tap(self, locator, x_offset=None, y_offset=None, count=1):
""" Tap element identified by ``locator``.
Args:
- ``x_offset`` - (optional) x coordinate to tap, relative to the top left corner of the element.
- ``y_offset`` - (optional) y coordinate. If y is used, x must also be se... | [
"def",
"tap",
"(",
"self",
",",
"locator",
",",
"x_offset",
"=",
"None",
",",
"y_offset",
"=",
"None",
",",
"count",
"=",
"1",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"el",
"=",
"self",
".",
"_element_find",
"(",
"loca... | 51.083333 | 0.009615 |
def _parse_url(url, fully_qualified=False):
"""Parse the given charm or bundle URL, provided as a string.
Return a tuple containing the entity reference fragments: schema, user,
series, name and revision.
Each fragment is a string except revision (int).
Raise a ValueError with a descriptive messag... | [
"def",
"_parse_url",
"(",
"url",
",",
"fully_qualified",
"=",
"False",
")",
":",
"# Retrieve the schema.",
"try",
":",
"schema",
",",
"remaining",
"=",
"url",
".",
"split",
"(",
"':'",
",",
"1",
")",
"except",
"ValueError",
":",
"if",
"fully_qualified",
":... | 37.753425 | 0.000354 |
def topics(self):
""" Ordered dictionary with path:topic ordered by path """
topics_sorted = sorted(self._topics.items(), key=lambda t: t[0])
return MappingProxyType(OrderedDict(topics_sorted)) | [
"def",
"topics",
"(",
"self",
")",
":",
"topics_sorted",
"=",
"sorted",
"(",
"self",
".",
"_topics",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
"return",
"MappingProxyType",
"(",
"OrderedDict",
"(",
"topics_... | 53.5 | 0.009217 |
def set_chat_photo(self, chat_id, photo):
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
Not... | [
"def",
"set_chat_photo",
"(",
"self",
",",
"chat_id",
",",
"photo",
")",
":",
"return",
"apihelper",
".",
"set_chat_photo",
"(",
"self",
".",
"token",
",",
"chat_id",
",",
"photo",
")"
] | 60.615385 | 0.00875 |
def gen_url_regex(resource):
" URL regex for resource class generator. "
if resource._meta.parent:
yield resource._meta.parent._meta.url_regex.rstrip('/$').lstrip('^')
for p in resource._meta.url_params:
yield '%(name)s/(?P<%(name)s>[^/]+)' % dict(name=p)
if resource._meta.prefix:
... | [
"def",
"gen_url_regex",
"(",
"resource",
")",
":",
"if",
"resource",
".",
"_meta",
".",
"parent",
":",
"yield",
"resource",
".",
"_meta",
".",
"parent",
".",
"_meta",
".",
"url_regex",
".",
"rstrip",
"(",
"'/$'",
")",
".",
"lstrip",
"(",
"'^'",
")",
... | 32 | 0.002336 |
def apply_transformer_types(network):
"""Calculate transformer electrical parameters x, r, b, g from
standard types.
"""
trafos_with_types_b = network.transformers.type != ""
if trafos_with_types_b.zsum() == 0:
return
missing_types = (pd.Index(network.transformers.loc[trafos_with_type... | [
"def",
"apply_transformer_types",
"(",
"network",
")",
":",
"trafos_with_types_b",
"=",
"network",
".",
"transformers",
".",
"type",
"!=",
"\"\"",
"if",
"trafos_with_types_b",
".",
"zsum",
"(",
")",
"==",
"0",
":",
"return",
"missing_types",
"=",
"(",
"pd",
... | 37.880952 | 0.008578 |
def get_url_from (base_url, recursion_level, aggregate,
parent_url=None, base_ref=None, line=0, column=0, page=0,
name=u"", parent_content_type=None, extern=None):
"""
Get url data from given base data.
@param base_url: base url from a link tag
@type base_url: string... | [
"def",
"get_url_from",
"(",
"base_url",
",",
"recursion_level",
",",
"aggregate",
",",
"parent_url",
"=",
"None",
",",
"base_ref",
"=",
"None",
",",
"line",
"=",
"0",
",",
"column",
"=",
"0",
",",
"page",
"=",
"0",
",",
"name",
"=",
"u\"\"",
",",
"pa... | 40.813559 | 0.001217 |
def create_message(self, project_id, category_id, title, body,
extended_body, use_textile=False, private=False, notify=None,
attachments=None):
"""
Creates a new message, optionally sending notifications to a selected
list of people. Note that you can also upload files using this... | [
"def",
"create_message",
"(",
"self",
",",
"project_id",
",",
"category_id",
",",
"title",
",",
"body",
",",
"extended_body",
",",
"use_textile",
"=",
"False",
",",
"private",
"=",
"False",
",",
"notify",
"=",
"None",
",",
"attachments",
"=",
"None",
")",
... | 53.1 | 0.009248 |
def current_id(self):
"""
Determine the current revision identifier for the working directory
of this Repository
Returns:
str: git HEAD revision identifier
(``git rev-parse --short HEAD``)
"""
try:
cmd = ['git', 'rev-parse', '--sho... | [
"def",
"current_id",
"(",
"self",
")",
":",
"try",
":",
"cmd",
"=",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'--short'",
",",
"'HEAD'",
"]",
"return",
"self",
".",
"sh",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"ignore_error",
"=",
"True",
")",
... | 32.722222 | 0.008251 |
def do_gate(self, gate: Gate):
"""
Perform a gate.
:return: ``self`` to support method chaining.
"""
gate_matrix, qubit_inds = _get_gate_tensor_and_qubits(gate=gate)
# Note to developers: you can use either einsum- or tensordot- based functions.
# tensordot seems... | [
"def",
"do_gate",
"(",
"self",
",",
"gate",
":",
"Gate",
")",
":",
"gate_matrix",
",",
"qubit_inds",
"=",
"_get_gate_tensor_and_qubits",
"(",
"gate",
"=",
"gate",
")",
"# Note to developers: you can use either einsum- or tensordot- based functions.",
"# tensordot seems a li... | 46.833333 | 0.008726 |
def interval_range(start=None, end=None, periods=None, freq=None,
name=None, closed='right'):
"""
Return a fixed frequency IntervalIndex
Parameters
----------
start : numeric or datetime-like, default None
Left bound for generating intervals
end : numeric or datetime-... | [
"def",
"interval_range",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"periods",
"=",
"None",
",",
"freq",
"=",
"None",
",",
"name",
"=",
"None",
",",
"closed",
"=",
"'right'",
")",
":",
"start",
"=",
"com",
".",
"maybe_box_datetimelike",
... | 39.22293 | 0.000158 |
def get_ref_dir(region, coordsys):
""" Finds and returns the reference direction for a given
HEALPix region string.
region : a string describing a HEALPix region
coordsys : coordinate system, GAL | CEL
"""
if region is None:
if coordsys == "GAL":
... | [
"def",
"get_ref_dir",
"(",
"region",
",",
"coordsys",
")",
":",
"if",
"region",
"is",
"None",
":",
"if",
"coordsys",
"==",
"\"GAL\"",
":",
"c",
"=",
"SkyCoord",
"(",
"0.",
",",
"0.",
",",
"frame",
"=",
"Galactic",
",",
"unit",
"=",
"\"deg\"",
")",
... | 38.888889 | 0.00223 |
def _parse_load(self, load):
""" Parse the load from a single packet """
# If the load is ??
if load in ['??']:
self._debug('IGNORING')
# If there is a start in load
elif any([start in load for start in STARTS]):
self._debug('START')
self.messa... | [
"def",
"_parse_load",
"(",
"self",
",",
"load",
")",
":",
"# If the load is ??",
"if",
"load",
"in",
"[",
"'??'",
"]",
":",
"self",
".",
"_debug",
"(",
"'IGNORING'",
")",
"# If there is a start in load",
"elif",
"any",
"(",
"[",
"start",
"in",
"load",
"for... | 40.484848 | 0.001462 |
def sign(uri, headers, credentials):
"""Sign the URI and headers.
A request method of `GET` with no body content is assumed.
:param credentials: A tuple of consumer key, token key, and token secret.
"""
consumer_key, token_key, token_secret = credentials
auth = OAuthSigner(token_key, token_sec... | [
"def",
"sign",
"(",
"uri",
",",
"headers",
",",
"credentials",
")",
":",
"consumer_key",
",",
"token_key",
",",
"token_secret",
"=",
"credentials",
"auth",
"=",
"OAuthSigner",
"(",
"token_key",
",",
"token_secret",
",",
"consumer_key",
",",
"\"\"",
")",
"aut... | 40.2 | 0.002433 |
def rect_to_cyl(X,Y,Z):
"""
NAME:
rect_to_cyl
PURPOSE:
convert from rectangular to cylindrical coordinates
INPUT:
X, Y, Z - rectangular coordinates
OUTPUT:
R,phi,z
HISTORY:
2010-09-24 - Written - Bovy (NYU)
"""
R= sc.sqrt(X**2.+Y**2.)
phi=... | [
"def",
"rect_to_cyl",
"(",
"X",
",",
"Y",
",",
"Z",
")",
":",
"R",
"=",
"sc",
".",
"sqrt",
"(",
"X",
"**",
"2.",
"+",
"Y",
"**",
"2.",
")",
"phi",
"=",
"sc",
".",
"arctan2",
"(",
"Y",
",",
"X",
")",
"if",
"isinstance",
"(",
"phi",
",",
"n... | 15.071429 | 0.03118 |
def _swap_optimizer_allows(self, p1, p2):
"""Identify easily discarded meaningless swaps.
This is motivated by the cost of millions of swaps being simulated.
"""
# setup local shortcuts
a = self._array
tile1 = a[p1]
tile2 = a[p2]
# 1) disallow same tiles
... | [
"def",
"_swap_optimizer_allows",
"(",
"self",
",",
"p1",
",",
"p2",
")",
":",
"# setup local shortcuts",
"a",
"=",
"self",
".",
"_array",
"tile1",
"=",
"a",
"[",
"p1",
"]",
"tile2",
"=",
"a",
"[",
"p2",
"]",
"# 1) disallow same tiles",
"if",
"tile1",
"==... | 45.883721 | 0.000993 |
def _cancelScheduledUpgrade(self, justification=None) -> None:
"""
Cancels scheduled upgrade
:param when: time upgrade was scheduled to
:param version: version upgrade scheduled for
"""
if self.scheduledAction:
why_prefix = ": "
why = justificati... | [
"def",
"_cancelScheduledUpgrade",
"(",
"self",
",",
"justification",
"=",
"None",
")",
"->",
"None",
":",
"if",
"self",
".",
"scheduledAction",
":",
"why_prefix",
"=",
"\": \"",
"why",
"=",
"justification",
"if",
"justification",
"is",
"None",
":",
"why_prefix... | 37.837838 | 0.001393 |
def _complete_original_tasks(
self,
setName):
"""*mark original tasks as completed if they are marked as complete in the index taskpaper document*
**Key Arguments:**
- ``setName`` -- the name of the sync tag set
"""
self.log.info('starting the ``_comp... | [
"def",
"_complete_original_tasks",
"(",
"self",
",",
"setName",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_complete_original_tasks`` method'",
")",
"if",
"self",
".",
"editorialRootPath",
":",
"taskpaperDocPath",
"=",
"self",
".",
"syncFolder"... | 36.169492 | 0.001825 |
def rotate_img_and_crop(img, angle):
"""
Rotate an image and then crop it so that there is no black area.
:param img: The image to rotate.
:param angle: The rotation angle in degrees.
:return: The rotated and cropped image.
"""
h, w, _ = img.shape
img = scipy.ndimage.interpolation.rotate... | [
"def",
"rotate_img_and_crop",
"(",
"img",
",",
"angle",
")",
":",
"h",
",",
"w",
",",
"_",
"=",
"img",
".",
"shape",
"img",
"=",
"scipy",
".",
"ndimage",
".",
"interpolation",
".",
"rotate",
"(",
"img",
",",
"angle",
")",
"w",
",",
"h",
"=",
"_ro... | 38.909091 | 0.002283 |
def _get_pos_name(pos_code, names='parent', english=True, pos_map=POS_MAP):
"""Gets the part of speech name for *pos_code*."""
pos_code = pos_code.lower() # Issue #10
if names not in ('parent', 'child', 'all'):
raise ValueError("names must be one of 'parent', 'child', or "
... | [
"def",
"_get_pos_name",
"(",
"pos_code",
",",
"names",
"=",
"'parent'",
",",
"english",
"=",
"True",
",",
"pos_map",
"=",
"POS_MAP",
")",
":",
"pos_code",
"=",
"pos_code",
".",
"lower",
"(",
")",
"# Issue #10",
"if",
"names",
"not",
"in",
"(",
"'parent'"... | 43.447368 | 0.000592 |
def _update_pop(self, pop_size):
"""Updates population according to crossover and fitness criteria."""
offspring = list(map(self.toolbox.clone, self.population))
for _ in range(pop_size // 2):
if random.random() < self.cxpb:
child1, child2 = self.toolbox.select(self.p... | [
"def",
"_update_pop",
"(",
"self",
",",
"pop_size",
")",
":",
"offspring",
"=",
"list",
"(",
"map",
"(",
"self",
".",
"toolbox",
".",
"clone",
",",
"self",
".",
"population",
")",
")",
"for",
"_",
"in",
"range",
"(",
"pop_size",
"//",
"2",
")",
":"... | 45.914286 | 0.001219 |
def getStates(self):
'''
Calculates updated values of normalized market resources and permanent income level.
Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow.
Parameters
----------
None
Returns
-------
None
'''
pLvlPrev = self.pLvlN... | [
"def",
"getStates",
"(",
"self",
")",
":",
"pLvlPrev",
"=",
"self",
".",
"pLvlNow",
"aNrmPrev",
"=",
"self",
".",
"aNrmNow",
"# Calculate new states: normalized market resources and permanent income level",
"self",
".",
"pLvlNow",
"=",
"pLvlPrev",
"*",
"self",
".",
... | 40.608696 | 0.009414 |
def find_zonefile_origins( self, missing_zfinfo, peer_hostports ):
"""
Find out which peers can serve which zonefiles
"""
zonefile_origins = {} # map peer hostport to list of zonefile hashes
# which peers can serve each zonefile?
for zfhash in missing_zfinfo.keys():
... | [
"def",
"find_zonefile_origins",
"(",
"self",
",",
"missing_zfinfo",
",",
"peer_hostports",
")",
":",
"zonefile_origins",
"=",
"{",
"}",
"# map peer hostport to list of zonefile hashes",
"# which peers can serve each zonefile?",
"for",
"zfhash",
"in",
"missing_zfinfo",
".",
... | 40.25 | 0.010622 |
def check_contract_allowed(func):
"""Check if Contract is allowed by token
"""
@wraps(func)
def decorator(*args, **kwargs):
contract = kwargs.get('contract')
if (contract and current_user.is_authenticated()
and not current_user.allowed(contract)):
return curre... | [
"def",
"check_contract_allowed",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"contract",
"=",
"kwargs",
".",
"get",
"(",
"'contract'",
")",
"if",
"(",
"contract",
"an... | 36.636364 | 0.002421 |
def list_tables(self):
"""
Lists the tables in mydb.
## Returns
* `tables` (list): A list of strings with all the table names from mydb.
"""
q = 'SELECT Distinct TABLE_NAME FROM information_schema.TABLES'
res = self.quick(q, context='MYDB', task_name='listtables... | [
"def",
"list_tables",
"(",
"self",
")",
":",
"q",
"=",
"'SELECT Distinct TABLE_NAME FROM information_schema.TABLES'",
"res",
"=",
"self",
".",
"quick",
"(",
"q",
",",
"context",
"=",
"'MYDB'",
",",
"task_name",
"=",
"'listtables'",
",",
"system",
"=",
"True",
... | 39.692308 | 0.00947 |
def async_fetch(self, task, callback=None):
'''Do one fetch'''
url = task.get('url', 'data:,')
if callback is None:
callback = self.send_result
type = 'None'
start_time = time.time()
try:
if url.startswith('data:'):
type = 'data'
... | [
"def",
"async_fetch",
"(",
"self",
",",
"task",
",",
"callback",
"=",
"None",
")",
":",
"url",
"=",
"task",
".",
"get",
"(",
"'url'",
",",
"'data:,'",
")",
"if",
"callback",
"is",
"None",
":",
"callback",
"=",
"self",
".",
"send_result",
"type",
"=",... | 39.935484 | 0.002366 |
def remove_server_data(server_id):
"""
Remove a server from the server data
Args:
server_id (int): The server to remove from the server data
"""
logger.debug("Removing server from serverdata")
# Remove the server from data
data = datatools.get_data()
if server_id in data["disco... | [
"def",
"remove_server_data",
"(",
"server_id",
")",
":",
"logger",
".",
"debug",
"(",
"\"Removing server from serverdata\"",
")",
"# Remove the server from data",
"data",
"=",
"datatools",
".",
"get_data",
"(",
")",
"if",
"server_id",
"in",
"data",
"[",
"\"discord\"... | 29.142857 | 0.002375 |
def get_assignment_by_name(self, assignment_name, assignments=None):
"""Get assignment by name.
Get an assignment by name. It works by retrieving all assignments
and returning the first assignment with a matching name. If the
optional parameter ``assignments`` is provided, it uses this
... | [
"def",
"get_assignment_by_name",
"(",
"self",
",",
"assignment_name",
",",
"assignments",
"=",
"None",
")",
":",
"if",
"assignments",
"is",
"None",
":",
"assignments",
"=",
"self",
".",
"get_assignments",
"(",
")",
"for",
"assignment",
"in",
"assignments",
":"... | 39.076923 | 0.00096 |
def _type_bool(label,default=False):
"""Shortcut fot boolean like fields"""
return label, abstractSearch.nothing, abstractRender.boolen, default | [
"def",
"_type_bool",
"(",
"label",
",",
"default",
"=",
"False",
")",
":",
"return",
"label",
",",
"abstractSearch",
".",
"nothing",
",",
"abstractRender",
".",
"boolen",
",",
"default"
] | 50 | 0.013158 |
def step( self, peer_table=None, zonefile_queue=None, path=None ):
"""
Run one step of this algorithm.
Push the zonefile to all the peers that need it.
Return the number of peers we sent to
"""
if path is None:
path = self.atlasdb_path
if BLOCKSTACK_T... | [
"def",
"step",
"(",
"self",
",",
"peer_table",
"=",
"None",
",",
"zonefile_queue",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"atlasdb_path",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"... | 33.018868 | 0.011099 |
def _parse(value, strict=True):
"""
Preliminary duration value parser
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
pattern = r'(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)'
match = re.match(pattern, ... | [
"def",
"_parse",
"(",
"value",
",",
"strict",
"=",
"True",
")",
":",
"pattern",
"=",
"r'(?:(?P<hours>\\d+):)?(?P<minutes>\\d+):(?P<seconds>\\d+)'",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"value",
")",
"if",
"not",
"match",
":",
"raise",
"ValueE... | 34.388889 | 0.001572 |
def derivative(n, coef, derivative=2, periodic=False):
"""
Builds a penalty matrix for P-Splines with continuous features.
Penalizes the squared differences between basis coefficients.
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with cons... | [
"def",
"derivative",
"(",
"n",
",",
"coef",
",",
"derivative",
"=",
"2",
",",
"periodic",
"=",
"False",
")",
":",
"if",
"n",
"==",
"1",
":",
"# no derivative for constant functions",
"return",
"sp",
".",
"sparse",
".",
"csc_matrix",
"(",
"0.",
")",
"D",
... | 31.128205 | 0.001597 |
def mutations(self, nbr, strength):
'''
Multiple gene mutations
'''
for i in range(nbr):
self.mutation(strength) | [
"def",
"mutations",
"(",
"self",
",",
"nbr",
",",
"strength",
")",
":",
"for",
"i",
"in",
"range",
"(",
"nbr",
")",
":",
"self",
".",
"mutation",
"(",
"strength",
")"
] | 19.666667 | 0.056911 |
def rdtext(file, lenout=_default_len_out): # pragma: no cover
"""
Read the next line of text from a text file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rdtext_c.html
:param file: Name of text file.
:type file: str
:param lenout: Available room in output line.
:type lenout: ... | [
"def",
"rdtext",
"(",
"file",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"# pragma: no cover",
"file",
"=",
"stypes",
".",
"stringToCharP",
"(",
"file",
")",
"line",
"=",
"stypes",
".",
"stringToCharP",
"(",
"lenout",
")",
"lenout",
"=",
"ctypes",
"... | 34.210526 | 0.001497 |
def execute(self):
"""
Execute the actions necessary to perform a `molecule init role` and
returns None.
:return: None
"""
role_name = self._command_args['role_name']
role_directory = os.getcwd()
msg = 'Initializing new role {}...'.format(role_name)
... | [
"def",
"execute",
"(",
"self",
")",
":",
"role_name",
"=",
"self",
".",
"_command_args",
"[",
"'role_name'",
"]",
"role_directory",
"=",
"os",
".",
"getcwd",
"(",
")",
"msg",
"=",
"'Initializing new role {}...'",
".",
"format",
"(",
"role_name",
")",
"LOG",
... | 39 | 0.001317 |
def get_netrc_auth(url):
"""Returns the Requests tuple auth for a given url from netrc."""
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
except KeyError:
... | [
"def",
"get_netrc_auth",
"(",
"url",
")",
":",
"try",
":",
"from",
"netrc",
"import",
"netrc",
",",
"NetrcParseError",
"netrc_path",
"=",
"None",
"for",
"f",
"in",
"NETRC_FILES",
":",
"try",
":",
"loc",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"... | 30.090909 | 0.001463 |
def _scobit_transform_deriv_shape(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
"""
Paramete... | [
"def",
"_scobit_transform_deriv_shape",
"(",
"systematic_utilities",
",",
"alt_IDs",
",",
"rows_to_alts",
",",
"shape_params",
",",
"output_array",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note the np.exp is needed because the raw curvature p... | 49.730769 | 0.000253 |
def is_normal(self, k):
'''
lmap.is_normal(k) yields True if k is a key in the given lazy map lmap that is neither lazy
nor a formerly-lazy memoized key.
'''
v = ps.PMap.__getitem__(self, k)
if not isinstance(v, (types.FunctionType, partial)) or [] != getargspec_py27like(... | [
"def",
"is_normal",
"(",
"self",
",",
"k",
")",
":",
"v",
"=",
"ps",
".",
"PMap",
".",
"__getitem__",
"(",
"self",
",",
"k",
")",
"if",
"not",
"isinstance",
"(",
"v",
",",
"(",
"types",
".",
"FunctionType",
",",
"partial",
")",
")",
"or",
"[",
... | 38 | 0.010283 |
def get_provider(moduleOrReq):
"""Return an IResourceProvider for the named module or requirement"""
if isinstance(moduleOrReq, Requirement):
return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
try:
module = sys.modules[moduleOrReq]
except KeyError:
__import__(mo... | [
"def",
"get_provider",
"(",
"moduleOrReq",
")",
":",
"if",
"isinstance",
"(",
"moduleOrReq",
",",
"Requirement",
")",
":",
"return",
"working_set",
".",
"find",
"(",
"moduleOrReq",
")",
"or",
"require",
"(",
"str",
"(",
"moduleOrReq",
")",
")",
"[",
"0",
... | 43 | 0.00207 |
def rollback(self):
"""Drop changes from current transaction."""
if not self._in_transaction:
raise NotInTransaction
self._init_cache()
self._in_transaction = False | [
"def",
"rollback",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_in_transaction",
":",
"raise",
"NotInTransaction",
"self",
".",
"_init_cache",
"(",
")",
"self",
".",
"_in_transaction",
"=",
"False"
] | 33.833333 | 0.009615 |
def astra_parallel_3d_geom_to_vec(geometry):
"""Create vectors for ASTRA projection geometries from ODL geometry.
The 3D vectors are used to create an ASTRA projection geometry for
parallel beam geometries, see ``'parallel3d_vec'`` in the
`ASTRA projection geometry documentation`_.
Each row of the... | [
"def",
"astra_parallel_3d_geom_to_vec",
"(",
"geometry",
")",
":",
"angles",
"=",
"geometry",
".",
"angles",
"mid_pt",
"=",
"geometry",
".",
"det_params",
".",
"mid_pt",
"vectors",
"=",
"np",
".",
"zeros",
"(",
"(",
"angles",
".",
"shape",
"[",
"-",
"1",
... | 37.318182 | 0.000396 |
def timeslot_offset_options(
interval=swingtime_settings.TIMESLOT_INTERVAL,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
fmt=swingtime_settings.TIMESLOT_TIME_FORMAT
):
'''
Create a list of time slot options for use in swingtime forms... | [
"def",
"timeslot_offset_options",
"(",
"interval",
"=",
"swingtime_settings",
".",
"TIMESLOT_INTERVAL",
",",
"start_time",
"=",
"swingtime_settings",
".",
"TIMESLOT_START_TIME",
",",
"end_delta",
"=",
"swingtime_settings",
".",
"TIMESLOT_END_TIME_DURATION",
",",
"fmt",
"=... | 33.961538 | 0.002203 |
def subnet2block(subnet):
"""Convert a dotted-quad ip address including a netmask into a tuple
containing the network block start and end addresses.
>>> subnet2block('127.0.0.1/255.255.255.255')
('127.0.0.1', '127.0.0.1')
>>> subnet2block('127/255')
('127.0.0.0', '127.255.255.255')
>>> sub... | [
"def",
"subnet2block",
"(",
"subnet",
")",
":",
"if",
"not",
"validate_subnet",
"(",
"subnet",
")",
":",
"return",
"None",
"ip",
",",
"netmask",
"=",
"subnet",
".",
"split",
"(",
"'/'",
")",
"prefix",
"=",
"netmask2prefix",
"(",
"netmask",
")",
"# conver... | 30.057143 | 0.000921 |
def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... | [
"def",
"select_mask",
"(",
"cls",
",",
"dataset",
",",
"selection",
")",
":",
"select_mask",
"=",
"None",
"for",
"dim",
",",
"k",
"in",
"selection",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"k",
",",
"tuple",
")",
":",
"k",
"=",
"slice... | 38.585366 | 0.001233 |
def fetch_public_key(repo):
"""Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
"""
keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)
data = json.loads(urlopen(keyurl).read())
if 'key' not in data:
errms... | [
"def",
"fetch_public_key",
"(",
"repo",
")",
":",
"keyurl",
"=",
"'https://api.travis-ci.org/repos/{0}/key'",
".",
"format",
"(",
"repo",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"urlopen",
"(",
"keyurl",
")",
".",
"read",
"(",
")",
")",
"if",
"'key'",... | 41.333333 | 0.001972 |
def write_frame(self, frame_type, channel, payload):
"""
Write out an AMQP frame.
"""
size = len(payload)
self._write(pack('>BHI%dsB' % size,
frame_type, channel, size, payload, 0xce)) | [
"def",
"write_frame",
"(",
"self",
",",
"frame_type",
",",
"channel",
",",
"payload",
")",
":",
"size",
"=",
"len",
"(",
"payload",
")",
"self",
".",
"_write",
"(",
"pack",
"(",
"'>BHI%dsB'",
"%",
"size",
",",
"frame_type",
",",
"channel",
",",
"size",... | 28.75 | 0.012658 |
def decimaltimestamp(t=None):
"""
A UNIX timestamp as a Decimal object (exact number type).
Returns current time when called without args, otherwise
converts given floating point number ``t`` to a Decimal
with 9 decimal places.
:param t: Floating point UNIX timestamp ("seconds since epoch").
... | [
"def",
"decimaltimestamp",
"(",
"t",
"=",
"None",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"if",
"t",
"is",
"None",
"else",
"t",
"return",
"Decimal",
"(",
"'{:.6f}'",
".",
"format",
"(",
"t",
")",
")"
] | 37.571429 | 0.001855 |
def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a ... | [
"def",
"bulkCmd",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"nonRepeaters",
",",
"maxRepetitions",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"_cbFun",
"(",
"snmpDispatcher",
",",
"stateHandle",
",",
"errorIndic... | 39.659091 | 0.001957 |
def d2logpdf_dlink2(self, inv_link_f, y, Y_metadata=None):
"""
Hessian at y, given inv_link_f, w.r.t inv_link_f the hessian will be 0 unless i == j
i.e. second derivative logpdf at y given inverse link of f_i and inverse link of f_j w.r.t inverse link of f_i and inverse link of f_j.
.... | [
"def",
"d2logpdf_dlink2",
"(",
"self",
",",
"inv_link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"#d2logpdf_dlink2 = -y/(inv_link_f**2) - (1-y)/((1-inv_link_f)**2)",
"#d2logpdf_dlink2 = np.where(y, -1./np.square(inv_link_f), -1./np.square(1.-inv_link_f))",
"arg",
"=",
... | 50.5 | 0.009022 |
def to_json(self):
"""
Return the individual info in a dictionary for json.
"""
self.logger.debug("Returning json info")
individual_info = {
'family_id': self.family,
'id':self.individual_id,
'sex':str(self.sex),
'phenotype': str(... | [
"def",
"to_json",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Returning json info\"",
")",
"individual_info",
"=",
"{",
"'family_id'",
":",
"self",
".",
"family",
",",
"'id'",
":",
"self",
".",
"individual_id",
",",
"'sex'",
":",
... | 31.8 | 0.016293 |
def commit(name, **kwargs):
'''
Commits the changes loaded into the candidate configuration.
.. code-block:: yaml
commit the changes:
junos:
- commit
- confirm: 10
Parameters:
Optional
* kwargs: Keyworded arguments which can be ... | [
"def",
"commit",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt__... | 38.97561 | 0.000611 |
def check_internal_consistency(self, **kwargs):
"""Check whether the database is internally consistent
We check that all variables are equal to the sum of their sectoral
components and that all the regions add up to the World total. If
the check is passed, None is returned, otherwise a ... | [
"def",
"check_internal_consistency",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"inconsistent_vars",
"=",
"{",
"}",
"for",
"variable",
"in",
"self",
".",
"variables",
"(",
")",
":",
"diff_agg",
"=",
"self",
".",
"check_aggregate",
"(",
"variable",
","... | 43.37931 | 0.001555 |
def has_item(self,jid,node=None):
"""Check if `self` contains an item.
:Parameters:
- `jid`: JID of the item.
- `node`: node name of the item.
:Types:
- `jid`: `JID`
- `node`: `libxml2.xmlNode`
:return: `True` if the item is found in `sel... | [
"def",
"has_item",
"(",
"self",
",",
"jid",
",",
"node",
"=",
"None",
")",
":",
"l",
"=",
"self",
".",
"xpath_ctxt",
".",
"xpathEval",
"(",
"\"d:item\"",
")",
"if",
"l",
"is",
"None",
":",
"return",
"False",
"for",
"it",
"in",
"l",
":",
"di",
"="... | 28.9 | 0.01675 |
def range_n(self):
"""Current interpolation range of refractive index"""
return self.sphere_index - self.dn, self.sphere_index + self.dn | [
"def",
"range_n",
"(",
"self",
")",
":",
"return",
"self",
".",
"sphere_index",
"-",
"self",
".",
"dn",
",",
"self",
".",
"sphere_index",
"+",
"self",
".",
"dn"
] | 50 | 0.013158 |
def replace_in_list(stringlist: Iterable[str],
replacedict: Dict[str, str]) -> List[str]:
"""
Returns a list produced by applying :func:`multiple_replace` to every
string in ``stringlist``.
Args:
stringlist: list of source strings
replacedict: dictionary mapping "ori... | [
"def",
"replace_in_list",
"(",
"stringlist",
":",
"Iterable",
"[",
"str",
"]",
",",
"replacedict",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"newlist",
"=",
"[",
"]",
"for",
"fromstring",
"in",
"stringlist",
"... | 29.055556 | 0.001852 |
def __send_message(self, operation):
"""Send a getmore message and handle the response.
"""
def kill():
self.__killed = True
self.__end_session(True)
client = self.__collection.database.client
try:
response = client._run_operation_with_respons... | [
"def",
"__send_message",
"(",
"self",
",",
"operation",
")",
":",
"def",
"kill",
"(",
")",
":",
"self",
".",
"__killed",
"=",
"True",
"self",
".",
"__end_session",
"(",
"True",
")",
"client",
"=",
"self",
".",
"__collection",
".",
"database",
".",
"cli... | 31.108696 | 0.001355 |
def blockreplace(
name,
marker_start='#-- start managed zone --',
marker_end='#-- end managed zone --',
source=None,
source_hash=None,
template='jinja',
sources=None,
source_hashes=None,
defaults=None,
context=None,
content='',
... | [
"def",
"blockreplace",
"(",
"name",
",",
"marker_start",
"=",
"'#-- start managed zone --'",
",",
"marker_end",
"=",
"'#-- end managed zone --'",
",",
"source",
"=",
"None",
",",
"source_hash",
"=",
"None",
",",
"template",
"=",
"'jinja'",
",",
"sources",
"=",
"... | 36.117834 | 0.000257 |
def join(self, room, nick, handler, password = None, history_maxchars = None,
history_maxstanzas = None, history_seconds = None, history_since = None):
"""
Create and return a new room state object and request joining
to a MUC room.
:Parameters:
- `room`: the nam... | [
"def",
"join",
"(",
"self",
",",
"room",
",",
"nick",
",",
"handler",
",",
"password",
"=",
"None",
",",
"history_maxchars",
"=",
"None",
",",
"history_maxstanzas",
"=",
"None",
",",
"history_seconds",
"=",
"None",
",",
"history_since",
"=",
"None",
")",
... | 38.916667 | 0.008877 |
def _system_config_file():
"""
Returns the path to the settings.cfg file. On Windows the file is
located in the AppData/Local/envipyengine directory. On Unix, the file
will be located in the ~/.envipyengine directory.
:return: String specifying the full path to the settings.cfg file
"""
if ... | [
"def",
"_system_config_file",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"config_path",
"=",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"[",
"_windows_system_appdata",
"(",
")",
",",
"_APP_DIRNAME",
",",
"_CONFIG_FILENAME",
"]... | 45.631579 | 0.00113 |
def f(x, a, c):
""" Objective function (sum of squared residuals) """
v = g(x, a, c)
return v.dot(v) | [
"def",
"f",
"(",
"x",
",",
"a",
",",
"c",
")",
":",
"v",
"=",
"g",
"(",
"x",
",",
"a",
",",
"c",
")",
"return",
"v",
".",
"dot",
"(",
"v",
")"
] | 27.25 | 0.008929 |
def total_level(source_levels):
"""
Calculates the total sound pressure level based on multiple source levels
"""
sums = 0.0
for l in source_levels:
if l is None:
continue
if l == 0:
continue
sums += pow(10.0, float(l) / 10.0)
level = 10.0 * math.l... | [
"def",
"total_level",
"(",
"source_levels",
")",
":",
"sums",
"=",
"0.0",
"for",
"l",
"in",
"source_levels",
":",
"if",
"l",
"is",
"None",
":",
"continue",
"if",
"l",
"==",
"0",
":",
"continue",
"sums",
"+=",
"pow",
"(",
"10.0",
",",
"float",
"(",
... | 25.769231 | 0.008646 |
def dimensionalIterator(dimensions, maxItems=-1):
"""
Given a list of n positive integers, return a generator that yields
n-tuples of coordinates to 'fill' the dimensions. This is like an
odometer in a car, but the dimensions do not each have to be 10.
For example: dimensionalIterator((2, 3)) will ... | [
"def",
"dimensionalIterator",
"(",
"dimensions",
",",
"maxItems",
"=",
"-",
"1",
")",
":",
"nDimensions",
"=",
"len",
"(",
"dimensions",
")",
"if",
"nDimensions",
"==",
"0",
"or",
"maxItems",
"==",
"0",
":",
"return",
"if",
"any",
"(",
"map",
"(",
"lam... | 37.882353 | 0.000757 |
def mapScan(mapFunc, reductionFunc, *iterables, **kwargs):
"""Exectues the :meth:`~scoop.futures.map` function and then applies a
reduction function to its result while keeping intermediate reduction
values. This is a blocking call.
:param mapFunc: Any picklable callable object (function or class objec... | [
"def",
"mapScan",
"(",
"mapFunc",
",",
"reductionFunc",
",",
"*",
"iterables",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"submit",
"(",
"_recursiveReduce",
",",
"mapFunc",
",",
"reductionFunc",
",",
"True",
",",
"*",
"iterables",
")",
".",
"result",
"... | 45.962963 | 0.002368 |
def correct_usage(self, metadata, federation_usage):
"""
Remove MS paths that are marked to be used for another usage
:param metadata: Metadata statement as dictionary
:param federation_usage: In which context this is expected to used.
:return: Filtered Metadata statement.
... | [
"def",
"correct_usage",
"(",
"self",
",",
"metadata",
",",
"federation_usage",
")",
":",
"if",
"'metadata_statements'",
"in",
"metadata",
":",
"_msl",
"=",
"{",
"}",
"for",
"fo",
",",
"ms",
"in",
"metadata",
"[",
"'metadata_statements'",
"]",
".",
"items",
... | 35.6 | 0.001823 |
def _render_mail(self, rebuild, success, auto_canceled, manual_canceled):
"""Render and return subject and body of the mail to send."""
subject_template = '%(endstate)s building image %(image_name)s'
body_template = '\n'.join([
'Image Name: %(image_name)s',
'Repositories:... | [
"def",
"_render_mail",
"(",
"self",
",",
"rebuild",
",",
"success",
",",
"auto_canceled",
",",
"manual_canceled",
")",
":",
"subject_template",
"=",
"'%(endstate)s building image %(image_name)s'",
"body_template",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"'Image Name: %(i... | 34.188679 | 0.001609 |
def read_fwf(self, *args, **kwargs):
"""Fetch the target and pass through to pandas.read_fwf.
Don't provide the first argument of read_fwf(); it is supplied internally. """
import pandas
t = self.resolved_url.get_resource().get_target()
return pandas.read_fwf(t.fspath, *args, ... | [
"def",
"read_fwf",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pandas",
"t",
"=",
"self",
".",
"resolved_url",
".",
"get_resource",
"(",
")",
".",
"get_target",
"(",
")",
"return",
"pandas",
".",
"read_fwf",
"(",
"t",... | 35.666667 | 0.009119 |
def normalizeGlyphUnicodes(value):
"""
Normalizes glyph unicodes.
* **value** must be a ``list``.
* **value** items must normalize as glyph unicodes with
:func:`normalizeGlyphUnicode`.
* **value** must not repeat unicode values.
* Returned value will be a ``tuple`` of ints.
"""
if... | [
"def",
"normalizeGlyphUnicodes",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Glyph unicodes must be a list, not %s.\"",
"%",
"type",
"(",
"value",
")",
".",
"__... | 39.222222 | 0.001383 |
def sync(to_install, to_uninstall, verbose=False, dry_run=False, install_flags=None):
"""
Install and uninstalls the given sets of modules.
"""
if not to_uninstall and not to_install:
click.echo("Everything up-to-date")
pip_flags = []
if not verbose:
pip_flags += ['-q']
if ... | [
"def",
"sync",
"(",
"to_install",
",",
"to_uninstall",
",",
"verbose",
"=",
"False",
",",
"dry_run",
"=",
"False",
",",
"install_flags",
"=",
"None",
")",
":",
"if",
"not",
"to_uninstall",
"and",
"not",
"to_install",
":",
"click",
".",
"echo",
"(",
"\"Ev... | 34.108696 | 0.002478 |
def list_public_containers(self):
"""
Returns a list of the names of all CDN-enabled containers.
"""
resp, resp_body = self.api.cdn_request("", "GET")
return [cont["name"] for cont in resp_body] | [
"def",
"list_public_containers",
"(",
"self",
")",
":",
"resp",
",",
"resp_body",
"=",
"self",
".",
"api",
".",
"cdn_request",
"(",
"\"\"",
",",
"\"GET\"",
")",
"return",
"[",
"cont",
"[",
"\"name\"",
"]",
"for",
"cont",
"in",
"resp_body",
"]"
] | 38.166667 | 0.008547 |
def gp_ccX():
"""fit experimental data"""
inDir, outDir = getWorkDirs()
data, alldata = OrderedDict(), None
for infile in os.listdir(inDir):
# get key and import data
key = os.path.splitext(infile)[0].replace('_', '/')
data_import = np.loadtxt(open(os.path.join(inDir, infile), 'r... | [
"def",
"gp_ccX",
"(",
")",
":",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"data",
",",
"alldata",
"=",
"OrderedDict",
"(",
")",
",",
"None",
"for",
"infile",
"in",
"os",
".",
"listdir",
"(",
"inDir",
")",
":",
"# get key and import data",
"... | 42.554054 | 0.021415 |
def _get_parsed_args(command_name, doc, argv):
# type: (str, str, typing.List[str]) -> typing.Dict[str, typing.Any]
"""Parse the docstring with docopt.
Args:
command_name: The name of the subcommand to parse.
doc: A docopt-parseable string.
argv: The list of arguments to pass to doc... | [
"def",
"_get_parsed_args",
"(",
"command_name",
",",
"doc",
",",
"argv",
")",
":",
"# type: (str, str, typing.List[str]) -> typing.Dict[str, typing.Any]",
"_LOGGER",
".",
"debug",
"(",
"'Parsing docstring: \"\"\"%s\"\"\" with arguments %s.'",
",",
"doc",
",",
"argv",
")",
"... | 37.684211 | 0.001362 |
def oauth_client_create(self, name, redirect_uri, **kwargs):
"""
Make a new OAuth Client and return it
"""
params = {
"label": name,
"redirect_uri": redirect_uri,
}
params.update(kwargs)
result = self.client.post('/account/oauth-clients', ... | [
"def",
"oauth_client_create",
"(",
"self",
",",
"name",
",",
"redirect_uri",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"\"label\"",
":",
"name",
",",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"}",
"params",
".",
"update",
"(",
"kwargs",
... | 30.555556 | 0.008818 |
def create_schema(self, connection):
"""
Will create the schema in the database
"""
if '.' not in self.table:
return
query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0])
connection.cursor().execute(query) | [
"def",
"create_schema",
"(",
"self",
",",
"connection",
")",
":",
"if",
"'.'",
"not",
"in",
"self",
".",
"table",
":",
"return",
"query",
"=",
"'CREATE SCHEMA IF NOT EXISTS {schema_name};'",
".",
"format",
"(",
"schema_name",
"=",
"self",
".",
"table",
".",
... | 33.555556 | 0.009677 |
def sign(xml, stream, password=None):
"""
Sign an XML document with the given private key file. This will add a
<Signature> element to the document.
:param lxml.etree._Element xml: The document to sign
:param file stream: The private key to sign the document with
:param str password: The passwo... | [
"def",
"sign",
"(",
"xml",
",",
"stream",
",",
"password",
"=",
"None",
")",
":",
"# Import xmlsec here to delay initializing the C library in",
"# case we don't need it.",
"import",
"xmlsec",
"# Resolve the SAML/2.0 element in question.",
"from",
"saml",
".",
"schema",
"."... | 37.89 | 0.000257 |
def getAvailableClassesInModule(prooveModule):
"""
return a list of all classes in the given module
that dont begin with '_'
"""
l = tuple(x[1] for x in inspect.getmembers(prooveModule, inspect.isclass))
l = [x for x in l if x.__name__[0] != "_"]
return l | [
"def",
"getAvailableClassesInModule",
"(",
"prooveModule",
")",
":",
"l",
"=",
"tuple",
"(",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"inspect",
".",
"getmembers",
"(",
"prooveModule",
",",
"inspect",
".",
"isclass",
")",
")",
"l",
"=",
"[",
"x",
"for",
... | 34.5 | 0.010601 |
def resolve_and_call(self, func, extra_env=None):
""" Resolve function arguments and call them, possibily filling from the environment """
kwargs = self.resolve_parameters(func, extra_env=extra_env)
return func(**kwargs) | [
"def",
"resolve_and_call",
"(",
"self",
",",
"func",
",",
"extra_env",
"=",
"None",
")",
":",
"kwargs",
"=",
"self",
".",
"resolve_parameters",
"(",
"func",
",",
"extra_env",
"=",
"extra_env",
")",
"return",
"func",
"(",
"*",
"*",
"kwargs",
")"
] | 60.25 | 0.012295 |
def sync_config(self, force=False):
"""Sync the file config into the library proxy data in the root dataset """
from ambry.library.config import LibraryConfigSyncProxy
lcsp = LibraryConfigSyncProxy(self)
lcsp.sync(force=force) | [
"def",
"sync_config",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"from",
"ambry",
".",
"library",
".",
"config",
"import",
"LibraryConfigSyncProxy",
"lcsp",
"=",
"LibraryConfigSyncProxy",
"(",
"self",
")",
"lcsp",
".",
"sync",
"(",
"force",
"=",
"f... | 50.8 | 0.011628 |
def integrate_chans(spec,freqs,chan_per_coarse):
'''
Integrates over each core channel of a given spectrum.
Important for calibrating data with frequency/time resolution different from noise diode data
Parameters
----------
spec : 1D Array (float)
Spectrum (any Stokes parameter) to be i... | [
"def",
"integrate_chans",
"(",
"spec",
",",
"freqs",
",",
"chan_per_coarse",
")",
":",
"num_coarse",
"=",
"spec",
".",
"size",
"/",
"chan_per_coarse",
"#Calculate total number of coarse channels",
"#Rearrange spectrum by coarse channel",
"spec_shaped",
"=",
"np",
".",
"... | 36.565217 | 0.016222 |
def decode_iter_request(data: dict) -> Optional[Union[str, int]]:
"""
Decode incoming response from an iteration request
Args:
data: Response data
Returns:
Next itervalue
"""
if "response_metadata" in data:
return data["response_metadata"].get("next_cursor")
elif "p... | [
"def",
"decode_iter_request",
"(",
"data",
":",
"dict",
")",
"->",
"Optional",
"[",
"Union",
"[",
"str",
",",
"int",
"]",
"]",
":",
"if",
"\"response_metadata\"",
"in",
"data",
":",
"return",
"data",
"[",
"\"response_metadata\"",
"]",
".",
"get",
"(",
"\... | 28.636364 | 0.001536 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.