text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def central_likelihood(self, axis):
"""Returns new histogram with all values replaced by their central likelihoods along axis."""
result = self.cumulative_density(axis)
result.histogram = 1 - 2 * np.abs(result.histogram - 0.5)
return result | [
"def",
"central_likelihood",
"(",
"self",
",",
"axis",
")",
":",
"result",
"=",
"self",
".",
"cumulative_density",
"(",
"axis",
")",
"result",
".",
"histogram",
"=",
"1",
"-",
"2",
"*",
"np",
".",
"abs",
"(",
"result",
".",
"histogram",
"-",
"0.5",
"... | 53.6 | 0.011029 |
def notify(title, message, retcode=None):
"""
adapted from https://gist.github.com/baliw/4020619
"""
try:
import Foundation
import objc
except ImportError:
import sys
import logging
logger = logging.getLogger(__name__)
if sys.platform.startswith('darw... | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"retcode",
"=",
"None",
")",
":",
"try",
":",
"import",
"Foundation",
"import",
"objc",
"except",
"ImportError",
":",
"import",
"sys",
"import",
"logging",
"logger",
"=",
"logging",
".",
"getLogger",
"(",... | 32.290323 | 0.00097 |
def _on_mode_change(self, mode):
"""Mode change broadcast from Abode SocketIO server."""
if isinstance(mode, (tuple, list)):
mode = mode[0]
if mode is None:
_LOGGER.warning("Mode change event with no mode.")
return
if not mode or mode.lower() not in ... | [
"def",
"_on_mode_change",
"(",
"self",
",",
"mode",
")",
":",
"if",
"isinstance",
"(",
"mode",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"mode",
"=",
"mode",
"[",
"0",
"]",
"if",
"mode",
"is",
"None",
":",
"_LOGGER",
".",
"warning",
"(",
"\"... | 39.846154 | 0.001885 |
def NoSuchEntityOk(f):
""" Decorator to remove NoSuchEntity exceptions, and raises all others. """
def ExceptionFilter(*args):
try:
return f(*args)
except boto.exception.BotoServerError as e:
if e.error_code == 'NoSuchEntity':
pass
else:
raise
except:
raise
... | [
"def",
"NoSuchEntityOk",
"(",
"f",
")",
":",
"def",
"ExceptionFilter",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
")",
"except",
"boto",
".",
"exception",
".",
"BotoServerError",
"as",
"e",
":",
"if",
"e",
".",
"error_co... | 24.571429 | 0.028011 |
def timTuVi(cuc, ngaySinhAmLich):
"""Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
cungDan = 3 # Vị trí cung Dần ban đầu là 3
cucBanDau = cuc
if c... | [
"def",
"timTuVi",
"(",
"cuc",
",",
"ngaySinhAmLich",
")",
":",
"cungDan",
"=",
"3",
"# Vị trí cung Dần ban đầu là 3",
"cucBanDau",
"=",
"cuc",
"if",
"cuc",
"not",
"in",
"[",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
"]",
":",
"# Tránh trường hợp infin... | 28.541667 | 0.001412 |
def reset(self, blocking=True):
"""Reset the environment.
Args:
blocking: Whether to wait for the result.
Returns:
New observation when blocking, otherwise callable that returns the new
observation.
"""
promise = self.call('reset')
if blocking:
return promise()
else... | [
"def",
"reset",
"(",
"self",
",",
"blocking",
"=",
"True",
")",
":",
"promise",
"=",
"self",
".",
"call",
"(",
"'reset'",
")",
"if",
"blocking",
":",
"return",
"promise",
"(",
")",
"else",
":",
"return",
"promise"
] | 21.866667 | 0.008772 |
def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={},
style={}, options={}, **kwargs):
"""
Get Chartjs html
"""
try:
xdata = list(self.df[xcol])
except Exception as e:
self.err(e, self._get_chartjs_chart,
... | [
"def",
"_get_chartjs_chart",
"(",
"self",
",",
"xcol",
",",
"ycol",
",",
"chart_type",
",",
"label",
"=",
"None",
",",
"opts",
"=",
"{",
"}",
",",
"style",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
... | 35.676471 | 0.002408 |
def create_user(user_name, path=None, region=None, key=None, keyid=None,
profile=None):
'''
Create a user.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.create_user myuser
'''
if not path:
path = '/'
if get_user(us... | [
"def",
"create_user",
"(",
"user_name",
",",
"path",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"'/'",
"if",
"get_user",... | 27.115385 | 0.00137 |
def least_squares_effective_mass( cartesian_k_points, eigenvalues ):
"""
Calculate the effective mass using a least squares quadratic fit.
Args:
cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points
eigenvalues (np.array): Energy eigenvalues at each k-point... | [
"def",
"least_squares_effective_mass",
"(",
"cartesian_k_points",
",",
"eigenvalues",
")",
":",
"if",
"not",
"points_are_in_a_straight_line",
"(",
"cartesian_k_points",
")",
":",
"raise",
"ValueError",
"(",
"'k-points are not collinear'",
")",
"dk",
"=",
"cartesian_k_poin... | 41.047619 | 0.021542 |
def _check_parsed(self, parsed, now): # type: (dict, pendulum.DateTime) -> dict
"""
Checks validity of parsed elements.
:param parsed: The elements to parse.
:return: The validated elements.
"""
validated = {
"year": parsed["year"],
"month": par... | [
"def",
"_check_parsed",
"(",
"self",
",",
"parsed",
",",
"now",
")",
":",
"# type: (dict, pendulum.DateTime) -> dict",
"validated",
"=",
"{",
"\"year\"",
":",
"parsed",
"[",
"\"year\"",
"]",
",",
"\"month\"",
":",
"parsed",
"[",
"\"month\"",
"]",
",",
"\"day\"... | 31.897436 | 0.00104 |
def syncEndpoints(self):
"""
Retrieve all current endpoints for the connected user.
"""
self.endpoints["all"] = []
for json in self("GET", "{0}/users/ME/presenceDocs/messagingService".format(self.msgsHost),
params={"view": "expanded"}, auth=self.Auth.RegT... | [
"def",
"syncEndpoints",
"(",
"self",
")",
":",
"self",
".",
"endpoints",
"[",
"\"all\"",
"]",
"=",
"[",
"]",
"for",
"json",
"in",
"self",
"(",
"\"GET\"",
",",
"\"{0}/users/ME/presenceDocs/messagingService\"",
".",
"format",
"(",
"self",
".",
"msgsHost",
")",... | 52.777778 | 0.008282 |
def lookup_id(self, group):
"""
Lookup GID for the given group.
Args:
group: Name of group whose ID needs to be looked up
Returns:
A bytestring representation of the group ID (gid)
for the group specified
Raises:
ldap_tools.excep... | [
"def",
"lookup_id",
"(",
"self",
",",
"group",
")",
":",
"filter",
"=",
"[",
"\"(cn={})\"",
".",
"format",
"(",
"group",
")",
",",
"\"(objectclass=posixGroup)\"",
"]",
"results",
"=",
"self",
".",
"client",
".",
"search",
"(",
"filter",
",",
"[",
"'gidNu... | 31.933333 | 0.002026 |
def AddFilesWithUnknownHashes(
client_path_blob_refs,
use_external_stores = True
):
"""Adds new files consisting of given blob references.
Args:
client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to
lists of blob references.
use_external_stores: A flag indicating if the fil... | [
"def",
"AddFilesWithUnknownHashes",
"(",
"client_path_blob_refs",
",",
"use_external_stores",
"=",
"True",
")",
":",
"hash_id_blob_refs",
"=",
"dict",
"(",
")",
"client_path_hash_id",
"=",
"dict",
"(",
")",
"metadatas",
"=",
"dict",
"(",
")",
"all_client_path_blob_r... | 37.244681 | 0.009182 |
def all_library_calls(self):
""" recursive version of library calls
"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls)
return self._all_library_calls | [
"def",
"all_library_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_library_calls",
"is",
"None",
":",
"self",
".",
"_all_library_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"library_calls",
")",
"return",
"self... | 42.333333 | 0.011583 |
def getResultsInterpretationByDepartment(self, department=None):
"""Returns the results interpretation for this Analysis Request
and department. If department not set, returns the results
interpretation tagged as 'General'.
:returns: a dict with the following keys:
{'u... | [
"def",
"getResultsInterpretationByDepartment",
"(",
"self",
",",
"department",
"=",
"None",
")",
":",
"uid",
"=",
"department",
".",
"UID",
"(",
")",
"if",
"department",
"else",
"'general'",
"rows",
"=",
"self",
".",
"Schema",
"(",
")",
"[",
"'ResultsInterpr... | 45.95 | 0.002132 |
def gedcom_lines(self, offset):
"""Generator method for *gedcom lines*.
GEDCOM line grammar is defined in Chapter 1 of GEDCOM standard, it
consists of the level number, optional reference ID, tag name, and
optional value separated by spaces. Chaper 1 is pure grammar level,
it do... | [
"def",
"gedcom_lines",
"(",
"self",
",",
"offset",
")",
":",
"self",
".",
"_file",
".",
"seek",
"(",
"offset",
")",
"prev_gline",
"=",
"None",
"while",
"True",
":",
"offset",
"=",
"self",
".",
"_file",
".",
"tell",
"(",
")",
"line",
"=",
"self",
".... | 44.92 | 0.000581 |
def samefile(p1, p2):
"""
Determine if two paths reference the same file.
Augments os.path.samefile to work on Windows and
suppresses errors if the path doesn't exist.
"""
both_exist = os.path.exists(p1) and os.path.exists(p2)
use_samefile = hasattr(os.path, 'samefile') and both_exist
i... | [
"def",
"samefile",
"(",
"p1",
",",
"p2",
")",
":",
"both_exist",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"p1",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"p2",
")",
"use_samefile",
"=",
"hasattr",
"(",
"os",
".",
"path",
",",
"'samefi... | 35.571429 | 0.001957 |
def vcsNodeState_originator_switch_info_switchIpV6Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs")
originator_switch_info = ET.SubElement(vcsNodeState, ... | [
"def",
"vcsNodeState_originator_switch_info_switchIpV6Address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"vcsNodeState",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"vcsNodeState\"",
","... | 52.545455 | 0.008503 |
def retrieve_remote_content(
id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None,
):
"""Retrieve remote content and return an Entity object.
Currently, due to no other protocols supported, always use the Diaspora protocol.
:param sender_k... | [
"def",
"retrieve_remote_content",
"(",
"id",
":",
"str",
",",
"guid",
":",
"str",
"=",
"None",
",",
"handle",
":",
"str",
"=",
"None",
",",
"entity_type",
":",
"str",
"=",
"None",
",",
"sender_key_fetcher",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
... | 46.263158 | 0.015608 |
async def facebook_request(
self,
path: str,
access_token: str = None,
post_args: Dict[str, Any] = None,
**args: Any
) -> Any:
"""Fetches the given relative API path, e.g., "/btaylor/picture"
If the request is a POST, ``post_args`` should be provided. Query
... | [
"async",
"def",
"facebook_request",
"(",
"self",
",",
"path",
":",
"str",
",",
"access_token",
":",
"str",
"=",
"None",
",",
"post_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"*",
"*",
"args",
":",
"Any",
")",
"->",
"Any",
... | 37.393443 | 0.002136 |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._public_uuid is not None:
ret... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_id_",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_created",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_updated",
"is",
"not",
"None",
... | 21.772727 | 0.001332 |
def padded_grid_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):
"""Setup an *PaddedSubGrid* for an input mask, sub-grid size and psf-shape.
The center of every sub-pixel is used to setup the grid's (y,x) arc-second coordinates, including \
masked-pixels which are bey... | [
"def",
"padded_grid_from_mask_sub_grid_size_and_psf_shape",
"(",
"cls",
",",
"mask",
",",
"sub_grid_size",
",",
"psf_shape",
")",
":",
"padded_shape",
"=",
"(",
"mask",
".",
"shape",
"[",
"0",
"]",
"+",
"psf_shape",
"[",
"0",
"]",
"-",
"1",
",",
"mask",
".... | 53.48 | 0.010287 |
def specshow(data, x_coords=None, y_coords=None,
x_axis=None, y_axis=None,
sr=22050, hop_length=512,
fmin=None, fmax=None,
bins_per_octave=12,
ax=None,
**kwargs):
'''Display a spectrogram/chromagram/cqt/etc.
Parameters
---------... | [
"def",
"specshow",
"(",
"data",
",",
"x_coords",
"=",
"None",
",",
"y_coords",
"=",
"None",
",",
"x_axis",
"=",
"None",
",",
"y_axis",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"hop_length",
"=",
"512",
",",
"fmin",
"=",
"None",
",",
"fmax",
"=",
... | 30.373444 | 0.000265 |
def getFileAuthor(self, fileInfo):
"""Function to get the file's author for file info, note that we are pretending that multiple authors do not exist here"""
author = fileInfo[fileInfo.find("Author"):]
author = author[author.find("<FONT ") + 47:]
author = author[author.find('<B>') + 3:]
authormail = author[au... | [
"def",
"getFileAuthor",
"(",
"self",
",",
"fileInfo",
")",
":",
"author",
"=",
"fileInfo",
"[",
"fileInfo",
".",
"find",
"(",
"\"Author\"",
")",
":",
"]",
"author",
"=",
"author",
"[",
"author",
".",
"find",
"(",
"\"<FONT \"",
")",
"+",
"47",
":",
"]... | 49.4 | 0.023857 |
def _der(self,x):
'''
Returns the first derivative of the interpolated function at each value
in x. Only called internally by HARKinterpolator1D.derivative (etc).
'''
if _isscalar(x):
pos = np.searchsorted(self.x_list,x)
if pos == 0:
dydx =... | [
"def",
"_der",
"(",
"self",
",",
"x",
")",
":",
"if",
"_isscalar",
"(",
"x",
")",
":",
"pos",
"=",
"np",
".",
"searchsorted",
"(",
"self",
".",
"x_list",
",",
"x",
")",
"if",
"pos",
"==",
"0",
":",
"dydx",
"=",
"self",
".",
"coeffs",
"[",
"0"... | 49.742857 | 0.017465 |
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
C... | [
"def",
"describe_cache_parameters",
"(",
"name",
"=",
"None",
",",
"conn",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"ret",
"=",
"{",
... | 42.189189 | 0.008766 |
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_p... | [
"def",
"init_logger",
"(",
"self",
")",
":",
"# All logs are comming to this logger",
"self",
".",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"self",
".",
"logger",
".",
"propagate",
"=",
"False",
"# Logging to console",
"if",
"self",
".",
"... | 35.548387 | 0.001767 |
def read_server_mode_cluster_definition(cluster, cl_args):
'''
Read the cluster definition for server mode
:param cluster:
:param cl_args:
:param config_file:
:return:
'''
client_confs = dict()
client_confs[cluster] = cliconfig.cluster_config(cluster)
# now check if the service-url from command li... | [
"def",
"read_server_mode_cluster_definition",
"(",
"cluster",
",",
"cl_args",
")",
":",
"client_confs",
"=",
"dict",
"(",
")",
"client_confs",
"[",
"cluster",
"]",
"=",
"cliconfig",
".",
"cluster_config",
"(",
"cluster",
")",
"# now check if the service-url from comma... | 29.65 | 0.014706 |
def edges_touching_tile(tile_id):
"""
Get a list of edge coordinates touching the given tile.
:param tile_id: tile identifier, Tile.tile_id
:return: list of edge coordinates touching the given tile, list(int)
"""
coord = tile_id_to_coord(tile_id)
edges = []
for offset in _tile_edge_offs... | [
"def",
"edges_touching_tile",
"(",
"tile_id",
")",
":",
"coord",
"=",
"tile_id_to_coord",
"(",
"tile_id",
")",
"edges",
"=",
"[",
"]",
"for",
"offset",
"in",
"_tile_edge_offsets",
".",
"keys",
"(",
")",
":",
"edges",
".",
"append",
"(",
"coord",
"+",
"of... | 34.538462 | 0.002169 |
def makebunches_alter(data, commdct, theidf):
"""make bunches with data"""
bunchdt = {}
dt, dtls = data.dt, data.dtls
for obj_i, key in enumerate(dtls):
key = key.upper()
objs = dt[key]
list1 = []
for obj in objs:
bobj = makeabunch(commdct, obj, obj_i)
... | [
"def",
"makebunches_alter",
"(",
"data",
",",
"commdct",
",",
"theidf",
")",
":",
"bunchdt",
"=",
"{",
"}",
"dt",
",",
"dtls",
"=",
"data",
".",
"dt",
",",
"data",
".",
"dtls",
"for",
"obj_i",
",",
"key",
"in",
"enumerate",
"(",
"dtls",
")",
":",
... | 31.384615 | 0.002381 |
def map_vals(func, dict_):
"""
applies a function to each of the keys in a dictionary
Args:
func (callable): a function or indexable object
dict_ (dict): a dictionary
Returns:
newdict: transformed dictionary
CommandLine:
python -m ubelt.util_dict map_vals
Exam... | [
"def",
"map_vals",
"(",
"func",
",",
"dict_",
")",
":",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'__call__'",
")",
":",
"func",
"=",
"func",
".",
"__getitem__",
"keyval_list",
"=",
"[",
"(",
"key",
",",
"func",
"(",
"val",
")",
")",
"for",
"key",... | 30.571429 | 0.000906 |
def get_usages(self):
"Return a dictionary mapping full usages Ids to plain values"
result = dict()
for key, usage in self.items():
result[key] = usage.value
return result | [
"def",
"get_usages",
"(",
"self",
")",
":",
"result",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"usage",
"in",
"self",
".",
"items",
"(",
")",
":",
"result",
"[",
"key",
"]",
"=",
"usage",
".",
"value",
"return",
"result"
] | 35.833333 | 0.009091 |
def detach_all_classes(self):
"""
Detach from all tracked classes.
"""
classes = list(self._observers.keys())
for cls in classes:
self.detach_class(cls) | [
"def",
"detach_all_classes",
"(",
"self",
")",
":",
"classes",
"=",
"list",
"(",
"self",
".",
"_observers",
".",
"keys",
"(",
")",
")",
"for",
"cls",
"in",
"classes",
":",
"self",
".",
"detach_class",
"(",
"cls",
")"
] | 28.285714 | 0.009804 |
def generate_n_vectors(N_max, dx=1, dy=1, dz=1, half_lattice=True):
r"""
Generate integer vectors, :math:`\boldsymbol{n}`, with
:math:`|\boldsymbol{n}| < N_{\rm max}`.
If ``half_lattice=True``, only return half of the three-dimensional
lattice. If the set N = {(i,j,k)} defines the lattice, we restr... | [
"def",
"generate_n_vectors",
"(",
"N_max",
",",
"dx",
"=",
"1",
",",
"dy",
"=",
"1",
",",
"dz",
"=",
"1",
",",
"half_lattice",
"=",
"True",
")",
":",
"vecs",
"=",
"np",
".",
"meshgrid",
"(",
"np",
".",
"arange",
"(",
"-",
"N_max",
",",
"N_max",
... | 32.055556 | 0.000561 |
def _hash2xy(hashcode, dim):
"""Convert hashcode to (x, y).
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
hashcode: int Hashcode to decode [0, dim**2)
dim: int Number of... | [
"def",
"_hash2xy",
"(",
"hashcode",
",",
"dim",
")",
":",
"assert",
"(",
"hashcode",
"<=",
"dim",
"*",
"dim",
"-",
"1",
")",
"x",
"=",
"y",
"=",
"0",
"lvl",
"=",
"1",
"while",
"(",
"lvl",
"<",
"dim",
")",
":",
"rx",
"=",
"1",
"&",
"(",
"has... | 27.928571 | 0.001236 |
def get_gravatar(email, size=80, default='identicon'):
""" Get's a Gravatar for a email address.
:param size:
The size in pixels of one side of the Gravatar's square image.
Optional, if not supplied will default to ``80``.
:param default:
Defines what should be displayed if no imag... | [
"def",
"get_gravatar",
"(",
"email",
",",
"size",
"=",
"80",
",",
"default",
"=",
"'identicon'",
")",
":",
"if",
"userena_settings",
".",
"USERENA_MUGSHOT_GRAVATAR_SECURE",
":",
"base_url",
"=",
"'https://secure.gravatar.com/avatar/'",
"else",
":",
"base_url",
"=",
... | 34.288889 | 0.00189 |
def all_files(models=[]):
r'''
Return a list of full path of files matching 'models', sorted in human
numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000).
Files are supposed to be named identically except one variable component
e.g. the list,
test.weights.e5.lstm1200.ldc93s1.pb
... | [
"def",
"all_files",
"(",
"models",
"=",
"[",
"]",
")",
":",
"def",
"nsort",
"(",
"a",
",",
"b",
")",
":",
"fa",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"a",
")",
".",
"split",
"(",
"'.'",
")",
"fb",
"=",
"os",
".",
"path",
".",
"basen... | 26.479167 | 0.000759 |
def apply_effect_expression_filters(
effects,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold):
"""
Filter collection of varcode effects by given gene
and transcript expression thresholds.
Parameters
... | [
"def",
"apply_effect_expression_filters",
"(",
"effects",
",",
"gene_expression_dict",
",",
"gene_expression_threshold",
",",
"transcript_expression_dict",
",",
"transcript_expression_threshold",
")",
":",
"if",
"gene_expression_dict",
":",
"effects",
"=",
"apply_filter",
"("... | 31.093023 | 0.00145 |
def font_list(text="test", test=False):
"""
Print all fonts.
:param text : input text
:type text : str
:param test: test flag
:type test: bool
:return: None
"""
fonts = set(FONT_MAP.keys())
if test:
fonts = fonts - set(TEST_FILTERED_FONTS)
for item in sorted(list(fon... | [
"def",
"font_list",
"(",
"text",
"=",
"\"test\"",
",",
"test",
"=",
"False",
")",
":",
"fonts",
"=",
"set",
"(",
"FONT_MAP",
".",
"keys",
"(",
")",
")",
"if",
"test",
":",
"fonts",
"=",
"fonts",
"-",
"set",
"(",
"TEST_FILTERED_FONTS",
")",
"for",
"... | 24.4 | 0.001972 |
def as_dict(self):
"""
Returns the CTRL as a dictionary. "SITE" and "CLASS" are of
the form {'CATEGORY': {'TOKEN': value}}, the rest is of the
form 'TOKEN'/'CATEGORY': value. It gets the conventional standard
structure because primitive cells use the conventional
a-lattic... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"ctrl_dict",
"=",
"{",
"\"@module\"",
":",
"self",
".",
"__class__",
".",
"__module__",
",",
"\"@class\"",
":",
"self",
".",
"__class__",
".",
"__name__",
"}",
"if",
"self",
".",
"header",
"is",
"not",
"None",
"... | 43.32 | 0.000903 |
def makedoetree(ddict, bdict):
"""makedoetree"""
dlist = list(ddict.keys())
blist = list(bdict.keys())
dlist.sort()
blist.sort()
#make space dict
doesnot = 'DOES NOT'
lst = []
for num in range(0, len(blist)):
if bdict[blist[num]] == doesnot:#belong
lst = lst + [bl... | [
"def",
"makedoetree",
"(",
"ddict",
",",
"bdict",
")",
":",
"dlist",
"=",
"list",
"(",
"ddict",
".",
"keys",
"(",
")",
")",
"blist",
"=",
"list",
"(",
"bdict",
".",
"keys",
"(",
")",
")",
"dlist",
".",
"sort",
"(",
")",
"blist",
".",
"sort",
"(... | 31.705882 | 0.010198 |
def _interfaces_ifconfig(out):
"""
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
"""
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]... | [
"def",
"_interfaces_ifconfig",
"(",
"out",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"piface",
"=",
"re",
".",
"compile",
"(",
"r'^([^\\s:]+)'",
")",
"pmac",
"=",
"re",
".",
"compile",
"(",
"'.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)'",
")",
"pip",
"="... | 38.301587 | 0.001212 |
def get_flatpages_i18n(parser, token):
"""
Retrieves all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populates the template context with them in a variable
whose name is defined by the ``as`` clause.
An opti... | [
"def",
"get_flatpages_i18n",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"syntax_message",
"=",
"(",
"\"%(tag_name)s expects a syntax of %(tag_name)s \"",
"\"['url_starts_with'] [for user] as context_name\"",
"%",
"dict",
... | 36.441176 | 0.000393 |
def create_or_reference_batch(self):
"""Save reference to batch, if existing batch specified
Create new batch, if possible with specified values
"""
client = self.aq_parent
batch_headers = self.get_batch_header_values()
if not batch_headers:
return False
... | [
"def",
"create_or_reference_batch",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"aq_parent",
"batch_headers",
"=",
"self",
".",
"get_batch_header_values",
"(",
")",
"if",
"not",
"batch_headers",
":",
"return",
"False",
"# if the Batch's Title is specified and e... | 43.37931 | 0.001555 |
def _add_global_secondary_index(ret, name, index_name, changes_old, changes_new, comments,
gsi_config, region, key, keyid, profile):
'''Updates ret iff there was a failure or in test mode.'''
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dynamo table... | [
"def",
"_add_global_secondary_index",
"(",
"ret",
",",
"name",
",",
"index_name",
",",
"changes_old",
",",
"changes_new",
",",
"comments",
",",
"gsi_config",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
":",
"if",
"__opts__",
"[",
"'test'",
... | 39.08 | 0.001998 |
def role_show(endpoint_id, role_id):
"""
Executor for `globus endpoint role show`
"""
client = get_client()
role = client.get_endpoint_role(endpoint_id, role_id)
formatted_print(
role,
text_format=FORMAT_TEXT_RECORD,
fields=(
("Principal Type", "principal_typ... | [
"def",
"role_show",
"(",
"endpoint_id",
",",
"role_id",
")",
":",
"client",
"=",
"get_client",
"(",
")",
"role",
"=",
"client",
".",
"get_endpoint_role",
"(",
"endpoint_id",
",",
"role_id",
")",
"formatted_print",
"(",
"role",
",",
"text_format",
"=",
"FORMA... | 25.0625 | 0.002404 |
def argmax(input_, multi=False):
"""
Returns index / key of the item with the largest value.
Args:
input_ (dict or list):
References:
http://stackoverflow.com/questions/16945518/python-argmin-argmax
Ignore:
list_ = np.random.rand(10000).tolist()
%timeit list_.index... | [
"def",
"argmax",
"(",
"input_",
",",
"multi",
"=",
"False",
")",
":",
"if",
"multi",
":",
"if",
"isinstance",
"(",
"input_",
",",
"dict",
")",
":",
"keys",
"=",
"list",
"(",
"input_",
".",
"keys",
"(",
")",
")",
"values",
"=",
"list",
"(",
"input... | 35.708333 | 0.000568 |
def _ndtri(p):
"""Implements ndtri core logic."""
# Constants used in piece-wise rational approximations. Taken from the cephes
# library:
# https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html
p0 = list(reversed([-5.99633501014107895267E1,
9.80010754185999661536E1,
... | [
"def",
"_ndtri",
"(",
"p",
")",
":",
"# Constants used in piece-wise rational approximations. Taken from the cephes",
"# library:",
"# https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html",
"p0",
"=",
"list",
"(",
"reversed",
"(",
"[",
"-",
"5.99633501014107895267E1",
... | 43.38835 | 0.008313 |
def _run_lint_on_file(file_path,
linter_functions,
tool_options,
fix_what_you_can):
"""Run each function in linter_functions on filename.
If fix_what_you_can is specified, then the first error that has a
possible replacement will be automati... | [
"def",
"_run_lint_on_file",
"(",
"file_path",
",",
"linter_functions",
",",
"tool_options",
",",
"fix_what_you_can",
")",
":",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"\"r+\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"found_file",
":",
"file_co... | 45.571429 | 0.000614 |
def _extract_path_from_service(self, service):
"""
Extract path object and its parameters from service definitions.
:param service:
Cornice service to extract information from.
:rtype: dict
:returns: Path definition.
"""
path_obj = {}
path =... | [
"def",
"_extract_path_from_service",
"(",
"self",
",",
"service",
")",
":",
"path_obj",
"=",
"{",
"}",
"path",
"=",
"service",
".",
"path",
"route_name",
"=",
"getattr",
"(",
"service",
",",
"'pyramid_route'",
",",
"None",
")",
"# handle services that don't crea... | 37.153846 | 0.001345 |
def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613
'''
List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkgutil.list_upgrades
'''
if salt.utils.data.is_true(refresh):
refresh_db()
upgrades = {}
lines = __sal... | [
"def",
"list_upgrades",
"(",
"refresh",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=W0613",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"refresh",
")",
":",
"refresh_db",
"(",
")",
"upgrades",
"=",
"{",
"}",
"li... | 26.217391 | 0.0016 |
def merge_noun_chunks(doc):
"""Merge noun chunks into a single token.
doc (Doc): The Doc object.
RETURNS (Doc): The Doc object with merged noun chunks.
DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks
"""
if not doc.is_parsed:
return doc
with doc.retokenize() as reto... | [
"def",
"merge_noun_chunks",
"(",
"doc",
")",
":",
"if",
"not",
"doc",
".",
"is_parsed",
":",
"return",
"doc",
"with",
"doc",
".",
"retokenize",
"(",
")",
"as",
"retokenizer",
":",
"for",
"np",
"in",
"doc",
".",
"noun_chunks",
":",
"attrs",
"=",
"{",
... | 31.466667 | 0.002058 |
def any_slug_field(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True
"""
letters = ascii_letters ... | [
"def",
"any_slug_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"letters",
"=",
"ascii_letters",
"+",
"digits",
"+",
"'_-'",
"return",
"xunit",
".",
"any_string",
"(",
"letters",
"=",
"letters",
",",
"max_length",
"=",
"field",
".",
"max_length",... | 33.583333 | 0.012077 |
def pin_chat_message(self, *args, **kwargs):
"""See :func:`pin_chat_message`"""
return pin_chat_message(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"pin_chat_message",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"pin_chat_message",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
")"
] | 55 | 0.011976 |
def print_traceback(self, always_print=False):
"""
Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false)
"""
if self._exception or always_print:
... | [
"def",
"print_traceback",
"(",
"self",
",",
"always_print",
"=",
"False",
")",
":",
"if",
"self",
".",
"_exception",
"or",
"always_print",
":",
"self",
".",
"__echo",
".",
"critical",
"(",
"\"--{ TRACEBACK }\"",
"+",
"\"-\"",
"*",
"100",
")",
"self",
".",
... | 54.333333 | 0.008048 |
def visit_Expr(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of nested expression."""
return self.visit(node.value) | [
"def",
"visit_Expr",
"(",
"self",
",",
"node",
":",
"AST",
",",
"dfltChaining",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"return",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")"
] | 53.333333 | 0.012346 |
def labelHealpix(pixels, values, nside, threshold=0, xsize=1000):
"""
Label contiguous regions of a (sparse) HEALPix map. Works by mapping
HEALPix array to a Mollweide projection and applying scipy.ndimage.label
Assumes non-nested HEALPix map.
Parameters:
... | [
"def",
"labelHealpix",
"(",
"pixels",
",",
"values",
",",
"nside",
",",
"threshold",
"=",
"0",
",",
"xsize",
"=",
"1000",
")",
":",
"proj",
"=",
"healpy",
".",
"projector",
".",
"MollweideProj",
"(",
"xsize",
"=",
"xsize",
")",
"vec",
"=",
"healpy",
... | 36.415094 | 0.014632 |
def build_attrs(self, *args, **kwargs):
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(*args, **kwargs)
return self.attrs | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"attrs",
"=",
"self",
".",
"widget",
".",
"build_attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"attrs"
] | 47 | 0.010471 |
def _set_callables(modules):
'''
Set all Ansible modules callables
:return:
'''
def _set_function(cmd_name, doc):
'''
Create a Salt function for the Ansible module.
'''
def _cmd(*args, **kw):
'''
Call an Ansible module as a function from the Sa... | [
"def",
"_set_callables",
"(",
"modules",
")",
":",
"def",
"_set_function",
"(",
"cmd_name",
",",
"doc",
")",
":",
"'''\n Create a Salt function for the Ansible module.\n '''",
"def",
"_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"'''\n ... | 28.769231 | 0.001294 |
def query_single_page(query, lang, pos, retry=50, from_user=False):
"""
Returns tweets from the given URL.
:param query: The query parameter of the query url
:param lang: The language parameter of the query url
:param pos: The query url parameter that determines where to start looking
:param re... | [
"def",
"query_single_page",
"(",
"query",
",",
"lang",
",",
"pos",
",",
"retry",
"=",
"50",
",",
"from_user",
"=",
"False",
")",
":",
"url",
"=",
"get_query_url",
"(",
"query",
",",
"lang",
",",
"pos",
",",
"from_user",
")",
"try",
":",
"response",
"... | 36.516129 | 0.00172 |
def move_leadership(self, partition, new_leader):
"""Return a new state that is the result of changing the leadership of
a single partition.
:param partition: The partition index of the partition to change the
leadership of.
:param new_leader: The broker index of the new lea... | [
"def",
"move_leadership",
"(",
"self",
",",
"partition",
",",
"new_leader",
")",
":",
"new_state",
"=",
"copy",
"(",
"self",
")",
"# Update the partition replica tuple",
"source",
"=",
"new_state",
".",
"replicas",
"[",
"partition",
"]",
"[",
"0",
"]",
"new_le... | 37.395349 | 0.001818 |
def get_device_model(self) -> str:
'''Show device model.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.product.model')
return output.strip() | [
"def",
"get_device_model",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'getprop'",
",",
"'ro.product.model'",
")",
"return",
"output",
".",
"strip... | 40.4 | 0.009709 |
def to_table(components, topo_info):
""" normalize raw logical plan info to table """
inputs, outputs = defaultdict(list), defaultdict(list)
for ctype, component in components.items():
if ctype == 'bolts':
for component_name, component_info in component.items():
for input_stream in component_inf... | [
"def",
"to_table",
"(",
"components",
",",
"topo_info",
")",
":",
"inputs",
",",
"outputs",
"=",
"defaultdict",
"(",
"list",
")",
",",
"defaultdict",
"(",
"list",
")",
"for",
"ctype",
",",
"component",
"in",
"components",
".",
"items",
"(",
")",
":",
"... | 42.821429 | 0.017129 |
def _sanity_check_scale(self, scale_x, scale_y):
"""Do a sanity check on the proposed scale vs. window size.
Raises an exception if there will be a problem.
"""
win_wd, win_ht = self.get_window_size()
if (win_wd <= 0) or (win_ht <= 0):
raise ImageViewError("window siz... | [
"def",
"_sanity_check_scale",
"(",
"self",
",",
"scale_x",
",",
"scale_y",
")",
":",
"win_wd",
",",
"win_ht",
"=",
"self",
".",
"get_window_size",
"(",
")",
"if",
"(",
"win_wd",
"<=",
"0",
")",
"or",
"(",
"win_ht",
"<=",
"0",
")",
":",
"raise",
"Imag... | 43.95 | 0.002227 |
def query(cls, name, use_kerberos=None, debug=False):
"""Query the LIGO Channel Information System a `ChannelList`.
Parameters
----------
name : `str`
name of channel, or part of it.
use_kerberos : `bool`, optional
use an existing Kerberos ticket as the ... | [
"def",
"query",
"(",
"cls",
",",
"name",
",",
"use_kerberos",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"from",
".",
"io",
"import",
"cis",
"return",
"cis",
".",
"query",
"(",
"name",
",",
"use_kerberos",
"=",
"use_kerberos",
",",
"debug",
"... | 34.291667 | 0.002364 |
def kids(self):
"""Alternative naming, you can use `node.kids.name` instead of `node.name`
for easier tab completion."""
if self._kids is None:
self._kids = NNTreeNodeKids(self)
return self._kids | [
"def",
"kids",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kids",
"is",
"None",
":",
"self",
".",
"_kids",
"=",
"NNTreeNodeKids",
"(",
"self",
")",
"return",
"self",
".",
"_kids"
] | 39 | 0.012552 |
def unassign_assessment_taken_from_bank(self, assessment_taken_id, bank_id):
"""Removes an ``AssessmentTaken`` from a ``Bank``.
arg: assessment_taken_id (osid.id.Id): the ``Id`` of the
``AssessmentTaken``
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
raise:... | [
"def",
"unassign_assessment_taken_from_bank",
"(",
"self",
",",
"assessment_taken_id",
",",
"bank_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'... | 52.136364 | 0.001712 |
def get_view_attr(view, key, default=None, cls_name=None):
"""
Get the attributes that was saved for the view
:param view: object (class or instance method)
:param key: string - the key
:param default: mixed - the default value
:param cls_name: str - To pass the class name associated to the view... | [
"def",
"get_view_attr",
"(",
"view",
",",
"key",
",",
"default",
"=",
"None",
",",
"cls_name",
"=",
"None",
")",
":",
"ns",
"=",
"view_namespace",
"(",
"view",
",",
"cls_name",
")",
"if",
"ns",
":",
"if",
"ns",
"not",
"in",
"_views_attr",
":",
"retur... | 36.75 | 0.001658 |
def workdaycount(self, date1, date2):
"""
Count work days between two dates, ignoring holidays.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval.
Note:
The adopted notation is C... | [
"def",
"workdaycount",
"(",
"self",
",",
"date1",
",",
"date2",
")",
":",
"date1",
"=",
"parsefun",
"(",
"date1",
")",
"date2",
"=",
"parsefun",
"(",
"date2",
")",
"if",
"date1",
"==",
"date2",
":",
"return",
"0",
"elif",
"date1",
">",
"date2",
":",
... | 31.805556 | 0.001695 |
def main(args):
"""
Nibble's entry point.
:param args: Command-line arguments, with the program in position 0.
"""
args = _parse_args(args)
# sort out logging output and level
level = util.log_level_from_vebosity(args.verbosity)
root = logging.getLogger()
root.setLevel(level)
... | [
"def",
"main",
"(",
"args",
")",
":",
"args",
"=",
"_parse_args",
"(",
"args",
")",
"# sort out logging output and level",
"level",
"=",
"util",
".",
"log_level_from_vebosity",
"(",
"args",
".",
"verbosity",
")",
"root",
"=",
"logging",
".",
"getLogger",
"(",
... | 24.607143 | 0.001397 |
def set_canvas_properties(self, canvas, x_title=None, y_title=None, x_lim=None, y_lim=None, x_labels=True, y_labels=True):
"""!
@brief Set properties for specified canvas.
@param[in] canvas (uint): Index of canvas whose properties should changed.
@param[in] x_title (string): Title ... | [
"def",
"set_canvas_properties",
"(",
"self",
",",
"canvas",
",",
"x_title",
"=",
"None",
",",
"y_title",
"=",
"None",
",",
"x_lim",
"=",
"None",
",",
"y_lim",
"=",
"None",
",",
"x_labels",
"=",
"True",
",",
"y_labels",
"=",
"True",
")",
":",
"self",
... | 65.8125 | 0.011236 |
def _flash_encryption_tweak_key(key, offset, tweak_range):
"""Apply XOR "tweak" values to the key, derived from flash offset
'offset'. This matches the ESP32 hardware flash encryption.
tweak_range is a list of bit indexes to apply the tweak to, as
generated by _flash_encryption_tweak_range() from the
... | [
"def",
"_flash_encryption_tweak_key",
"(",
"key",
",",
"offset",
",",
"tweak_range",
")",
":",
"if",
"esptool",
".",
"PYTHON2",
":",
"key",
"=",
"[",
"ord",
"(",
"k",
")",
"for",
"k",
"in",
"key",
"]",
"else",
":",
"key",
"=",
"list",
"(",
"key",
"... | 33.035714 | 0.00105 |
def _CheckLocation(self, file_entry, search_depth):
"""Checks the location find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
bool: True if the file entry matches the find specification, False if not.
... | [
"def",
"_CheckLocation",
"(",
"self",
",",
"file_entry",
",",
"search_depth",
")",
":",
"if",
"self",
".",
"_location_segments",
"is",
"None",
":",
"return",
"False",
"if",
"search_depth",
"<",
"0",
"or",
"search_depth",
">",
"self",
".",
"_number_of_location_... | 31.894737 | 0.011206 |
def Distance_Calculation(self):
print(self.whole_labels)
distance_result={}
#distance_result[self.whole_labels[i]] = []
print(distance_result)
for i in range(len(self.whole_labels)):
#print(self.whole_labels[i], self.fa_result[self.result_to_fit.index == self.whol... | [
"def",
"Distance_Calculation",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"whole_labels",
")",
"distance_result",
"=",
"{",
"}",
"#distance_result[self.whole_labels[i]] = []",
"print",
"(",
"distance_result",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(... | 37.583333 | 0.011345 |
def submit(course, tid=None, pastebin=False, review=False):
"""
Submit the selected exercise to the server.
"""
if tid is not None:
return submit_exercise(Exercise.byid(tid),
pastebin=pastebin,
request_review=review)
else:
... | [
"def",
"submit",
"(",
"course",
",",
"tid",
"=",
"None",
",",
"pastebin",
"=",
"False",
",",
"review",
"=",
"False",
")",
":",
"if",
"tid",
"is",
"not",
"None",
":",
"return",
"submit_exercise",
"(",
"Exercise",
".",
"byid",
"(",
"tid",
")",
",",
"... | 36.538462 | 0.002053 |
def regular_triangle_mesh(nx, ny):
"""Construct a regular triangular mesh in the unit square.
Parameters
----------
nx : int
Number of nodes in the x-direction
ny : int
Number of nodes in the y-direction
Returns
-------
Vert : array
nx*ny x 2 vertex list
E2V :... | [
"def",
"regular_triangle_mesh",
"(",
"nx",
",",
"ny",
")",
":",
"nx",
",",
"ny",
"=",
"int",
"(",
"nx",
")",
",",
"int",
"(",
"ny",
")",
"if",
"nx",
"<",
"2",
"or",
"ny",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'minimum mesh dimension is 2: %s'",... | 28.234043 | 0.000728 |
def make_tag(cls, tag_name):
"""
Make a Tag object from a tag name. Registers it with the content manager
if possible.
"""
if cls.cm:
return cls.cm.make_tag(tag_name)
return Tag(tag_name.strip()) | [
"def",
"make_tag",
"(",
"cls",
",",
"tag_name",
")",
":",
"if",
"cls",
".",
"cm",
":",
"return",
"cls",
".",
"cm",
".",
"make_tag",
"(",
"tag_name",
")",
"return",
"Tag",
"(",
"tag_name",
".",
"strip",
"(",
")",
")"
] | 25.375 | 0.042857 |
def is_int_vector(l):
r"""Checks if l is a numpy array of integers
"""
if isinstance(l, np.ndarray):
if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):
return True
return False | [
"def",
"is_int_vector",
"(",
"l",
")",
":",
"if",
"isinstance",
"(",
"l",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"l",
".",
"ndim",
"==",
"1",
"and",
"(",
"l",
".",
"dtype",
".",
"kind",
"==",
"'i'",
"or",
"l",
".",
"dtype",
".",
"kind",
"... | 27.5 | 0.008811 |
def check_sorted(cards, ranks=None):
"""
Checks whether the given cards are sorted by the given ranks.
:arg cards:
The cards to check. Can be a ``Stack``, ``Deck``, or ``list`` of
``Card`` isntances.
:arg dict ranks:
The ranks to check against. Default is DEFAULT_RANKS.
:re... | [
"def",
"check_sorted",
"(",
"cards",
",",
"ranks",
"=",
"None",
")",
":",
"ranks",
"=",
"ranks",
"or",
"DEFAULT_RANKS",
"sorted_cards",
"=",
"sort_cards",
"(",
"cards",
",",
"ranks",
")",
"if",
"cards",
"==",
"sorted_cards",
"or",
"cards",
"[",
":",
":",... | 24.454545 | 0.001789 |
def getColCellIdx(self, idx):
"""
Get column and cell within column from a global cell index.
The global index is ``idx = colIdx * nCellsPerCol() + cellIdxInCol``
:param idx: (int) global cell index
:returns: (tuple) (colIdx, cellIdxInCol)
"""
c = idx//self.cellsPerColumn
i = idx - ... | [
"def",
"getColCellIdx",
"(",
"self",
",",
"idx",
")",
":",
"c",
"=",
"idx",
"//",
"self",
".",
"cellsPerColumn",
"i",
"=",
"idx",
"-",
"c",
"*",
"self",
".",
"cellsPerColumn",
"return",
"c",
",",
"i"
] | 31.454545 | 0.008427 |
def td_is_finished(tomodir):
"""Return the state of modeling and inversion for a given tomodir. The
result does not take into account sensitivities or potentials, as
optionally generated by CRMod.
Parameters
----------
tomodir: string
Directory to check
Returns
-------
crmo... | [
"def",
"td_is_finished",
"(",
"tomodir",
")",
":",
"if",
"not",
"is_tomodir",
"(",
"tomodir",
")",
":",
"raise",
"Exception",
"(",
"'Supplied directory is not a tomodir!'",
")",
"# crmod finished is determined by:",
"# config.dat/rho.dat/crmod.cfg are present",
"# volt.dat is... | 38.596491 | 0.000443 |
def parse_links(args_link):
"""Parse --link options.
Uses parse_link() to parse each option.
"""
links = []
if (args_link is not None):
for link_str in args_link:
try:
links.append(parse_link(link_str))
except ClientFatalError as e:
ra... | [
"def",
"parse_links",
"(",
"args_link",
")",
":",
"links",
"=",
"[",
"]",
"if",
"(",
"args_link",
"is",
"not",
"None",
")",
":",
"for",
"link_str",
"in",
"args_link",
":",
"try",
":",
"links",
".",
"append",
"(",
"parse_link",
"(",
"link_str",
")",
"... | 29.133333 | 0.002217 |
def _connect(self, servers):
""" connect to the given server, e.g.: \\connect localhost:4200 """
self._do_connect(servers.split(' '))
self._verify_connection(verbose=True) | [
"def",
"_connect",
"(",
"self",
",",
"servers",
")",
":",
"self",
".",
"_do_connect",
"(",
"servers",
".",
"split",
"(",
"' '",
")",
")",
"self",
".",
"_verify_connection",
"(",
"verbose",
"=",
"True",
")"
] | 48 | 0.010256 |
def imatch_any(patterns, name):
# type: (Iterable[Text], Text) -> bool
"""Test if a name matches any of a list of patterns (case insensitive).
Will return `True` if ``patterns`` is an empty list.
Arguments:
patterns (list): A list of wildcard pattern, e.g ``["*.py",
"*.pyc"]``
... | [
"def",
"imatch_any",
"(",
"patterns",
",",
"name",
")",
":",
"# type: (Iterable[Text], Text) -> bool",
"if",
"not",
"patterns",
":",
"return",
"True",
"return",
"any",
"(",
"imatch",
"(",
"pattern",
",",
"name",
")",
"for",
"pattern",
"in",
"patterns",
")"
] | 29.277778 | 0.001838 |
def detectGamingHandheld(self):
"""Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita.
"""
return UAgentInfo.devicePl... | [
"def",
"detectGamingHandheld",
"(",
"self",
")",
":",
"return",
"UAgentInfo",
".",
"devicePlaystation",
"in",
"self",
".",
"__userAgent",
"and",
"UAgentInfo",
".",
"devicePlaystationVita",
"in",
"self",
".",
"__userAgent"
] | 51.625 | 0.009524 |
def load_identity_signer(key_dir, key_name):
"""Loads a private key from the key directory, based on a validator's
identity.
Args:
key_dir (str): The path to the key directory.
key_name (str): The name of the key to load.
Returns:
Signer: the cryptographic signer for the key
... | [
"def",
"load_identity_signer",
"(",
"key_dir",
",",
"key_name",
")",
":",
"key_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"key_dir",
",",
"'{}.priv'",
".",
"format",
"(",
"key_name",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
... | 34.675676 | 0.000758 |
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias):
"""Called prior to self-attention, to incorporate memory items.
Args:
segment: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. A... | [
"def",
"pre_attention",
"(",
"self",
",",
"segment",
",",
"query_antecedent",
",",
"memory_antecedent",
",",
"bias",
")",
":",
"assert",
"memory_antecedent",
"is",
"None",
",",
"\"We only support language modeling\"",
"# In eval mode, batch size may be variable",
"memory_ba... | 48.779661 | 0.002384 |
def on_moved(self, event):
"""
Called when a file or a directory is moved or renamed.
Many editors don't directly change a file, instead they make a
transitional file like ``*.part`` then move it to the final filename.
Args:
event: Watchdog event, either ``watchdog.... | [
"def",
"on_moved",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"_event_error",
":",
"# We are only interested for final file, not transitional file",
"# from editors (like *.part)",
"pathtools_options",
"=",
"{",
"'included_patterns'",
":",
"self",
".",... | 44.72 | 0.001751 |
def train_supervised(problem, model_name, hparams, data_dir, output_dir,
train_steps, eval_steps, local_eval_frequency=None,
schedule="continuous_train_and_eval"):
"""Train supervised."""
if local_eval_frequency is None:
local_eval_frequency = FLAGS.local_eval_frequency... | [
"def",
"train_supervised",
"(",
"problem",
",",
"model_name",
",",
"hparams",
",",
"data_dir",
",",
"output_dir",
",",
"train_steps",
",",
"eval_steps",
",",
"local_eval_frequency",
"=",
"None",
",",
"schedule",
"=",
"\"continuous_train_and_eval\"",
")",
":",
"if"... | 43.357143 | 0.01129 |
def write_geo_file(self, filename):
"""
Write the .geo file
"""
fid = open(filename, 'w')
# 2D mesh algorithm (1=MeshAdapt, 2=Automatic, 5=Delaunay, 6=Frontal,
# 7=bamg, 8=delquad)
# according to the GMSH-mailing list the frontal algorithm should be
# one ... | [
"def",
"write_geo_file",
"(",
"self",
",",
"filename",
")",
":",
"fid",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"# 2D mesh algorithm (1=MeshAdapt, 2=Automatic, 5=Delaunay, 6=Frontal,",
"# 7=bamg, 8=delquad)",
"# according to the GMSH-mailing list the frontal algorithm shou... | 32.304348 | 0.001306 |
def _de_casteljau_one_round(nodes, degree, lambda1, lambda2, lambda3):
r"""Performs one "round" of the de Casteljau algorithm for surfaces.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
.. note::
This is a helper function, ... | [
"def",
"_de_casteljau_one_round",
"(",
"nodes",
",",
"degree",
",",
"lambda1",
",",
"lambda2",
",",
"lambda3",
")",
":",
"dimension",
",",
"num_nodes",
"=",
"nodes",
".",
"shape",
"num_new_nodes",
"=",
"num_nodes",
"-",
"degree",
"-",
"1",
"new_nodes",
"=",
... | 32.546875 | 0.000466 |
def drive(self) -> DriveChannel:
"""Return the primary drive channel of this qubit."""
if self._drives:
return self._drives[0]
else:
raise PulseError("No drive channels in q[%d]" % self._index) | [
"def",
"drive",
"(",
"self",
")",
"->",
"DriveChannel",
":",
"if",
"self",
".",
"_drives",
":",
"return",
"self",
".",
"_drives",
"[",
"0",
"]",
"else",
":",
"raise",
"PulseError",
"(",
"\"No drive channels in q[%d]\"",
"%",
"self",
".",
"_index",
")"
] | 39.333333 | 0.008299 |
def mean(x):
"""
Return a numpy array of column mean.
It does not affect if the array is one dimension
Parameters
----------
x : ndarray
A numpy array instance
Returns
-------
ndarray
A 1 x n numpy array instance of column mean
Examples
--------
>>> a =... | [
"def",
"mean",
"(",
"x",
")",
":",
"if",
"x",
".",
"ndim",
">",
"1",
"and",
"len",
"(",
"x",
"[",
"0",
"]",
")",
">",
"1",
":",
"return",
"np",
".",
"mean",
"(",
"x",
",",
"axis",
"=",
"1",
")",
"return",
"x"
] | 20.214286 | 0.001686 |
def _openResources(self):
""" Opens the root Dataset.
"""
logger.info("Opening: {}".format(self._fileName))
self._ncGroup = Dataset(self._fileName) | [
"def",
"_openResources",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Opening: {}\"",
".",
"format",
"(",
"self",
".",
"_fileName",
")",
")",
"self",
".",
"_ncGroup",
"=",
"Dataset",
"(",
"self",
".",
"_fileName",
")"
] | 35 | 0.011173 |
def cli(env, package_keyname, location, preset, name, send_email, complex_type,
extras, order_items):
"""Place a quote.
This CLI command is used for creating a quote of the specified package in
the given location (denoted by a datacenter's long name). Orders made via the CLI
can then be conver... | [
"def",
"cli",
"(",
"env",
",",
"package_keyname",
",",
"location",
",",
"preset",
",",
"name",
",",
"send_email",
",",
"complex_type",
",",
"extras",
",",
"order_items",
")",
":",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client... | 41.074627 | 0.002484 |
def get_direct_band_gap_dict(self):
"""
Returns a dictionary of information about the direct
band gap
Returns:
a dictionary of the band gaps indexed by spin
along with their band indices and k-point index
"""
if self.is_metal():
raise ... | [
"def",
"get_direct_band_gap_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_metal",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"get_direct_band_gap_dict should\"",
"\"only be used with non-metals\"",
")",
"direct_gap_dict",
"=",
"{",
"}",
"for",
"spin",
",",
... | 43.384615 | 0.001735 |
def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
def get_template(filename):
"""
There are a cou... | [
"def",
"install_script",
"(",
"self",
",",
"dist",
",",
"script_name",
",",
"script_text",
",",
"dev_path",
"=",
"None",
")",
":",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"is_script",
"=",
"is_python_script",
"(",
"script_tex... | 46.423077 | 0.002435 |
async def set_playback_settings(self, target, value) -> None:
"""Set playback settings such a shuffle and repeat."""
params = {"settings": [{"target": target, "value": value}]}
return await self.services["avContent"]["setPlaybackModeSettings"](params) | [
"async",
"def",
"set_playback_settings",
"(",
"self",
",",
"target",
",",
"value",
")",
"->",
"None",
":",
"params",
"=",
"{",
"\"settings\"",
":",
"[",
"{",
"\"target\"",
":",
"target",
",",
"\"value\"",
":",
"value",
"}",
"]",
"}",
"return",
"await",
... | 68 | 0.010909 |
def editMessageText(self, msg_identifier, text,
parse_mode=None,
disable_web_page_preview=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagetext
:param msg_identifier:
a 2-tuple (`... | [
"def",
"editMessageText",
"(",
"self",
",",
"msg_identifier",
",",
"text",
",",
"parse_mode",
"=",
"None",
",",
"disable_web_page_preview",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
",",
"more",
... | 44.125 | 0.008322 |
def _openFile(self):
""" Open the HDF5 file for reading/writing.
This methad is called during the initialization of this class.
"""
if self.filename is not None:
self.h5 = h5py.File(self.filename)
else:
return
if 'bp' not in self.h5:
... | [
"def",
"_openFile",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
"is",
"not",
"None",
":",
"self",
".",
"h5",
"=",
"h5py",
".",
"File",
"(",
"self",
".",
"filename",
")",
"else",
":",
"return",
"if",
"'bp'",
"not",
"in",
"self",
".",
"h5... | 31.191489 | 0.001984 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.